Most tutorials on how to build an AI agent show a 30-line while True: loop that calls a mock get_weather("Tokyo") function. It runs once on a laptop and teaches the wrong mental model.
An AI agent is not an autonomous program inside the model. The model only predicts tokens—sometimes prose, sometimes a structured JSON request asking your program to run a tool. Your code (the harness) owns the loop, the permissions, the deadlines, and every real side effect. Mixing up what the model proposed with what your program executed is where production agents break.
Below is the complete, framework-free architecture of a working AI agent—starting with a runnable ~90-line Python harness you can point at OpenAI or a local Ollama model, followed by the six real failure modes we hit building agents and MCP tools across Colophon CMS, Personal Voice Agent, and our local Qwen experiments.
First: do you actually need an AI agent?
Before writing a loop, check whether the steps are already known ahead of time:
| Problem shape | What to build instead | Why |
|---|---|---|
| Fixed sequence (extract → validate → save) | A single structured-output LLM call + regular code | Deterministic, cheaper, faster, zero loop risk |
| Fixed branching (classify ticket → route to 1 of 4 queues) | A router call + normal if/else handlers | Easy to test and bound |
| Unknown number of lookup/edit steps based on what earlier steps discover | An AI agent loop | The model needs tool outputs to decide what to inspect next |
If a plain script with one model call solves the job, ship the script. Use an agent loop only when the next step genuinely depends on inspecting intermediate results.
The four parts of a real AI agent
Every agent framework—no matter how many abstractions it wraps around it—reduces to four components:
- Tool schemas (interface, not code): JSON Schema descriptions sent with each request telling the model what it may ask for. The model never sees or runs your implementation (see the model never called my function).
- A bounded harness loop: Sends conversation history + schemas, inspects
tool_calls, validates arguments, runs allowed tools, appends structured results, and stops cleanly on a final answer or a hard budget limit. - A policy and approval boundary: Separates read-only lookups from state-changing writes. Destructive or external actions require a human (or deterministic policy) to approve the exact payload.
- An execution ledger: Records what the user asked, what the model proposed, and what the harness actually executed as separate facts.
User goal
│
▼
┌──────────────────────────────────────────────────────────┐
│ Harness loop (max_steps, deadline, byte cap) │
│ 1. Send messages + tool schemas to LLM │
│ 2. No tool_calls? ──► Return final answer + ledger │
│ 3. Has tool_calls? │
│ ├─ Validate JSON + strict schema │
│ ├─ Check policy (read vs. approval-gated write) │
│ ├─ Execute tool with timeout + output truncation │
│ ├─ Append structured result to messages & ledger │
│ └─ Repeat until done or budget exhausted │
└──────────────────────────────────────────────────────────┘A bounded AI agent in ~90 lines of Python (zero frameworks)
This uses only Python’s standard library (urllib, json, time) and talks to any OpenAI-compatible /chat/completions endpoint—including OpenAI (https://api.openai.com/v1) or a local Ollama server (http://localhost:11434/v1).
Notice what is built in from line one that toy tutorials leave out: a step ceiling, a wall-clock deadline, output byte truncation, structured error envelopes (never crashing the loop on bad JSON), a read/write approval split, and an explicit execution ledger.
import json
import os
import time
import urllib.error
import urllib.request
from pathlib import Path
BASE_URL = os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1")
API_KEY = os.environ.get("LLM_API_KEY", "ollama")
MODEL = os.environ.get("LLM_MODEL", "qwen3:8b")
# Hard guardrails enforced by the harness, never by the prompt
MAX_STEPS = 6
DEADLINE_SECONDS = 45
MAX_TOOL_OUTPUT_BYTES = 4_000
WORKSPACE = Path("./sandbox").resolve()
TOOLS_SCHEMA = [
{
"type": "function",
"function": {
"name": "read_note",
"description": "Read a UTF-8 text file inside the sandbox directory.",
"parameters": {
"type": "object",
"properties": {"filename": {"type": "string"}},
"required": ["filename"],
"additionalProperties": False,
},
},
},
{
"type": "function",
"function": {
"name": "propose_note_update",
"description": "Write updated text to a file in the sandbox. Requires human approval.",
"parameters": {
"type": "object",
"properties": {
"filename": {"type": "string"},
"content": {"type": "string"},
},
"required": ["filename", "content"],
"additionalProperties": False,
},
},
},
]
def safe_path(filename: str) -> Path:
target = (WORKSPACE / filename).resolve()
if not target.is_relative_to(WORKSPACE):
raise ValueError("path_outside_sandbox")
return target
def read_note(filename: str) -> dict:
path = safe_path(filename)
if not path.exists():
return {"ok": False, "error": "not_found", "filename": filename}
with path.open("rb") as f:
raw = f.read(MAX_TOOL_OUTPUT_BYTES + 1)
truncated = len(raw) > MAX_TOOL_OUTPUT_BYTES
return {
"ok": True,
"filename": filename,
"content": raw[:MAX_TOOL_OUTPUT_BYTES].decode("utf-8", errors="replace"),
"truncated": truncated,
}
def propose_note_update(filename: str, content: str) -> dict:
path = safe_path(filename)
# Human approval gate bound to the exact target and payload
print(f"\n[APPROVAL REQUIRED] Write {len(content)} chars to {path.name}?")
if input("Type 'yes' to execute: ").strip().lower() != "yes":
return {"ok": False, "error": "denied_by_human"}
WORKSPACE.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
return {"ok": True, "filename": path.name, "bytes_written": len(content.encode("utf-8"))}
TOOL_REGISTRY = {
"read_note": ("read", read_note),
"propose_note_update": ("write", propose_note_update),
}
def call_llm(messages: list[dict], timeout: float) -> dict:
payload = json.dumps({"model": MODEL, "messages": messages, "tools": TOOLS_SCHEMA}).encode()
req = urllib.request.Request(
f"{BASE_URL.rstrip('/')}/chat/completions",
data=payload,
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}",
},
)
with urllib.request.urlopen(req, timeout=timeout) as resp:
return json.loads(resp.read().decode("utf-8"))
def run_agent(goal: str) -> dict:
started = time.monotonic()
messages = [
{
"role": "system",
"content": (
"You are a precise assistant. Use tools when needed. "
"Never claim a write succeeded unless the tool result returned ok=true."
),
},
{"role": "user", "content": goal},
]
executed_ledger = [] # Ground truth of what actually ran
for step in range(1, MAX_STEPS + 1):
remaining = DEADLINE_SECONDS - (time.monotonic() - started)
if remaining <= 0:
return {"status": "deadline_exceeded", "executed": executed_ledger}
try:
data = call_llm(messages, timeout=min(remaining, 20.0))
except (urllib.error.URLError, TimeoutError) as exc:
return {"status": "model_unreachable", "error": str(exc), "executed": executed_ledger}
msg = data["choices"][0]["message"]
messages.append(msg)
tool_calls = msg.get("tool_calls") or []
if not tool_calls:
return {"status": "done", "answer": msg.get("content", ""), "executed": executed_ledger}
for tc in tool_calls:
name = tc["function"]["name"]
raw_args = tc["function"].get("arguments", "{}")
try:
args = json.loads(raw_args) if isinstance(raw_args, str) else raw_args
if name not in TOOL_REGISTRY:
result = {"ok": False, "error": f"unknown_tool:{name}"}
else:
mode, fn = TOOL_REGISTRY[name]
result = fn(**args)
executed_ledger.append({"step": step, "tool": name, "mode": mode, "ok": result.get("ok")})
except (json.JSONDecodeError, TypeError, ValueError) as exc:
result = {"ok": False, "error": f"invalid_arguments:{exc}"}
messages.append({
"role": "tool",
"tool_call_id": tc["id"],
"content": json.dumps(result),
})
return {"status": "max_steps_reached", "executed": executed_ledger}
Every line in that loop exists to prevent a specific failure mode. Here are the six bugs we actually hit when moving from toy loops to real tools.
Six real failures that break naive agent loops
1. Unbounded loops and unbounded tool outputs
A while True: loop fails quietly when a model retries a failing lookup 40 times in a row. Worse, a single tool that returns a 200 KB log file or full SQL table can blow past the context window, balloon KV-cache memory and token cost (see KV cache explained), or push the original instructions out of attention.
Fix: Cap three numbers in code, not in the system prompt: MAX_STEPS, total DEADLINE_SECONDS, and MAX_TOOL_OUTPUT_BYTES (returning truncated: true so the model knows it only saw a slice).
2. Tight enum schemas force confident hallucinations
When you put a fixed enum of valid IDs or project names in a tool schema, a model asked about an unlisted item often picks the closest valid enum value just to satisfy the schema—and then confidently answers about the wrong record.
Fix: Accept a plain string, validate it inside your tool, and return an explicit {"ok": false, "error": "not_found"} envelope. Teach the model through clear error data rather than silently coercing inputs.
3. Confusing “the tool ran” with “the underlying task succeeded”
In our local troubleshooting experiment (the assistant failed before the model got a turn), two separate boundaries mattered:
- First, the runtime failed with
EPERMbefore reaching Ollama—wrapping that as a genericfetch failedhid whether the server was down, timed out, or blocked by the sandbox. - Second, reading a saved build failure record succeeds as a tool call (
ok: true), even though the build inside the record failed.
Fix: Surface distinct transport errors (model_unreachable vs. tool_error) and structure tool payloads so tool_ok and domain_status are separate fields.
4. Models claim they completed actions they never executed
Even with a strict system prompt, language models sometimes say “I’ve updated the file” when no write tool ran—or when a tool failed. While testing Personal Voice Agent on held-out sentences, 7% of completion claims (5 of 70) came back without disclosure even after multiple review passes.
Fix: Keep heard/asked, inferred (model text), and executed (harness ledger) as three separate records. In the code above, executed_ledger is populated strictly by the Python harness, never by parsing the model’s prose. Your UI or caller should display what actually executed alongside the text reply.
5. Giving the loop direct write/delete power (prompt injection)
If an agent reads untrusted text—emails, web pages, CMS drafts, support tickets—and also holds a delete or publish tool, prompt injection turns into unauthorized execution. Even subtle bugs in approval matching matter: when we moved Colophon’s own site onto Colophon CMS through MCP, checking whether a tool name contained "review" accidentally matched "preview" and triggered approval prompts on read-only draft previews.
Fix: Make tools read-only or draft-only by default, bind approvals to explicit tool lists and exact payload hashes, and never let the agent’s credential call the approval endpoint (see securing MCP servers for AI agents).
6. No-op writes and missing idempotency
Agents retry. If a model calls a write tool twice with the same content—or repeats a network request after a transient timeout—a naive backend creates duplicate rows, charges twice, or mints fake “unpublished changes” revisions (another real bug we hit on day one of MCP dogfooding).
Fix: Reject or short-circuit byte-identical no-op writes, use optimistic locking (version/revision checks) on edits, and back external mutations with PostgreSQL idempotency keys.
When to reach for a framework (and when not to)
Start without a framework until you feel a specific missing piece:
- Stay framework-free for single-loop agents, CLI assistants, internal dev tools, and MCP-backed workflows. You can read every line of retry, timeout, and auth logic in one file.
- Add focused libraries (not giant abstractions) when you need one concrete capability: durable crash-safe job retries (like Durable Runner), OpenTelemetry / gap-aware traces, or standard tool transport over MCP so multiple clients (Claude, Codex, custom apps) can share the same server.
Quick production checklist before shipping an AI agent
-
Step & time budgets: Hard
max_steps, per-call timeout, and total wall-clock deadline enforced in code. -
Bounded I/O: Tool outputs truncated to a fixed byte cap with an explicit
truncatedflag; filesystem and URL inputs validated against traversal and SSRF / DNS rebinding. - Safe errors: Unknown tool names and malformed JSON return structured error objects instead of crashing or retrying forever.
- Write isolation: Read-only by default; state-changing actions create drafts or require human approval bound to the exact payload.
- Separate execution ledger: Ground-truth log of every tool call, arguments (with secrets redacted), decision, and outcome—never trusting the model’s text summary as proof of execution.
- Eval on real failure cases: Test unknown inputs, unavailable backends, prompt injections, and multi-step loops before trusting the agent with real users.
Frequently asked questions
How many lines of code does it take to build an AI agent from scratch? A working, bounded agent loop takes roughly 80–120 lines of plain Python, TypeScript, or Rust using standard HTTP calls. Most of the real engineering is not the loop itself—it is schema design, output caps, approval boundaries, idempotency, and tests on failure paths.
Can I run a scratch-built AI agent locally without paying API fees?
Yes. Point LLM_BASE_URL at Ollama (http://localhost:11434/v1) or any local OpenAI-compatible server with a tool-capable model like qwen3:8b. Expect smaller local models to need cleaner tool descriptions, fewer tools per call, and stricter JSON/argument validation than frontier models.
What is the difference between tool calling and an AI agent? Tool calling is a single turn where a model emits structured JSON requesting a function call. An AI agent wraps tool calling in a loop so the harness executes the tool, feeds the result back into the conversation, and lets the model decide whether to call another tool or finish.