Building a Production AI Agent: Architecture, Code & Real Failure Modes
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.
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
- Proposal Brain: A fast, reliable reasoning model (e.g. Claude Sonnet 5 or DeepSeek-V3) that parses observations and proposes a strictly typed tool call.
- Deterministic Action Boundary: A Python or TypeScript runtime that intercepts the tool call, verifies permissions, checks circuit breakers, and runs the operation outside the model.
- Context & State Store: A sliding conversation buffer where tool outputs are normalized, truncated if too large, and paired with cache-stable system prefixes.
- Circuit Breaker & Exit Gates: Hard limits on step counts, token spend, and identical repeat actions to prevent runaway credit card bills.
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 item | Example | Enforced by |
|---|---|---|
| Identity | Signed-in repository contributor | Application authentication |
| Read scope | One repository at a pinned revision | Workspace and API allowlist |
| Write scope | Ephemeral branch only | Scoped credential and branch policy |
| Budget | Eight turns, twelve tool calls, ninety seconds | Orchestrator counters |
| Success | Patch produced and specified tests pass | Deterministic verifier |
| Approval | Human reviews diff before publication | Separate privileged action |
5. Build the Smallest Observable Loop
- Construct context: include durable policy, the current task, and only the evidence needed for the next decision.
- Ask for a typed proposal: answer, stop, request input, or call one of a narrow set of tools.
- Validate: check schema, authorization, budgets, paths, URLs, and action class outside the model.
- Execute: run the tool in an isolated environment and return a bounded structured result.
- Record: persist the state transition, evidence IDs, decision, result, cost, and stop reason.
- 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
- Credentials are scoped, short-lived, and unavailable to the model text.
- Untrusted documents and tool output cannot change policy or authorization.
- Filesystem and network access use explicit allowlists.
- High-impact actions show exact targets and require fresh approval.
- Logs contain identifiers and outcomes without unnecessary sensitive content.
- Model, prompt, tool schema, dataset, and policy versions are recorded.
- Rollback and incident response do not depend on the agent.
8. Primary References
- OpenAI practical guide to building agents
- Anthropic: Building effective agents
- OWASP prompt injection guidance
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.