pythonadvanced
Build a ReAct Agent Loop
Implement a reasoning-action loop for an AI agent that uses tools iteratively.
pythonPress β/Ctrl + Shift + C to copy
from openai import OpenAI
import json
client = OpenAI()
# Define tools
def search_docs(query: str) -> str:
return f"Found 3 results for '{query}': [doc1, doc2, doc3]"
def calculate(expression: str) -> str:
try:
return str(eval(expression)) # In production, use a safe evaluator
except Exception as e:
return f"Error: {e}"
TOOL_MAP = {"search_docs": search_docs, "calculate": calculate}
TOOLS = [
{"type": "function", "function": {
"name": "search_docs",
"description": "Search documentation",
"parameters": {"type": "object", "properties": {
"query": {"type": "string"}
}, "required": ["query"]}
}},
{"type": "function", "function": {
"name": "calculate",
"description": "Evaluate a math expression",
"parameters": {"type": "object", "properties": {
"expression": {"type": "string"}
}, "required": ["expression"]}
}}
]
def agent_loop(user_query: str, max_steps: int = 5) -> str:
messages = [
{"role": "system", "content": "You are a helpful assistant. Use tools when needed."},
{"role": "user", "content": user_query}
]
for step in range(max_steps):
response = client.chat.completions.create(
model="gpt-4o", messages=messages, tools=TOOLS
)
msg = response.choices[0].message
messages.append(msg)
if not msg.tool_calls:
return msg.content # Final answer
for call in msg.tool_calls:
fn = TOOL_MAP[call.function.name]
args = json.loads(call.function.arguments)
result = fn(**args)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": result
})
return "Max steps reached."
print(agent_loop("Search for Python decorators and calculate 2**10"))Use Cases
- AI agents
- Multi-step reasoning
- Automated research
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonadvanced
LangChain ReAct Agent Pattern
Implement a ReAct (Reason+Act) agent that thinks step-by-step before calling tools.
Best for: reasoning agents
#langchain#react
pythonadvanced
Manual OpenAI Agent Loop in Python
Implement a bare-metal AI agent loop with tool execution and conversation management without frameworks.
Best for: custom agents
#openai#agent
typescriptbeginner
Claude Messages API (Anthropic SDK)
Send messages to Claude using the official Anthropic SDK with system prompt and user turn.
Best for: AI assistant
#anthropic#claude
typescriptbeginner
DALLΒ·E 3 Image Generation
Generate images from a text prompt using the OpenAI DALLΒ·E 3 API and return a URL.
Best for: AI art generation
#openai#dall-e