Building a Production AI Agent: Architecture, Code & Real Failure Modes

By Meng Guoying (mengg) · Review method · Corrections

Hands-on Guide · 6 min read · Updated November 2026

Building an autonomous agent isn't about writing a clever 500-word prompt. It's about writing defensive software around a model that is constantly trying to hallucinate, fall into infinite loops, or emit broken arguments. Here is the exact architecture, minimal Python implementation, and production guardrails we run in staging.

TL;DR Verdict & Boundary: Start with a single deterministic Python loop, strict schema validation, and a hard step/budget circuit breaker before touching multi-agent frameworks. Only adopt stateful graph orchestration (e.g. LangGraph) when your workflow needs human-in-the-loop checkpoints or branching retries.

1. The Reality: Stripping Away the Hype

A standard LLM call is just a stateless function: Prompt → Model → String. An AI Agent is simply a state machine wrapped around that function:

Observation (State) → Next Action Proposal (Model) → Validation (Sandbox) → Execution (Tool) → Feedback (Result)

The hard part is never getting the model to call a tool. The hard part is what happens when the tool fails, when permissions are denied, or when the model repeats the exact same failing action four times in a row.

2. Core Components You Actually Need

1. Context Builder System + State + History 2. LLM Planner Tool Call / Final Answer 3. Circuit Breaker Max Steps / Cost Cap / Repeat 4. Tool Sandbox Read / Diff / Test Runner 5. Verified Output / Abort Observation Feedback Loop (Aborted if Circuit Breaker trips)
Figure 1: Production agent execution loop featuring a mandatory Circuit Breaker guard before every external tool invocation.

3. The $48 Infinite Loop: A Real Production War Story

The Incident: During our early staging deployment of a coding agent, we gave the model permission to commit git patches. On step 14, a git push failed with HTTP 403: Permission Denied. Instead of halting, the ReAct loop saw the error message, assumed it was a syntax issue, and retried the exact same command with slight flag variations: git push --force, git push -u origin HEAD, git push origin main:main.

Because there was no loop-detection circuit breaker, the agent cycled 62 times in under 8 minutes, burning $48 in uncached input tokens before we killed the process manually.

The Fix: Never trust the LLM to decide when to give up. Enforce deterministic loop detection in code:

# Cycle detector: Hash tool name + sorted arguments
action_signature = f"{tool_name}:{json.dumps(args, sort_keys=True)}"
if action_history.count(action_signature) >= 2:
    raise RuntimeError(f"Circuit breaker: Duplicate action detected ({tool_name}). Forcing human review.")

4. Production Python Implementation

Below is a clean, dependency-minimal Python implementation of a ReAct agent loop with defensive budgeting and loop termination:

import json
from openai import OpenAI

client = OpenAI(api_key="your-api-key")

# 1. Registered Tool Functions
def calculate_budget(daily_cost: float, days: int) -> str:
    return json.dumps({"monthly_total": round(daily_cost * days, 2)})

tools_schema = [
    {
        "type": "function",
        "function": {
            "name": "calculate_budget",
            "description": "Calculate total monthly budget from daily spend",
            "parameters": {
                "type": "object",
                "properties": {
                    "daily_cost": {"type": "number"},
                    "days": {"type": "integer"}
                },
                "required": ["daily_cost", "days"]
            }
        }
    }
]

# 2. Defensive Agent Loop with Circuit Breakers
def run_defensive_agent(prompt: str, max_steps: int = 10):
    messages = [{"role": "user", "content": prompt}]
    action_history = []
    
    for step in range(max_steps):
        response = client.chat.completions.create(
            model="deepseek-v3",
            messages=messages,
            tools=tools_schema
        )
        msg = response.choices[0].message
        
        # Check if model wants to call a tool
        if msg.tool_calls:
            tool_call = msg.tool_calls[0]
            name = tool_call.function.name
            args = json.loads(tool_call.function.arguments)
            
            # Circuit Breaker: Duplicate Action Check
            signature = f"{name}:{json.dumps(args, sort_keys=True)}"
            if action_history.count(signature) >= 2:
                print(f"[ERROR] Cycle detected: {name} called twice with same args. Aborting.")
                break
            action_history.append(signature)
            
            print(f"Step {step+1}: Executing {name} -> {args}")
            result = calculate_budget(**args) if name == "calculate_budget" else "Unknown tool"
            
            messages.append(msg)
            messages.append({"role": "tool", "tool_call_id": tool_call.id, "content": result})
        else:
            print(f"\nFinal Answer:\n{msg.content}")
            return
            
    print("[WARNING] Max steps reached without resolution.")

run_defensive_agent("If our server spend is $8.25 per day, what is our 30-day cost?")

5. The Task Contract: Guarding What the Agent Can Touch

Before writing a line of agent orchestration, define the rigid boundaries of what it is allowed to touch. A production agent should have one single responsibility: read an assigned issue, search an approved repo, propose a git patch in a temporary branch, run tests, and stop. It should never have access to production credentials, master branches, or customer notifications.

Contract itemExampleEnforced by
IdentitySigned-in repository contributorApplication authentication
Read scopeOne repository at a pinned revisionWorkspace and API allowlist
Write scopeEphemeral branch onlyScoped credential and branch policy
BudgetEight turns, twelve tool calls, ninety secondsOrchestrator counters
SuccessPatch produced and specified tests passDeterministic verifier
ApprovalHuman reviews diff before publicationSeparate privileged action

5. Build the Smallest Observable Loop

  1. Construct context: include durable policy, the current task, and only the evidence needed for the next decision.
  2. Ask for a typed proposal: answer, stop, request input, or call one of a narrow set of tools.
  3. Validate: check schema, authorization, budgets, paths, URLs, and action class outside the model.
  4. Execute: run the tool in an isolated environment and return a bounded structured result.
  5. Record: persist the state transition, evidence IDs, decision, result, cost, and stop reason.
  6. Verify: use tests and business rules; require approval before consequential side effects.

Do not add multiple agents merely to imitate an organization chart. Add a second role only when it provides a measurable boundary, such as an independent verifier with no write access or a specialist that uses a distinct evidence source. A deterministic function is often a better router than another model call.

6. Evaluation and Failure Handling

Create fixtures before launch: ordinary success, incomplete input, tool timeout, stale state, conflicting evidence, permission denial, prompt injection inside a file, and budget exhaustion. Measure accepted-task success, unsafe-action rate, unnecessary tool calls, human override rate, latency, and cost. Preserve the complete trajectory so a failure can be attributed to context, model decision, policy, tool, or verifier.

Every run needs a visible terminal state. Retry only typed transient failures and use idempotency keys for operations that may already have succeeded. After repeated equivalent failures, stop and ask for help instead of rewriting the prompt indefinitely.

7. Production Readiness Checklist

8. Primary References

9. Try the Interactive Studio

Ready to customize your agent architecture and generate TypeScript or Python boilerplate? Try our interactive AI Agent Builder Lab tool.

What a working prototype costs to run

Prototypes are usually built on a flagship model and never re-priced, which is how teams end up with a bill that surprises them at launch. Below: one agent run at 40K input, 20K cached, 5K output. Of the 40,000 input tokens, 20,000 are billed at the cache-read rate and 20,000 at full input rate.

Model Cost per run Monthly at 2,000 runs
DeepSeek V4.1 Flash$0.0061$12.12
Claude Sonnet 5$0.094$188
GPT-5.6 Terra$0.104$208
Gemini 3.1 Pro$0.104$208

The gap between the default choice and the cheap end is roughly twentyfold at this shape. Most prototypes never need the flagship for the majority of their calls, which is exactly the case the multi-model routing guide makes.

Rates verified against provider documentation on November 26, 2026. Promotional rates expire, so re-check before budgeting: LLM API cost planning · September 2026 pricing update. Run your own numbers in the cost calculator.

Written & Verified by Meng Guoying

Independent AI systems engineer building production agent loops, local vLLM/Ollama clusters, and cost-controlled LLM pipelines. Every token rate and benchmark on this page is cross-checked against provider documentation.

Report Error / Feedback → Discuss on GitHub ↗