Theme
‹Blog

Notes on agent engineering

An agent is a small loop around a fixed, stochastic policy. On each step, your code builds a context from the conversation history and external state, then asks the model to sample an action. A gate checks whether that action is allowed, the harness runs it, and the observation goes back into the history until the model stops calling tools or hits a budget.

You almost never train the model. You pick one and design everything around it: the tools, the context builder, the permission gate, the external store, the loop, and the evaluator.In reinforcement learning you optimize the policy itself. In agent engineering the weights stay frozen, so every engineering lever lives in the harness around the policy. Because the policy is stochastic, every run is a random draw, and any claim that a change improved performance is a statistical claim.

Diagram of an agent harness surrounding a fixed model policy
The model is the only component you do not write. Everything inside the dashed boundary is the harness: context assembly, action gating, tool execution, and logging for evaluation.

When to use an agent

Before building an agent, decide who should control the next step: your code ahead of time, or the model at runtime.

ArchitectureWho decides control flowTrade-off
Plain codeProgrammerCheapest, deterministic, easy to test
WorkflowProgrammer (fixed steps, some LLM calls)Predictable, bounded cost
RouterModel picks one branchNarrow flexibility
Single agentModel picks every stepHandles unknown paths; noisy and slower
Multi-agentAgents delegate to agentsParallel breadth; expensive, harder to keep coherent

Most production systems mix levels, such as a workflow whose steps contain small agents or an agent whose tools are deterministic scripts. Four questions filter out poor fits before you hand control flow to a model:

  1. Is the sequence of steps genuinely unpredictable? If you can write the steps down in advance, write a workflow.
  2. Can the environment tell you whether an action worked?
  3. Are mistakes cheap and reversible? Editing a git working tree is recoverable; sending an email is not.
  4. Is the outcome worth tens or hundreds of model calls where a fixed workflow uses a few?

Software engineering satisfies all four criteria, which is a major reason coding agents became useful early on.See SWE-bench (Jimenez et al., 2024) and SWE-agent (Yang et al., 2024) for the benchmark and interface work around repository-level bug fixing. The second criterion (verifiability) deserves a quick calculation because it explains why environment feedback dominates long-horizon reliability.

Suppose a task takes TT steps, each step succeeds independently with probability rr, and any error is fatal:

P(success)=rTP(\text{success}) = r^T

At r=0.95r = 0.95 over 50 steps, 0.9550≈0.0770.95^{50} \approx 0.077. Even a 99%-per-step model over 100 steps finishes only 0.99100≈0.370.99^{100} \approx 0.37 of the time. Pure open-loop execution decays geometrically with horizon length.

Now add environment feedback: an error gets detected with probability dd (a test fails, a tool rejects bad input, a schema check trips) and, once detected, is repaired in a few extra steps. Assuming detected errors are repaired, only undetected errors are fatal, so the effective per-step failure rate drops from 1−r1 - r to (1−r)(1−d)(1 - r)(1 - d):

P(success)≈(1−(1−r)(1−d))TP(\text{success}) \approx \bigl(1 - (1 - r)(1 - d)\bigr)^T

Plug in the same r=0.95r = 0.95 and T=50T = 50, with d=0.9d = 0.9, and success rises tenfold to 0.99550≈0.780.995^{50} \approx 0.78.This trade-off is why stronger test suites and clearer tool error messages often yield larger reliability gains than switching models.

Range-frame plot comparing task success probability over 100 steps for r = 0.95 across detection rates d = 0 to 0.95
Family of survival curves for an r = 0.95 model as error detection d increases from 0 to 0.95. At d = 0.80, effective per-step error matches an open-loop r = 0.99 model; at d = 0.90, 50-step success climbs from 0.077 to 0.78.

The loop and quadratic token cost

Early agent frameworks wrapped the loop in planners, task queues, and role hierarchies. As models improved, much of that scaffolding got in the way, and current practice leans toward a minimal loop backed by good tools and explicit verification.Anthropic's Building effective agents (2024) documents this shift toward composable primitives and simple loops, a local instance of Rich Sutton's Bitter Lesson. The core loop takes roughly forty lines of code: build a view of the history, call the model, check why generation stopped, execute any tool calls, and append the observations. Around that loop, enforce budgets on steps, tokens, wall-clock time, and spend, plus timeouts for hung tools.

Inside the loop, every failure should become an observation. An unknown tool name, invalid arguments, a denied permission, or a runtime exception should return readable error text so the model can adjust, raising dd. Always check tool existence and argument schemas before running permission logic; otherwise a gate can crash on bad types or get bypassed when the gate and the tool interpret malformed arguments differently (such as an extra key or an unnormalized path).

Distinguish how a run ends from whether it succeeded. A loop has at least three terminal states: answered (normal stop, no tool calls), budget_exhausted, and stopped (truncated at max_tokens or refused by the provider). Treating a truncated reply with no tool calls as a finished answer is a common silent bug, and answered says nothing about correctness.

Keep the provider behind a narrow adapter that translates wire payloads into your own ToolCall and Reply types. Store the provider's raw assistant content verbatim so you can resend it unchanged on later turns; reasoning models often attach signed thinking blocks and reject edited histories. A thin Model interface also lets you plug in a scripted model to unit-test the harness offline: unit tests find harness bugs, while evals measure model behavior.

Model APIs are stateless, so every step resends the full growing history. If the fixed prefix (system prompt plus tool schemas) takes c0c_0 tokens and each step appends Δ\Delta tokens, step tt sends c0+tΔc_0 + t\Delta tokens. Over TT steps, total input is:

∑t=1T(c0+tΔ)=Tc0+ΔT(T+1)2\sum_{t=1}^{T} (c_0 + t\Delta) = T c_0 + \Delta \frac{T(T + 1)}{2}

Total input grows quadratically with steps. With c0=5,000c_0 = 5{,}000, Δ=2,000\Delta = 2{,}000, and T=50T = 50, a single run reads roughly 2.8 million input tokens even though only 100,000 history tokens are new (105,000 uncached tokens including step 1's prefix).At a 90% cache discount on the unchanged prefix, those 2.8 million tokens bill like 374,500 full-price tokens, roughly a 7.5× cost reduction from layout discipline alone. Prompt caching makes multi-step loops affordable by billing an unchanged byte-for-byte prefix at a fraction of the input rate. Put static material first and keep the history append-only: inserting a live timestamp into the system prompt, or mutating tool definitions mid-run, silently invalidates the cache on every step.

Cumulative input tokens over 50 steps comparing uncached quadratic cost against 90 percent prompt caching
Cumulative billed input for c_0 = 5,000 and Δ = 2,000 over 50 steps. Uncached resending reaches 2.80M tokens while a 90% prefix cache bills like 374.5k tokens, a 7.5× reduction.

Tool design

The model reads a tool's name, description, and JSON Schema; the harness reads its implementation and effect class (read, write, execute, external). With the model held fixed, tool interface design changes task success rates substantially.In SWE-agent (Yang et al., 2024), a bounded line-numbered file viewer beat raw cat, summarized search beat raw match dumps, and a linter-backed editor beat unchecked edits, all without changing model weights.

Return what the next decision needs. Number lines in file reads, format search hits as file:line: text, and put PASSED or FAILED at the top of test output so truncation never hides the verdict. Prefer readable identifiers over opaque database IDs, and make errors instructive: if an edit tool replaces a target string, require it to appear exactly once and return "found 3 occurrences; include more context" when it does not. A bare exception gives the model nothing to act on, while silently replacing the first match produces wrong edits without signaling failure.

Bound outputs at the source. One unrestricted read on a 10,000-line file can fill a context window, so support paging and filtering, with truncation as a backstop that states how much was omitted. Pick tool granularity deliberately as well. General tools (bash, executable Python) compose cleanly: looping over twenty files in one script takes one step instead of twenty context round trips. Specific tools (edit_file, restart_service) give the gate and audit log structured fields to check. Make an operation its own tool when you want to validate it, permission it separately, or render a dedicated approval prompt.

Keep the toolset small and distinct. Every schema consumes tokens on every call, and overlapping tools force the model to guess. When you have a large library of domain procedures, use progressive disclosure (skills): keep only a short name and description in context, and load full instructions or scripts on demand when a task matches.

Protocols like MCP standardize how external tools are discovered and invoked across servers, but they do not change the underlying constraints. An MCP tool still occupies context, can return large or adversarial text, and must pass through your permission gate.

Managing the context budget

At step tt, the model sees only its weights and whatever your context builder put into ctc_t. Filling a large context window degrades quality and raises cost:

  1. Attention dilutes as irrelevant tokens accumulate. Models retrieve information placed at the beginning or end of a prompt more reliably than information in the middle.See Lost in the Middle (Liu et al., 2024), RULER (Hsieh et al., 2024), and Chroma's Context Rot report (Hong, Troynikov & Huber, 2025). Exact curves vary across model generations, though the degradation pattern persists.
  2. Effective context length sits well below nominal window limits, and stale observations (old test output, files read during a dead end) compete directly with current evidence.
  3. Every token kept early in the run is re-read on every subsequent turn.

Treat context assembly as selection under a token budget. The main reduction technique is replacing raw contents with cheap references (file paths, IDs) and letting the agent pull details just in time. Coding agents use this hybrid pattern by default: load a short project briefing up front, then grep and open files on demand.

When history still grows too large, four remedies shrink what the model sees, ordered from recoverable to lossy:

  1. Bound outputs at the source with paging and filtering.
  2. Elide old tool results in the model's view, replacing long outputs older than the last few turns with a stub noting the length and how to re-fetch while leaving the recorded history untouched.
  3. Offload plans, notes, and bulky intermediate results to files and keep only their paths in context.
  4. Compact the history by asking the model to summarize the run and continue from a fresh window. Because compaction is irreversible, specify what must survive: the task, definition of done, files modified and why, failed approaches, and next steps.

Two small layout habits help on long runs. Keep failed calls and their error messages visible (removing them invites the model to repeat the same dead end), and restate a short objective or status list near the end of the context where retrieval is strongest.

Retrieval and memory outside the window

Once you replace contents with references, you need an external store with a read path (retrieval) and a write path (memory).

On the read path, fixed RAG pipelines (retrieve top kk, then generate) suit straightforward lookups: they are cheaper and easier to benchmark. When a question requires following leads across files or documents, expose search as a tool inside the loop. On codebases, plain grep-style search often works without a vector index because identifiers are exact and files change constantly.

For prose corpora, lexical search (BM25) catches exact terms and error strings while dense embeddings catch paraphrases. Merging both with reciprocal rank fusion avoids calibrating incomparable score scales, and a reranker can refine the top candidates:Reciprocal rank fusion and the k=60k = 60 default come from Cormack, Clarke & Büttcher (SIGIR 2009).

RRF⁡(d)=∑r∈rankers1k+rank⁡r(d),k≈60\operatorname{RRF}(d) = \sum_{r \in \text{rankers}} \frac{1}{k + \operatorname{rank}_r(d)}, \qquad k \approx 60

Always evaluate retrieval separately (recall@k\text{recall}@k, MRR, or whether an agentic trace ever opened the relevant file), because retrieval failures look identical to reasoning failures if you inspect only the final answer. Attach stable provenance to every retrieved chunk so the harness can verify that cited IDs were fetched.

On the write path, write long-term memory (preferences, project facts, recurring lessons) sparingly. Record source and date, update instead of appending contradictions, and treat stored memory as untrusted input. A note saved while reading a hostile document can carry injected instructions into every later session.

Verification, long horizons, and multi-agent trade-offs

Verification exploits the generator-verifier gap: checking a solution is usually easier than producing one. Verifiers rank from strongest to weakest:

  1. Deterministic checks (types, schemas, recomputed numbers, unmodified test files).
  2. Executable tests and ground-truth assertions.
  3. Model-based judges with explicit rubrics, calibrated against human labels.
  4. Unaided self-critique without new external evidence.In Reflexion (Shinn et al., 2023), verbal self-reflection helped most when grounded in an external signal such as a failing test.

Make "done" checkable, and block obvious shortcuts: "make the test suite pass without modifying the tests" prevents an agent from deleting a failing assertion. When the final output has no programmatic verifier, verify intermediate pieces (recompute numbers, check citations against retrieved sources). State explicitly that stopping to report a blocker is acceptable; otherwise models tend to fabricate workarounds.

Work that spans hours and multiple context windows needs clean handoff state for each fresh session. Five pieces carry progress across resets: a structured goal list (items marked passing only after verification), concise progress notes written by the outgoing session, version control, a startup check that validates inherited state, and scoping each session to one concrete milestone.

For crashes during side effects, standard distributed-systems rules apply. Persist an append-only event log and record pending before sending an external request. If the process dies before recording the acknowledgement, that effect's state is unknown, not failed. Never retry blindly: either attach a deterministic idempotency key derived from the operation's identity (reused across retries, never regenerated per attempt) or query the destination to reconcile first.

Subagents are tools that run another loop. Their main role is isolating noisy reads from the parent context: a read-only helper can consume 40,000 tokens skimming a dozen files and return a 200-token report with file:line citations, with its read-only toolset enforced by construction.

Multi-agent systems buy parallel breadth on search and research at high token cost; Anthropic reported roughly 15× the token usage of single-turn chat on its multi-agent research evaluation (2025). On code edits or any single coherent artifact, independent subagents make conflicting implicit decisions.Walden Yan (Cognition, Don't build multi-agents, 2025) makes this case for coding agents: split work needs shared context and visible prior decisions. Delegate read-heavy searches, keep writing under one agent with one context, and give every delegated subagent an explicit contract (objective, output format, boundaries, step budget).

Be cautious with majority voting as well. Condorcet's jury theorem makes voting look strong on paper (five independent voters at p=0.7p = 0.7 hit 0.8370.837, eleven hit 0.9220.922, the basis of self-consistency), but samples from the same model on the same prompt share blind spots. Voting reduces independent slips; shared misunderstandings survive across every sample. Diversifying prompts, evidence, or models buys more than extra draws from one setup.

Scale-accurate bar chart comparing 40,000 tokens read by a subagent against 200 tokens returned to the parent
Drawn to scale (100 tokens per pixel): a read-only child reads 12 files (40,000 tokens) in isolation and passes back a 200-token summary, a 200:1 reduction in parent context growth.

The model is not a security boundary

Everything inside the context (system prompt, user message, repository files, web pages, MCP tool descriptions, memories, subagent reports) feeds the same next-token distribution. Models are trained to prioritize system and user instructions over data, but that is a learned tendency, and untrusted text inside the context can still steer the model.AgentDojo (Debenedetti et al., 2024), which scores both task utility and resistance to tool-output injections, shows that prompt-level defenses lower attack success, often at a utility cost, but do not drive it to zero. Prompt instructions lower how often harmful actions get proposed, while actual guarantees come from which tools exist, what the gate permits, and what the sandbox confines.

Venn diagram of private data, untrusted content, and external communication overlapping at exfiltration
Exfiltration requires all three capabilities in the same loop. Removing any leg breaks the path regardless of model behavior.

Simon Willison's lethal trifecta is the fastest threat check for any agent design. Severe data exfiltration requires three capabilities at once:

  1. Access to private data.
  2. Exposure to untrusted content.
  3. The ability to communicate externally.

Remove any one leg for a given task and the exfiltration path breaks regardless of what the model gets tricked into proposing. A bug-fixing agent reads untrusted repo content and holds private code, so it gets no outbound network. A web-browsing research agent should not have access to private local files.

When a task genuinely touches sensitive state, layer controls so no single failure is catastrophic:

LayerControlWhat it bounds
1. Action spaceExpose only the tools the task needsPrevents unused capabilities from being called
2. Gate policyAllow, ask, or deny by effect class and normalized argsBlocks disallowed actions before execution
3. SandboxConfine files and processes; default-deny egress; proxy credentialsLimits damage from allowed calls and executed code
4. ApprovalBind human confirmation to the exact action or diff hashKeeps irreversible actions on a trusted channel
5. MonitoringWrite append-only logs outside the agent's reachPreserves an audit trail the agent cannot alter

Where stronger guarantees are needed, architectural defenses keep untrusted data out of control flow altogether.See Design Patterns for Securing LLM Agents against Prompt Injections (Beurer-Kellner et al., 2025) and CaMeL (Debenedetti et al., 2025). Plan-then-execute fixes the sequence of actions from the trusted task before reading untrusted data. Dual-model separation lets a privileged model plan and invoke tools while a toolless quarantined model processes untrusted text and returns opaque handles. Capability and taint-tracking systems such as CaMeL have the privileged model emit a program whose interpreter tracks data provenance and blocks untrusted values from reaching sensitive sinks.

Grade autonomy by reversibility to avoid approval fatigue. If a user gets prompted fifty times an hour, they stop reading and click yes. Reads, sandboxed writes under version control, and offline test runs can usually proceed freely; external or irreversible actions get gated or replaced by staging a draft. Containment buys autonomy with fewer prompts, and the same guardrails protect against ordinary accidents (deleting the wrong directory, force-pushing) as well as deliberate attacks.

Evaluation and operating over time

Because agent runs are stochastic and every component interacts with every other component, inspecting a handful of runs after a prompt change misleads easily: a tweak that fixes one failure often breaks others.

As a starting point, build 20 to 50 real tasks from actual usage and observed failures, organized into capability, regression, adversarial, and held-out sets.See Anthropic's Demystifying evals for AI agents (2026) on suite design, and Judging LLM-as-a-Judge (Zheng et al., 2023) on verbosity, position, and self-preference biases in model graders. Run every trial on an isolated fresh copy of the environment, and grade the final state, not the agent's transcript. Prefer programmatic code graders; when you need model judges for open-ended criteria, calibrate specific rubric items against human labels.

Report the metric that matches deployment. Given per-trial success rate pp, pass⁡@k=1−(1−p)k\operatorname{pass}@k = 1 - (1 - p)^k measures the probability that at least one of kk tries succeeds, which applies when a verifier or human selects among candidates. Conversely, pass⁡k=pk\operatorname{pass}^k = p^k measures the probability that all kk tries succeed, which applies when unattended consistency matters.For nn trials with cc successes, unbiased estimators are 1−(n−ck)/(nk)1 - \binom{n-c}{k}/\binom{n}{k} for pass⁡@k\operatorname{pass}@k (Chen et al., 2021) and (ck)/(nk)\binom{c}{k}/\binom{n}{k} for pass⁡k\operatorname{pass}^k (Yao et al., 2024). At p=0.7p = 0.7, pass⁡@3=0.973\operatorname{pass}@3 = 0.973 while pass⁡3=0.343\operatorname{pass}^3 = 0.343.

Run candidate harnesses on the exact same tasks and analyze per-task differences di=xiB−xiAd_i = x_i^B - x_i^A to remove task-difficulty variance. More trials per task reduce model noise, but cannot substitute for more tasks. For unpaired binary outcomes near rate pp, making a difference Δ\Delta equal two standard errors requires:

N≈8p(1−p)Δ2N \approx \frac{8 p(1 - p)}{\Delta^2}

That is roughly 670 tasks for p=0.7p = 0.7 and Δ=0.05\Delta = 0.05, so small suites detect only large effects.

Three-panel small multiple comparing pass@k and pass^k across p = 0.5, 0.7, and 0.9
Small multiples across three per-trial reliabilities on a shared vertical scale. Even a coin-flip agent (p = 0.5) hits pass@5 = 0.969 when a verifier picks the winner, while a strong p = 0.9 agent drops to pass^10 = 0.349 when every trial must hold.

In production, instrument every model call and tool call into structured traces (tokens, latency, stop reasons, arguments, errors, approvals), and read both failed transcripts and a sample of successful ones. No aggregate chart will warn you that the agent started bypassing checks. Error analysis (bucketing twenty failed traces by root cause: retrieval, tool interface, context, control, or gate) pinpoints which component to fix far better than guessing.

Version the whole configuration as one artifact: exact model ID (never a floating alias), reasoning effort, system prompt, tools, context policy, and gate rules. Measure cost per completed task. A cheaper model that needs twice as many steps or fails a third of the time can cost more overall. Start with the most capable affordable model to establish what is achievable, then step down once the harness is solid, and delete scaffolding built for weaker models whenever the underlying model upgrades.