An agent is a language model wrapped in a loop that can call tools, read and write memory, and decide when to stop. That loop is where demos become systems: every extra iteration multiplies cost and latency, every unvalidated tool call is a potential production incident, and every unbounded memory buffer eventually blows the context window. Operating agents well means engineering the loop itself â budgets, timeouts, health checks, and traces â rather than trusting the model to be well-behaved.
This lesson covers the operational core of agent platforms: a tool registry that knows the health of each tool, a memory manager that keeps context small but useful, a ReAct-style executor with hard iteration and token caps, and the metrics and failure containment strategies that keep the whole thing predictable under load.
Anatomy of an agent request in production
A single user request fans out into a surprising amount of machinery. The orchestrator loads conversation state, assembles a prompt containing instructions, memory, and the current tool schemas, and calls the model. The model either emits a final answer or a structured tool call, which is validated, rate-checked, executed in a sandbox, and fed back as the next observation. Each hop adds latency, and each hop can fail in its own way: the model emits malformed JSON, the tool times out, the database returns a permission error, or the loop simply never finds a stopping condition.
The operational discipline that separates a toy agent from a service is treating every one of those hops as observable and bounded. Set a maximum number of iterations and a maximum cumulative token budget per request. Wrap each tool in a circuit breaker so a flapping dependency stops receiving traffic after a few failures. Trace every model call and tool call under one correlation ID so a slow request can be reconstructed after the fact. Without those three controls â caps, breakers, traces â an agent that works in testing will page someone at three in the morning.
A tool registry that tracks health, not just signatures
Tools are the agent's actuators, and an agent that calls a broken tool produces confident nonsense faster than one with no tools at all. A production registry stores the JSON schema each model sees, but also live counters: call volume, error rate, and a moving average of latency. When a tool crosses an error or latency threshold, the registry marks it unavailable, and the next prompt simply omits it â the model adapts, and the user gets a degraded but honest answer.
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Callable, Dict, List
class ToolStatus(Enum):
AVAILABLE = "available"
RATE_LIMITED = "rate_limited"
CIRCUIT_OPEN = "circuit_open"
@dataclass
class ToolRecord:
name: str
description: str
parameters: Dict[str, Any]
fn: Callable
status: ToolStatus = ToolStatus.AVAILABLE
calls: int = 0
errors: int = 0
avg_latency_ms: float = 0.0
failure_window: List[float] = field(default_factory=list)
def schema(self) -> Dict[str, Any]:
return {
"type": "function",
"function": {
"name": self.name,
"description": self.description,
"parameters": self.parameters,
},
}
class ToolRegistry:
def __init__(self, error_threshold: float = 0.25, window_s: float = 60.0):
self.tools: Dict[str, ToolRecord] = {}
self.error_threshold = error_threshold
self.window_s = window_s
def register(self, name, description, parameters, fn) -> None:
self.tools[name] = ToolRecord(name, description, parameters, fn)
def available_schemas(self) -> List[Dict[str, Any]]:
now = time.time()
for tool in self.tools.values():
recent = [t for t in tool.failure_window if now - t < self.window_s]
tool.failure_window = recent
if tool.status is ToolStatus.CIRCUIT_OPEN and len(recent) < 3:
tool.status = ToolStatus.AVAILABLE
if tool.calls >= 10 and tool.errors / tool.calls > self.error_threshold:
tool.status = ToolStatus.CIRCUIT_OPEN
return [t.schema() for t in self.tools.values()
if t.status is ToolStatus.AVAILABLE]
def execute(self, name: str, args: Dict[str, Any]) -> Dict[str, Any]:
tool = self.tools.get(name)
if tool is None:
return {"error": f"unknown tool {name}"}
if tool.status is not ToolStatus.AVAILABLE:
return {"error": f"tool {name} is {tool.status.value}"}
start = time.time()
try:
result = tool.fn(**args)
tool.calls += 1
latency = (time.time() - start) * 1000
tool.avg_latency_ms += (latency - tool.avg_latency_ms) / tool.calls
return {"result": result, "latency_ms": round(latency, 2)}
except Exception as exc:
tool.calls += 1
tool.errors += 1
tool.failure_window.append(time.time())
return {"error": f"{type(exc).__name__}: {exc}"}
Two details matter here. Arguments should be schema-validated before the function is invoked, because a model will occasionally invent a parameter name. And tool results must be size-limited before they re-enter memory â a tool that returns a 200 KB JSON blob will silently evict the rest of the conversation from the context window.
Memory: three tiers, one context budget
Human-like "memory" in agents is really three mechanisms with different lifetimes. Short-term memory is the recent message and observation list, usually capped by a deque. Working memory is the scratchpad the model is explicitly told to use for intermediate state. Long-term memory is durable storage â a vector index or database â from which relevant facts are retrieved per request. The memory manager's real job is fitting all three into a fixed token budget while keeping the most useful content.
import json
from collections import deque
from dataclasses import dataclass, field
from typing import Dict, List, Optional
@dataclass
class MemoryEntry:
text: str
kind: str
importance: float = 0.5
metadata: Dict[str, str] = field(default_factory=dict)
class AgentMemory:
def __init__(self, short_term_max: int = 24):
self.short_term: deque = deque(maxlen=short_term_max)
self.long_term: List[MemoryEntry] = []
def remember(self, text: str, kind: str = "event",
importance: float = 0.5) -> None:
self.short_term.append(MemoryEntry(text, kind, importance))
if importance >= 0.8:
self.long_term.append(MemoryEntry(text, kind, importance))
def context_block(self, token_budget: int = 2000) -> str:
blocks: List[str] = []
used = 0
for entry in self.long_term[-10:]:
cost = len(entry.text.split())
if used + cost > token_budget:
break
blocks.append(f"[long-term] {entry.text}")
used += cost
for entry in reversed(self.short_term):
cost = len(entry.text.split())
if used + cost > token_budget:
break
blocks.append(f"[recent] {entry.text}")
used += cost
return "\n".join(reversed(blocks))
def dump_trajectory(self) -> str:
return json.dumps(
[{"kind": e.kind, "text": e.text} for e in self.short_term],
ensure_ascii=False,
)
Note the word-based token estimate â it is crude, but it keeps the memory manager honest about budgeting. Swap it for the real tokenizer in production, and always leave headroom for the model's answer and any tool schema updates in the same request.
The bounded executor: where reliability actually lives
The executor ties tools, memory, and model calls together, and its loop parameters are the single most important reliability lever you control. A maximum iteration count prevents runaway costs on adversarial or ambiguous inputs. A cumulative token budget stops one pathological conversation from dominating the bill. A per-tool timeout converts a hung dependency into an ordinary error the model can route around.
import json
from typing import Any, Dict, List
class BoundedAgentLoop:
def __init__(self, registry: ToolRegistry, memory: AgentMemory,
llm: Any, max_steps: int = 8, token_budget: int = 20000):
self.registry = registry
self.memory = memory
self.llm = llm
self.max_steps = max_steps
self.token_budget = token_budget
self.spent = 0
def run(self, user_input: str) -> Dict[str, Any]:
self.memory.remember(f"user: {user_input}", "user", 0.6)
trace: List[Dict[str, Any]] = []
for step in range(self.max_steps):
prompt = self._compose_prompt()
response = self.llm(prompt, tools=self.registry.available_schemas())
self.spent += response.usage.total_tokens
if self.spent > self.token_budget:
return {"answer": "Budget exhausted; try a narrower request.",
"trace": trace, "stopped": "budget"}
decision = self._parse(response.text)
if decision["type"] == "answer":
self.memory.remember(f"agent: {decision['text']}", "agent", 0.7)
return {"answer": decision["text"], "trace": trace, "stopped": "done"}
result = self.registry.execute(decision["tool"], decision["args"])
trace.append({"step": step, "tool": decision["tool"], "result": result})
observation = json.dumps(result)[:1500]
self.memory.remember(f"tool {decision['tool']} -> {observation}",
"observation", 0.4)
return {"answer": "Stopped after max steps without a final answer.",
"trace": trace, "stopped": "max_steps"}
def _compose_prompt(self) -> str:
schemas = json.dumps(self.registry.available_schemas())
return (f"{self.memory.context_block()}\n\n"
f"Available tools: {schemas}\n"
"Reply with either a tool call or a final answer.")
def _parse(self, text: str) -> Dict[str, Any]:
try:
payload = json.loads(text)
if "tool" in payload:
return {"type": "tool", "tool": payload["tool"],
"args": payload.get("args", {})}
return {"type": "answer", "text": payload.get("answer", text)}
except json.JSONDecodeError:
return {"type": "answer", "text": text}
Prefer structured tool calling (the provider's native function-calling API) over free-text parsing in real deployments; the fallback parser above is what you keep for models that only emit prose. Either way, record the stopped reason on every request. A rising share of max_steps terminations is the earliest signal that prompts have drifted or a tool's output has degraded.
Prompt assembly: the part everyone underestimates
Composing the agent prompt looks trivial and is not. The system instructions, the memory block, the tool schemas, and the current observation all compete for the same context window, and their arrangement changes behavior measurably. Models follow instructions placed near the end of the prompt more reliably than instructions buried at the top, which is why the current task and the stopping criteria belong after the memory block, not before it. Tool schemas are large; exposing thirty tools can consume tens of thousands of tokens before the conversation even starts, so production systems filter the schema list per request using the router's guess at task type.
The observation handling deserves equal care. A tool result is untrusted text authored by an external system â it can contain phrasing that looks like instructions, and a careless template lets it override the system prompt. Wrap observations in explicit delimiters, strip anything resembling role markers, and state in the system prompt that content inside delimiters is data, never directives. Finally, keep the prompt assembly deterministic and logged: given the same memory state and tool set, two requests should produce byte-identical prompts, or a replayed incident will not reproduce.
Metrics, cost control, and failure containment
Agent observability has three layers: model telemetry (tokens, latency, provider errors per call), tool telemetry (call counts, error rates, latency per tool), and outcome telemetry (steps to completion, stopped reason, user escalation rate). Correlate all three with one trace ID per request so a single slow conversation can be replayed.
Cost control is mostly structural. Cap steps, cache deterministic tool results with a short TTL, route easy subtasks to a smaller model, and reserve the frontier model for planning and synthesis. A common pattern is a cheap "router" model classifying the request, with only hard cases escalating to the full agent loop.
| Failure mode | Symptom | Containment |
|---|---|---|
| Tool hallucination | Model calls tools that do not exist | Schema filtering plus strict validation |
| Infinite tool loop | Same tool and arguments repeat | Detect repeats, force a final answer |
| Context overflow | Early messages dropped mid-task | Fixed memory budget with pinned task state |
| Dependency outage | Tool timeouts spike | Circuit breaker removes tool from schemas |
| Prompt injection | Tool output overrides instructions | Treat observations as untrusted data, never instructions |
Common Mistakes
Giving the agent unlimited iterations to be safe
Fix: Cap steps and tokens; a capped loop fails predictably, an uncapped one fails expensively.
Logging only the final answer
Fix: Trace every model call and tool call with a shared request ID, or postmortems are impossible.
Trusting tool output as instructions
Fix: Wrap observations as quoted data and strip anything resembling system directives before they reach the prompt.
Storing full tool payloads in memory
Fix: Truncate and summarize observations; only persist fields the agent is likely to need later.
Deploying new tool schemas silently
Fix: Version schemas with evals; a bad description changes model behavior as much as a bad function body.
Best Practices
- Treat max steps, token budget, and per-tool timeouts as configuration with sane defaults, not constants buried in code.
- Run a regression suite of recorded agent trajectories on every prompt or schema change before rollout.
- Expose per-tool error rates on the same dashboard as model latency; they move together when something breaks.
- Give every request a trace ID surfaced to support teams, so users reporting weird answers can be debugged quickly.
- Escalate from a small model to a large one only when confidence is low, instead of paying frontier prices for every routing decision.
Key Takeaways
- Agent reliability comes from bounding the loop: maximum steps, cumulative token budgets, per-tool timeouts, and circuit breakers.
- A production tool registry tracks health â call volume, error rate, latency â and hides unhealthy tools from the model automatically.
- Memory management is budgeting: tiered short-term and long-term stores fitted into a fixed token allowance per request.
- Structured tool calling beats prose parsing; always record why a loop stopped so degradation is visible in aggregate metrics.
- Observability must correlate model calls, tool calls, and outcomes under one trace ID to make any single slow request debuggable.