AI Agents in Production

Agent loops, tools, memory, guardrails, cost control: what changes between a demo and production.

Advanced8 min read
Language
Theme
Goal + contextLLMreason + decidetool callToolsearch / API / coderesultloop until doneMemoryshort + long-termGuardrails: max steps / cost / time, human approval, traces, evals
Key idea at a glance

The problem, stated properly

An LLM call answers one question. An agent pursues a goal: "research these five vendors and produce a comparison", "find the bug and fix it", "monitor this inbox and file invoices." The difference is a loop: the model plans, calls a tool, reads the result, plans again, repeating until the goal is met or it gives up. The system-design question is not "how smart is the model" but how you build a reliable system around an unreliable component: state, tools, guardrails, memory, evaluation, and cost control. That framing is the entire lesson.

The agent loop, precisely

  1. Observe: assemble context: the goal, conversation history, tool results so far, relevant memory.
  2. Reason: the LLM decides the next action, given available tools and their schemas (ReAct-style: interleaved reasoning traces and actions work better than plan-once-execute, because plans built before seeing the world break on contact with it).
  3. Act: emit a structured tool call. The runtime validates it (schema, permissions) and executes: search, code execution, API call, browser action.
  4. Persist: append the result to the trajectory. This running transcript is the agent's working memory.
  5. Loop or stop: the model decides "done" and produces the final answer, or hits a budget (max steps, max time, max dollars) and must stop and report partial progress.

Everything else in agent engineering is hardening this loop.

Why agents fail: error compounding is the boss fight

If each step is 90% reliable (optimistic for hard tasks), a 20-step task succeeds 0.9^20 which is about 12% of the time. This one equation drives every architectural decision in the field:

  • Decompose: split the big goal into sub-tasks, each with its own short loop and a verifiable output. Five 4-step tasks at 65% each beats one 20-step task at 12%, and failures localize instead of poisoning the whole run.
  • Verify at each step: cheap deterministic checks (did the API return 200? does the code compile? does the file exist?) catch errors before they compound. LLM-as-judge adds a second, semantic layer for outputs with no deterministic check.
  • Ground every load-bearing step: the model's plan says "email the receipt to finance." A hard gate checks the address against a directory before the send tool will fire. Models propose, deterministic code disposes.
  • Keep trajectories short: context pollution is real; a 50-step transcript full of dead ends degrades the model's next decisions. Summarize or restart with a clean context carrying only what was learned.

Memory: the three kinds, and their failure modes

  • Working memory (the context window): the trajectory itself. Failure mode: overflow and pollution, handled by summarization and sub-task isolation.
  • Episodic memory (what happened before): past runs, retrieved when relevant (often RAG over past trajectories). Failure mode: retrieving a past mistake and faithfully repeating it.
  • Semantic memory (facts and preferences): a curated store the agent reads and writes ("user prefers morning meetings"). Failure mode: unreviewed writes, where one bad inference becomes a permanent false belief, so writes need confidence gates or human review.

Tools and guardrails

Tool design makes or breaks agents more than prompt engineering does. Rules that survive production: tools should be narrow and semantic (one create_calendar_event, not raw API access), arguments validated strictly, every tool documented for a non-human reader, and permissions tiered: read-only tools run free; writes and external sends require policy gates or human approval. The security model from the MCP lesson applies verbatim: the agent is a caller that must never be trusted by the executor, and prompt injection through tool-read content (a poisoned email, a web page) is the primary attack path.

Multi-agent: when it helps and when it is resume decoration

Splitting work across specialized agents (researcher, coder, reviewer) helps when sub-tasks are genuinely independent, benefit from separate clean contexts, or need different tools and permissions. It hurts when agents must share fine-grained state (coordination cost exceeds the benefit) and it multiplies cost and latency by the agent count. The orchestrator-worker pattern (one planner decomposes, workers execute in parallel, results merge) is the shape that has earned production use; chatty agent societies mostly have not.

Real numbers

  • Latency: each loop iteration is one LLM call (2-10 s with thinking) plus tool time. A 15-step task is 1-5 minutes. Async operation with progress updates is not optional; nobody stares at a spinner for 3 minutes.
  • Cost: each step re-sends the growing context: a 20-step run can spend 100K-1M tokens. Budgets (max steps, max dollars per run) are a reliability feature, not just finance.
  • Reliability math in practice: well-engineered agents on bounded tasks (form filling, research summaries, code fixes with tests) reach 70-95% task completion; open-ended multi-hour tasks remain research territory. Design the product for the 5-30% that fail: checkpoints, human handoff, resumability.

Evaluation: the part everyone skips

You cannot improve what you do not measure, and agent quality is invisible in single demos. Production agent systems keep golden task suites (50-500 representative tasks with known-good outcomes), run them on every prompt/model/tool change, and track task completion rate, cost per success, and failure taxonomy (tool misuse vs bad plan vs bad retrieval vs premature stop). Trajectory review, reading full transcripts of failures, is the debugging tool; there is no stack trace for "the model decided to give up."

Common interview traps

  • Describing the loop and stopping there. The question is always really about reliability engineering.
  • No answer for error compounding. If you have not said 0.9^20, you have not designed the system yet.
  • Tools as raw API passthrough. Wide tools produce wide failure surfaces.
  • Claiming more agents automatically means more capability. Coordination is a cost you must justify.
  • No evaluation story. "It worked in the demo" is not a design.

Interview Q&A

Q: Your agent succeeds 40% of the time on a 15-step task. What do you do first?
A: Read trajectories and classify failures before touching anything. The fix depends entirely on the distribution: if one tool causes half the failures, fix that tool's schema and docs; if failures cluster at steps 10+, it is context pollution, so decompose or summarize; if the model plans badly from step 1, give it worked examples in the prompt or a planning sub-step. The universal mistake is tweaking the prompt against vibes instead of a failure taxonomy. Measure, classify, then fix the biggest bucket.

Q: How do you let an agent send emails on a user's behalf without disasters?
A: Layered gates, because the model will eventually be manipulated or wrong: (1) tool tiering: draft-creation runs free, send is a separate privileged tool; (2) deterministic policy checks in the send path: recipient in approved domain list, no attachments unless declared, rate limits; (3) human approval for anything outside the policy, with the full draft shown; (4) content inspection: block sends triggered by instructions found inside tool-read content (the prompt-injection path), which means tracking which text came from the user vs from the outside world; (5) full audit log of every send. The principle: the model proposes, policy disposes, and no single layer is trusted to catch everything.

Key takeaways

Interview pointer

Asked to design an AI product, spend 60% of your time on guardrails, cost and observability. Everyone talks about LLM capabilities; few think about production.