python --version
pip install openai
export OPENAI_API_KEY=sk-...
Build a thought-action-observation loop where the LLM decides when to call tools and when to return a final answer.
1 import json 2 from openai import OpenAI 3 4 client = OpenAI() 5 6 TOOLS = [ 7 { 8 "type": "function", 9 "function": { 10 "name": "search", 11 "description": "Search the web for a query", 12 "parameters": { 13 "type": "object", 14 "properties": { 15 "query": {"type": "string", "description": "Search query"} 16 }, 17 "required": ["query"] 18 } 19 } 20 } 21 ] 22 23 def search(query: str) -> str: 24 # Stub: replace with real search 25 return f"Results for '{query}': [result 1, result 2]" 26 27 def run_agent(user_message: str, max_iterations: int = 5) -> str: 28 messages = [ 29 {"role": "system", "content": "You are a helpful assistant with access to tools."}, 30 {"role": "user", "content": user_message}, 31 ] 32 for _ in range(max_iterations): 33 response = client.chat.completions.create( 34 model="gpt-4o", 35 messages=messages, 36 tools=TOOLS, 37 tool_choice="auto", 38 ) 39 msg = response.choices[0].message 40 messages.append(msg) 41 42 if not msg.tool_calls: 43 return msg.content or "" 44 45 for tc in msg.tool_calls: 46 args = json.loads(tc.function.arguments) 47 result = search(**args) if tc.function.name == "search" else "Unknown tool" 48 messages.append({ 49 "role": "tool", 50 "tool_call_id": tc.id, 51 "content": result, 52 }) 53 54 return "Max iterations reached" 55 56 if __name__ == "__main__": 57 answer = run_agent("What is the capital of France and what is it known for?") 58 print(answer) 59
An agent that correctly chains 2+ tool calls to answer a multi-step question
Sign in to share your feedback and join the discussion.