AS·169
Agents
Systems where a model decides what to do next: the spectrum from deterministic workflows through LLM workflows to autonomous agents and how to choose deliberately, the agent loop (goal, plan, action, tool, observation, state, next action) implemented from scratch with budgets and stopping rules, ReAct-style reasoning and acting, planning strategies (plan-then-execute, replanning, decomposition), state and observations, memory in brief, execution environments (APIs, code sandboxes, browsers, computer use), human approval gates and autonomy levels, the composable workflow patterns (prompt chaining, routing, parallelisation, orchestrator–workers, evaluator–optimiser), multi-agent systems and when they help, coding and research agents as case studies, failure modes (loops, drift, compounding errors, tool misuse, cost blow-ups), and design principles for reliable agents.
Start here: a model in a loop
Tool calling (chapter 168) lets a model request one action. An agent keeps going: it looks at the goal and what has happened so far, decides the next action, observes the result, and repeats until it decides it's done.
goal: "Refund order A101 because it arrived late, and tell the customer."
1. think: I should check the order. act: get_order(A101) observe: ₹450, delivered 2 days late
2. think: Late delivery qualifies. act: refund_order(A101, 450, "late") observe: refunded
3. think: Tell the customer. act: send_message(...) observe: sent
4. done.
Workflow or agent?
| Workflow | Agent | |
|---|---|---|
| who decides the steps | your code, fixed in advance | the model, at run time |
| predictability | high | lower |
| good for | known, repeatable processes | open-ended tasks where the path can't be planned |
Most production "AI features" are workflows with a model inside some steps. Use an agent only when the steps genuinely can't be known in advance.
Why long agent runs are hard: errors compound
If each step succeeds 95% of the time, a 20-step task succeeds only 0.95²⁰ = 36% of the time. The lab simulated what fixes this: when 90% of failed steps are noticed (a test fails, a tool returns an error, a check catches it) and retried, the same task succeeded 86% of the time for only 5% more model calls. Agents become reliable through checks the agent can see, not through hoping each step is perfect.
And they need brakes
An agent can get stuck repeating itself. In a simulation where 3% of steps send the agent into a loop, runs with no guard averaged 549 steps (most of them wasted), while a step budget plus a repeated-action detector kept the worst run to 25 steps.
How deep to go in agents
Volume 17 defines six mastery levels; for agents they look like this:
| Level | You can… |
|---|---|
| L1 | explain the agent loop and the difference between workflows and agents |
| L2 | build an agent with tools, budgets and a stopping condition |
| L3 | explain ReAct, planning, reflection, multi-agent patterns and their costs |
| L4 | debug agent traces: wrong tool choice, loops, lost context, compounding errors |
| L5 | design autonomy levels, approvals, environments and evaluation for an agent product |
| L6 | run agents in production with sandboxes, observability, cost controls and incident response |
Workflow, LLM workflow or agent?
The roadmap asks you to choose deliberately among three designs:
| Deterministic workflow | LLM workflow | Agent | |
|---|---|---|---|
| Control flow | Code decides every step | Code decides the steps; LLMs perform some of them | The LLM decides the next step, in a loop, until done |
| Example | Nightly ETL; order fulfilment state machine | Ticket → classify (LLM) → route → draft reply (LLM) → human review | "Investigate why checkout latency rose yesterday and propose a fix" |
| Predictability | Highest | High | Lower: paths vary per run |
| Cost / latency | Lowest | Bounded | Variable, often higher |
| Handles novelty | No | Limited to designed paths | Yes: open-ended tasks, unknown number of steps |
| Testing | Unit tests | Unit tests + evals per LLM step | Trajectory and outcome evaluations (chapter 175) |
Start at the left; move right only when the task demands it. Most production "AI features" are LLM workflows. Agents earn their cost when the number and kind of steps can't be known in advance, the environment gives feedback the model can use (test results, search results, error messages), and the value of success outweighs extra cost, latency and risk.
The agent loop
goal → plan → action → tool → observation → state → next action
Components:
- Goal: the task, success criteria, constraints ("don't modify production; open a PR").
- Policy (the LLM + system prompt): reasons about state and picks the next action.
- Actions/tools (chapter 168): APIs, search, code execution, file edits, browser actions.
- Observations: tool results, errors, test output, screenshots.
- State: the conversation/trajectory so far, a scratchpad or plan, task variables, artefacts (files changed, findings).
- Memory beyond the context window (chapter 170).
- Control: budgets, stopping rules, approval gates, error recovery.
A minimal agent
import json, time
from dataclasses import dataclass, field
@dataclass
class Budget:
max_steps: int = 12
max_tokens: int = 60_000
max_seconds: float = 120.0
steps: int = 0
tokens: int = 0
started: float = field(default_factory=time.monotonic)
def charge(self, tokens):
self.steps += 1; self.tokens += tokens
def exceeded(self):
if self.steps >= self.max_steps: return "step limit"
if self.tokens >= self.max_tokens: return "token limit"
if time.monotonic() - self.started > self.max_seconds: return "time limit"
return None
@dataclass
class AgentState:
goal: str
history: list = field(default_factory=list) # (action, observation) pairs: the trajectory
notes: list = field(default_factory=list) # scratchpad / findings
done: bool = False
answer: str | None = None
SYSTEM = """You are an operations agent. Work step by step toward the goal.
Each turn, output JSON: {"thought": "...", "action": "<tool name or 'finish'>", "input": {...}}.
Prefer read-only tools. Stop with action 'finish' and input {"answer": "..."} when the goal is met."""
def run_agent(goal, llm, tools, approve, budget=None):
budget = budget or Budget(); state = AgentState(goal)
recent = []
while not state.done:
if (why := budget.exceeded()):
return state, f"Stopped ({why}). Findings so far: {state.notes}"
prompt = {"system": SYSTEM, "goal": goal, "tools": {n: t["description"] for n, t in tools.items()},
"trajectory": state.history[-8:], "notes": state.notes} # bounded context
decision, used_tokens = llm(prompt)
budget.charge(used_tokens)
action, args = decision["action"], decision.get("input", {})
if action == "finish":
state.done, state.answer = True, args.get("answer"); break
sig = (action, json.dumps(args, sort_keys=True))
recent = (recent + [sig])[-3:]
if len(recent) == 3 and len(set(recent)) == 1: # repeated identical call → loop
observation = {"error": "repeated_action", "message": "You've tried this 3 times; change approach."}
elif action not in tools:
observation = {"error": "unknown_tool", "available": sorted(tools)}
elif tools[action]["risky"] and not approve(action, args): # human approval gate
observation = {"error": "declined", "message": "A human declined this action."}
else:
try:
observation = tools[action]["fn"](**args)
except Exception as e: # errors become observations
observation = {"error": type(e).__name__, "message": str(e)[:300]}
state.history.append({"action": action, "input": args, "observation": observation})
if "note" in decision: state.notes.append(decision["note"])
return state, state.answer
Exercising it with scripted model decisions (a real system would call an LLM that returns the JSON decision):
METRICS = {"checkout_p95_ms": {"2026-10-23": 410, "2026-10-24": 1290}}
DEPLOYS = [{"service": "checkout", "version": "v812", "at": "2026-10-24T09:12Z", "change": "added fraud-score call"}]
tools = {
"get_metric": {"description": "Daily p95 latency for a metric", "risky": False,
"fn": lambda name: METRICS.get(name, {"error": "no such metric"})},
"list_deploys": {"description": "Recent deploys for a service", "risky": False,
"fn": lambda service: [d for d in DEPLOYS if d["service"] == service]},
"rollback": {"description": "Roll back a service to its previous version", "risky": True,
"fn": lambda service: {"status": "rolled back"}},
}
decisions = iter([
{"thought": "Check the latency trend", "action": "get_metric", "input": {"name": "checkout_p95_ms"},
"note": "p95 tripled on 24 Oct"},
{"thought": "Look for a change that day", "action": "list_deploys", "input": {"service": "checkout"},
"note": "v812 at 09:12Z added a fraud-score call"},
{"thought": "Propose rollback", "action": "rollback", "input": {"service": "checkout"}},
{"thought": "Rollback needs approval; report instead", "action": "finish",
"input": {"answer": "Checkout p95 rose from 410 ms to 1,290 ms on 24 Oct, right after v812 added a synchronous "
"fraud-score call. Recommend rolling back v812 or making the call asynchronous."}},
])
state, answer = run_agent("Why did checkout latency rise yesterday?", lambda p: (next(decisions), 1200),
tools, approve=lambda a, x: False)
[h["action"] for h in state.history], answer[:60]
Reasoning and acting
ReAct (Yao et al., 2022) interleaves reasoning ("thought: the latency rose on the 24th; check deploys") with actions and observations, letting the model plan, gather information and adjust. Modern models do this natively through tool calling, with extended thinking between steps on reasoning models; the explicit "thought" field remains useful for logging and debugging, but don't rely on displayed reasoning as a faithful account of the model's process.
Planning
| Strategy | How | Trade-offs |
|---|---|---|
| Implicit, step-by-step | Decide one action at a time from the trajectory | Simple, adaptive; can wander on long tasks |
| Plan-then-execute | First write a plan (list of steps), then execute steps (possibly with a cheaper model) | Clearer structure, fewer LLM calls; brittle if the plan is wrong |
| Replanning | Revise the plan when observations contradict it | Robust; more calls |
| Decomposition / hierarchical | Break the goal into sub-goals handled by sub-agents or sub-workflows | Scales to big tasks; coordination cost |
| Search over plans | Try several approaches, evaluate, keep the best (tree search, best-of-n) | Higher quality on hard problems; expensive |
A written plan or to-do list kept in state (and shown to the user) improves long tasks: it survives context trimming, makes progress visible, and gives humans a place to intervene.
State and observations
- Keep the trajectory (actions, arguments, results) but compact it: summarise or drop old tool outputs, keep key findings in notes, store large artefacts outside the context and reference them by id (chapter 170).
- Observations should be informative: errors with guidance, results with ids for follow-up calls, truncated large outputs with a way to fetch more.
- Ground truth from the environment (tests pass, the API returned 200, the page shows the confirmation) is worth more than the model's belief that something worked; verify before declaring success.
- Make state durable for long-running agents (checkpoints, chapter 171) so they can resume after failures or human pauses.
Execution environments
| Environment | Examples | Key controls |
|---|---|---|
| APIs / business tools | CRM, ticketing, databases, internal services | Scoped credentials, authorisation per call, rate limits |
| Code execution | Data analysis, test running, scripting | Sandboxed containers/microVMs, no secrets, network allowlists, resource limits |
| File systems / repositories | Coding agents editing a working copy | Work on branches/worktrees; review diffs; never push to protected branches without approval |
| Browsers | Web research, form filling | Isolated profiles, domain allowlists, confirmation before submitting forms or purchases |
| Computer use | Operating desktop apps via screenshots and clicks | Dedicated VMs, narrow permissions, human supervision |
Human approval and autonomy levels
Decide explicitly how much the agent may do on its own:
| Level | Agent may | Human |
|---|---|---|
| 0. Suggest | Draft a plan or answer only | Executes everything |
| 1. Read | Use read-only tools | Approves every write |
| 2. Act with approval | Prepare actions; execute after per-action confirmation | Reviews each consequential action |
| 3. Act within policy | Execute actions inside pre-approved limits (refunds under ₹2,000, edits on a branch) | Reviews exceptions and samples |
| 4. Autonomous | Execute end to end | Monitors outcomes, audits |
Approval UX matters: show exactly what will happen (diff, recipients, amounts), allow edit-and-approve, time out safely to "no", and log the decision. Irreversible or high-impact actions (payments, deletions, external communications, permission changes, production deploys) should require approval regardless of level.
Composable workflow patterns
Many "agentic" systems are better built from a few simple patterns (as described in Anthropic's "Building effective agents", 2024):
| Pattern | Use when |
|---|---|
| Prompt chaining | Task splits into fixed steps (outline → draft → check); add programmatic gates between steps |
| Routing | Inputs fall into categories best handled by specialised prompts, tools or models (chapter 158's routing) |
| Parallelisation | Independent sub-tasks (sectioning) or multiple attempts to vote (self-consistency, guardrail checks in parallel with the main call) |
| Orchestrator–workers | Sub-tasks can't be predicted in advance (which files to change; which sources to research) |
| Evaluator–optimiser | Clear evaluation criteria and iterative refinement improves results (translation, code that must pass tests) |
| Autonomous agent | Open-ended problems with environmental feedback; trust built through evaluation and guardrails |
Multi-agent systems
Several LLM "agents" with different roles, prompts or tools cooperating: a planner and executors; a researcher, a writer and a critic; parallel sub-agents exploring different leads with separate context windows.
Benefits: parallelism (breadth-first research), context isolation (each sub-agent keeps a clean, focused context and returns a summary), specialisation (different tools, prompts or models). Costs: many more tokens (multi-agent research systems can use several times the tokens of single-agent runs), coordination failures (duplicated work, conflicting edits, lost information in hand-offs), and harder debugging. Use them when sub-tasks are genuinely parallel and separable; a single well-equipped agent is often better for tightly coupled work like editing one codebase.
Case studies
Coding agents (Claude Code, Codex-style agents, Cursor/Copilot agents and others): tools to read and search files, edit them, run commands, tests and linters, plus git. Strengths come from environmental feedback: tests and compilers tell the agent whether a change works. Practices: work in a branch or worktree, run tests after edits, keep changes small and reviewable, provide repository instructions (a project memory file such as CLAUDE.md or AGENTS.md), and require human review before merging.
Research agents: iterative search, reading, note-taking and synthesis with citations; often orchestrator–workers with parallel sub-agents; evaluated on factual accuracy, citation correctness and coverage.
Customer-operations agents: read tools broadly, write tools narrowly (refunds within policy), escalation to humans, strict authorisation and audit.
Failure modes
| Failure | Mitigation |
|---|---|
| Loops (same call repeatedly, oscillating between approaches) | Repeated-action detection, step budgets, require changed approach after errors |
| Goal drift (pursuing a tangent) | Restate goal and plan each turn; checklists; evaluator checks against success criteria |
| Compounding errors (early mistake poisons later steps) | Verification after key steps; ground truth from tools; replanning |
| Premature success claims | Require evidence (tests, API confirmations) before "done" |
| Tool misuse (wrong tool or arguments) | Better tool descriptions; fewer, clearer tools; validation errors with guidance |
| Context overflow | Compaction, notes, external memory, sub-agents |
| Cost and latency blow-ups | Token/time/cost budgets, cheaper models for sub-steps, caching |
| Unsafe actions (from injection or misunderstanding) | Least privilege, approval gates, sandboxes, policy checks (chapter 176) |
Design principles
- Simplest thing that works: workflow before agent; one agent before many.
- Invest in the agent–computer interface: tool design and documentation matter as much as prompts.
- Make progress observable: plans, to-do lists, intermediate artefacts, traces (chapter 177).
- Bound everything: steps, tokens, time, money, permissions.
- Verify with the environment, not with the model's confidence.
- Keep humans in the loop where stakes are high, and make approval easy and informative.
- Evaluate trajectories and outcomes on realistic task suites before widening autonomy (chapter 175).
Lab: the arithmetic of agent reliability
Substitute, stated plainly: this lab is a simulation. Running real agents needs a capable model, which the lab machine doesn't have, and the questions here (how per-step reliability compounds, what detection buys, what guards cost) are about probabilities, which simulation answers precisely. NumPy Monte Carlo, 100,000 runs per row (20,000 in Experiment 3).
Experiment 1: compounding
Chance that all n steps succeed when each succeeds with probability p:
| p | n = 1 | 5 | 10 | 20 | 50 |
|---|---|---|---|---|---|
| 0.90 | 0.900 | 0.590 | 0.349 | 0.122 | 0.005 |
| 0.95 | 0.950 | 0.774 | 0.599 | 0.358 | 0.077 |
| 0.99 | 0.990 | 0.951 | 0.904 | 0.818 | 0.605 |
A model that's "right 95% of the time" is a poor 50-step agent. Two levers: fewer steps (better tools, workflows for the predictable parts) and higher effective per-step reliability.
Experiment 2: detection and retries
20 steps, p = 0.95 per attempt. A failed step is detected with probability d (by a test, a validator or a tool error) and retried up to r times; an undetected failure silently spoils the run.
| Detection | Retries | Task success | Model calls per run |
|---|---|---|---|
| 0% | 0 | 0.357 | 20.0 |
| 50% | 1 | 0.585 | 20.5 |
| 90% | 1 | 0.864 | 20.9 |
| 90% | 3 | 0.901 | 20.9 |
| 100% | 3 | 1.000 | 21.1 |
Going from one retry to three barely helped; raising detection from 50% to 90% helped enormously, for about 2% more calls. This is why coding agents run tests, why tool errors should be explicit, and why verifiable environments (compilers, type checkers, schema validators, unit tests) make agents work. Invest in making failures visible.
Experiment 3: loop guards
Each step finishes the task with probability 0.08; with probability 0.03 the agent falls into a loop, repeating the same action; runs are cut off at 2,000 steps.
| Guard | Tasks completed | Mean steps | p99 steps | Max steps |
|---|---|---|---|---|
| none | 0.729 | 549.1 | 2,001 | 2,001 |
| max 25 steps | 0.688 | 13.1 | 25 | 25 |
| stop after 3 identical actions | 0.728 | 10.2 | 42 | 98 |
| both | 0.688 | 9.6 | 25 | 25 |
- With no guard, 27% of runs looped until the hard cap, so the mean cost was 50× the typical cost: one stuck agent can burn a day's budget.
- The repeat detector caught loops without hurting legitimate runs (0.728 completed); the step budget also cut off some long legitimate runs (0.688). Real agents loop in less obvious ways (alternating between two actions, rephrasing the same search), so production guards combine budgets of steps, tokens, money and time with similarity-based repeat detection, and report "stopped: budget" as a distinct outcome rather than a silent failure.
Try it yourself
- Add a planner that reduces the number of steps by 30% but has p = 0.93; does the task success go up or down?
- Model a reviewer step that catches 70% of undetected errors at the end, with one full retry of the task.
- Simulate a two-action alternating loop and design a detector for it.
- With any capable model and a sandbox, run 20 real tasks with and without unit tests visible to the agent, and compare success.
Revision sheet: agents
Key ideas
- Spectrum: workflow (code-defined steps) → LLM workflow (model inside fixed steps) → agent (model chooses steps). Use the least autonomy that works.
- Agent loop: observe → decide (reason) → act (tool) → observe, until a stop condition; ReAct interleaves reasoning and acting.
- Planning: plan-and-execute, re-planning on failure, task decomposition; reflection/critique loops when feedback is checkable.
- State: messages, scratchpads, files, external state; keep observations concise.
- Environments: sandboxes, browsers, code execution, with least privilege.
- Autonomy levels and human approval for consequential actions.
- Patterns: prompt chaining, routing, parallelisation, orchestrator–workers, evaluator–optimiser; multi-agent only when it pays for its coordination cost.
- Failure modes: compounding errors, loops, tool misuse, context overload, goal drift, unsafe actions, cost blow-ups.
Numbers to remember
- p^n: 0.95²⁰ = 0.36; 0.99⁵⁰ = 0.61.
- Simulation: 90% failure detection + 1 retry → 0.86 success on 20 steps (from 0.36).
- Simulation: no loop guard → mean 549 steps; guards → max 25.
Pitfalls
- Building an agent where a workflow would do.
- Silent tool failures the agent can't see.
- No budgets on steps, tokens, money and time.
- Multi-agent designs that multiply calls without improving results.
- Granting broad credentials to a sandbox "for convenience".
Glossary
- Agent: a system in which a model directs its own sequence of actions.
- ReAct: reason + act prompting pattern.
- Orchestrator–workers: a lead model delegating sub-tasks to others.
- Evaluator–optimiser: generate, critique, revise loop.
- Autonomy level: how much an agent may do without human approval.