|
| 1 | +"""Search and execute example: LLM-driven tool discovery and execution. |
| 2 | +
|
| 3 | +There are two ways to give tools to an LLM: |
| 4 | +
|
| 5 | +1. ``toolset.openai()`` — fetches ALL tools and converts them to OpenAI format. |
| 6 | + Token cost scales with the number of tools in your catalog. |
| 7 | +
|
| 8 | +2. ``toolset.openai(mode="search_and_execute")`` — returns just 2 tools |
| 9 | + (tool_search + tool_execute). The LLM discovers and runs tools on-demand, |
| 10 | + keeping token usage constant regardless of catalog size. |
| 11 | +
|
| 12 | +This example demonstrates approach 2 with two patterns: |
| 13 | +- Raw client (OpenAI): manual agent loop with ``toolset.execute()`` |
| 14 | +- LangChain: framework handles tool execution automatically |
| 15 | +
|
| 16 | +Prerequisites: |
| 17 | + - STACKONE_API_KEY environment variable |
| 18 | + - STACKONE_ACCOUNT_ID environment variable |
| 19 | + - OPENAI_API_KEY environment variable |
| 20 | +
|
| 21 | +Run with: |
| 22 | + uv run python examples/agent_tool_search.py |
| 23 | +""" |
| 24 | + |
| 25 | +from __future__ import annotations |
| 26 | + |
| 27 | +import json |
| 28 | +import os |
| 29 | + |
| 30 | +try: |
| 31 | + from dotenv import load_dotenv |
| 32 | + |
| 33 | + load_dotenv() |
| 34 | +except ModuleNotFoundError: |
| 35 | + pass |
| 36 | + |
| 37 | +from stackone_ai import StackOneToolSet |
| 38 | + |
| 39 | + |
| 40 | +def example_openai() -> None: |
| 41 | + """Raw client: OpenAI. |
| 42 | +
|
| 43 | + Shows: init toolset -> get OpenAI tools -> manual agent loop with toolset.execute(). |
| 44 | + """ |
| 45 | + print("=" * 60) |
| 46 | + print("Example 1: Raw client (OpenAI) — manual execution") |
| 47 | + print("=" * 60) |
| 48 | + print() |
| 49 | + |
| 50 | + try: |
| 51 | + from openai import OpenAI |
| 52 | + except ImportError: |
| 53 | + print("Skipped: pip install openai") |
| 54 | + print() |
| 55 | + return |
| 56 | + |
| 57 | + if not os.getenv("OPENAI_API_KEY"): |
| 58 | + print("Skipped: Set OPENAI_API_KEY to run this example.") |
| 59 | + print() |
| 60 | + return |
| 61 | + |
| 62 | + # 1. Init toolset |
| 63 | + account_id = os.getenv("STACKONE_ACCOUNT_ID") |
| 64 | + toolset = StackOneToolSet( |
| 65 | + account_id=account_id, |
| 66 | + search={"method": "semantic", "top_k": 3}, |
| 67 | + execute={"account_ids": [account_id]} if account_id else None, |
| 68 | + ) |
| 69 | + |
| 70 | + # 2. Get tools in OpenAI format |
| 71 | + openai_tools = toolset.openai(mode="search_and_execute") |
| 72 | + |
| 73 | + # 3. Create OpenAI client and run agent loop |
| 74 | + client = OpenAI() |
| 75 | + messages: list[dict] = [ |
| 76 | + { |
| 77 | + "role": "system", |
| 78 | + "content": ( |
| 79 | + "You are a helpful scheduling assistant. Use tool_search to find relevant tools, " |
| 80 | + "then tool_execute to run them. Always read the parameter schemas from tool_search " |
| 81 | + "results carefully. If a tool needs a user URI, first search for and call a " |
| 82 | + '"get current user" tool to obtain it. If a tool execution fails, try different ' |
| 83 | + "parameters or a different tool." |
| 84 | + ), |
| 85 | + }, |
| 86 | + {"role": "user", "content": "List my upcoming Calendly events for the next week."}, |
| 87 | + ] |
| 88 | + |
| 89 | + for _step in range(10): |
| 90 | + response = client.chat.completions.create( |
| 91 | + model="gpt-5.4", |
| 92 | + messages=messages, |
| 93 | + tools=openai_tools, |
| 94 | + tool_choice="auto", |
| 95 | + ) |
| 96 | + |
| 97 | + choice = response.choices[0] |
| 98 | + |
| 99 | + # 4. If no tool calls, print final answer and stop |
| 100 | + if not choice.message.tool_calls: |
| 101 | + print(f"Answer: {choice.message.content}") |
| 102 | + break |
| 103 | + |
| 104 | + # 5. Execute tool calls manually and feed results back |
| 105 | + messages.append(choice.message.model_dump(exclude_none=True)) |
| 106 | + for tool_call in choice.message.tool_calls: |
| 107 | + print(f" -> {tool_call.function.name}({tool_call.function.arguments})") |
| 108 | + result = toolset.execute(tool_call.function.name, tool_call.function.arguments) |
| 109 | + messages.append( |
| 110 | + { |
| 111 | + "role": "tool", |
| 112 | + "tool_call_id": tool_call.id, |
| 113 | + "content": json.dumps(result), |
| 114 | + } |
| 115 | + ) |
| 116 | + |
| 117 | + print() |
| 118 | + |
| 119 | + |
| 120 | +def example_langchain() -> None: |
| 121 | + """Framework: LangChain with auto-execution. |
| 122 | +
|
| 123 | + Shows: init toolset -> get LangChain tools -> bind to model -> framework executes tools. |
| 124 | + No toolset.execute() needed — the framework calls _run() on tools automatically. |
| 125 | + """ |
| 126 | + print("=" * 60) |
| 127 | + print("Example 2: LangChain — framework handles execution") |
| 128 | + print("=" * 60) |
| 129 | + print() |
| 130 | + |
| 131 | + try: |
| 132 | + from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage |
| 133 | + from langchain_openai import ChatOpenAI |
| 134 | + except ImportError: |
| 135 | + print("Skipped: pip install langchain-openai") |
| 136 | + print() |
| 137 | + return |
| 138 | + |
| 139 | + if not os.getenv("OPENAI_API_KEY"): |
| 140 | + print("Skipped: Set OPENAI_API_KEY to run this example.") |
| 141 | + print() |
| 142 | + return |
| 143 | + |
| 144 | + # 1. Init toolset |
| 145 | + account_id = os.getenv("STACKONE_ACCOUNT_ID") |
| 146 | + toolset = StackOneToolSet( |
| 147 | + account_id=account_id, |
| 148 | + search={"method": "semantic", "top_k": 3}, |
| 149 | + execute={"account_ids": [account_id]} if account_id else None, |
| 150 | + ) |
| 151 | + |
| 152 | + # 2. Get tools in LangChain format and bind to model |
| 153 | + langchain_tools = toolset.langchain(mode="search_and_execute") |
| 154 | + tools_by_name = {tool.name: tool for tool in langchain_tools} |
| 155 | + model = ChatOpenAI(model="gpt-5.4").bind_tools(langchain_tools) |
| 156 | + |
| 157 | + # 3. Run agent loop |
| 158 | + messages = [ |
| 159 | + SystemMessage( |
| 160 | + content=( |
| 161 | + "You are a helpful scheduling assistant. Use tool_search to find relevant tools, " |
| 162 | + "then tool_execute to run them. Always read the parameter schemas from tool_search " |
| 163 | + "results carefully. If a tool needs a user URI, first search for and call a " |
| 164 | + '"get current user" tool to obtain it. If a tool execution fails, try different ' |
| 165 | + "parameters or a different tool." |
| 166 | + ), |
| 167 | + ), |
| 168 | + HumanMessage(content="List my upcoming Calendly events for the next week."), |
| 169 | + ] |
| 170 | + |
| 171 | + for _step in range(10): |
| 172 | + response: AIMessage = model.invoke(messages) |
| 173 | + |
| 174 | + # 4. If no tool calls, print final answer and stop |
| 175 | + if not response.tool_calls: |
| 176 | + print(f"Answer: {response.content}") |
| 177 | + break |
| 178 | + |
| 179 | + # 5. Framework-compatible execution — invoke LangChain tools directly |
| 180 | + messages.append(response) |
| 181 | + for tool_call in response.tool_calls: |
| 182 | + print(f" -> {tool_call['name']}({json.dumps(tool_call['args'])})") |
| 183 | + tool = tools_by_name[tool_call["name"]] |
| 184 | + result = tool.invoke(tool_call["args"]) |
| 185 | + messages.append(ToolMessage(content=json.dumps(result), tool_call_id=tool_call["id"])) |
| 186 | + |
| 187 | + print() |
| 188 | + |
| 189 | + |
| 190 | +def main() -> None: |
| 191 | + """Run all examples.""" |
| 192 | + api_key = os.getenv("STACKONE_API_KEY") |
| 193 | + if not api_key: |
| 194 | + print("Set STACKONE_API_KEY to run these examples.") |
| 195 | + return |
| 196 | + |
| 197 | + example_openai() |
| 198 | + example_langchain() |
| 199 | + |
| 200 | + |
| 201 | +if __name__ == "__main__": |
| 202 | + main() |
0 commit comments