Free chapter, full text

Chapter 1: What an agent actually is

A definition precise enough to design, budget and argue with.

What an agent actually is

PDF, chapters 1 and 2 (PDF, 1184 KB)

Free in full. The figures and the end-of-chapter exercises are in the PDF.

Ask five people what an "agent" is and you get five answers, each implying a different budget, risk profile and team.

Four parts and a harness

An agent is a model that runs in a loop, choosing tools, with a managed context, inside a harness. Strip any of the four parts and you have something else. Strip the harness and you have a demo.

The model

The model is the decision maker: on each turn it reads the context and returns a final answer or a tool call. It does not "remember" or "act"; your code does, when the model asks. When a run fails, find the first step in its trace that went off course and ask, in order:

  1. Was the needed information in the context? If not, context failure: fix retrieval or context management.
  2. Was it there, but the model chose the wrong tool or arguments? Model failure: fix instructions, tool descriptions or model choice, and add the case to your eval set.
  3. Was the call sensible, but the tool misbehaved? Software failure: fix the code, add a unit test.

This needs every model and tool call traced with its inputs.

Choose the model as a pair: model and reasoning effort. Launch tables report maximum effort; shipped defaults are often lower (Chapter 19 has a dated example). Pin both values in config and compare pairs on cost per successful task.

The tools

A tool is a name, a description, a parameter schema and a function the model can ask you to run. Most risk lives here: a read-only search and a "refund customer" tool look alike in a schema and are not the same kind of object (Chapter 3).

The loop

Send the context to the model; if it returns a tool call, validate it, run it, append the result; if it returns a final answer or a stop condition is hit, exit; otherwise repeat. This is usually called ReAct, after the 2022 paper, and it is the default loop in most SDKs.

The context

The context is everything the model sees on a turn: instructions, tool definitions, retrieved documents, history, tool results, memory. Recall degrades as it grows, a pattern Chroma's research named context rot (Chroma, Jul 2025); managing it is what Anthropic calls context engineering (Anthropic, 2025-09-29), so a loop that appends every result forever gets worse as it runs. Memory is not a fifth part: it is a source of context, read in by the loop and written through tools (Chapter 5).

The harness

The harness is the production wrapper, with four jobs:

  • Budget: caps on steps, tokens, money and wall-clock time.
  • Guardrails: allowed tools, tools that need human approval, blocked inputs and outputs.
  • State: checkpoints so a run can resume after a crash, and durable waits for approval.
  • Telemetry: traces of every model and tool call, the data your evals run on.

Framework defaults are a start, not a design (Chapter 6). The whole thing in one sketch; call_model and run_tool are placeholders for your model client and tool registry. This is the shape; Chapter 8 has the version to copy.

import time

MAX_STEPS, MAX_COST_USD, TIMEOUT_S = 10, 0.50, 120

def run_agent(task: str, tools: dict, ctx: list) -> dict:
    ctx.append({"role": "user", "content": task})
    cost, start = 0.0, time.monotonic()
    for step in range(MAX_STEPS):
        reply, call_cost = call_model(ctx, tools)
        cost += call_cost
        ctx.append(reply.as_message())
        trace("model_call", step=step, cost=call_cost)
        # done only on a validated submit_* call (Chapter 8)
        if reply.submit:
            return {"status": "done", "output": reply.submit}
        if cost > MAX_COST_USD:
            return {"status": "handoff", "reason": "budget"}
        if time.monotonic() - start > TIMEOUT_S:
            return {"status": "handoff", "reason": "timeout"}
        if not reply.tool_calls:  # free text is not done
            return {"status": "handoff", "reason": "no submit"}
        # approval pauses the whole turn (Chapter 8)
        pending = [c for c in reply.tool_calls
                   if needs_approval(tools, c)]
        if pending:
            checkpoint(ctx)
            return {"status": "awaiting_human", "pending": pending}
        for call in reply.tool_calls:
            tool = tools.get(call.name)
            if tool is None:
                ctx.append(tool_error(call.id, "unknown tool"))
                continue
            ctx.append(safe_run(tool, call))
        checkpoint(ctx)
    return {"status": "handoff", "reason": "step cap"}

def safe_run(tool, call):
    try:
        return tool_result(call.id, run_tool(tool, call.args))
    except Exception as e:
        return tool_error(call.id, f"{type(e).__name__}: {e}")

A run ends in one of three statuses: done, a handoff with its reason (budget, timeout, no submit, step cap), or awaiting a human. A demo has one. A production agent treats the other two as normal outcomes. On "awaiting human", persist the checkpoint and the pending calls under a run ID; for long waits, use durable execution rather than a held worker (Chapter 7).

[!ANTI] The harness as an afterthought The common pilot has no step cap, no cost cap and no traces, "until launch". By then prompts were tuned against unbounded runs, and a 10-step cap breaks tasks that quietly took 25. Put the harness in the first commit with generous numbers, and tighten them with data.

Choosing the first numbers

  1. Start generous: step cap about three times what a good run needs.
  2. Run your eval set: 30 to 50 real tasks; record steps, cost, outcome.
  3. Set the step cap from successful runs only, just above the slowest (around the 95th percentile). Longer runs are usually loops or tasks for a human.
  4. Derive the cost cap from value: one attempt must cost well below what a success is worth (Chapter 14).
  5. Set the timeout from the caller: seconds for chat, minutes for a background job.

A per-run cap stops one run, not a bug that triggers thousands; add a daily spend limit and per-user rate limits too (Chapters 8 and 10).

The autonomy ladder

Each step up adds capability, and also cost, latency, variance and risk.

Level Name Who decides the next step Model calls per task Example Main risk
L0 Single call Your code 1 Classify a ticket Wrong answer on one input
L1 Chain Your code, fixed sequence Fixed Extract, draft, check tone Errors compound
L2 Router / workflow Your code, model picks branches Small, known per branch Route a ticket to billing, tech or sales Misrouting
L3 Tool-using agent, bounded loop The model, inside your caps Variable, up to the cap Investigate a ticket with search and CRM, max 10 steps Wrong actions, loops, cost spikes
L4 Multi-agent Several models, delegating Sum of every loop Orchestrator splits research across workers Coordination failures
L5 Long-running autonomous The model, over hours or days Open-ended Agent that works a backlog Drift, unbounded spend

Up to L2 you can price a task before you ship. From L3 you only know the ceiling, and because each step re-sends the growing context, cost rises faster than the step count.

  • Climb one rung at a time. A well-built L2 router beats a fragile L3 agent on almost every metric finance cares about.
  • L2 to L3 is the big jump. Below L3 your code decides the control flow and you can draw it. From L3 the model decides and you can only bound it: you need trajectory evals, and the harness stops being optional.
  • L4 and L5 multiply everything: calls, context and hiding places for errors (Chapter 2).

[!DECIDE] Which rung to start on Start at the lowest level that can plausibly do the task. Steps you can write down in advance: L1 or L2. Steps that depend on what you discover: L3 with a step cap you can justify. Never start at L4 or L5; let L3's failures tell you what extra agents must fix.

Where real deployments sit

The most useful public evidence as of late 2026 is the UC Berkeley-led study "Measuring Agents in Production" (MAP): 20 case studies plus a survey of 306 practitioners, 86 of whom reported on agents in production or pilot (arXiv).

  • Short leashes (survey). 68% of deployed agents run 10 steps or fewer before a human intervenes; 47% fewer than 5.
  • Humans judge (survey, 31 respondents to this question). 74% depend primarily on human evaluation; 52% use LLM-as-judge.
  • Custom code (case studies). 17 of 20 teams built on direct model API calls, while 61% of survey respondents use a framework.
  • Weak measurement (case studies). 75% evaluate without formal benchmark sets.

Most production agents are L2 workflows or tightly capped L3 agents with a human close by. Only one of the 20 case studies let its agent explore without constraints, inside a sandbox with strict CI checks. If a first project promises L5, ask for the L3 version with a step cap, a review queue and a date for eval results.

Agent, automation, chatbot, copilot: vocabulary that ends meetings

The test is who decides the next step and who acts.

Term Who decides the next step Who acts Example
Automation Your code (rules or flowchart) Your code A workflow with an LLM step that classifies emails
Chatbot The user, turn by turn The model answers; nothing else happens FAQ assistant over documentation
Copilot The user, with model suggestions The user accepts or rejects A draft reply the support agent edits
Agent The model, within bounds The model, through tools, with approvals Investigates a ticket and proposes a resolution
  • An automation with an LLM call inside is still an automation. Calling it an agent raises expectations and lowers rigor.
  • A chatbot becomes an agent the moment it can call tools that change something, or chain tool calls on its own.
  • A copilot is often the best first version of an agent: every accept or reject becomes eval data.
  • "Autonomous" is a rung, not a type. Say "L3 with approval on writes". An "AI agent" node in n8n or Zapier that loops over tools is L3, whatever the canvas looks like (Chapter 13).

Composite case: the assistant that became an agent

A mid-size software company built an internal documentation assistant: fixed retrieval, cited answers, L1. Questions like "why did this customer's import fail yesterday" led the team to add tools one at a time: a second document source, an ownership lookup, a read-only pipeline-status query. After the third, the system chose which tools to call and in which order.

Nobody had decided to build an agent; the team had one anyway, with the harness of a chatbot. A question that triggered a long chain of rephrased searches was slow, expensive and invisible until each step was traced. The fixes were a step cap, a per-question budget, traced tool calls, read-only credentials, and an eval set from questions that had gone wrong.

[!PROD] Notice the moment you cross L2 The move from chatbot to agent rarely happens in a design review; it happens one tool at a time. Make the second tool added to any assistant trigger a harness review: caps, tracing, credential scope, eval set.

Checklist

  • [ ] Every AI feature has its autonomy level (L0 to L5) written down.
  • [ ] Every agent has a step cap, cost cap and timeout in config.
  • [ ] Every agent handles three statuses: done, handoff with a reason, awaiting human.
  • [ ] Every model call and tool call is traced, not only the final answer.
  • [ ] Write tools require approval or have a documented reason not to.
  • [ ] Adding a tool to an existing assistant triggers a harness review.