08D.1 One Agent or Several: Roles and the Two Basic Patterns
You already know what one agent is: a model with tools in a loop (08A.2). This lesson asks the next beginner question: when should a second agent exist at all? You will learn the small set of roles agents usually play, the two basic ways to connect agents (an orchestrator with workers, and an agent used as a tool), what one agent must hand to the next so the work does not fall apart, and the three problems that show up first in every multi-agent system: loops, cost growth and one wrong answer spreading. Every idea comes with a short program that runs with scripted models, so you can see each failure with real output and no API key. The next lesson, 08D.2, builds a full two-agent project and evaluates it against a single agent.
What you'll learn
- A simple rule for single agent vs several agents: start with one agent, and add another only when one clearly cannot do the job, plus the short list of reasons that really count
- Four roles an agent can play (planner, researcher, writer, reviewer), and the test for whether a role deserves its own agent
- The two basic patterns: an orchestrator with workers, and an agent used as a tool, with runnable code for both and a table for choosing
- The handoff contract: what one agent passes to the next (the task, the context it needs and the answer format expected), and a checker that enforces it
- The three common problems, each reproduced in code: agents looping, cost growing quickly and one wrong answer spreading to the next agent, with the first fix for each
- How to evaluate a multi-agent change with the Module 10A agent metrics (the full hands-on is 08D.2)
What you don't need
- API keys. Every program in this lesson uses scripted fake models and plain Python functions. No network, no Docker, no services. The provider sketch in Part 3 is illustrative and not run.
- The full catalogue of ten architectures, the research evidence or A2A. 08D.3 has those. This lesson is the short, beginner path into them.
- Any framework. LangGraph, the OpenAI Agents SDK and the Claude Agent SDK appear only as pointers to where the same ideas are packaged.
Setup
Python 3.11 or newer and nothing else. The programs use only the standard library. As of 1 December 2026 there is nothing to install, and nothing in this lesson needs a key.
mkdir multi-agent-basics && cd multi-agent-basics
python3 --version # 3.11 or newerSave each program under the name in its first comment and run it with python3 <file>.
What you must be able to do after this lesson#
- Decide whether a task needs one agent or several by naming the test a second agent passes
- Describe the four basic roles (planner, researcher, writer, reviewer) and what tools and context each should have
- Build an orchestrator with workers and an agent-as-a-tool, and say who decides the order in each
- Write a handoff contract (task, context, expected answer format) and check the reply in code
- Reproduce and fix three multi-agent problems: agents looping, cost growing and one wrong answer spreading
- Choose the metrics and a pass rule to judge a split before running it
Why this matters for an AI engineer#
"Let's use a team of agents" is one of the most common sentences in AI project meetings, and one of the most expensive to say. A second agent means a second prompt to write, a second context window to pay for, a second place for a bug to hide, and a handoff that can lose information. Sometimes that price is worth paying. Often it is not. An engineer who can say which case they are in, and who knows the three failure modes by sight, saves the team months.
| You'll hear... | You'll understand it after... |
|---|---|
| "Do we really need more than one agent?" | Part 1 |
| "Give it a planner and a reviewer." | Part 2: Roles |
| "The orchestrator calls the workers." / "Wrap it as a tool." | Part 3: The two basic patterns |
| "The researcher's output did not match what the writer expected." | Part 4: What one agent hands to the next |
| "The agents keep passing it back and forth." | 5.1 Looping |
| "This run cost ten times a normal one." | 5.2 Cost growth |
| "The reviewer approved a wrong answer." | 5.3 One wrong answer spreading |
| "Is the two-agent version actually better?" | Part 6: Evaluate it |
Part 1: Single agent or several#
1.1 The rule: start with one#
Start with one agent and add a second only when you can name what one agent clearly cannot do. "It would be cleaner" is not a reason. This is the rule of 08A.9 applied to agent count: use the simplest thing that works. 08D.3, 1.2 lists the four taxes (cost, errors, coordination, debugging) every added agent pays, and Part 5 lets you meet each tax in code. Before splitting, try a better prompt, a better tool and a plain workflow first. An agent here means a model call in a loop with tools, with its own prompt and its own context: giving one agent two tools is not "two agents".
1.2 Reasons that really count#
08D.3, 1.3 has the full table. The short version is four tests, and a second agent is justified only if it passes at least one:
- Different tools or permissions: the step needs rights the first agent should not have (a researcher reads untrusted web pages, the agent that sends emails never should).
- Different context: the first agent's history would be noise or a leak for this step (a reviewer that sees only the draft and the source judges more independently).
- Different model: one step is cheap and simple, another needs a stronger model.
- Real parallelism: independent pieces can run at once and speed or coverage matters.
If you cannot name the test, keep one agent. 13A.8, 11.2 puts this decision next to the other architecture decisions, and Part 6 measures whether a split helped.
Part 2: Simple roles an agent can play#
A role is a job description for an agent: a system prompt, a tool set and, sometimes, a model. Four roles cover most beginner systems.
| Role | What it does | Usually has | Usually does not have |
|---|---|---|---|
| Planner | Breaks the task into steps or subtasks and says who should do each | No tools, or read-only ones | Write access, side-effect tools |
| Researcher | Finds facts: searches, reads, looks things up, reports what it found | Read tools (search, lookup, retrieval) | Permission to act on the world |
| Writer | Turns facts into the final answer in the required format | Often no tools | The raw tools the researcher used |
| Reviewer | Checks a draft against the source or a checklist and says approve or reject, with reasons | A way to see the source | The author's reasoning (so it judges independently) |
Two warnings keep this useful.
First, a role is only worth an agent if it passes one of the four tests in 1.2. Often a "planner" is just the first step of one agent's loop, and a "writer" is its last step. Splitting them gives you two prompts, two contexts and a handoff, and buys you nothing. A good split follows a real difference: the researcher reads untrusted pages, so the writer (who can talk to the customer) should not share its context.
Second, a reviewer is only as good as what it can check. A reviewer that is shown only the draft can judge tone and format. It cannot catch a wrong fact. A reviewer that is shown the draft and the original source can. You will see that difference run in 5.3.
Part 3: The two basic patterns#
08D.3, 2.1 and 2.4 describe both patterns. This part extends them with a runnable side-by-side comparison, a trace of who decided what, and a table for choosing.
There are many multi-agent architectures (08D.3, Part 2 lists ten). Two of them carry almost all beginner systems, and they differ in one question: who decides what happens next?
3.1 Pattern 1: orchestrator with workers#
An orchestrator splits the job and sends pieces to workers; it gathers the results and produces the final answer. In the simplest and most reliable form the orchestrator is plain code: your program decides the order (research first, then write), and each worker is an agent. The model never decides who runs next, so the flow is predictable. A fancier form lets an orchestrator model plan the subtasks at run time (08A.10, 5.3 builds that one).
3.2 Pattern 2: agent-as-a-tool#
Here one manager agent has a normal tool, and the tool's implementation happens to run another agent. To the manager, ask_researcher(question) looks like any tool: it passes a string, gets a string back, and keeps its own context. The model decides when to call it, how many times, and what to ask. 08D.3, 2.4 discusses the boundary with handoffs. 08A.11 goes through the mechanics (isolated context, budgets per call, parallel calls).
3.3 Both patterns, running#
This program builds both with the same researcher and scripted models. run_agent is the loop from 08A.2 in miniature. ScriptedModel replays canned replies, so the output is exactly reproducible.
# patterns.py: the two basic multi-agent patterns, side by side, with scripted models
import json
TRACE: list[str] = [] # one line per event, so you can see who did what
class ScriptedModel:
"""Replays canned replies. A reply is {"text": ...} or {"tool": name, "args": {...}}."""
def __init__(self, name, replies):
self.name, self.replies = name, list(replies)
def __call__(self, messages):
return self.replies.pop(0)
def run_agent(model, system, user, tools=None, max_steps=5):
"""The raw loop in miniature (08A.2 has the full version): call, run tools, repeat."""
tools = tools or {}
messages = [{"role": "system", "content": system}, {"role": "user", "content": user}]
for _ in range(max_steps):
reply = model(messages)
if "tool" in reply:
TRACE.append(f"{model.name} -> tool {reply['tool']}({json.dumps(reply['args'])})")
result = tools[reply["tool"]](**reply["args"])
messages.append({"role": "tool", "content": result})
continue
TRACE.append(f"{model.name} -> answer")
return reply["text"]
raise RuntimeError(f"{model.name} hit max_steps")
# ---- shared worker: a researcher with one tool -------------------------------------------
def make_researcher():
return ScriptedModel("researcher", [
{"tool": "policy_lookup", "args": {"topic": "refunds"}},
{"text": "Refunds are allowed within 30 days of delivery."},
])
POLICY = {"refunds": "Refunds are allowed within 30 days of delivery."}
researcher_tools = {"policy_lookup": lambda topic: POLICY[topic]}
# ---- Pattern 1: orchestrator with workers. CODE decides the order; agents do the steps ---
def orchestrator_with_workers(question):
TRACE.append("orchestrator (plain code): step 1, ask the researcher")
facts = run_agent(make_researcher(), "You research policy.", question, researcher_tools)
TRACE.append("orchestrator (plain code): step 2, ask the writer, passing only the facts")
writer = ScriptedModel("writer", [{"text": "Yes. Order A17 is eligible: policy says " + facts.lower()}])
return run_agent(writer, "You write the customer reply.", f"Question: {question}\nFacts: {facts}")
# ---- Pattern 2: agent-as-a-tool. A MANAGER agent decides when to call the specialist ----
def agent_as_a_tool(question):
def ask_researcher(question: str) -> str: # the specialist, wrapped as a plain tool
return run_agent(make_researcher(), "You research policy.", question, researcher_tools)
manager = ScriptedModel("manager", [
{"tool": "ask_researcher", "args": {"question": "What is the refund window?"}},
{"text": "Yes. Order A17 is eligible: policy says refunds are allowed within 30 days of delivery."},
])
return run_agent(manager, "You answer customers. Use ask_researcher for policy.", question,
{"ask_researcher": ask_researcher})
for fn in (orchestrator_with_workers, agent_as_a_tool):
TRACE.clear()
answer = fn("Can the customer with order A17 (delivered 10 days ago) get a refund?")
print(f"== {fn.__name__}")
for line in TRACE:
print(" ", line)
print(" final:", answer, "\n")== orchestrator_with_workers
orchestrator (plain code): step 1, ask the researcher
researcher -> tool policy_lookup({"topic": "refunds"})
researcher -> answer
orchestrator (plain code): step 2, ask the writer, passing only the facts
writer -> answer
final: Yes. Order A17 is eligible: policy says refunds are allowed within 30 days of delivery.
== agent_as_a_tool
manager -> tool ask_researcher({"question": "What is the refund window?"})
researcher -> tool policy_lookup({"topic": "refunds"})
researcher -> answer
manager -> answer
final: Yes. Order A17 is eligible: policy says refunds are allowed within 30 days of delivery.
Same answer, different shape. In the first trace the code chose the order. In the second the manager model chose to call the researcher, and the manager could have skipped it or called it three times. Notice that in both cases the writer or manager received only a string, not the researcher's whole history. That separation is what you are paying for.
3.4 Choosing between them#
| Orchestrator with workers | Agent-as-a-tool | |
|---|---|---|
| Who decides the order | Your code (or a planner you control) | The manager model, at run time |
| Predictability | High: same steps every run | Lower: the manager may call the specialist 0, 1 or many times |
| Good when | The steps are known in advance (research, then write, then check) | Needing a specialist is occasional or depends on the question |
| Typical failure | A fixed order that does not fit an odd input | The manager over-calls, under-calls or ignores the tool |
| Cost shape | Predictable: one call per worker | Variable: depends on how often the manager delegates |
When you are unsure, start with the orchestrator in plain code: it is easier to test and trace. Move to agent-as-a-tool when the order really depends on the input and a fixed pipeline wastes calls. The next lesson builds the plain-code version first for the same reason.
3.5 How the providers' SDKs describe the second pattern (illustrative)#
Agent-as-a-tool does not need a special SDK feature. To the provider API, the specialist is a function tool whose implementation runs another loop. Only the tool definition differs by provider. Both definitions below follow the shapes in the official function-calling docs (checked 1 December 2026). They are illustrative: they need a key to run, and this lesson does not run them.
# provider_tool_defs.py: the specialist exposed as a tool (illustrative, not run)
OPENAI_TOOL = { # Responses API: client.responses.create(model=..., input=..., tools=[...])
"type": "function",
"name": "ask_researcher",
"description": "Ask the research specialist a policy question. Returns a short factual answer.",
"parameters": {
"type": "object",
"properties": {"question": {"type": "string"}},
"required": ["question"],
"additionalProperties": False,
},
"strict": True,
}
ANTHROPIC_TOOL = { # Messages API: client.messages.create(model=..., tools=[...], messages=[...])
"name": "ask_researcher",
"description": "Ask the research specialist a policy question. Returns a short factual answer.",
"input_schema": {
"type": "object",
"properties": {"question": {"type": "string"}},
"required": ["question"],
},
}
# Your loop runs the researcher when the manager calls the tool. On OpenAI the call arrives as a
# `function_call` output item (name, arguments as a JSON string, call_id); on Anthropic as a `tool_use`
# content block (id, name, input) and stop_reason "tool_use". 08A.2 shows both loops in full.Part 4: What one agent hands to the next#
08D.3, 3.2 to 3.3 explain why context is isolated and why results should be structured. This part turns that advice into a small contract and a checker you can run.
A handoff is the moment one agent's work becomes another agent's input. It is where most multi-agent bugs live, because the receiving agent has nothing but what you gave it. It cannot ask a clarifying question the way a colleague could, and it cannot see the sender's history (08D.3, 3.2 explains why that isolation is deliberate). So every handoff should carry three things.
- The task. What to do, in one or two plain sentences. Not "handle this", but "find out whether order A17 is inside the refund window".
- The context it needs. The facts the receiver cannot work without: ids, constraints, the source text to check against. Not the whole conversation. Too little context makes the receiver guess. Too much costs money and buries the point (5.2).
- The answer format expected. The exact shape of the reply, ideally a small schema (field names and types). The next step in your code, or the next agent, depends on it.
08D.3, 3.3 discusses messages versus artefacts. For a beginner system, a small JSON object with named fields is the safest message.
4.1 A handoff contract in code#
A handoff contract is that triple, written down as data, plus a check on the way back. The sender does not trust the receiver to follow the format. It validates the reply, tells the receiver exactly what was wrong, tries once more, and then fails loudly.
# handoff.py: a handoff contract (task, context, expected output) and a checker for the answer
import json
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Handoff:
task: str # what to do, in one or two sentences
context: dict = field(default_factory=dict) # only the facts the receiver needs
expected: dict = field(default_factory=dict) # output field name -> Python type
def render(self) -> str:
"""The text the receiving agent actually sees."""
shape = {name: t.__name__ for name, t in self.expected.items()}
return (
f"TASK: {self.task}\n"
f"CONTEXT: {json.dumps(self.context, sort_keys=True)}\n"
f"ANSWER FORMAT: reply with one JSON object with exactly these fields: {json.dumps(shape)}"
)
def check_answer(raw: str, expected: dict) -> tuple[dict | None, list[str]]:
"""Return (parsed, problems). Never trust the receiver to follow the format."""
try:
data = json.loads(raw)
except json.JSONDecodeError:
return None, ["answer is not valid JSON"]
if not isinstance(data, dict):
return None, ["answer must be a JSON object"]
problems = []
for name, typ in expected.items():
if name not in data:
problems.append(f"missing field '{name}'")
elif not isinstance(data[name], typ):
problems.append(f"field '{name}' should be {typ.__name__}, got {type(data[name]).__name__}")
for name in data:
if name not in expected:
problems.append(f"unexpected field '{name}'")
return (data if not problems else None), problems
# A scripted "worker": it replays canned replies, one per call. No model, no network.
class ScriptedWorker:
def __init__(self, replies: list[str]):
self.replies = list(replies)
def __call__(self, prompt: str) -> str:
return self.replies.pop(0)
def delegate(worker, handoff: Handoff, max_attempts: int = 2) -> dict:
"""Send the handoff, check the answer, feed problems back once. Fail loudly after that."""
prompt = handoff.render()
for attempt in range(1, max_attempts + 1):
raw = worker(prompt)
data, problems = check_answer(raw, handoff.expected)
print(f" attempt {attempt}: {raw!r} -> {'OK' if data else problems}")
if data:
return data
prompt = handoff.render() + "\nYOUR LAST ANSWER WAS REJECTED: " + "; ".join(problems)
raise ValueError(f"worker never met the contract: {problems}")
if __name__ == "__main__":
h = Handoff(
task="Find out whether order A17 is inside the refund window.",
context={"order_id": "A17", "policy": "Refunds are allowed within 30 days of delivery."},
expected={"order_id": str, "days_since_delivery": int, "within_window": bool},
)
print(h.render())
print("\nCase 1: the worker follows the format")
print(delegate(ScriptedWorker(['{"order_id": "A17", "days_since_delivery": 10, "within_window": true}']), h))
print("\nCase 2: wrong format first, fixed after feedback")
print(delegate(ScriptedWorker([
"Sure! A17 was delivered 10 days ago, so yes.",
'{"order_id": "A17", "days_since_delivery": 10, "within_window": true}',
]), h))
print("\nCase 3: the worker keeps ignoring the format")
try:
delegate(ScriptedWorker(["yes", '{"order_id": "A17"}']), h)
except ValueError as err:
print(" ->", err)TASK: Find out whether order A17 is inside the refund window.
CONTEXT: {"order_id": "A17", "policy": "Refunds are allowed within 30 days of delivery."}
ANSWER FORMAT: reply with one JSON object with exactly these fields: {"order_id": "str", "days_since_delivery": "int", "within_window": "bool"}
Case 1: the worker follows the format
attempt 1: '{"order_id": "A17", "days_since_delivery": 10, "within_window": true}' -> OK
{'order_id': 'A17', 'days_since_delivery': 10, 'within_window': True}
Case 2: wrong format first, fixed after feedback
attempt 1: 'Sure! A17 was delivered 10 days ago, so yes.' -> ['answer is not valid JSON']
attempt 2: '{"order_id": "A17", "days_since_delivery": 10, "within_window": true}' -> OK
{'order_id': 'A17', 'days_since_delivery': 10, 'within_window': True}
Case 3: the worker keeps ignoring the format
attempt 1: 'yes' -> ['answer is not valid JSON']
attempt 2: '{"order_id": "A17"}' -> ["missing field 'days_since_delivery'", "missing field 'within_window'"]
-> worker never met the contract: ["missing field 'days_since_delivery'", "missing field 'within_window'"]Three things to notice. The receiver sees only the three parts (the render() text). The format check is code, not a request in a prompt, so it cannot be talked out of failing. And after two attempts the sender raises an error instead of passing a broken answer along. A visible failure at the handoff is far cheaper than a wrong answer three agents later.
Part 5: Common problems#
08D.3, 3.5 to 3.7 cover loops, error propagation and cost accounting across agents. This part extends them with one short program per problem, so you see each failure and its first fix in real output.
Three problems appear in nearly every first multi-agent system. Each program below reproduces one with scripted agents, so you can recognise it later in a real trace.
5.1 Agents looping#
Two agents can hand a task back and forth forever. The writer says "need more detail", the researcher answers and asks "anything else?", the writer says "need more detail" again. No single agent is looping on its own, so a per-agent step limit (08A.2, 3.3) never triggers. The loop is between them.
The fix has two parts: a handoff budget (a hard limit on how many times control may move) and repeat detection (stop when the same message appears again, which is a sign of no progress; 08A.2, 3.4 does this per tool call, and 08A.3 goes deeper). When either trips, stop and escalate to a human or return a clear "could not finish" status. Do not silently return the last message.
5.2 Cost growing quickly#
Each agent call is a full-price request that includes its whole input. If every agent receives the full transcript of everything before it, input size grows with each step, so total cost grows much faster than the number of agents. A brief (only the task and the facts needed) resets the size. Note that this is not unique to multi-agent systems: a single agent that loops also re-sends its growing history (03.5, 1.3). Splitting into agents adds a system prompt per agent and a handoff per hop. What a good split buys you is the chance to give each agent a short context.
5.3 One wrong answer spreading to the next agent#
Agents trust their input. If the researcher misreads "30 days" as "60 days", the writer will happily write "60 days", and a reviewer that only checks style will approve it. The error did not stay in one agent; it travelled, and each step made it look more finished. This is the multi-agent version of error compounding (08D.3, 3.6). The defence is a check that compares against something outside the chain: the source text, a database, or a tool result.
5.4 All three, reproduced#
# failures.py: three multi-agent failure demos with scripted agents (no model, no network)
import hashlib
def tokens(text: str) -> int:
return len(text.split()) # stand-in for a real tokenizer: 1 word = 1 token here
# ---- 1. Looping: two agents keep handing the task back and forth ------------------------
def ping_pong(max_handoffs, stop_on_repeat):
msg, seen = "Draft the refund reply.", set()
for n in range(1, 40):
speaker = "writer" if n % 2 else "researcher"
reply = ("Need more detail on the policy." if speaker == "writer"
else "Policy: 30 days from delivery. Anything else?")
digest = hashlib.md5(reply.encode()).hexdigest()[:6]
flag = " (same reply seen before)" if digest in seen else ""
seen.add(digest)
print(f" handoff {n:2d} {speaker:10s} {reply!r}{flag}")
if flag and stop_on_repeat:
return f"stopped at handoff {n}: repeat detected, escalate to a human"
if n >= max_handoffs:
return f"stopped at handoff {n}: handoff budget used up"
return "never stopped"
print("1a. Nothing stops it except a cap of 8 that I added so the demo ends:")
print(" ->", ping_pong(8, stop_on_repeat=False))
print("1b. Repeat detection, with a handoff budget of 8 as the backstop:")
print(" ->", ping_pong(8, stop_on_repeat=True))
# ---- 2. Cost growth: pass the whole transcript vs pass a brief --------------------------
PRICE_IN, PRICE_OUT = 0.002, 0.010 # toy prices per 1,000 tokens, NOT any provider's price
STEP_OUTPUT = " ".join(["finding"] * 150) # each agent writes a 150-token result
SYSTEM = " ".join(["instruction"] * 100) # each agent has a 100-token system prompt
def chain_cost(n_agents, pass_full_transcript):
transcript, total_in, total_out = "task " * 40, 0, 0
rows = []
for i in range(1, n_agents + 1):
seen = SYSTEM + " " + (transcript if pass_full_transcript else STEP_OUTPUT if i > 1 else transcript)
total_in += tokens(seen)
total_out += tokens(STEP_OUTPUT)
transcript += " " + STEP_OUTPUT
rows.append((i, tokens(seen)))
cost = total_in / 1000 * PRICE_IN + total_out / 1000 * PRICE_OUT
return rows, total_in, total_out, cost
print("\n2. A chain of agents; input tokens each agent reads:")
for mode in (True, False):
rows, tin, tout, cost = chain_cost(5, mode)
label = "full transcript" if mode else "short brief "
print(f" {label} per-agent input: {[r[1] for r in rows]} total in={tin} out={tout} cost={cost:.4f}")
# ---- 3. One wrong answer spreading ------------------------------------------------------
SOURCE = "Refunds are allowed within 30 days of delivery."
def researcher_wrong(): return {"window_days": 60} # misread the source
def writer(facts): return f"Good news: refunds are allowed within {facts['window_days']} days."
def reviewer_format_only(draft): return ("APPROVED", "polite, one sentence, no typos")
def reviewer_checks_source(draft, source):
ok = all(tok in source for tok in ("30",)) and "60" not in draft
return ("APPROVED", "matches source") if ok else ("REJECTED", f"draft disagrees with source: {source!r}")
print("\n3. One wrong fact moving down a pipeline:")
facts = researcher_wrong()
draft = writer(facts)
print(" researcher ->", facts)
print(" writer ->", draft)
print(" reviewer (checks style only) ->", reviewer_format_only(draft))
print(" reviewer (checks against source) ->", reviewer_checks_source(draft, SOURCE))1a. Nothing stops it except a cap of 8 that I added so the demo ends:
handoff 1 writer 'Need more detail on the policy.'
handoff 2 researcher 'Policy: 30 days from delivery. Anything else?'
handoff 3 writer 'Need more detail on the policy.' (same reply seen before)
handoff 4 researcher 'Policy: 30 days from delivery. Anything else?' (same reply seen before)
handoff 5 writer 'Need more detail on the policy.' (same reply seen before)
handoff 6 researcher 'Policy: 30 days from delivery. Anything else?' (same reply seen before)
handoff 7 writer 'Need more detail on the policy.' (same reply seen before)
handoff 8 researcher 'Policy: 30 days from delivery. Anything else?' (same reply seen before)
-> stopped at handoff 8: handoff budget used up
1b. Repeat detection, with a handoff budget of 8 as the backstop:
handoff 1 writer 'Need more detail on the policy.'
handoff 2 researcher 'Policy: 30 days from delivery. Anything else?'
handoff 3 writer 'Need more detail on the policy.' (same reply seen before)
-> stopped at handoff 3: repeat detected, escalate to a human
2. A chain of agents; input tokens each agent reads:
full transcript per-agent input: [140, 290, 440, 590, 740] total in=2200 out=750 cost=0.0119
short brief per-agent input: [140, 250, 250, 250, 250] total in=1140 out=750 cost=0.0098
3. One wrong fact moving down a pipeline:
researcher -> {'window_days': 60}
writer -> Good news: refunds are allowed within 60 days.
reviewer (checks style only) -> ('APPROVED', 'polite, one sentence, no typos')
reviewer (checks against source) -> ('REJECTED', "draft disagrees with source: 'Refunds are allowed within 30 days of delivery.'")What the output shows:
- Looping. Without a rule, the only thing that ended demo 1a was the cap I added. In real systems nothing adds that cap for you. Repeat detection (1b) stopped it at the third handoff and chose a clear outcome: escalate.
- Cost. With the full transcript, each agent reads more than the one before (140, 290, 440, 590, 740 tokens). With a short brief the growth stops after the second agent. In this toy, the brief saves nearly half the input tokens, and the saving grows with chain length. The numbers are word counts and toy prices, so only the shape is meaningful. For real prices, use your provider's pricing page, and see 08D.3, 3.7 for accounting across agents.
- Spreading. The reviewer that checked style approved a wrong fact. The one that compared the draft against the source rejected it. Same reviewer role, different access, different result.
Part 6: Evaluate it#
You split one agent into two. Is the new system better? "It feels cleaner" is not an answer. Modules 10A and 10B give you the tools, and this part says which to use for this lesson's topic.
Read the concept lessons first.
- 10A.7 Evaluating Agents, Tool Use and Multimodal Systems: the metrics that matter for any agent change: task success rate and cost per successful task, and tool-call precision and recall.
- 10A.12 Evaluating Multi-Agent Systems and Validating User Simulators: handoff correctness, attribution (which agent caused a failure) and how multi-agent systems fail (1.3, the MAST failure codebook).
- 10A.11 Evaluating Agent Memory and Context: useful when the question is what each agent saw.
Then the DeepEval lessons (required track, tooling for the same ideas): 10B.2 fundamentals, 10B.3 judges and custom metrics, 10B.4 built-in metrics, 10B.5 tracing and agent evaluation (Part 13 covers multi-agent spans), 10B.6 datasets and simulation and 10B.7 red teaming, CI and platform.
Then, optionally, the Inspect lessons. The most relevant is 10B.14 Inspect: tools and agents (optional), whose Part 9 covers handoffs and agents as tools. The rest of the Inspect track is in 10B.8, 10B.9, 10B.10, 10B.11, 10B.12, 10B.13, 10B.15, 10B.16 and 10B.17, all optional.
6.1 What to measure for this topic#
For "one agent or several", measure the same three things on both versions of the system, on the same task set:
- Task success rate: did the final answer pass the outcome check? This is the headline.
- Tool-call correctness: did the right tools get called with the right arguments, and nothing extra? Compare against a reference set of calls.
- Cost per successful task: total spend on all runs (failed ones included) divided by the number of successes.
Add two checks that are specific to multi-agent designs: handoff contract compliance (share of handoffs whose reply passed the format check) and error containment (when you inject a wrong fact into one agent, how often does it reach the final answer?).
6.2 A concrete tiny eval design#
| Part | Choice |
|---|---|
| Inputs | 20 refund questions: 12 ordinary, 4 edge cases (boundary day, unknown order, final sale, not yet shipped), 4 with a deliberately wrong fact injected into the researcher's reply |
| Versions | Version A: one agent with all tools. Version B: researcher plus writer through a handoff contract |
| Metrics | Task success rate, mean tool-call F1, cost per successful task, handoff contract compliance, error containment |
| Pass rule for B to replace A | Task success for B is not lower than A by more than the noise (compare with intervals, 10A.7, 5.2); cost per successful task for B is within the budget you set before running; contract compliance is at least 95%; at most 1 of the 4 injected errors reaches a final answer |
Decide the pass rule before you run, not after you see the numbers. 08D.2 builds exactly this comparison with code and real output.
Common misconceptions#
- "More agents means smarter systems." More agents means more prompts, more contexts and more handoffs. It can help on the right task shape (08D.3, 1.3), and it often hurts on sequential tasks.
- "A role needs its own agent." A role is a prompt and a tool set. It needs its own agent only if it passes one of the four tests in 1.2.
- "Agent-as-a-tool is just a normal tool." Mechanically yes, but its cost, latency and failure modes are those of a whole loop. Budget it like one.
- "The reviewer will catch mistakes." Only mistakes it can check. A reviewer without access to the source can only judge style.
- "If the JSON parses, the handoff is fine." Parsing proves the shape, not the truth. Required fields must match what the next step needs.
- "Per-agent step limits are enough." A loop between agents has no single agent exceeding its limit. You need a budget on handoffs.
Key takeaways#
- Start with one agent. Add another only when one clearly cannot do the job, and name the test it passes: different tools or permissions, different context, different model, or real parallelism.
- Four roles cover most beginner designs: planner, researcher, writer, reviewer. A role is a prompt plus tools plus context, not a person.
- Two basic patterns: an orchestrator with workers (code or a planner decides the order) and agent-as-a-tool (a manager model decides when to delegate). Prefer the plain-code orchestrator first.
- Every handoff carries three things: the task, the context the receiver needs, and the answer format expected. Check the answer in code and fail loudly.
- Loops between agents need a handoff budget and repeat detection. Costs grow with context passed, so pass briefs, not transcripts. Errors spread, so check against something outside the chain.
- Judge any split with task success, tool-call correctness and cost per successful task, on the same tasks, with a pass rule decided in advance.
Terms introduced in this lesson#
| Term | Meaning |
|---|---|
| Multi-agent system | Two or more agents, each with its own prompt and context, working on one task |
| Role | A job description for an agent: system prompt, tools, context and sometimes a model |
| Planner | A role that splits a task into steps and says who does each |
| Researcher | A role that finds facts with read tools and reports them |
| Writer | A role that turns facts into the final answer in the required format |
| Reviewer | A role that checks a draft against a source or checklist and approves or rejects |
| Orchestrator | The part (plain code or an agent) that splits the job and sends pieces to workers |
| Worker | An agent that does one piece of a job for an orchestrator |
| Agent-as-a-tool | A specialist agent exposed to a manager agent as an ordinary tool |
| Handoff | The moment one agent's work becomes another's input |
| Handoff contract | The task, the context and the expected answer format for a handoff, plus a check on the reply |
| Handoff budget | A hard limit on how many times control may pass between agents |
| Repeat detection | Stopping when the same message or call appears again, as a sign of no progress |
| Error propagation | A wrong output from one agent being accepted and built on by the next |
Exercises#
- Count the agents. For each system, say how many agents it has and which test in 1.2 (if any) justifies each one: (a) one prompt with a search tool and a calculator tool; (b) a router prompt that picks one of three specialist prompts, each with its own tools; (c) a planner prompt, then a loop that runs each step with the same tools. Hint: count separate contexts and prompts, not tools.
- Add a third pattern case. Edit
patterns.pyso the manager callsask_researchertwice (two scripted calls) before answering. Show in the trace how the cost shape differs from the orchestrator version. Hint: add a second tool call to the manager's script, and countresearcher ->lines. - Tighten the contract. In
handoff.py, add a rule thatdays_since_deliverymust be between 0 and 3650. Write a scripted reply that passes the old checker and fails the new one. Hint: extendexpectedto carry a validator function per field, or add a second check aftercheck_answer. - Fix the loop. In
failures.py, make the writer stop asking after one round by including the policy text in the first handoff. Does the loop disappear? What does that tell you about handoff context? Hint: the writer asked only because it lacked context. - A reviewer that can check. Extend
reviewer_checks_sourceto extract the number of days from both the draft and the source with a regular expression and compare them, instead of looking for the strings"30"and"60". Hint:re.search(r"(\d+) days", text). - Write your pass rule. For the 20-question design in 6.2, write the pass rule you would use if cost mattered much more than speed, and say what extra number you would collect. Hint: think about cost per successful task and a hard per-task cost cap.
Check yourself#
- What is the rule for choosing between a single agent and several, and what three cheaper things should you try before splitting?Start with one agent and add more only when one clearly cannot do the job. Try a better prompt, a better tool, and a plain workflow first.
- Name the four tests that justify a second agent.Different tools or permissions, different context, different model, or real parallelism.
- Name the four basic roles and say what each usually has and does not have.Planner: no or read-only tools, plans. Researcher: read tools, finds facts, cannot act. Writer: usually no tools, turns facts into the answer. Reviewer: can see the source, usually not the author's reasoning, approves or rejects with reasons.
- In an orchestrator with workers, who decides the order of steps? In agent-as-a-tool?Your code (or a planner you control) decides in the orchestrator pattern. The manager model decides at run time in agent-as-a-tool.
- Why is a plain-code orchestrator a good first choice?The flow is predictable, which makes it easy to test, trace and budget.
- What three things does a handoff carry?The task, the context the receiver needs, and the answer format expected.
- Why validate the answer in code instead of just asking for a format in the prompt?A prompt request can be ignored or misread. A code check cannot, it gives a precise error to feed back, and it lets you fail loudly after a bounded number of tries.
- Why can a loop between two agents escape a per-agent step limit, and what stops it?Neither agent exceeds its own step limit because control keeps moving. A budget on handoffs and detection of repeated messages stop it.
- Why does passing the full transcript make costs grow faster than passing a brief?Each agent re-reads everything before it, so input size rises at every hop. A brief keeps each input roughly constant.
- Why did the style-only reviewer approve a wrong answer, and what changed when it was given the source?It was shown only the draft, so it could judge style but not truth. With the source it could compare and reject.
Further resources#
- 08D.3 — Multi-Agent Systems: the full architecture zoo, the four taxes with evidence, and a larger from-scratch build.
- 08A.10 — Agent Patterns: orchestrator-workers and routing inside a single loop.
- 08F.13 — Subgraphs and Multi-Agent Systems: the same patterns in LangGraph.
- 08A.2 — The Tool Loop: the loop every agent here is built on.
- 08A.11 — Reflection, Parallel Fan-Out and Agent-as-a-Tool: the mechanics of agent-as-a-tool.
- 13A.8 — Decision Frameworks: Eight Decisions Plus One: the single-versus-multi-agent decision next to the other architecture decisions.
- Anthropic: Building effective agents: workflows, agents and when to add complexity.
- Anthropic: How we built our multi-agent research system: a production orchestrator-worker system and its costs.
- OpenAI: Function calling guide: the tool definition and call shapes used in 3.5.
- Anthropic: Handle tool calls:
tool_useandtool_resultblocks.
← Module 08C: Planning and Long-Running Agents | Module 08D overview | 08D.2 — Hands-On: Two-Agent vs Single-Agent, Built, Traced and Evaluated →