pythonadvanced

Build a ReAct Agent Loop

Implement a reasoning-action loop for an AI agent that uses tools iteratively.

python
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.