Building an Agent (Capstone)
After this lesson, you will be able to:
- Architect a production-grade autonomous agent end-to-end, tool use + memory + planning + reflection + safety + observability + evaluation
- Wire together MCP servers + ReAct + agentic memory + evaluator-optimizer into a coding or research agent
- Apply the 12-point production hardening checklist before shipping any agent to users
- Identify the most common production failure modes in agentic systems and the architectural patterns that prevent them
Before you start
#The Production Agent Architecture
┌─────────────────────────────┐
│ USER REQUEST (issue, query)│
└─────────────┬───────────────┘
│
┌─────────────▼───────────────┐
│ 1. Intake & Sanitize │
│ - Rate limit │
│ - PII redaction │
│ - Prompt injection scan │
└─────────────┬───────────────┘
│
┌─────────────▼───────────────┐
│ 2. Plan │
│ - Decompose into steps │
│ - Dispatch to right │
│ workflow pattern │
└─────────────┬───────────────┘
│
┌─────────────▼───────────────┐
│ 3. Execute (ReAct loop) │
│ - Tool calls via MCP │
│ - Memory updates │
│ - Cost tracking │
│ - Max iterations cap │
└─────────────┬───────────────┘
│
┌─────────────▼───────────────┐
│ 4. Evaluate (Reflexion) │
│ - Self-critique │
│ - Run tests/checks │
│ - Retry if failed │
│ - Confidence threshold │
└─────────────┬───────────────┘
│
┌─────────────▼───────────────┐
│ 5. Safety Filter │
│ - Output classifier │
│ - Citation validation │
│ - Refusal detection │
└─────────────┬───────────────┘
│
┌─────────────▼───────────────┐
│ 6. Human-in-Loop Gate │
│ - High-stakes actions │
│ require approval │
└─────────────┬───────────────┘
│
┌─────────────▼───────────────┐
│ 7. Stream Response │
│ + Log trace │
│ + Update memory │
│ + Run eval pipeline │
└─────────────────────────────┘
You take a working ReAct-pattern prototype that nails 95% of your eval set on your laptop and ship it as-is to 10K users. Which production-only failure mode is MOST likely to bite first?
A user reports that your agent gave a wrong answer 4 days ago. You have logs but no traces. What is the cheapest thing you should add today to make this debuggable in the future?
#The 12-Point Production Hardening Checklist
Before shipping ANY agent to real users, verify each:
| # | Concern | Solution |
|---|---|---|
| 1 | Cost runaway | Per-user/session token budget; hard cap at 100K tokens |
| 2 | Infinite loops | Max iterations 10-20; no-progress detection; LLM stuck-detection |
| 3 | Prompt injection | Sanitize tool outputs before re-injecting; treat external content as untrusted; never let chunks override system prompt |
| 4 | Tool sandboxing | Code execution in containers; file system in scoped temp dirs; web requests via proxy with allow-list |
| 5 | Streaming responses | First-token latency < 1.5s; full response < 30s for typical tasks |
| 6 | Observability | Distributed tracing with correlation IDs; per-step latency, cost, errors logged |
| 7 | Eval pipeline | Golden set + RAGAS-style metrics in CI; fail builds on > 3% regression |
| 8 | Fallback behavior | If primary LLM fails, fall back to secondary; if tools fail, return graceful error |
| 9 | Safety filter | Output classifier blocks unsafe responses; citation validator catches hallucinations |
| 10 | Human-in-loop | Critical actions (delete data, send email, money transfer) require user approval |
| 11 | A/B testing | Run 5-10% of traffic on candidate config; compare RAGAS-style metrics |
| 12 | Cost monitoring | Per-query and per-user cost dashboards; alert on anomalies |
#Implementation: A Coding Agent
openai package, an API key, and a project to work on, so it does not run on this page. Copy it to Google Colab or run it on your own machine.# Copy to Colab: needs the openai package and an API key, so it cannot run on this page.
# A production-shaped coding agent in ~250 lines
# Real products add far more tooling than this sketch
import os
import json
import asyncio
import subprocess
import tempfile
from openai import OpenAI
client = OpenAI()
# --- Tools (in production: MCP servers) ---
def list_files(path: str = ".") -> str:
return "\n".join(os.listdir(path))
def read_file(path: str) -> str:
with open(path) as f:
return f.read()
def write_file(path: str, content: str) -> str:
with open(path, 'w') as f:
f.write(content)
return f"Wrote {len(content)} bytes to {path}"
def run_tests(test_path: str = ".") -> str:
result = subprocess.run(
["python", "-m", "pytest", test_path, "-v", "--tb=short"],
capture_output=True, text=True, timeout=60,
)
return f"exit_code={result.returncode}\nstdout:\n{result.stdout[-2000:]}\nstderr:\n{result.stderr[-500:]}"
def search_web(query: str) -> str:
# In production: use a real search API
return f"[Mocked] Search results for '{query}'"
TOOLS = [
{"type": "function", "function": {"name": "list_files", "description": "List files in a directory", "parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": []}}},
{"type": "function", "function": {"name": "read_file", "description": "Read a file's contents", "parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}},
{"type": "function", "function": {"name": "write_file", "description": "Write content to a file", "parameters": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}}},
{"type": "function", "function": {"name": "run_tests", "description": "Run pytest in a directory", "parameters": {"type": "object", "properties": {"test_path": {"type": "string"}}, "required": []}}},
{"type": "function", "function": {"name": "search_web", "description": "Search the web for information", "parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}},
]
TOOL_MAP = {"list_files": list_files, "read_file": read_file, "write_file": write_file, "run_tests": run_tests, "search_web": search_web}
# --- Plan: decompose task into subtasks ---
def plan_task(issue: str) -> list[str]:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a senior engineer. Decompose the given issue into 3-5 concrete subtasks. Output ONLY a JSON array of strings."},
{"role": "user", "content": issue},
],
)
try:
return json.loads(response.choices[0].message.content)
except Exception:
return ["analyze_issue", "implement_fix", "test_fix"]
# --- Execute: ReAct loop with cost cap ---
def execute_subtask(subtask: str, max_iters: int = 8, max_tokens: int = 30_000) -> str:
messages = [
{"role": "system", "content": f"You are a code-editing agent. Use tools to complete: {subtask}\n\nWhen done, say 'DONE: <summary>'. If stuck, say 'STUCK: <reason>'."},
{"role": "user", "content": "Begin."},
]
total_tokens = 0
for i in range(max_iters):
response = client.chat.completions.create(model="gpt-4o-mini", messages=messages, tools=TOOLS)
msg = response.choices[0].message
total_tokens += response.usage.total_tokens
if total_tokens > max_tokens:
return f"BUDGET_EXCEEDED after {total_tokens} tokens"
messages.append({"role": "assistant", "content": msg.content, "tool_calls": msg.tool_calls})
if not msg.tool_calls:
if msg.content and ("DONE:" in msg.content or "STUCK:" in msg.content):
return msg.content
return msg.content or "(no output)"
for tc in msg.tool_calls:
args = json.loads(tc.function.arguments)
try:
result = TOOL_MAP[tc.function.name](**args)
except Exception as e:
result = f"Error: {e}"
messages.append({"role": "tool", "tool_call_id": tc.id, "content": str(result)[:5000]})
return "MAX_ITERS"
# --- Evaluate: Reflexion on test failures ---
def evaluate(subtask_result: str) -> dict:
"""Run final tests; return pass/fail."""
result = run_tests(".")
return {"passed": "exit_code=0" in result, "evidence": result}
# --- Top-level orchestration ---
def coding_agent(issue: str, max_revisions: int = 2) -> dict:
print(f"\n=== AGENT START ===\nIssue: {issue}\n")
subtasks = plan_task(issue)
print(f"Plan: {subtasks}\n")
history = []
for revision in range(max_revisions + 1):
for subtask in subtasks:
print(f" ▸ Subtask: {subtask}")
result = execute_subtask(subtask)
history.append({"subtask": subtask, "result": result})
print(f" Result: {result[:200]}\n")
# Evaluate
eval_result = evaluate("\n".join([h["result"] for h in history]))
print(f"\n=== EVAL: {'PASS' if eval_result['passed'] else 'FAIL'} ===")
if eval_result["passed"]:
return {"status": "success", "revisions": revision, "history": history}
# Reflection
reflection_response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "Tests failed. Write a 1-sentence reflection on what went wrong, to guide the next revision."},
{"role": "user", "content": f"Subtasks done: {history}\n\nTest output: {eval_result['evidence']}"},
],
)
reflection = reflection_response.choices[0].message.content
print(f"\nReflection: {reflection}\n")
# Re-plan with reflection
subtasks = plan_task(f"{issue}\n\nPrevious attempt failed because: {reflection}")
return {"status": "max_revisions_exceeded", "history": history}
# --- Run ---
# In production: load the issue from GitHub, set up the working directory, etc.
print("This skeleton would be deployed to Modal/Railway with:")
print(" - Containerized sandbox per agent run")
print(" - GitHub webhook to trigger on issues")
print(" - Langfuse tracing for every LLM/tool call")
print(" - Per-user cost dashboards")
print(" - Human-in-loop approval before opening PRs")
print("\nTry: result = coding_agent('Add a __repr__ method to the User class')")
print("\nCHALLENGE: Wire this to a real GitHub repo + add observability via")
print("Langfuse tracing. Add semantic memory store of past resolutions to")
print("inform future planning (long-term memory).")#Production Patterns from Real Systems
| System | Pattern |
|---|---|
| Devin (Cognition) | Long-running session, full IDE access, browser tool, comprehensive memory, human-in-loop on critical actions |
| Cursor (Anysphere) | Inline-edit agent + agent mode (multi-file changes) + composer; deep IDE integration |
| Claude Code (Anthropic) | Terminal-native, MCP server ecosystem, hooks for project-specific commands, sub-agent orchestration |
| Manus AI (Butterfly) | General-purpose autonomous agent; tool-use heavy; runs in cloud sandboxes |
| Perplexity Pro Search | Lightweight agentic RAG: retrieve → reason → answer with citations; not a full agent |
| GitHub Copilot Workspace | Repo-scoped multi-step planning + edits; tight integration with PR workflow |
#Common Production Failure Modes
#Key Takeaways
- Production agents are integration projects, not algorithm projects. The components are well-understood; the hard part is the wiring, the safety, the observability, the eval
- Always implement the 12-point hardening checklist before any user touches your agent
- The architecture is universal: Intake → Plan → Execute → Evaluate → Safety → Stream + Log; agents differ in tools and prompts, not in architecture
- Real production agents use ALL the patterns you've learned, ReAct + Reflexion + workflow patterns + memory + safety + observability, combined judiciously
- Cap costs and iterations religiously. Runaway agents are a leading production incident
#Quick Check
You ship an autonomous code-fix agent. On day 1, one user's session costs $850. What were the most likely 3 missing controls?