StackPractices
advanced By Mathias Paulenko

Complete Guide to AI Agents in Production

Design, deploy, and operate LLM agents that survive real traffic: architectures, tools, memory, human-in-the-loop, safety, and observability.

Introduction

An AI agent is a system where an LLM decides what to do next: it reasons about a task, calls tools, reads the results, and iterates until the work is done — or until something stops it. That “something” is where production work lives. A demo agent runs ten successful loops in a notebook; a production agent hits rate limits, hallucinated tool names, runaway iterations, and inputs nobody predicted, at 3 AM, with a cost meter running.

This guide covers the patterns that separate the two: how to pick an architecture, how much autonomy to give, where humans belong in the loop, how to keep agents from hurting themselves, and how to see what they actually did afterwards. The code examples are deliberately framework-free — LangGraph, CrewAI, and the OpenAI Agents SDK all implement these same primitives, so understanding them at this level transfers to whatever stack you end up on. If you want the framework-specific view, see the LangChain in Production guide.

Agent Architectures

Every production agent is a variation on five architectures. Choosing wrong here is the most expensive mistake, because the architecture caps reliability more than the model does — a frontier model inside the wrong loop fails more often than a small model inside the right one.

Decision diagram for agent architectures: a task routes to Chain/ReAct for simple bounded work, Plan-and-Execute for predictable steps, Router for distinct skills, or Supervisor for complex parallel work; all paths pass through a human-in-the-loop gate before observability and safety layers.

ReAct (Reason → Act → Observe) interleaves the model’s thinking with tool calls. It is the default for open-ended tasks because it needs no upfront plan — the agent reacts to what each tool returns. Its weakness is wandering: without iteration caps and token budgets, a ReAct agent will happily spend $4 deciding which of two near-identical tools to call.

Plan-and-Execute generates the full step list first, then executes it. It is cheaper per token and easier to review — you can show the plan to a human before spending anything — but brittle when a step’s output invalidates the plan. Use it for tasks whose shape you already know: report generation, ETL-style pipelines, migrations.

Router is the least agentic and the most reliable: a cheap model classifies the input, then a specialized handler (sometimes an agent, often just a chain) takes over. Most “agents” in successful production systems are actually routers over 3–5 handlers.

Supervisor / Multi-Agent delegates to sub-agents, each with its own system prompt and tools. It buys you separation of concerns and parallelism, and costs you coordination overhead, harder debugging, and a debugging surface where “why did it do that” spans several agents. Worth it only when sub-tasks genuinely need different toolsets or models.

Collaborative patterns have agents debate or review each other’s work. Powerful for code review and red-teaming, expensive everywhere else.

The agent types map to concrete components in every implementation:

Agent Types:
1. ReAct Agent: Reason → Act → Observe → Repeat
2. Plan-and-Execute: Plan all steps first, then execute sequentially
3. Router Agent: Classify input, route to specialized handler
4. Multi-Agent: Multiple agents collaborate on complex tasks
5. Supervisor Agent: One agent delegates to sub-agents

Key Components:
- LLM: The reasoning engine
- Tools: Functions the agent can call
- Memory: Short-term (conversation) and long-term (knowledge base)
- Planner: Breaks down complex tasks into steps
- Executor: Runs each step
- Observer: Evaluates results and decides next action

When to Use

Agents earn their complexity only in specific situations:

  • The task can’t be scripted — inputs vary enough that a fixed pipeline would need constant maintenance (research, triage, multi-format extraction).
  • The workflow needs dynamic tool selection — the agent must choose which API, query, or action applies instead of following a predetermined order.
  • Steps are interdependent and adaptive — each step’s output changes what the next step should be, which is exactly what ReAct handles.
  • You can bound the blast radius — tools are read-only or reversible, or a human approves irreversible actions.

Do not use an agent when a chain or a script does the job. If the steps are always the same in the same order, an agent adds cost, latency, and nondeterminism for zero benefit — a router over deterministic handlers is almost always the better answer. If the task is a single LLM call with structured output, it’s a prompt, not an agent.

ReAct Pattern

ReAct, from the 2022 paper by Yao et al., alternates reasoning and acting: the model writes a thought, picks a tool, observes the result, and repeats. Modern chat APIs with function calling implement this loop natively — the model returns tool_calls, you execute them, feed the results back, and let it continue.

Two things matter in the implementation below and are easy to miss. First, max_iterations is the only hard stop — without it the loop is unbounded. Second, tool errors are fed back to the model as observations (result = f"Error: {e}"), not raised: letting the agent see its own failures is what makes ReAct self-correcting instead of crashing on the first bad call.

Basic ReAct Agent

from openai import OpenAI
import json
from typing import Callable

client = OpenAI()

class ReActAgent:
    def __init__(self, tools: dict[str, Callable], model: str = "gpt-4o", max_iterations: int = 10):
        self.tools = tools
        self.model = model
        self.max_iterations = max_iterations
        self.tool_schemas = self._build_tool_schemas()
    
    def _build_tool_schemas(self) -> list[dict]:
        schemas = []
        for name, func in self.tools.items():
            schemas.append({
                "type": "function",
                "function": {
                    "name": name,
                    "description": func.__doc__ or f"Tool: {name}",
                    "parameters": getattr(func, "params", {"type": "object", "properties": {}})
                }
            })
        return schemas
    
    def run(self, task: str) -> str:
        messages = [
            {
                "role": "system",
                "content": "You are an autonomous agent. Use tools to complete the task. "
                           "Think step by step. If a tool fails, try a different approach."
            },
            {"role": "user", "content": task}
        ]
        
        for i in range(self.max_iterations):
            response = client.chat.completions.create(
                model=self.model,
                messages=messages,
                tools=self.tool_schemas,
                tool_choice="auto"
            )
            
            msg = response.choices[0].message
            messages.append(msg)
            
            if msg.tool_calls:
                for call in msg.tool_calls:
                    func_name = call.function.name
                    func_args = json.loads(call.function.arguments)
                    
                    # Execute tool
                    try:
                        result = self.tools[func_name](**func_args)
                    except Exception as e:
                        result = f"Error: {e}"
                    
                    messages.append({
                        "role": "tool",
                        "tool_call_id": call.id,
                        "content": str(result)
                    })
            else:
                # No tool calls — agent is done
                return msg.content
        
        return "Max iterations reached without completion."

# Define tools
def search_web(query: str) -> str:
    """Search the web for information."""
    return f"Search results for '{query}': Result 1, Result 2, Result 3"

def write_file(filename: str, content: str) -> str:
    """Write content to a file."""
    return f"File '{filename}' written successfully ({len(content)} bytes)"

def run_code(code: str) -> str:
    """Execute Python code and return the output."""
    try:
        exec_globals = {}
        exec(code, exec_globals)
        return "Code executed successfully"
    except Exception as e:
        return f"Execution error: {e}"

# Create agent
agent = ReActAgent(
    tools={"search_web": search_web, "write_file": write_file, "run_code": run_code}
)

result = agent.run("Search for Python best practices and write a summary to a file called 'best_practices.txt'")
print(result)

A few production notes on this skeleton:

  • self.tools[func_name] will raise KeyError if the model invents a tool name — the except catches it and feeds the error back, which is the behavior you want, but in production also log unknown-tool calls as a quality signal: frequent hallucinated tools mean your tool descriptions are unclear.
  • getattr(func, "params", ...) is a placeholder for real JSON schemas. Use Pydantic models or a decorator that derives parameters from type hints — vague parameters produce malformed calls.
  • The run_code tool executes arbitrary Python. It is here because agents with code execution solve problems no other tool can — but it must run in a sandboxed environment (container, Firecracker microVM, exec with restricted builtins at minimum), never in-process next to your secrets. The Safety section covers the guardrails; the short version is that exec in the same process as your API keys is how incidents happen.

Plan-and-Execute Pattern

Plan-and-Execute splits the agent into a planner that produces the step list and an executor that runs each step. The separation is the point: planning is one expensive, reviewable call; execution is cheap and can even use a smaller model.

from openai import OpenAI
import json

client = OpenAI()

class PlanExecuteAgent:
    def __init__(self, tools: dict, model: str = "gpt-4o"):
        self.tools = tools
        self.model = model
    
    def plan(self, task: str) -> list[dict]:
        """Break down the task into steps."""
        response = client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": "Break down the task into concrete steps. Return JSON array of steps."},
                {"role": "user", "content": f"Task: {task}"}
            ],
            response_format={"type": "json_object"}
        )
        
        data = json.loads(response.choices[0].message.content)
        return data.get("steps", [])
    
    def execute_step(self, step: str, context: str = "") -> str:
        """Execute a single step using tools if needed."""
        response = client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": f"Execute this step. Previous results: {context}"},
                {"role": "user", "content": f"Step: {step}"}
            ]
        )
        return response.choices[0].message.content
    
    def run(self, task: str) -> dict:
        # Phase 1: Plan
        steps = self.plan(task)
        
        # Phase 2: Execute
        results = []
        context = ""
        
        for i, step in enumerate(steps):
            step_desc = step.get("description", str(step))
            result = self.execute_step(step_desc, context)
            results.append({"step": step_desc, "result": result})
            context += f"\nStep {i+1}: {step_desc}\nResult: {result}"
        
        return {"plan": steps, "results": results}

agent = PlanExecuteAgent(tools={})
result = agent.run("Research Python web frameworks, compare them, and write a recommendation report")

The code above is the minimal version — note that execute_step in this example doesn’t call tools at all, it just prompts the model with accumulated context. In a real deployment each step is either a tool call or a sub-prompt, and context needs a budget: concatenating every result unbounded will blow the context window on long plans. Cap it (last N results, or a summarized context maintained by a cheap model).

The known failure mode is plan invalidation: step 3 assumed a result step 2 did not produce. Production variants add a replanning step — after each execution, ask the planner whether the remaining steps still make sense. That reintroduces ReAct-like adaptivity while keeping the plan reviewable.

Multi-Agent Systems

Multi-agent is where architecture diagrams get pretty and debugging gets ugly. It is justified when sub-tasks have genuinely different toolsets, contexts, or models — a researcher with search tools, a coder with a sandbox, a writer with style rules — not because the org chart looks tidy.

Supervisor Pattern

The supervisor is a router with a brain: it inspects the task, picks the sub-agent, and hands off a scoped instruction. The delegation call below returns JSON describing who should do what:

from openai import OpenAI
import json

client = OpenAI()

class SupervisorAgent:
    def __init__(self, sub_agents: dict, model: str = "gpt-4o"):
        self.sub_agents = sub_agents
        self.model = model
    
    def delegate(self, task: str) -> dict:
        """Decide which sub-agent(s) to use for the task."""
        agent_descriptions = "\n".join(
            f"- {name}: {desc}" for name, desc in self.sub_agents.items()
        )
        
        response = client.chat.completions.create(
            model=self.model,
            messages=[
                {
                    "role": "system",
                    "content": f"You are a supervisor. Delegate tasks to the appropriate agent.\n\nAvailable agents:\n{agent_descriptions}\n\nReturn JSON: {{\"agent\": \"name\", \"task\": \"specific task for the agent\"}}"
                },
                {"role": "user", "content": task}
            ],
            response_format={"type": "json_object"}
        )
        
        return json.loads(response.choices[0].message.content)
    
    def run(self, task: str) -> str:
        delegation = self.delegate(task)
        agent_name = delegation["agent"]
        sub_task = delegation["task"]
        
        # In production, route to actual sub-agent implementation
        return f"Delegated to {agent_name}: {sub_task}"

# Define sub-agents
sub_agents = {
    "research_agent": "Searches the web and gathers information",
    "code_agent": "Writes, tests, and debugs code",
    "writer_agent": "Writes reports, documentation, and content",
    "data_agent": "Analyzes data and creates visualizations"
}

supervisor = SupervisorAgent(sub_agents)
result = supervisor.run("Write a Python script to analyze sales data and create a report")
print(result)

Notice that run() here only prints the delegation decision — the wiring from agent_name to an actual sub-agent implementation is deliberately left to you. That wiring is where production supervisors live: each sub-agent is usually a ReAct loop of its own, the supervisor collects their outputs, and a final synthesis step produces the answer. Keep the delegation contract explicit ({"agent": ..., "task": ...}) and validate it — a supervisor that returns an unknown agent name or an empty task is a routing bug, not a content bug, and should fail fast.

Collaborative Agents

Collaborative patterns have multiple agents review or discuss the same artifact — the classic use is parallel code review, where a security reviewer, a performance reviewer, and a style reviewer each see the same code:

class CollaborativeAgents:
    def __init__(self, agents: dict[str, str], model: str = "gpt-4o", max_rounds: int = 5):
        self.agents = agents  # name -> system_prompt
        self.model = model
        self.max_rounds = max_rounds
    
    def discuss(self, topic: str) -> list[dict]:
        """Multiple agents discuss a topic and reach consensus."""
        conversation = [{"role": "user", "content": f"Topic for discussion: {topic}"}]
        messages_log = []
        
        for round_num in range(self.max_rounds):
            for agent_name, system_prompt in self.agents.items():
                messages = [
                    {"role": "system", "content": system_prompt},
                    *conversation
                ]
                
                response = client.chat.completions.create(
                    model=self.model,
                    messages=messages
                )
                
                reply = response.choices[0].message.content
                conversation.append({"role": "assistant", "content": f"[{agent_name}]: {reply}"})
                messages_log.append({"round": round_num + 1, "agent": agent_name, "message": reply})
        
        return messages_log

# Example: Code review discussion
agents = {
    "security_reviewer": "You are a security expert. Review code for vulnerabilities.",
    "performance_reviewer": "You are a performance expert. Review code for bottlenecks.",
    "style_reviewer": "You are a code style expert. Review code for readability and conventions."
}

collab = CollaborativeAgents(agents)
discussion = collab.discuss("Review this code: def process(data): return [d*2 for d in data if d > 0]")
for msg in discussion:
    print(f"[Round {msg['round']}] {msg['agent']}: {msg['message'][:100]}...")

The cost model deserves attention: with N agents and R rounds you pay N×R completions, and each completion carries the whole conversation so far. Three reviewers over five rounds of a long discussion get expensive fast. In practice, one round of independent reviews followed by a synthesis is 80% of the value at a fraction of the cost — reserve multi-round debate for genuinely contested questions.

Agent Memory

Agents need two kinds of memory, and conflating them is a common design error. Short-term memory is the conversation itself — the message list the model sees. Long-term memory is a store the agent queries explicitly, usually a vector database of prior interactions or domain knowledge.

Short-Term Memory (Conversation)

The naive approach — append everything — dies on context limits and cost. The standard fix is a sliding window that always preserves the system prompt:

from dataclasses import dataclass, field

@dataclass
class AgentMemory:
    max_messages: int = 20
    messages: list = field(default_factory=list)
    
    def add(self, role: str, content: str):
        self.messages.append({"role": role, "content": content})
        if len(self.messages) > self.max_messages:
            # Keep system message + recent messages
            system = [m for m in self.messages if m["role"] == "system"]
            non_system = [m for m in self.messages if m["role"] != "system"]
            self.messages = system + non_system[-(self.max_messages - len(system)):]
    
    def get_messages(self) -> list:
        return self.messages
    
    def clear(self):
        system = [m for m in self.messages if m["role"] == "system"]
        self.messages = system

A sliding window drops old tool results, which is fine until the agent needs a result from 15 messages ago. More robust strategies summarize evicted messages into a running digest, or move durable facts into long-term memory before eviction — the agent “writes down” what matters before forgetting it.

Long-Term Memory (Vector Store)

For facts that must survive across sessions or beyond the window, store embeddings and retrieve the relevant ones per task:

import chromadb
from openai import OpenAI

client = OpenAI()

class LongTermMemory:
    def __init__(self, collection_name: str = "agent_memory"):
        self.db = chromadb.PersistentClient(path="./agent_memory")
        self.collection = self.db.get_or_create_collection(collection_name)
    
    def store(self, content: str, metadata: dict = None):
        embedding = client.embeddings.create(
            model="text-embedding-3-small",
            input=content
        ).data[0].embedding
        
        import hashlib
        doc_id = hashlib.md5(content.encode()).hexdigest()
        
        self.collection.add(
            ids=[doc_id],
            documents=[content],
            embeddings=[embedding],
            metadatas=[metadata or {}]
        )
    
    def recall(self, query: str, n_results: int = 5) -> list[str]:
        query_embedding = client.embeddings.create(
            model="text-embedding-3-small",
            input=query
        ).data[0].embedding
        
        results = self.collection.query(
            query_embeddings=[query_embedding],
            n_results=n_results
        )
        
        return results["documents"][0]
    
    def get_context(self, query: str) -> str:
        memories = self.recall(query)
        if memories:
            return "Previous relevant context:\n" + "\n".join(f"- {m}" for m in memories)
        return ""

# Usage in agent
memory = LongTermMemory()

# Store important facts
memory.store("User prefers Python over JavaScript", {"type": "preference"})
memory.store("User's project uses FastAPI and PostgreSQL", {"type": "project_info"})

# Recall during agent execution
context = memory.get_context("What language should I use?")
# Returns stored preferences

Two practical cautions. First, retrieved memories are untrusted content — a poisoned memory store is a prompt-injection channel, so tag memory blocks clearly and keep injection-resistant system instructions. Second, md5(content) as an ID means identical content silently overwrites; that is usually what you want for dedup, but version facts that change (“user’s plan is Pro” today, “Enterprise” next month) instead of overwriting them, or you will have an agent confidently citing stale state. The retrieval side of this pattern is RAG — see the RAG in Production guide for chunking and retrieval quality.

Human-in-the-Loop

The question is never whether humans stay in the loop, but at which gate. Full autonomy is appropriate for read-only and reversible actions; anything that sends, deletes, pays, or publishes deserves a gate. The pattern below pauses only for tools on an approval list — safe tools flow through unblocked:

from enum import Enum
from typing import Optional

class ApprovalStatus(Enum):
    APPROVED = "approved"
    REJECTED = "rejected"
    MODIFIED = "modified"

class HumanInTheLoopAgent:
    def __init__(self, tools: dict, require_approval_for: list[str]):
        self.tools = tools
        self.require_approval_for = require_approval_for
        self.pending_actions: list[dict] = []
    
    def propose_action(self, tool_name: str, args: dict) -> dict:
        """Propose an action for human approval."""
        action = {"tool": tool_name, "args": args, "status": "pending"}
        
        if tool_name in self.require_approval_for:
            self.pending_actions.append(action)
            return {"status": "needs_approval", "action": action}
        else:
            # Auto-approve safe tools
            result = self.tools[tool_name](**args)
            return {"status": "executed", "result": result}
    
    def approve_action(self, action_id: int, status: ApprovalStatus, modified_args: dict = None) -> dict:
        """Human approves, rejects, or modifies an action."""
        action = self.pending_actions[action_id]
        
        if status == ApprovalStatus.REJECTED:
            action["status"] = "rejected"
            return {"status": "rejected"}
        
        args = modified_args or action["args"]
        result = self.tools[action["tool"]](**args)
        action["status"] = "executed"
        action["result"] = result
        return {"status": "executed", "result": result}
    
    def get_pending(self) -> list[dict]:
        return [a for a in self.pending_actions if a["status"] == "pending"]

# Usage
agent = HumanInTheLoopAgent(
    tools={"send_email": lambda **k: f"Email sent to {k.get('to')}", "search": lambda **k: "results"},
    require_approval_for=["send_email"]
)

# Agent proposes sending an email
result = agent.propose_action("send_email", {"to": "boss@company.com", "subject": "Report", "body": "Here is the report."})
print(result)  # {"status": "needs_approval", ...}

# Human approves
approval = agent.approve_action(0, ApprovalStatus.APPROVED)
print(approval)  # {"status": "executed", "result": "Email sent to boss@company.com"}

The MODIFIED status is the underrated part: humans rarely just approve or reject — they edit (“send it, but change the subject”). Capturing the edited args and executing them keeps the audit trail honest: the trace shows what the agent proposed and what actually ran. Design the approval surface for speed — if reviewing an action takes longer than doing it manually, people will approve without reading, which is worse than no gate.

Safety and Guardrails

Agent safety has two distinct layers that both need to exist. Input-side checks inspect tool calls before execution — is this command destructive, is this tool allowed, is this within budget. Output-side checks inspect what the agent produces or returns — did it leak PII, credentials, or content it should not have. The LLM Security guide covers the broader threat model, including prompt injection through tool results, which is the attack most agent deployments underestimate.

Agent Safety Layer

import re
from dataclasses import dataclass

@dataclass
class SafetyCheck:
    passed: bool
    reason: str = ""

class AgentSafetyLayer:
    DANGEROUS_PATTERNS = [
        r"rm\s+-rf",
        r"DROP\s+TABLE",
        r"DELETE\s+FROM",
        r"format\s+C:",
        r"sudo\s+",
        r"chmod\s+777",
    ]
    
    def check_action(self, tool_name: str, args: dict) -> SafetyCheck:
        # Check for dangerous commands
        args_str = str(args)
        for pattern in self.DANGEROUS_PATTERNS:
            if re.search(pattern, args_str, re.IGNORECASE):
                return SafetyCheck(False, f"Dangerous pattern detected: {pattern}")
        
        # Check tool whitelist
        allowed_tools = ["search_web", "write_file", "run_code", "send_email"]
        if tool_name not in allowed_tools:
            return SafetyCheck(False, f"Tool '{tool_name}' not in whitelist")
        
        # Check rate limits per tool
        # (implementation depends on your tracking system)
        
        return SafetyCheck(True)
    
    def check_output(self, output: str) -> SafetyCheck:
        # Check for sensitive data leakage
        sensitive_patterns = [
            (r'\b\d{3}-\d{2}-\d{4}\b', 'SSN detected'),
            (r'\b\d{16}\b', 'Credit card number detected'),
            (r'password\s*[:=]\s*\S+', 'Password in output'),
        ]
        
        for pattern, reason in sensitive_patterns:
            if re.search(pattern, output, re.IGNORECASE):
                return SafetyCheck(False, f"Sensitive data in output: {reason}")
        
        return SafetyCheck(True)

safety = AgentSafetyLayer()

# Check before executing tool
check = safety.check_action("run_code", {"code": "import os; os.system('rm -rf /')"})
if not check.passed:
    print(f"BLOCKED: {check.reason}")

Be honest about what regex checklists are: a first line of defense, not a boundary. rm -rf written as rm -r -f, encoded, or split across arguments slips past patterns like these. The real control is structural — sandbox code execution, scope tool credentials to minimum permissions, require approval for irreversible actions — and the pattern checks are there to catch the obvious cases cheaply and log the attempts. Budget checks belong in the same layer: a per-run cap on tokens and tool calls stops both loops and cost runaway before they reach the bill.

Cost and Latency Budgets

Agents spend tokens nonlinearly: every iteration re-sends the full conversation, so cost grows roughly with iterations squared, not linearly. A ReAct loop that averages 4 iterations per task can hit 12 on a hard one — and the 12th iteration carries eleven previous results. Budget at three levels:

  • Per run: a hard cap on total tokens and tool calls per task (max_iterations bounds the loop, but token budget is the real stop because context inflates each call).
  • Per task type: research tasks legitimately cost more than classification tasks — alert on per-type averages drifting, not on a single expensive run.
  • Per deployment: a daily/monthly ceiling that fails closed — when the budget trips, the agent returns a graceful degraded response instead of burning on.

Latency has its own math. Each LLM call costs 1–10 seconds, so a 10-iteration agent takes 30–90 seconds even before tools respond. Anything user-facing needs either async execution (queue the task, stream progress) or a hard budget of 3–4 iterations. And cache what you can: identical tool calls across runs — the same web search, the same file read — are pure waste, and a simple result cache keyed on tool+args cuts both cost and latency on repeated work.

Observability

You cannot debug what you can’t see, and agents fail in ways unit tests never predicted — wrong tool, right tool with wrong arguments, right arguments in the wrong order, infinite politeness loops between two agents. The minimum viable observability is a trace of every thought, action, and error per run:

Agent Tracing

import time
import json
from uuid import uuid4
from dataclasses import dataclass, field
from typing import Any

@dataclass
class AgentTrace:
    trace_id: str = field(default_factory=lambda: str(uuid4()))
    events: list = field(default_factory=list)
    
    def log(self, event_type: str, **kwargs):
        self.events.append({
            "timestamp": time.time(),
            "type": event_type,
            **kwargs
        })
    
    def log_thought(self, thought: str):
        self.log("thought", content=thought)
    
    def log_action(self, tool: str, args: dict, result: Any):
        self.log("action", tool=tool, args=args, result=str(result)[:500])
    
    def log_error(self, error: str):
        self.log("error", error=error)
    
    def summary(self) -> dict:
        actions = [e for e in self.events if e["type"] == "action"]
        errors = [e for e in self.events if e["type"] == "error"]
        thoughts = [e for e in self.events if e["type"] == "thought"]
        
        duration = 0
        if len(self.events) >= 2:
            duration = self.events[-1]["timestamp"] - self.events[0]["timestamp"]
        
        return {
            "trace_id": self.trace_id,
            "total_events": len(self.events),
            "thoughts": len(thoughts),
            "actions": len(actions),
            "errors": len(errors),
            "duration_seconds": duration,
            "tools_used": list(set(e["tool"] for e in actions)),
        }
    
    def export(self) -> str:
        return json.dumps(self.events, indent=2)

# Usage in agent
trace = AgentTrace()
trace.log_thought("I need to search for information about Python frameworks")
trace.log_action("search_web", {"query": "Python web frameworks"}, "Found: Django, Flask, FastAPI")
trace.log_thought("Now I'll compare them")
trace.log_action("write_file", {"filename": "comparison.txt"}, "File written")
print(trace.summary())

Traces are also the raw material for testing and evaluation. Recorded traces let you replay runs, diff behavior across model upgrades, and feed evaluation pipelines — the LLM Evaluation guide covers scoring runs systematically. On top of traces, track the operational metrics agents-specifically need: iterations per run, tool-call error rate, token cost per task type, approval rate on human gates (a rate near 100% means your gate is decorative), and max-iteration hits, which are the canary for agents getting stuck.

Best Practices

  • Start with the dumbest architecture that works. A chain beats ReAct when the steps are fixed; a router beats multi-agent when handlers are separable. Add autonomy only when the simpler form measurably fails.
  • Bound every loop. max_iterations, a token budget, and a wall-clock timeout, all three — each catches a failure mode the others miss.
  • Design tools like APIs, not like prompts. Small, single-purpose, typed parameters, docstrings that say when not to use the tool. Three to five tools per agent; more than ten and selection quality collapses.
  • Feed errors back as observations. An agent that sees “Error: unknown tool ‘searchWeb’, did you mean ‘search_web’?” self-corrects; an agent that crashes teaches you nothing.
  • Gate irreversible actions by blast radius, not by tool. The approval list should follow consequences (sends, deletes, payments, publishes), not tool names.
  • Trace everything, alert on patterns. One failed tool call is noise; a run that burns its iteration budget is a bug report.

Common Mistakes

  • Using an agent where a chain suffices. If the plan never changes, you are paying agent prices for script behavior — and inheriting nondeterminism for free.
  • Trusting tool calls blindly. The model will eventually pass a file path to run_code or a customer address to send_email. Validate arguments before execution, always.
  • Letting memory grow unbounded. Concatenating everything into context is the default until the first 200k-token bill; window, summarize, or externalize from day one.
  • Over-gating humans. If every action needs approval, reviewers rubber-stamp. Gate the irreversible 5% and let the rest flow.
  • Treating regex safety as a security boundary. Pattern lists catch accidents, not adversaries. Sandbox execution and scoped credentials are the boundary; checks are the tripwire.
  • Shipping without a replay story. The first prod incident will be a trace you can’t reconstruct. Log structured events from the first deploy, not the first postmortem.

See Also

Further Reading

Frequently Asked Questions

What is the difference between an agent and a chain?

A chain follows a fixed sequence of steps. An agent dynamically decides which steps to take based on the task and intermediate results. Agents use tools, reason about results, and adapt their approach. Chains are predictable and fast. Agents are flexible but slower, more expensive, and harder to debug.

How do I prevent agents from running forever?

Set a max iteration limit (5-20 depending on complexity). Track token usage and stop if it exceeds a budget. Implement a timeout for each tool call. Use a "completion detector" — ask the LLM if the task is done after each iteration. Log all actions for debugging when agents get stuck in loops.

Should I use multi-agent or single-agent architecture?

Start with a single agent. Move to multi-agent when: the task has distinct phases (research, code, write), different expertise is needed, or you want parallel execution. Multi-agent adds complexity in coordination, state management, and debugging. Use a supervisor pattern where one agent delegates to specialized sub-agents.

How do I test AI agents?

Test individual tools with unit tests. Test the agent's decision-making with mocked LLM responses. Create scenario-based tests where you verify the agent takes the expected sequence of actions. Use replay testing — record agent traces and replay them to verify consistency. Test edge cases: tool failures, invalid inputs, max iterations.

What tools should I give my agent?

Give agents tools that are specific, well-documented, and have clear input/output schemas. Start with 3-5 tools. Too many tools confuse the agent and increase latency. Each tool should have a clear docstring describing what it does and when to use it. Use Pydantic schemas for tool parameters to help the agent call them correctly.

How do I handle agent failures in production?

Implement retry logic for transient failures (API timeouts, rate limits). Log all agent actions and intermediate states for debugging. Set up alerts for agents that hit max iterations or exceed token budgets. Use fallback responses when agents fail. Implement circuit breakers for external tools. Consider human-in-the-loop for high-stakes actions.