Agents I: The Loop
The function-calling loop, tool design, ReAct, memory, MCP and A2A.
An agent is a language model that chooses its own next step. That one property separates it from everything in Parts 3 and 4, where you decided the steps and the model filled them in. It is why agents can handle tasks whose shape nobody knew in advance, and why they fail in ways a fixed pipeline cannot.
This chapter covers the loop itself: what it is, what the model needs in order to choose well, how its reliability behaves as tasks get longer, and when to build one at all. Chapter 19 covers the engineering that surrounds the loop.
18.1What an agent is
A function-calling loop with a budget.
Take the function-calling exchange from section 11.5 and put it inside a loop.
messages = [system_prompt, user_task]
for step in range(MAX_STEPS): # the budget is part of the design
reply = model(messages, tools=TOOLS)
if not reply.tool_calls:
return reply.text # the model decided it was done
for call in reply.tool_calls: # there may be several
result = execute(call) # your code, your permissions
messages.append(tool_result(call, result))
return hand_off("budget exhausted") # the exit that demos leave outThat is the whole of it. The model chooses an action, your code carries it out, the result goes back into the transcript, and the cycle repeats until the model answers or the budget runs out.
The new property is that control flow is decided at run time by the model. In a pipeline (section 13.6) you wire the boxes. In an agent, the next step depends on what the last result said. Two mechanical facts follow at once.
- The transcript is the agent’s only state. Every step re-reads the whole history, so long runs consume tokens at a growing rate and each step starts a little slower than the last. Prompt caching (section 11.6) is what makes multi-step loops affordable, since each step extends a prefix that is already cached. Chapter 20 is about managing that transcript.
- The loop does not care what the tools are. With a search tool it is the agentic retrieval of section 16.6. With file and shell tools it is a coding agent.
Common take“An agent is an autonomous AI that can do tasks for you.”
Sharper take“An agent is a model choosing tool calls in a loop, with my code executing them and a budget on the loop. Everything interesting about agents follows from the model deciding the control flow.”
18.2Tool design
You are writing an API for a client that reads the documentation and cannot read your mind.
The model picks tools from their names, descriptions and schemas, and from nothing else. The quality of those three things is the quality of the agent.
| Principle | Weak | Strong | Why |
|---|---|---|---|
| Shaped like a task, not like an endpoint | db_query(sql), http_get(url) | find_customer(email), get_order_status(order_id) | Each tool should be one decision the model is good at. Raw SQL and URLs invite invented syntax and injection |
| The description is a routing contract | “Gets data.” | “Fetch an order’s status by ID. Use when the user asks where an order is. Not for refunds; use start_refund.” | The model routes by reading it. Say when to use the tool and when not to |
| Errors address the model | KeyError: 'cust_id' | “No customer with that email. Try find_customer_by_name, or ask the user to confirm it.” | An error goes back into the loop. A good one is an instruction; a stack trace is noise |
| Results are curated | 40 KB of raw JSON | The six fields that matter, formatted | Results are prompt tokens and distractors (section 15.7) |
| Few and distinct | 42 overlapping tools | 5 to 12 per agent, with no overlap | Every definition is sent on every call, and overlap causes wrong picks |
A useful test from Anthropic’s guidance: if a person could not say for certain which tool to use in a given situation, the model cannot either.
One failure pattern is worth naming. A team exposes a general execute_sql tool “for flexibility”. Some weeks later the agent, trying to resolve a discrepancy it has misread, runs an UPDATE. The mature design is task-shaped tools that only read, plus a separate path for writes that requires confirmation (section 19.4).
Common take“I exposed our REST API to the agent, one tool per endpoint.”
Sharper take“I designed the tool set as a public API for a very literal new engineer: a few task-shaped tools, descriptions that say when not to use each one, and errors that say what to try next.”
18.3ReAct
Reasoning between actions, chain of thought given hands.
Thought: The user wants Acme's refund total for the second quarter. I need their ID first.
Action: find_customer(email="ops@acme.com")
Observation: {id: "C-8812", name: "Acme GmbH"}
Thought: Now their refunds, limited to that quarter.
Action: list_refunds(customer_id="C-8812", from="2026-04-01", to="2026-06-30")
Observation: [3 refunds, total 4,120]
Thought: I have what I need.
Answer: Acme's refunds for the quarter total 4,120 across 3 refunds.The pattern is called ReAct, for reason and act. The thought before each action is the serial computation of section 13.5, bought between tool calls: the model conditions its next choice on reasoning it has written about the last result. Compared with acting immediately, this gives fewer impulsive tool picks and a trace that can be debugged. When a run goes wrong, the thoughts show where the belief went wrong.
Three points keep it in proportion.
- Thoughts are output tokens, paid for at every step.
- A thought is plausible narration, not a log. Models sometimes act well after a wrong thought, and the reverse (section 10.9).
- Current models do this unprompted. Tool-use training built the rhythm in, and reasoning models think between tool calls by design (section 10.8). ReAct is now less a technique you add than the default behavior.
Common take“We use the ReAct framework for our agent.”
Sharper take“ReAct is the name for reasoning before each tool call. Models trained for tool use already do it. I add an explicit reasoning step only when traces show the model grabbing tools without thinking.”
18.4Plan or react
Decide up front, or decide as you go.
| Reactive | Plan, then execute | |
|---|---|---|
| How it works | Decide each step after seeing the last result | A strong model writes a list of steps; a cheaper model or plain code carries them out, replanning only on a surprise |
| Adaptivity | High: any result can change direction | Lower: the plan is sticky |
| Cost and speed | The strong model reasons at every step | The strong model reasons once |
| Typical failure | Goal drift: twelve steps in, it is solving an interesting side problem | Brittleness: step 2 invalidates steps 3 to 5 and execution marches on |
| Auditability | Low: the path emerges | High: a person can read and approve the plan first |
| Fits | Short, exploratory tasks: research, debugging | Long tasks of known shape: reports, migrations |
For long tasks the usual production design is a hybrid: plan first, react within each step, replan on a surprise, and keep the plan itself in the transcript so that progress survives.
Common take“A good agent figures out the plan as it goes.”
Sharper take“If the task’s shape is known, I plan first: it’s cheaper and a person can review the plan. If the shape is discovered along the way, I let it react. For long tasks I do both, with the plan kept in the transcript.”
18.5Memory
A context budget and a database, and nothing more mysterious.
“Agent memory” is two engineering problems you have already met.
Short-term memory is the transcript. Thirty steps at about 800 tokens each is 24,000 tokens and rising. What stays in it is a matter of policy:
- drop or shorten stale results, such as search results from step 3 that have already been used;
- summarize finished phases: “steps 1 to 9: found the customer, pulled the quarter’s data”;
- keep the goal, the plan and the constraints pinned at the start or the end, never the middle;
- curate tool results at the source (section 18.2), which is the cheapest policy of all.
Long-term memory is a store outside the loop whose contents are retrieved back in. That is the retrieval of Chapter 15, pointed at the agent’s own history: past runs and conversations, or facts and preferences it has learned. The hard part is the write path: deciding what is worth keeping.
Two failure patterns come with memory. An agent that searches again for something it found five steps ago has had that result cut or summarized away, which is a policy bug and not stupidity; look at what the context contained at the failing step. And whatever is written to long-term memory is fed back in later as trusted context, so one invented “fact” becomes a recurring wrong belief, and one injected instruction becomes a standing exploit (Chapter 26).
Common take“We’ll add a memory system so the agent learns over time.”
Sharper take“Memory is context management inside a run and retrieval between runs. I design what is forgotten before what is remembered, because storing without curating just pollutes the context later.”
18.6Errors compound
Reliability is an exponent on the number of steps.
Suppose each step goes right 95% of the time: the right tool, the right arguments, a sane reading of the result. That is a good step. A task that needs n of them succeeds with probability 0.95n.
Errors do something worse than end a run. They corrupt it. A wrong result enters the transcript as fact, and every later step reasons from it: one invented identifier can flow through four more tool calls before anyone sees an answer.
The figure shows the three levers.
- Shorten the chain. One task-shaped tool in place of three primitive calls, plans that batch work, retrieval that lands on the first try. Fewer steps is the cheapest reliability there is.
- Raise the per-step rate. Schema-enforced arguments, retries with the error fed back, curated results.
- Check as you go. Verify results against ground truth mid-run, so that an error is caught at the step where it happened and not at the end.
Chapter 19 builds each of these into the system around the loop.
Common take“It works in the demo, so it will work on longer tasks too.”
Sharper take“Reliability is per-step accuracy raised to the number of steps. A demo is five steps. At twenty, the same agent succeeds about a third of the time, unless I shorten the chain or check each step.”
18.7MCP
A standard plug between agents and tools.
Without a standard, connecting M agent applications to N tools means M × N custom integrations. The Model Context Protocol (MCP) replaces them with one interface. A tool provider ships an MCP server that exposes tools, resources and prompts. Any MCP client, whether a chat application, an editor or your own agent, can discover and call them the same way. The tool schemas arrive at run time.
Anthropic released MCP in late 2024, and in December 2025 handed it to a foundation under the Linux Foundation, alongside contributions from OpenAI and Block. It is now supported by the major model providers and development tools, which is what makes it worth building against.
Be clear about what it is. MCP standardizes plumbing: discovery, schemas, transport. It adds no intelligence, since the model still chooses by reading descriptions, and a badly described MCP tool is still a badly described tool. And it is not a security layer. Because tools are discovered at run time, an agent’s capabilities can change without a deployment on your side. A third-party server’s descriptions are untrusted text entering your prompt, and each server carries its own credentials and its own blast radius.
The production posture: allow only named servers and pinned versions, review their descriptions as you would a dependency, and put MCP tools behind the same sandbox and confirmation rules as your own (sections 19.4 and 19.6).
Common take“We added MCP, so the agent can now use any tool safely.”
Sharper take“MCP standardizes the plug, not the judgment. Integration got cheap. Choosing which servers to trust, reviewing their descriptions and limiting what they can do is still my job.”
18.8A2A
A protocol for other parties’ agents, which earns its place only at trust boundaries.
MCP gives an agent hands. The Agent2Agent protocol (A2A) gives it colleagues: agents that are run by someone else, opaque to you, and not automatically trusted. An agent publishes a card describing what it can do. Other agents send it tasks, which move through states such as submitted, working, input needed and completed, and receive results back. Internals are deliberately hidden; only the task-level contract is shared.
The rule for when to use it is strict. Inside one system, you do not need a network protocol to talk to yourself. A “planner agent” handing work to a “coder agent” in your own application is your code calling your code. A typed function call or a queue message is simpler, faster, easier to debug, and transactional. At a real boundary, such as another company’s agent, a marketplace, or a separately governed division, you do need discovery, a task lifecycle and mutual distrust, and that is what a protocol is for.
A2A began at Google in 2025, reached version 1.0 in 2026, and now sits under the same foundation as MCP. It is much less widely deployed than MCP. And the security consequence follows directly: a peer agent is an untrusted counterparty, and what it sends back can carry instructions aimed at your model.
Common take“Our agents communicate with each other over A2A.”
Sharper take“MCP is for tools and A2A is for other organizations’ agents. Inside my own system, agents ‘talking’ are function calls, and I keep them as function calls.”
18.9Archetypes and skills
Coding agents, computer-use agents, background agents and skills.
Four shapes of agent recur often enough to know by name.
| Archetype | Tools | Why it works, or where it strains |
|---|---|---|
| Coding agent | Read and edit files, run commands and tests | The most successful agents so far, for a structural reason: the environment is text, and tests and compilers act as a checker on every step (section 10.4) |
| Computer-use agent | Screenshots, mouse and keyboard | Works on software with no API. Strains on pointing accuracy and on cost, at one screenshot per step (section 12.8) |
| Background agent | Any, run without a person watching | Works for minutes or hours and reports back, for example by opening a pull request. Needs durable execution and review of results (section 19.8) |
| Research agent | Search, fetch, read | The agentic retrieval of section 16.6, often with sub-agents (section 20.7) |
A fifth idea cuts across all of them. A skill is a packaged set of instructions, optionally with scripts and reference files, that an agent loads only when a task calls for it. Only a short description of each skill sits in the context all the time. The full instructions are read when the model decides the skill is relevant. This lets one agent carry many specialized procedures without paying for them on every step. Chapter 20 returns to the principle, which is called progressive disclosure.
Common take“Coding agents work, so agents for every domain are about to work as well.”
Sharper take“Coding agents work because code has a built-in checker: tests pass or they don’t. When I assess a new domain for agents, the first thing I ask is what plays the role of the test suite.”
18.10Workflow first
Build an agent only when the task’s shape cannot be known in advance.
| Signal | Build a workflow: a fixed pipeline | Build an agent: control flow at run time |
|---|---|---|
| Shape of the task | Known steps that can be listed | Discovered along the way |
| Branching | A handful of cases: a router | Combinatorial or unforeseeable |
| Reliability | High: a fixed path with a test per stage | Tolerant of variance, or gated by verification |
| Cost and latency | Tight budgets | Research-grade budgets |
| Examples | Invoice extraction, support triage, report generation | Debugging, open-ended research, “work out why this happened” |
The doctrine: a fixed workflow behind a router is the right default. An agent is what you build when the structure of the task truly cannot be known beforehand, because the exponent of section 18.6 taxes every step of freedom you grant.
Most shipped “agents” reflect this. They are mostly workflow, with a bounded loop in one or two places: an agentic search branch behind a router, or a tool loop capped at five steps inside one stage of a pipeline. That is the mature design and no compromise. Each loop has been earned by a failure the workflow could not handle.
Common take“We’re building this as an agent because agents are more capable.”
Sharper take“I start with a workflow and add a loop where the workflow demonstrably can’t cope. Every step the model gets to choose costs reliability, so I make each one earn its place.”
Key takeaways
- An agent is a model choosing tool calls in a loop, with your code executing them and a budget on the loop.
- Tools are an API for a very literal reader: task-shaped, described with when not to use them, with errors that say what to try next.
- ReAct is reasoning before each action. Current models do it by default.
- Plan when the task’s shape is known; react when it is discovered; for long tasks, plan and keep the plan in the transcript.
- Memory is context management within a run and retrieval between runs. Design forgetting first.
- Errors compound: 95% per step is 36% over 20 steps. Halving the steps gives 60%; checking each step gives 79%.
- MCP standardizes the connection to tools. It adds no judgment and no security.
- A2A is for agents across a trust boundary. Inside your own system, use function calls.
- Coding agents lead because tests and compilers check every step.
- Default to a workflow, and add a loop only where the task’s shape cannot be known in advance.
Check your understanding
-
Your support agent has 38 tools, mirrored one-to-one from your internal API. It often picks the wrong one, and each request sends about 11,000 tokens of tool definitions. Propose a redesign and say how you would measure whether it worked.
Answer outline
Replace endpoint-shaped tools with a small set of task-shaped ones, each a single decision such as finding a customer or checking an order, with descriptions that say when to use it and when to use a sibling instead. Where the work divides naturally, put a router in front and give each route its own handful of tools. Curate what tools return, and write errors as instructions. Measure tool-selection accuracy on labeled requests, task success, steps per task and input tokens per request, before and after.
-
An agent completes eight-step tasks about 70% of the time. Product wants it to handle twenty-step tasks. Estimate what will happen if nothing changes, and name three changes with the mechanism of each.
Answer outline
Seventy percent over eight steps implies about 95.6% per step, so twenty steps would succeed about 41% of the time. Changes: shorten the chain, with tools that do more per call and plans that batch work, since success depends on the number of steps; raise the per-step rate, with schema-enforced arguments and retries that include the error; and verify results as the run proceeds, so that errors are caught where they occur and do not corrupt later steps. Then ask whether the twenty-step task should be an agent at all, or a workflow with one or two bounded loops.
-
An architect proposes that the planner, researcher and writer components of your application communicate over A2A “to be future-proof”, with every tool behind MCP. Which parts of that do you accept, and why?
Answer outline
MCP for tools is reasonable where it saves integration work or where tools are shared across applications, provided servers are allow-listed, versions pinned and their descriptions reviewed, since those enter the prompt. A2A between components of one application is not: both ends have the same owner, so a function call or a queue is simpler, faster, transactional and far easier to debug. A2A earns its cost when the other agent belongs to another organization and discovery, a task lifecycle and distrust are real requirements. Being future-proof is not a requirement.
Further reading
- Anthropic, “Building effective agents”: the case for workflows first, and the common workflow patterns.
- Maarten Grootendorst and Jay Alammar, An Illustrated Guide to AI Agents (O’Reilly, 2026), or Michael Albada, Building Applications with AI Agents (O’Reilly, 2025).
- Yao et al. (2022), “ReAct: Synergizing Reasoning and Acting in Language Models”: the paper behind section 18.3.
- The Model Context Protocol and A2A specifications: short, and the clearest statement of what each protocol does and does not cover.