08D.3 Multi-Agent Systems
So far in this module you have built one agent: a model in a tool loop, with budgets, approvals and a trace. A multi-agent system is what happens when more than one such agent works on the same task — a lead that plans and delegates, specialists that each own a context window, reviewers that check the work, or peers that debate. It is also the pattern most likely to be over-applied: every extra agent multiplies tokens, compounds errors and adds a coordination problem you now own. This lesson teaches when multi-agent earns its cost, the ten architectures you will actually meet, the hard parts nobody warns you about (delegation prompts, context boundaries, termination, cost accounting, nested traces), the A2A protocol for agent-to-agent communication, human-agent teaming, and a complete from-scratch orchestrator–subagent research system you can run and test without any API key.
What you'll learn
- What "multi-agent" actually means, where it sits on the spectrum from a single call to a swarm, and why it is usually the wrong first move
- The four taxes every extra agent charges: multiplied tokens, compounded errors, coordination overhead and debugging difficulty — with the field data (Anthropic's production numbers, a 260-configuration study, and a respected counter-argument) rather than vibes
- The five cases where multi-agent genuinely earns its place: parallelisable research, context isolation and overflow, specialised prompts/tools/permissions, independent verification, and different models per role
- Ten architectures — orchestrator–subagents, handoffs/swarm, supervisor/hierarchical, agents-as-tools, peer debate/ensembles/voting, pipeline, blackboard/shared-state, parallel research fan-out, critic/verifier agents and role-play teams — each with a diagram, a code sketch over an injectable
call_model, when to use it and how it fails - The hard parts: writing delegation prompts a subagent can't misread, deciding what context crosses the boundary, passing artefacts instead of transcripts, who decides "done", conflicts and shared-state consistency, deadlocks and loops, error propagation, cost accounting across agents, nested tracing and evaluating systems whose paths vary run to run
- A2A: the agent-to-agent protocol (v1.0, Linux Foundation / Agentic AI Foundation), agent cards, tasks, messages and artifacts, how it differs from MCP, and when it is worth the indirection
- Human-agent teaming: approvals, escalation and takeover as first-class design concerns
- A complete orchestrator–subagent research system in pure Python: the lead plans, spawns bounded parallel workers, collects results and synthesises an answer with citations — testable end-to-end with a scripted fake model
- What the provider agent SDKs and frameworks give you for free (preview of 08F.1): Claude Agent SDK subagents and Managed Agents, OpenAI Agents SDK handoffs and agents-as-tools, Google ADK workflows, Microsoft Agent Framework, LangGraph's subagent pattern
What you don't need
- API keys. The entire build runs on pure Python plus a scripted fake model; provider samples are labelled illustrative. The free local stand-in from lesson 03.1, Part 12 works for the illustrative provider snippets too.
- Prior code from earlier lessons. 08A.2 built the production single-agent loop (
ChatAdapter,ModelTurn,Budget,run_agent) and 08A.10 re-implemented a minimal version of it for its patterns. This lesson'smulti_agent.pyis self-contained: it re-implements the same ideas — bounded loop, tool registry, budgets, scripted fake, trace — in a slimmer multi-agent-aware form, because an orchestrator needs a model boundary that knows which agent is calling. The names rhyme with theirs but the signatures are this file's own (the mapping is in 6.2). Read 08A.2 or 08A.10 first if the concepts — tool loop, budgets, scripted fakes — are unfamiliar; nothing here imports their files. - MCP internals (08E.1) or framework APIs (08F.1); both get a preview and a link, not a re-teach.
Setup
No packages are required: every runnable sample is standard-library Python 3.11+ (asyncio, dataclasses, json). If you built the llm-apis project for Module 03, reuse it; otherwise uv init agents --bare --python 3.13 is enough. The illustrative provider snippet in 6.3 uses the openai-agents package — see 08F.1 for the versions it was checked against when you get there (install it unpinned and check the version you get).
What you must be able to do after this lesson#
- Decide whether a task needs multiple agents or just one
- Name the four taxes that every extra agent adds
- Choose an architecture such as orchestrator-subagents, handoffs or agents-as-tools
- Write a delegation prompt a subagent cannot misread
- Build an orchestrator with bounded parallel workers
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "Let's split this into a team of agents." | 1.2 The four taxes and 2.11 The decision table |
| "The orchestrator should delegate to subagents." | 3.1 Task decomposition and delegation prompts |
| "Each subagent gets its own context window." | 3.2 Context isolation vs sharing |
| "Pass the findings back as artefacts, not transcripts." | 3.3 Communication formats: messages vs artefacts |
| "Who decides when the run is done?" | 3.4 Coordination and termination |
| "Two workers contradicted each other." | 3.5 Conflicts, shared state, deadlocks and loops |
| "This run cost 40× a chat call." | 3.7 Cost accounting across agents |
| "I can't tell which agent did what." | 3.8 Observability: nested traces |
| "How do we test a system that takes a different path every run?" | 3.9 Evaluating multi-agent systems |
| "Should agents talk over A2A or just share a database?" | Part 4: A2A |
| "The agent needs a human to approve refunds." | Part 5: Human-agent teaming |
Part 1: What multi-agent means — and why it's usually the wrong first move#
The beginner version of this Part is 08D.1, Part 1: start with one agent, and add a second only when you can name the test it passes. Here you get the spectrum, the four taxes with their evidence and the field data behind the rule.
1.1 One agent, many agents: the spectrum#
Recall the module's definition (08A.2): an agent is an LLM using tools in a loop to reach a goal, with the model controlling the flow. A multi-agent system is two or more such agents working on a shared task — each with its own model calls, context window, tool set, instructions and (often) its own model and permissions — coordinated by code, by another agent, or by a protocol.
The boundary matters. Inside one agent you can already have orchestrator-workers, routing, parallel tool calls, reflection and handoff-like behaviour — those are patterns within one loop, covered in 08A.9 and 08A.10. Multi-agent begins when the units are separate agent instances: separate contexts, separate budgets, possibly separate machines. An orchestrator that calls a "worker" as a tool is on the boundary — 2.4 is exactly about that ambiguity, and the OpenAI Agents SDK draws the same line between agents as tools and handoffs (see 6.3).
Picture the spectrum this module has been climbing:
flowchart LR
A["Single call<br/>prompt → answer"] --> B["Workflow<br/>fixed code path"]
B --> C["Single agent<br/>model controls the loop"]
C --> D["Multi-agent<br/>separate instances coordinate"]
D --> E["Agent networks<br/>protocols, discovery, markets"]
style A fill:#f5f5f5
style E fill:#f5f5f5Each step right buys capability and pays for it in predictability, cost and debuggability. The question of this lesson — and of most architecture reviews — is how far right a given task actually needs to go.
1.2 The four taxes: cost, errors, coordination, debugging#
Multi-agent's reputation for burning tokens is not folklore; the providers measured it.
Tax 1 — Cost multiplication. Anthropic's engineering post on their production Research feature (June 2025) reports that agents use roughly 4× more tokens than chat interactions, and their multi-agent research system uses roughly 15× more tokens than chats. Their analysis of the BrowseComp browsing benchmark found that token usage alone explained 80% of the variance in performance — three factors (tokens, tool calls, model choice) explained 95%. In other words, much of what looks like "multi-agent intelligence" is "more tokens spent in parallel", and you are paying list price for all of it. Cost accounting across agents is 3.7.
Tax 2 — Error compounding. Each agent is a probabilistic component. If one step of a single agent is wrong 5% of the time, a five-step chain is wrong roughly 23% of the time assuming independence (the arithmetic is in 08A.9). Now imagine five agents each running ten steps, passing lossy summaries to each other. The DeepMind/MIT scaling study (arXiv 2512.08296, December 2025) found that architectures without centralised verification propagated errors more than those with it. The first version's abstract (v1, 9 December 2025, 180 configurations) put error amplification at 17.2× for independent agents against 4.4× for centralised coordination, and said every multi-agent variant lost 39–70% on sequential reasoning tasks; the current version (v3, April 2026, 260 configurations) no longer quotes them in its abstract, though its introduction and Table 5 still report error amplification of 17.2 (independent), 7.8 (decentralised), 4.4 (centralised) and 5.1 (hybrid), and it reports −70.0% against the single-agent baseline on sequential planning as the worst case. Treat the multipliers as figures for its benchmarks and that version, not a law. Errors also change trajectories: one worker's misread doesn't just produce a bad answer, it can send the lead down a different research path entirely.
Tax 3 — Coordination overhead. Agents must decompose the task, describe it to each other, wait for results, resolve conflicts and decide when to stop. Anthropic's early multi-agent prototypes "made errors like spawning 50 subagents for simple queries, scouring the web endlessly for nonexistent sources, and distracting each other with excessive updates" — coordination isn't free even when the models are smart. Their fix was mostly prompting: explicit effort-scaling rules (simple fact-finding → 1 agent with 3–10 tool calls; comparisons → 2–4 agents with 10–15 calls each; complex research → 10+ agents) and detailed delegation briefs (3.1).
Tax 4 — Debugging difficulty. A single agent's failure is one trajectory to inspect. A multi-agent failure is a tree of trajectories plus the messages between them, and it's non-deterministic: the same question can take a different decomposition next run. Anthropic reports that "minor changes cascade into large behavioral changes" in agentic systems and that they built full production tracing specifically because users reported agents "not finding obvious information" and nobody could see why. Nested traces are 3.8; evaluation is 3.9.
1.3 When it earns its place#
Five cases recur in the literature and in production write-ups. Each maps to a structural property of the task, not a preference.
| Case | Why one agent can't do it | Architectures that fit | Watch out for |
|---|---|---|---|
| Parallelisable research / fan-out | The task splits into independent directions; wall-clock and coverage both improve | Orchestrator–subagents, research fan-out (2.1, 2.8) | Duplicated work, vague delegation, synthesis bottlenecks |
| Context isolation / overflow | One trajectory would exceed the window; subagents compress their findings to summaries | Orchestrator–subagents, agents-as-tools, handoffs with summarisation (3.2) | Telephone-game information loss, lost provenance |
| Specialised prompts / tools / permissions | Different subtasks need different instructions, tool sets or privilege levels | Supervisor, agents-as-tools, handoffs (2.3, 2.4) | Permission leakage, inconsistent behaviour at boundaries |
| Independent verification | The checker must not share the generator's blind spots | Critic/verifier, ensembles/voting (2.5, 2.9) | Correlated errors (same model, same prompt → same mistake) |
| Different models per role | A cheap fast model suffices for triage; a frontier model is needed for synthesis | Any architecture with per-agent model config | Cost accounting, capability mismatches at handoffs |
The DeepMind/MIT study adds the quantitative version: across 260 configurations, multi-agent helped most on decomposable tasks (Finance-Agent: +80.8% over a single agent for centralised coordination) and hurt most on sequential ones (PlanCraft: every multi-agent variant lost, from −39% for the hybrid design to −70% for independent agents). Their fitted model predicted the best architecture for 87% of held-out configurations, and they found a capability-saturation effect — once a single agent's baseline exceeds roughly 45% on a benchmark, the paper reports negative returns from adding agents (its regression boundary is raw performance of about 0.45). Treat that number as an empirical rule of thumb for their benchmarks, not a universal constant — but the direction is consistent with Anthropic's and Cognition's experience.
1.4 What the field data says — three honest sources#
Anthropic, "How we built our multi-agent research system" (June 2025). Production orchestrator–worker: a lead agent plans, spawns parallel subagents with web search, and a citation agent attributes claims. Wins: +90.2% over single-agent on internal research eval; up to 90% faster research via parallel subagents and parallel tool calls. Costs: ~15× chat tokens. Lessons: delegation briefs need objective + output format + tool guidance + boundaries; scale effort to query complexity; subagent outputs go to a filesystem/artefact store to avoid the "game of telephone"; synchronous execution is a bottleneck they hadn't yet solved. Source: https://www.anthropic.com/engineering/multi-agent-research-system
Cognition, "Don't Build Multi-Agents" (Walden Yan, June 2025). The strongest published counter-argument, from a company whose product is a coding agent. Two principles: share context (full traces, not just messages) and actions carry implicit decisions (two agents that can't see each other's work make conflicting assumptions — the Flappy Bird example: one subagent builds a Mario-style background, another a bird that doesn't match). Their prescription: default to a single-threaded agent; when context overflows, compress history with a dedicated model rather than fragmenting authority. Notably, they point out Claude Code's own subagents are sequential and question-only — isolation for context hygiene, not parallel authorship. Source: https://cognition.com/blog/dont-build-multi-agents
DeepMind/MIT, "Towards a Science of Scaling Agent Systems" (arXiv 2512.08296, December 2025). The first large controlled study: 260 configurations, five architectures (single-agent, independent, centralised, decentralised, hybrid), six benchmarks, three model families, matched tools/prompts/compute. Findings: coordination helps decomposable tasks and hurts sequential ones; centralised verification reduces error propagation; stronger single agents erode the multi-agent advantage. Source: https://arxiv.org/abs/2512.08296
A fourth source, on how these systems break: MAST (Cemri et al., UC Berkeley and collaborators, arXiv 2503.13657, first posted March 2025, revised October 2025). The three sources above argue about whether and when; this one catalogues failures. The authors annotated 1,600+ execution traces from 7 popular multi-agent frameworks and built a taxonomy of 14 failure modes in three categories — system-design issues, inter-agent misalignment, and task verification (inter-annotator agreement kappa = 0.88; they also released an LLM-as-judge annotator). Modes you will recognise from this lesson's failure gallery include disobeying a role specification, step repetition, loss of conversation history, being unaware of stopping conditions, conversation reset and premature termination. Two lessons for engineers: the taxonomy's emphasis is that failures are largely organisational (how roles, hand-offs and stopping are designed) rather than one model's raw limits, and verification gaps (no verifier, or one that checks format not truth) are a category of their own — which is why 2.9 and 3.4 carry so much weight. Use the taxonomy as a checklist when you label failed traces (10A.12, 1.3 turns it into a labelling codebook and counts the failures per category), and treat its quantitative shares as describing the frameworks and models they studied (the models were GPT-4, Claude 3, Qwen2.5 and CodeLlama-era), not today's. Source: https://arxiv.org/abs/2503.13657 (opened 2026-11-08).
Part 2: The architecture zoo#
Ten patterns cover almost everything you'll meet in production and in frameworks. For each: what it is, when it fits, how it fails, and a code sketch over this lesson's call_model boundary — the same runtime names Part 6 builds in full (AgentRuntime, AgentSpec, run_agent, ToolSpec, ToolRegistry, TraceLog).
Read the sketches as sketches, not runnable files. They show the coordination logic — the part that differs between architectures — over the Part 6 runtime, but the small helpers (parse_plan, brief_for, worker_spec_for, synthesis_prompt, format_answers, user_message, agent_step, with_extra_tool, error_result, handoff_marker, make_transfer_fn) are illustrative stand-ins, not definitions. Part 6's real helpers are _parse_plan, _brief, _worker_spec and _synthesise; the swarm-only helpers have no counterpart because the build doesn't implement handoffs. And if a name looks familiar from 08A.2 or 08A.10, it is this file's own minimal variant — same idea, different signature (the mapping table is in 6.2). multi_agent.py is the only file here you run.
A note on diagrams: in every architecture below, solid arrows are control flow (who decides what happens next) and dashed arrows are data flow (what information moves). Keep that distinction in your head — most multi-agent bugs are data-flow bugs wearing control-flow clothes.
2.1 Orchestrator–subagents#
A lead agent owns the user-facing conversation. It decomposes the task, spawns subagents — separate agent instances with their own context windows — waits for their condensed results, and synthesises the final answer. This is Anthropic's Research architecture and the OpenAI Agents SDK's "manager" pattern.
flowchart TD
U["User question"] --> L["Lead agent<br/>plans, delegates, synthesises"]
L -->|"spawn + brief"| S1["Subagent A<br/>own context window"]
L -->|"spawn + brief"| S2["Subagent B<br/>own context window"]
L -->|"spawn + brief"| S3["Subagent C<br/>own context window"]
S1 -.->|"condensed findings + sources"| L
S2 -.->|"condensed findings + sources"| L
S3 -.->|"condensed findings + sources"| L
L --> A["Final answer with citations"]# patterns.py — SKETCHES, not a runnable file. The coordination logic below is
# real; the runtime primitives (AgentRuntime, AgentSpec, run_agent, ToolSpec,
# ToolRegistry, TraceLog) and helpers (parse_plan, brief_for, agent_step, ...)
# are stand-ins for the versions Part 6 implements in multi_agent.py.
import asyncio
async def orchestrator_subagents(runtime, lead_spec, worker_spec, question: str):
"""The canonical multi-agent shape: plan -> fan out -> synthesise."""
# 1. The lead produces a structured plan (a list of delegation briefs).
plan = await runtime.call_model(
[{"role": "system", "content": lead_spec.system_prompt},
{"role": "user", "content": f"Question: {question}\nReturn the plan as JSON."}],
tools=None, agent=lead_spec.name)
subtasks = parse_plan(plan.text) # [{"id","title","instructions",...}]
# 2. Workers run concurrently, each in its own context, under a bound.
sem = asyncio.Semaphore(3) # max_parallel: never spawn unboundedly
async def work(sub):
async with sem:
return await run_agent(
runtime, worker_spec_for(worker_spec, sub),
brief_for(sub, question))
results = await asyncio.gather(*(work(s) for s in subtasks))
# 3. The lead synthesises from condensed results, not raw transcripts.
synthesis = await runtime.call_model(
[{"role": "system", "content": lead_spec.system_prompt},
{"role": "user", "content": synthesis_prompt(question, results)}],
tools=None, agent=lead_spec.name)
return synthesis.text, resultsWhen it fits: breadth-first research, report generation, multi-source investigation, any task where subtasks are independent and each produces more context than the lead needs. When it doesn't: sequential tasks (each step needs the previous step's full context), tasks with heavy inter-agent dependencies, anything where a single well-prompted agent with search tools suffices. Cost: Anthropic's ~15× figure is the realistic planning number for research workloads. Fails by: vague delegation briefs (3.1), duplicated subtask coverage, synthesis bottlenecks, and unbounded spawning — Anthropic's "50 subagents for a simple query" bug.
2.2 Handoffs and swarm-style routing#
In a handoff architecture there is no manager that narrates results back. Control transfers: a triage agent decides the user's request belongs to a specialist, and the specialist becomes the active agent for the rest of the turn — owning the conversation, the tools and the answer. A swarm generalises this: any agent can hand off to any other, and the system remembers who was active last.
flowchart LR
U["User"] --> T["Triage agent"]
T -->|"handoff: billing"| B["Billing specialist"]
T -->|"handoff: technical"| X["Tech support agent"]
B -->|"handoff: escalation"| H["Human queue"]
X -->|"handoff: returns"| R["Returns agent"]
R -.->|"state persists across turns"| Uasync def run_swarm(runtime, agents: dict, first: str, task: str, *,
max_handoffs: int = 4, max_turns: int = 12):
"""One active agent at a time; a transfer_to_agent tool call moves control.
The conversation is shared; the system prompt and tool set switch.
max_turns bounds total model calls — a handoff cap alone doesn't stop a
specialist that keeps calling ordinary tools."""
active, messages = agents[first], [user_message(task)]
handoffs = turns = 0
transfer = ToolSpec("transfer_to_agent",
"Hand the conversation to another agent.",
{"agent": {"type": "string"}},
make_transfer_fn(agents))
while turns < max_turns and handoffs < max_handoffs:
spec = with_extra_tool(active, transfer)
reply = await agent_step(runtime, spec, messages) # one model call + tool exec
turns += 1
if reply.finished:
return reply.text, active.name
if reply.called("transfer_to_agent"):
target = reply.arg("transfer_to_agent", "agent")
if target not in agents:
messages.append(error_result(reply, f"no agent named {target!r}"))
continue
active, handoffs = agents[target], handoffs + 1
messages.append(handoff_marker(active.name)) # "You are now handled by X"
else:
messages.extend(reply.tool_results)
return "turn or handoff budget exhausted", active.nameWhen it fits: customer-support routing, triage-then-specialist flows, long conversations where different phases need different personalities or permissions. This is the pattern behind OpenAI's Agents SDK handoffs and LangGraph's swarm (both in 6.3). Fails by: ping-pong loops (A hands to B, B hands back — hence max_handoffs), specialists that loop on ordinary tool calls forever (a handoff cap doesn't bound those — hence max_turns), context that doesn't survive the switch (the receiving agent sees a transcript written for someone else's prompt), and specialists that can't escalate to a human. Note the LangGraph warning verified in 6.3: handoffs must carry both the tool-call message and its result or the receiving agent sees a malformed history.
2.3 Supervisor and hierarchical#
A supervisor sits above workers in a tree: it decomposes, delegates, reviews what comes back, and may re-delegate or escalate. Unlike the flat orchestrator–subagents of 2.1, the supervisor can manage other supervisors, forming a hierarchy — a programme manager over project managers over workers. Google's ADK "collaborative workflow" (a coordinator agent with sub-agents) and LangGraph's (now-legacy) create_supervisor are the canonical implementations.
flowchart TD
S["Supervisor<br/>decomposes, reviews, re-delegates"]
S --> M1["Sub-supervisor: research"]
S --> M2["Sub-supervisor: analysis"]
M1 --> W1["Worker"] & W2["Worker"]
M2 --> W3["Worker"]
W1 -.->|"findings"| M1
W2 -.->|"findings"| M1
W3 -.->|"findings"| M2
M1 -.->|"section report"| S
M2 -.->|"section report"| SWhen it fits: genuinely large tasks with nested decomposition (a market-research programme with per-region managers), or when different branches need different models/budgets. When it doesn't: most tasks — each hierarchy level adds a lossy summarisation boundary and another coordination failure point. Cognition's principle applies with force here: every level that can't see the level below's raw work is another place for conflicting implicit decisions. Fails by: telephone-game degradation (each hop compresses), supervisors that can't verify worker claims, and unbounded recursion — cap depth explicitly.
2.4 Agents as tools#
The lightest form of multi-agent: register a whole agent as a tool in another agent's registry. The caller sees one tool call; underneath, a full agent loop runs. OpenAI's Agents SDK literally implements this as Agent.as_tool() — "a manager agent keeps control of the conversation and calls specialist agents through Agent.as_tool()".
# sketch — AgentSpec, ToolSpec and run_agent are the Part 6 definitions (multi_agent.py)
from multi_agent import AgentSpec, ToolSpec, run_agent
def agent_as_tool(runtime, spec: AgentSpec, *, name: str | None = None,
description: str | None = None) -> ToolSpec:
"""Wrap a complete agent (own context, own budget) as one tool call."""
async def _delegate(task: str) -> dict:
result = await run_agent(runtime, spec, task)
return {"agent": spec.name, "status": result.status,
"summary": result.text[:4000], "sources": result.sources}
return ToolSpec(
name=name or spec.name,
description=description or f"Delegate a self-contained subtask to the {spec.name} agent.",
parameters={"task": {"type": "string",
"description": "Complete, self-contained instructions for the subtask."}},
fn=_delegate)flowchart LR
M["Main agent<br/>sees: one tool call"] -->|"call: invoice_auditor(task)"| A["Auditor agent<br/>own loop, own context"]
A -->|"returns summary + status"| MWhen it fits: bounded, well-specified subtasks ("audit this invoice", "summarise this contract clause"), different tool/permission sets per specialist, and when you want the manager's context to stay clean — the subagent's intermediate tool calls never enter the parent's history. This is also the cleanest answer to context overflow: the parent gets a summary, not a transcript. When it doesn't: open-ended collaboration where the specialist needs to ask clarifying questions mid-task, or when the "tool" needs many turns of back-and-forth — a tool call is one round trip. Fails by: the manager writing vague task arguments (same disease as bad delegation briefs), and by treating a multi-minute agent run as if it were a cheap function call — budget it like one (3.7).
2.5 Peer debate, ensembles and voting#
Ensembles/voting run the same task through several agents (same or different models, different prompts or temperatures) and aggregate: majority vote, an aggregator/judge agent, or programmatic scoring. Peer debate goes further: agents see each other's answers and argue toward consensus. Both are special cases of Anthropic's "parallelization → voting" workflow.
# sketch — AgentSpec and run_agent are the Part 6 definitions (multi_agent.py)
import asyncio
from multi_agent import AgentSpec, run_agent
async def vote(runtime, specs: list[AgentSpec], question: str,
*, aggregator_prompt: str) -> str:
"""Run the same question through N agents, then aggregate."""
answers = await asyncio.gather(
*(run_agent(runtime, s, question) for s in specs))
tally = await runtime.call_model(
[{"role": "system", "content": aggregator_prompt},
{"role": "user", "content": format_answers(answers)}],
tools=None, agent="aggregator")
return tally.textflowchart TD
Q["Question"] --> A1["Agent 1"] & A2["Agent 2"] & A3["Agent 3"]
A1 -.->|"answer A"| J["Aggregator / judge"]
A2 -.->|"answer B"| J
A3 -.->|"answer C"| J
J --> F["Final answer"]When it fits: high-stakes classification or extraction where you can verify the answer mechanically or by a judge; building an eval signal (Module 10A uses exactly this for LLM-as-judge); squeezing reliability out of a borderline task. When it doesn't: open-ended generation (there's no "right" answer to vote on), cost-sensitive paths, or when the errors are correlated — three agents with the same model and near-identical prompts make the same mistake together, and voting amplifies confident wrongness. Debate adds rounds of tokens for gains that are real on some reasoning benchmarks and absent on others; treat it as an experimental pattern, measure before adopting. Fails by: correlated errors, judge capture (the aggregator inherits the majority's bias), and cost multiplying by N with no quality gain — always A/B against the single-agent baseline.
2.6 Pipeline and assembly line#
A pipeline is multi-agent in the mildest sense: a fixed sequence of specialised agents, each transforming the previous one's output — draft → critique → revise → format → publish. Control flow is code, not model choice; the "multi" part is that each stage can have its own prompt, tools, model and context reset.
flowchart LR
I["Input"] --> S1["Research agent"] --> S2["Writer agent"] --> S3["Editor agent"] --> S4["Fact-checker"] --> O["Output"]# sketch — AgentSpec and run_agent are the Part 6 definitions (multi_agent.py)
from multi_agent import AgentSpec, run_agent
async def pipeline(runtime, stages: list[AgentSpec], initial: str) -> str:
"""Each stage sees ONLY the previous stage's output — full isolation."""
text = initial
for spec in stages:
result = await run_agent(runtime, spec, text)
text = result.text
return textWhen it fits: content production (brief → draft → edit → approve), ETL-shaped LLM work (extract → transform → load), staged approvals where each stage has different permissions. This is arguably a workflow (08A.9) with agent-shaped stages — and that's the right way to think about it: if the sequence is fixed, you're building a workflow; the agents are just the stages. Fails by: error propagation with no way back (a bad stage-1 output poisons everything downstream — add gates between stages, as in 08A.9), and context amnesia (stage 3 can't ask stage 1 a question; pass structured state, not just text).
2.7 Blackboard and shared state#
A blackboard architecture gives agents a shared workspace — a key-value store, a document, a database — instead of direct messages. Agents read what others wrote, write their own findings, and coordinate through the state rather than through each other. Classic AI (the 1970s–80s blackboard systems for speech recognition) and modern equivalents (a shared scratchpad file, a SQLite state table, a shared vector store) share the same idea.
import asyncio
from typing import Any
class Blackboard:
"""Shared state agents read/write via tools, not via messages."""
def __init__(self):
self.data: dict[str, Any] = {}
self.revision = 0 # bumps on every write, so readers can spot staleness
self.lock = asyncio.Lock()
async def read(self, key: str) -> Any:
return self.data.get(key)
async def write(self, key: str, value: Any, *, agent: str) -> dict:
async with self.lock:
self.revision += 1
self.data[key] = {"value": value, "written_by": agent, "revision": self.revision}
return {"key": key, "revision": self.revision}flowchart TD
subgraph board ["Shared blackboard (store)"]
K1["plan"] & K2["findings: region-A"] & K3["open questions"]
end
A1["Agent 1"] <-->|"read/write"| board
A2["Agent 2"] <-->|"read/write"| board
A3["Agent 3"] <-->|"read/write"| boardWhen it fits: loosely-coupled collaboration where agents work asynchronously or opportunistically ("whoever finds a citation writes it"), human-in-the-loop workflows where people and agents share the same surface, and long-running systems where the state must outlive any single agent run. When it doesn't: tight coordination — blackboards have no semantics, so agents must infer what others meant from raw state (the ultimate telephone game), and concurrent writes need conflict rules you design yourself. Fails by: stale reads (an agent acts on findings another agent already superseded), unstructured growth (the board becomes a junk drawer — give keys a schema and TTLs), and the same correlated-context problem: everyone reads the same board, so "independence" is an illusion unless you partition it.
2.8 Parallel research fan-out#
The specialist case of orchestrator–subagents: the lead decomposes a question into independent research directions, workers run the full search→read→note loop in parallel, and the lead synthesises. This is the architecture Anthropic productised and the one Part 6 builds in full.
flowchart TD
Q["Research question"] --> P["Lead: plan N subtasks"]
P --> W1["Worker 1: subtask + own searches"]
P --> W2["Worker 2: subtask + own searches"]
P --> W3["Worker N: subtask + own searches"]
W1 -.->|"notes + sources"| C["Lead: synthesise + cite"]
W2 -.->|"notes + sources"| C
W3 -.->|"notes + sources"| C
C --> R["Cited report"]When it fits: exactly the Anthropic case — breadth-first questions ("compare all X", "what are the approaches to Y"), information that exceeds one context window, many independent sources. Cost: this is where the ~15× token multiplier lives; budget per worker, cap N, and require the plan to justify each subtask. Fails by: overlapping subtasks (two workers research the same ground — dedupe in the plan), workers that can't find sources and fabricate them (require citations or explicit "not found"), and synthesis that drops minority findings.
2.9 Critic and verifier agents#
A critic/verifier is a second agent whose only job is to check the first agent's work: does the answer address the question, do the citations support the claims, does the code pass tests, is the JSON schema-valid? It can be a separate model call in a loop (evaluator-optimizer from 08A.9/08A.10) or a genuinely separate agent with different tools — a verifier that re-runs the query, checks a database, or executes the code rather than just re-reading the text.
flowchart LR
G["Generator agent"] -->|"draft + claims"| V["Verifier agent<br/>different tools, maybe different model"]
V -->|"verdict: pass"| O["Ship"]
V -->|"verdict: fail + reasons"| GWhen it fits: verifiable outputs (citations that exist, code that runs, numbers that recompute), high-stakes answers, and as the centralised verification the DeepMind study found reduces error propagation. When it doesn't: subjective outputs (the critic's taste becomes the bottleneck), when generator and critic share the same blind spots (same model + same context → correlated approval — give the verifier different evidence: tools, not just the draft), and unbounded critique loops — cap rounds and escalate to a human after that (08A.10 covers bounded reflection; 3.4 covers termination). Fails by: critique loops that degrade the answer (each revision drifts further from the user's actual ask), and verifiers that check format but not truth.
2.10 Role-play teams#
The pattern you'll see in demos and low-code tools: agents named "CEO", "Engineer", "Marketing" that "discuss" the problem in character. It is almost always the wrong tool: role-play adds persona prompts and message-passing overhead while reducing the separation of concerns that makes multi-agent work — the "CEO" and the "Engineer" share the same context, the same tools and the same blind spots, so you get the costs of multi-agent (tokens, coordination, debugging) with none of the benefits (isolation, specialisation, verification).
Where it can earn a place: structured adversarial review (a "red team" persona given explicit attack instructions and different tools — that's a verifier with a costume), and multi-perspective analysis where the prompt-level framing genuinely changes the output (a "sceptic" pass over a plan). Even then, prefer 2.5's explicit ensemble or 2.9's verifier — same effect, honest about what's happening. The rule: if removing the personas wouldn't change the architecture, they were decoration.
2.11 The decision table#
| You need... | Use | Avoid |
|---|---|---|
| One bounded subtask inside a managed conversation | Agents-as-tools (2.4) | Full handoff (loses the manager's context) |
| Routing to specialists who own the turn | Handoffs/swarm (2.2) | Orchestrator that narrates everything back |
| Breadth-first research / parallel independent work | Orchestrator–subagents / fan-out (2.1, 2.8) | Sequential single agent (too slow, context overflow) |
| Nested decomposition at scale | Supervisor hierarchy (2.3) | Flat swarm (coordination chaos) |
| Reliability on verifiable outputs | Critic/verifier, ensembles (2.5, 2.9) | Same-model same-prompt voting (correlated errors) |
| Fixed sequence of specialised stages | Pipeline/workflow (2.6 → 08A.9) | "Agents" that just pass text down a chain |
| Async, opportunistic, human-shared state | Blackboard (2.7) | Blackboard for tight coordination (no semantics) |
| Open-ended collaboration / persona theatre | — | Role-play teams (2.10) unless explicitly adversarial |
If you build on LangChain and LangGraph, 08F.13, Part 8 maps these ten architectures onto LangChain's five official patterns (an optional track).
And the meta-rule above all of them, from 1.3: default to the simplest architecture that satisfies the task's structural requirements, and add agents only where they buy something measurable.
Part 3: The hard parts#
Architecture diagrams are the easy half. Everything below is where multi-agent systems actually succeed or fail in production — and where most of the engineering effort goes.
3.1 Task decomposition and delegation prompts#
The single highest-leverage artifact in a multi-agent system is the delegation brief: the message that tells a subagent what to do. Anthropic's post is blunt about this — early versions gave subagents instructions like "research the semiconductor shortage", which were "vague enough that subagents misinterpreted the task or performed the exact same searches as other agents" (one investigated the 2021 chip crisis while two duplicated 2025 supply-chain work).
A delegation brief needs five things:
| Element | What it does | Example (research worker) |
|---|---|---|
| Objective | The question this subagent alone must answer | "Which vector-index types does pgvector offer, and what are their recall/latency trade-offs?" |
| Output format | Exactly what comes back and how it's shaped | "Return ≤400 words of findings plus a sources list of URLs you actually fetched." |
| Boundaries | What is not this subagent's job (prevents overlap) | "Do not cover Qdrant or hosted vector DBs — two other workers own those." |
| Tool guidance | Which tools to prefer, in what order, and when to stop | "Use web_search with 2–4 word queries, web_fetch only on promising results, stop after 8 tool calls." |
| Effort scaling | How much work is proportionate | "Light: 3–5 calls. Normal: 6–12. Deep: up to 20." (Anthropic's scaling rules, adapted) |
Two supporting prompt-engineering rules from the same source:
- Teach the orchestrator to delegate, not just the workers to work. The lead's system prompt should contain the same five-element template, plus rules for how many subagents to spawn for a given complexity — Anthropic embeds explicit bands (1 agent for simple fact-finding, 2–4 for comparisons, 10+ for complex research) because models can't judge effort well on their own.
- Let the plan be data, not prose. Have the lead emit a structured plan (JSON list of subtasks) that your code validates before spawning anything: count cap, required fields, no duplicate objectives, each subtask's tool set is a subset of what the worker is allowed. A malformed plan should fail loudly, not spawn five confused agents. Part 6 implements exactly this.
3.2 Context isolation vs sharing#
Every subagent gets a fresh context window — it does not see the parent's conversation, the sibling agents' work, or anything that happened before its spawn. This is the feature and the bug.
What isolation buys you:
- Compression. A worker that reads 40 search results returns a 300-word summary; the lead's context stays small. This is Anthropic's core argument: "the essence of search is compression".
- Separation of concerns. Each agent gets the prompt, tools and trajectory suited to its subtask — a tax researcher doesn't carry the engineering agent's instructions.
- Parallelism. N agents explore N directions at once; total context across the system exceeds any single window.
- Containment. A worker that goes wrong (loops, gets prompt-injected by a web page) burns its own budget, not the parent's.
What it costs — the boundary problem. 04.7, Part 7 owns the general theory; the multi-agent specifics:
- Downward (parent → child): the child sees only what you put in the brief. Everything the parent learned while planning — dead ends, corrected assumptions, the user's actual constraint buried in turn 3 — must be re-stated or it is lost. Cognition's Flappy Bird failure is exactly this: the subagent never saw the parent's full task, so it guessed.
- Upward (child → parent): the child returns only what you ask for. Its final message is a summary written for the parent's benefit; intermediate evidence, dead ends and confidence levels are gone unless the child was told to report them.
- Laterally (sibling → sibling): siblings can't see each other at all. Two workers can research the same ground, contradict each other, or leave a gap between them — and neither knows. Mitigations: dedupe subtasks in the plan, give each worker an explicit "out of scope" list, and have the lead check coverage before synthesising.
- Across turns: when a run spans many context windows (a long research session), the system must carry state — plan, findings, open questions — in durable storage the next session can reload. Anthropic's production system saves its plan to memory because "if the context window exceeds 200,000 tokens it will be truncated". 08B.2 owns memory design; the multi-agent rule is: the plan and the findings are state, the conversation is not.
The design question for every delegation is therefore: what is the minimum context that lets the child succeed, and the maximum fidelity return that lets the parent verify? Err toward more structure (fields, artefact references) and less prose.
3.3 Communication formats: messages vs artefacts#
Subagents can return findings two ways: in the message (text embedded in the result the parent reads) or as artefacts (files/objects in a store, with the message carrying only a reference).
Anthropic's appendix is explicit: "Subagent output to a filesystem to minimize the 'game of telephone'" — direct outputs bypassing the coordinator "improve both fidelity and performance", because "passing large outputs through conversation history" loses information and burns tokens. A2A independently converged on the same idea: its Artifact object is "a tangible output generated by an agent during a task… the actual deliverables", separate from the conversational Message.
| Message-passed findings | Artefact-passed findings | |
|---|---|---|
| Mechanism | Child's final text becomes part of parent's context | Child writes to a store; parent gets an ID/URL |
| Fidelity | Lossy — summarised for the channel | High — the artefact is the real output |
| Parent context cost | High for long findings | Low — a reference is cheap |
| Provenance | Implicit (who said it?) | Explicit — artefacts carry author, version, source |
| Best for | Short summaries, verdicts, small structured results | Reports, datasets, code, long research notes |
| Failure mode | Telephone game: each hop re-summarises | Orphaned artefacts nobody reads; stale versions |
Practical pattern (implemented in Part 6): workers store_finding(title, content) into an artefact store and return a one-paragraph digest with the artefact ID. The synthesiser reads digests first, fetches artefacts only for the findings it cites. This is also the answer to "how do I stop a 10,000-word worker report from flooding the lead's context" — the same tool-result management problem as 04.7, Part 5, one level up.
Two format rules regardless of channel:
- Structured over prose. A subagent result should be parseable:
{status, summary, findings[], sources[], artefacts[], confidence, open_questions[]}. Prose summaries are fine for humans; machines need fields. Use schema-constrained output (03.4) for worker reports where the provider supports it. - Label provenance and trust. Anything that originated outside your trust boundary — a fetched page, a tool result, another agent's output — is data, not instructions. Tag it (
source: web,author: worker-3,trust: untrusted) so downstream agents can't be prompt-injected through the back channel. This is the multi-agent version of 04.6's provenance labelling.
3.4 Coordination and termination#
The question "who decides the run is done?" has three honest answers, and most systems need all three:
- The model decides, bounded by code. The lead agent judges "enough research done" and emits the final answer — but only inside hard budgets: max subagents, max steps per agent, max tokens, max wall-clock, max cost. Without the bounds, Anthropic's "50 subagents for a simple query" happens. Budgets are 08A.2's stop conditions applied per-agent and system-wide.
- Code decides on structure. Some terminators are not judgement calls: plan emitted, all workers returned, synthesis produced, citation pass finished. Your orchestrator should know the expected shape and refuse to "finish" early — a lead that synthesises from 1 of 5 workers hasn't finished, it's failed.
- A human decides on policy. Irreversible actions (send, pay, delete, publish) don't terminate in the model at all — they terminate in an approval (Part 5).
Coordination mechanics that keep this sane:
- Spawn caps and queues. Never let the model decide concurrency.
asyncio.Semaphore(or a worker pool) bounds parallelism; a queue serialises the rest. Anthropic runs subagents synchronously in batches today precisely because asynchronous coordination is harder — "agents working concurrently and creating new subagents when needed" is where they want to go, and they flag the unsolved problems: result coordination, state consistency, error propagation. - Join semantics. Decide what "all workers done" means when one fails: fail the whole run, or synthesise from partial results labelled as partial? For research, partial-with-caveats usually beats nothing; for verification, partial is a fail. Make it explicit per architecture.
- Cancellation propagates. Cancelling the run must cancel in-flight subagents —
asyncio.Taskcancellation, or acancel_eventevery loop checks. A cancelled parent with orphaned workers still burning tokens is a real production bug (03.3, Part 8 covers cancellation mechanics). - Idempotent delegation. If the orchestrator retries after a crash, re-spawning workers duplicates work and cost. Give each delegation a deterministic ID (hash of parent run + subtask) so a retry can recognise "worker-3 already completed" from the artefact store or run journal.
3.5 Conflicts, shared state, deadlocks and loops#
Conflicts happen when agents make decisions on stale or contradictory information: two workers both conclude "the answer is X" for different reasons, or a worker acts on a finding a sibling already superseded. There's no distributed consensus here — the honest mitigations are: partition work so conflicts can't arise (disjoint subtasks), timestamp/sequence shared state so "latest wins" is defined, and give the lead a verification step before synthesis (does the evidence actually support the claim?).
Shared state consistency is the blackboard problem (2.7) generalised: if agents share a store, define who may write which keys, whether writes are last-write-wins or versioned, and how readers detect staleness. For most systems, append-only event logs beat mutable state — every finding is an event with {author, ts, parent_run}; "current truth" is a fold over events, and contradictions are visible rather than silently overwritten.
Deadlocks in agent systems are rare but real: agent A waits for agent B's result while B waits for A's; or the lead waits for workers that are themselves waiting on a tool the lead holds. Prevent by construction — the orchestrator→worker direction is a DAG (workers never call back up except through the return channel); if you allow peer-to-peer or upward calls, you need timeouts and a wait-for graph.
Loops are the common case: A delegates to B, B's result prompts A to delegate to B again; or two agents hand off to each other forever. Defences, in order of cheapness: per-agent step budgets, per-system delegation budgets (max_handoffs, max_subagents), loop detection on identical calls (08A.2's repeated-call detector, applied to delegation edges — "A→B with the same brief three times"), and a wall-clock circuit breaker for the whole run. Track the delegation graph in your trace (3.8) so loops are visible after the fact, not just prevented before.
3.6 Error propagation and partial failure#
In a single agent, a tool error becomes an error result the model reads and routes around (08A.2). In multi-agent, errors have topology:
| Failure | Spreads how | Handling |
|---|---|---|
| Worker tool fails | Contained — worker returns status: error in its result |
Lead decides: retry, re-delegate, proceed without, or fail |
| Worker model call fails (rate limit, timeout, API error) | Contained the same way — the loop converts it to status: error, and the orchestrator's gather normalises anything that still escapes |
agent_end shows status: error + error; lead decides as above |
| Worker returns garbage | Contained to its slice, but poisons synthesis if trusted | Schema-validate worker results; confidence flags; verifier pass |
| Worker hangs | Blocks the join (or the semaphore slot) | Per-agent wall-clock timeout → status: timeout; slot frees |
| Lead's plan is wrong | Systemic — every worker inherits the bad decomposition | Plan validation in code; plan-review step (critic agent on the plan, cheap insurance) |
| Synthesis call fails | Terminal for the run | Retry with backoff (03.8); cached worker results mean you don't re-run them |
| One worker's output is prompt-injected | Can poison the lead's context → final answer | Provenance labels, untrusted-content quarantine (3.3, Module 12) |
The design principle: make every agent boundary a typed, fallible interface. A worker result is {status, summary, findings, sources, artefacts, usage, error} — never raw prose the parent must interpret. status is a small enum (ok | partial | error | timeout | budget_exhausted | cancelled) so the orchestrator can route on it mechanically. (The build in 6.2 implements the subset ok | partial | error | budget_exhausted; a per-call wall-clock overrun there is reported as budget_exhausted.) Partial failure is a first-class outcome, not an exception: decide per architecture whether partial results are usable (research: yes, labelled; verification: no).
3.7 Cost accounting across agents#
Cost in a multi-agent system is multiplicative in three dimensions: agents × steps × context size. A system with 1 lead + 5 workers × 15 steps each is ~90 model calls where a single agent might use 15 — before counting that each call re-sends its whole context as input tokens.
Build the accounting the same way 03.7 does for single calls, one level up:
- Every agent run emits a usage record
{agent, parent_run, model, input_tokens, output_tokens, tool_calls, wall_clock, cost}— theusageobject per call, summed per run, rolled up per system run. The trace ID ties them together (3.8). - Attribute cost to the delegation tree. A report should answer "what did the
supplier-risksubtask cost?" — so eachAgentResultcarries its own usage and itsparent_trace_id. The orchestrator's rollup is then a tree-fold, not a guess. - Budget at every level. Per-agent budgets (steps, tokens, wall-clock) stop one runaway worker; a system budget (total tokens, total cost, max wall-clock, max subagents) stops the whole run. Enforce the system budget before each spawn — "we've spent 80% of budget, no new delegations" is a check your code makes, not a prompt instruction.
- Price the pattern, not just the call. Anthropic's ~15× and ~4× figures are the honest priors for agentic workloads; DeepMind matched token budgets across architectures in their study precisely because unbudgeted comparisons are meaningless. When you A/B a multi-agent design against a single agent, match total tokens — otherwise you're measuring spend, not architecture.
- Cheap models for cheap roles. Different-models-per-role is a cost lever and a capability lever: triage/routing workers on a small fast model, synthesis on the frontier model. Track cost per role so you can see whether the cheap-role savings are real.
3.8 Observability: nested traces#
A single agent's trace is a flat list of model calls and tool calls. A multi-agent trace is a tree: system run → agent runs → model calls and tool calls within each. If your observability can't show the nesting, you can't debug the system — "which agent spawned this worker, what brief did it get, what did the worker actually see, where did the bad claim enter?"
Minimum viable structure (what Part 6 implements):
run <trace_id> kind: system_run
├─ agent lead kind: agent_start/end, parent: run
│ ├─ model_call (plan) tokens, latency, finish_reason
│ ├─ delegation → worker-1 brief hash, subtask id
│ ├─ model_call (synthesis) ...
├─ agent worker-1 kind: agent_start/end, parent: run
│ ├─ model_call ...
│ ├─ tool_call web_search args, result summary, latency
│ ├─ tool_call store_finding artefact id
│ └─ model_call (final) ...
└─ agent worker-2 ...Rules that make traces actually debuggable:
- One
trace_idper system run,parent_idper agent run. Every event carries both; aspan_id/parent_span_idpair if you want OpenTelemetry-style nesting. 03.10 owns logging mechanics; 03.11, Part 9 shows hooks that emit exactly this shape. - Log the delegation brief, not just the result. The #1 multi-agent debugging question is "what did the worker think it was supposed to do?" — store the brief (or its hash + a reference to the full text in the artefact store).
- Log decisions, not just calls. "Lead decided to spawn 3 workers because plan had 3 subtasks" is a
kind: decisionevent. Anthropic "monitor[s] agent decision patterns and interaction structures" for exactly this reason. - Redact and budget the trace itself. Tool results can be huge; store summaries + artefact references, not full payloads, in the hot path — full payloads go to the artefact store with the trace pointing at them. And apply the same secret-redaction rules as 03.10.
- Emit OpenTelemetry spans if you can. GenAI semantic conventions exist for model calls; map
agent_run→ span,delegation→ span,tool_call→ span. Platforms (Langfuse, LangSmith, Phoenix, Logfire — the Module 11A survey) ingest this natively; 08A.14 goes deep.
3.9 Evaluating multi-agent systems#
Evaluation is where multi-agent bites hardest, because the path is not fixed. Anthropic's eval section is the best public guidance:
- You can't check the steps; you check the outcome and the process quality. A research agent might find the right answer via 3 searches or 30 — both can be valid. Evaluate: (a) outcome correctness against a rubric, (b) process reasonableness (right tools, sane effort, no thrashing) via an LLM judge or trajectory checks.
- Start small. ~20 representative queries is enough to see large effects in early development; effect sizes are big when systems are immature.
- LLM-as-judge with a rubric works — factual accuracy, citation accuracy, completeness, source quality, tool efficiency — as a single call producing scores + pass/fail.
- Human evaluation catches what automation misses — edge cases, weird failures, subtle biases (their agents preferred SEO content farms over authoritative PDFs until prompted otherwise).
- End-state evaluation for state-mutating agents. If agents change persistent state over many turns, judge the final state, not the trajectory — with checkpoints where specific state changes should have occurred.
Multi-agent adds three eval-specific problems:
- Component vs end-to-end. A worker can be "good" (finds relevant sources) while the system is bad (lead ignores them). Evaluate both levels: unit-test workers against canned briefs (deterministic, cheap — this is what
ScriptedModelenables), and evaluate the full system end-to-end on real tasks. - Variance. Non-deterministic decomposition means pass@1 is noisy; report pass@k or run-to-run variance, and evaluate the distribution of cost/steps/latency, not just mean quality. Module 10A owns the formal metrics: 10A.12 grades handoffs (Part 3), attributes failures to agents (Part 4), measures orchestration overhead as distributions (Part 5) and compares against an equal-budget single-agent baseline (Part 6).
- Regression from "improvements". Changing the lead's prompt can silently change how all workers behave (Anthropic: "small changes to the lead agent can unpredictably change how subagents behave"). Version the whole system — prompts, tool descriptions, worker specs, budgets — as one release unit (04.10 for prompts; the same discipline applies to agent configs).
A pragmatic eval ladder for a multi-agent system: (1) ScriptedModel trajectory tests — deterministic, CI-friendly, catch regressions in coordination logic; (2) recorded-trajectory replay — feed real model outputs back through your orchestrator to test synthesis without re-spending tokens; (3) small live suite (~20 tasks) with LLM-judge rubric; (4) production sampling with human review of failures. 08A.14 builds the harness; 10A.12 owns the methodology.
3.10 The failure gallery#
Every failure mode above, gathered where you can scan it. The "detection" column assumes the 3.8 trace — without it, most of these are invisible until a user complains.
| Symptom | Root cause | Detection (trace signal) | Mitigation |
|---|---|---|---|
| Two workers research the same ground; the synthesis repeats itself | Duplicated work — overlapping subtasks or vague delegation briefs | decision/delegation events show near-identical subtask titles; digests cite the same sources |
Five-element briefs with explicit out-of-scope lists; dedupe and coverage-check the plan in code before spawning (3.1) |
| A worker returns confident nonsense or invents sources | Vague delegation — the brief didn't bound the task or demand evidence | Worker result has empty sources, or URLs it never fetched; missing store_finding artefact |
Require citations-or-"not found" in the brief; schema-validate worker results; a verifier agent re-checks claims (3.6, 2.9) |
| The lead spawns 50 subagents for a simple question | Runaway spawning — no cap and no effort-scaling rules (Anthropic's reported bug) | decision event lists an absurd subtask count; system budget burns in minutes |
max_subtasks/max_parallel enforced in code, not prompts; Anthropic's effort bands in the lead's system prompt (3.4) |
| A worker loops until someone notices | Missing per-agent budgets — step/tool/wall-clock limits absent or too generous | Repeated identical model_call→tool_call pairs; agent_end shows budget_exhausted |
Per-agent Budgets on every spec; identical-call loop detection; a wall-clock circuit breaker for the whole run (3.5) |
| The final answer ignores half the plan or contradicts a worker | Lost context — the parent saw digests, never the evidence; or a sibling's finding never reached it | Synthesis model_call input contains no artefact fetches; coverage gaps between subtask briefs |
Artefact store + digest-and-ID protocol; the lead verifies coverage and claims before synthesising (3.2, 3.3) |
| Details drift or vanish at every hop — "the game of telephone" | Lossy message-passing — findings re-summarised through each agent boundary | Deep delegation chains in the trace; claims lose citations and qualifiers along the way | Artefacts over messages; flatten hierarchies; quote critical facts verbatim rather than paraphrasing (3.3) |
| An ensemble votes confidently and unanimously wrong | Correlated errors — same model, same prompt, same blind spot | All voters' answers near-identical yet wrong; the judge agrees with the majority | Different models or prompts per voter; ensembles only on verifiable outputs; always A/B against the single-agent baseline at matched tokens (2.5) |
| A cancelled run keeps spending tokens | Orphaned workers — cancellation didn't propagate through the delegation tree | agent_start events with no matching agent_end after the run is cancelled; usage accrues post-cancel |
asyncio task cancellation or a cancel_event every loop checks; define join semantics per architecture (3.4) |
| Worker output smuggles instructions into the lead's context | Prompt injection via agent output — untrusted content (fetched pages, user docs) flows back inside briefs and reports | Lead model_call input contains worker text with imperative phrasing; the final answer echoes it |
Provenance labels (trust: untrusted) on everything that crossed a boundary; quarantine worker output; approval gates on consequential actions (3.3, Module 12) |
Part 4: Agent-to-agent protocols: A2A#
Deep-dive
Everything so far assumed your agents live in your process, coordinated by your code. Agent-to-agent protocols solve a different problem: letting agents built by different teams, in different frameworks, possibly on different machines, discover and delegate to each other.
4.1 What A2A is, and what problem it solves#
A2A (Agent2Agent) is an open protocol for communication between opaque agentic applications. Originally developed by Google and donated to the Linux Foundation, it reached v1.0 in March 2026 and joined the Agentic AI Foundation (AAIF) — the Linux Foundation-directed home it shares with sibling projects MCP, goose and AGENTS.md — in August 2026. As of November 2026 it is backed by 150+ organizations, has native support in Google Cloud, AWS Bedrock AgentCore Runtime and Microsoft Azure AI Foundry, and is supported by frameworks including LangGraph, CrewAI, Pydantic AI, AG2 and IBM BeeAI. Sources: https://a2a-protocol.org/latest/, https://a2a-protocol.org/latest/blog/2026/08/27/a-new-chapter-for-a2a-joining-the-agentic-ai-foundation/
The problem it solves is M×N integration: without a standard, every pair of agents from different vendors needs custom glue code. With A2A, an agent publishes a structured agent card describing its capabilities, and any compliant client can discover it, negotiate modalities and delegate a task — "securely read it, negotiate modalities, and delegate tasks without manual intervention" (AAIF announcement). The mental model the A2A docs themselves push: MCP is the vertical layer (agent ↔ tools), A2A is the horizontal layer (agent ↔ agent).
What A2A explicitly is not (their own list): not an agent development kit, not a sub-agent or tool-call protocol (your framework's primitives or MCP handle those), not a replacement for MCP, not a chat app. It's a machine-to-machine delegation protocol between independent agents that stay opaque to each other.
4.2 The core objects: agent card, task, message, artifact#
| Object | What it is | Analogy |
|---|---|---|
| Agent Card | A JSON "digital business card" at a well-known URI (.well-known/agent-card.json): name, description, version, supported interfaces (endpoint URL + protocol binding + version), capabilities (streaming, extended card), auth requirements, and a list of skills |
DNS SRV record / OpenAPI spec for an agent |
| Agent Skill | A capability declaration inside the card: id, name, description, tags, examples, input/output media modes, security requirements |
A function signature in an API spec |
| Task | A stateful unit of work with a unique ID and a lifecycle: TASK_STATE_SUBMITTED, WORKING, INPUT_REQUIRED, AUTH_REQUIRED, then a terminal COMPLETED, FAILED, CANCELED or REJECTED (v1.0 names; v0.x used kebab-case such as input-required); the thing you poll or stream |
A job in a job queue |
| Message | One turn of communication: role (user/agent) + one or more Parts |
A chat message |
| Part | The content container: exactly one of text, raw (bytes), url, or data (structured JSON), plus media type and metadata |
A MIME part |
| Artifact | A tangible output the agent produces during a task (document, data, code) — the deliverable, separate from conversation | A build artifact / file output |
| contextId | A server-generated ID grouping related tasks across interactions | A session/conversation ID |
Interaction patterns: request/response with polling for short tasks, SSE streaming for incremental results on long tasks, and push notifications (webhook callbacks) for very long-running or disconnected work. Auth is standard web security — schemes declared in the agent card, credentials in HTTP headers (OAuth 2.0-based for HTTP transports).
A card looks like this (shape verified against the v1.0 Python SDK docs; the a2a package provides these types):
# Illustrative — the a2a SDK builds this; you publish it at .well-known/agent-card.json
from a2a.types import (AgentCard, AgentCapabilities, AgentInterface,
AgentSkill)
card = AgentCard(
name="Invoice Auditor",
description="Audits supplier invoices for duplicates, tax errors and policy violations.",
version="1.2.0",
default_input_modes=["text/plain", "application/json"],
default_output_modes=["application/json"],
capabilities=AgentCapabilities(streaming=True, extended_agent_card=True),
supported_interfaces=[
AgentInterface(protocol_binding="JSONRPC",
url="https://agents.example.com/auditor",
protocol_version="1.0"),
],
skills=[AgentSkill(
id="audit_invoice",
name="Audit invoice",
description="Check an invoice against policy and return findings.",
tags=["finance", "audit"],
input_modes=["application/json"],
output_modes=["application/json"],
)],
)4.3 v1.0 and what changed#
v1.0 (March 2026) was a maturation release, not a tweak. The changes that matter to you:
- Renamed operations for consistency:
message/send→SendMessage,message/stream→SendStreamingMessage,tasks/get→GetTask,tasks/cancel→CancelTask,tasks/resubscribe→SubscribeToTask;ListTasksis new. If you learned v0.x, the wire names all changed. - Stricter typing: enum values moved from
kebab-casetoSCREAMING_SNAKE_CASE(ProtoJSON compliance); discriminatorkindfields were removed in favour of JSON member polymorphism;camelCasefield names; ISO 8601 timestamps. - Three formal bindings (HTTP/JSON, gRPC, JSON-RPC) with equivalence guarantees, replacing the earlier "JSON-RPC is the payload" framing — check which binding your endpoint declares in
supported_interfaces. - Enterprise features: Agent Card signature verification (JWS + RFC 8785 canonicalisation),
google.rpc.Statuserror taxonomy, multi-tenancy support,A2A-Version/A2A-Extensionsheaders, extension governance. - Simpler IDs: complex compound IDs like
tasks/{id}were replaced by plain UUIDs.
The lesson for you: pin to v1.0 and read the "What's New" page when upgrading — the operation renames and polymorphism change are breaking. Sources: https://a2a-protocol.org/latest/whats-new-v1/, https://a2a-protocol.org/latest/topics/key-concepts/
4.4 A2A vs MCP vs your own loop — the decision table#
| Situation | Use | Why |
|---|---|---|
| Subagent inside your own process | Your framework's primitives / your own loop (Part 6) | No protocol needed; you own context, budgets, tracing |
| Agent needs tools/APIs/data | MCP (08E.1) | Standard agent↔tool; your agent stays in charge |
| Two agents from different vendors/teams must collaborate | A2A | Discovery (agent card) + task delegation + opaque boundaries |
| Agents in the same codebase, same trust domain | Shared store / artefact passing (3.3) | Cheaper and simpler than any protocol |
| Agent marketplaces / public agent ecosystems | A2A | It's what the ecosystem is standardising on (150+ orgs) |
The honest caveats: A2A solves interoperability, not intelligence — two agents delegating over A2A still face every problem in Part 3 (delegation briefs, context boundaries, termination, cost), now across a network boundary with less visibility. It adds latency, auth surface and a new failure domain. Most teams will write A2A servers before they write A2A clients — expose your specialised agents (the invoice auditor, the docs researcher) as A2A endpoints so other systems can use them, long before you build a system that discovers and orchestrates strangers. Security is real here: agent cards can lie, tasks can be malicious, and you're delegating work to code you don't control — apply the same vetting you'd apply to a third-party API dependency, plus the prompt-injection surface of any agent output (Module 12).
Adjacent and moving fast: agentic payments and agent identity. The moment an agent can spend money or commit the user to a purchase, delegation stops being the only question — you also need proof of what the user authorised. Two protocol families are emerging (names and status as of November 2026 — verify before relying on either): AP2 (Agent Payments Protocol, originated by Google, donated to the FIDO Alliance in April 2026), which expresses user authorisation as signed "mandates" — a checkout mandate for what to buy and a payment mandate for how to pay, with human-present and human-not-present variants; and x402, a Coinbase-originated protocol reviving the HTTP 402 Payment Required status for machine payments, now stewarded by the x402 Foundation at the Linux Foundation, with an A2A extension for agent-to-agent settlement. Standards here are not settled. The engineering takeaway that applies today: treat "the agent can spend" as a risk tier above irreversible writes — require mandate-scoped credentials that cap amount and merchant, per-transaction limits, and human approval for anything beyond a small threshold — exactly the policy-layer pattern 08A.14 builds for tool calls.
Part 5: Human-agent teaming#
Deep-dive
Multi-agent systems don't remove the human; they change where the human sits. Three placements cover almost every production design:
5.1 Approvals and escalation#
The human is a gate on the delegation graph. An agent that wants to run issue_refund doesn't execute it — it creates an approval request, the run pauses (state checkpointed), a person approves/edits/rejects, and the run resumes. This is the same interrupt/resume mechanism as 08A.10's human-in-the-loop, applied at agent boundaries: the approval can gate a tool call, a delegation ("may I spawn the payments agent?"), or a final action ("may I send this report?").
Design rules:
- Approval is a state transition, not a prompt instruction. "Please ask before refunding" in a system prompt is a suggestion the model can forget mid-run; an approval gate in code is a guarantee. The tool registry wraps dangerous tools in a policy check that suspends until a decision arrives.
- Know how far a gate reaches. A deny-style rule (a disallowed tool, an argument check) can sit at every level of the delegation tree, because the model simply reads an error and carries on. A pause-style approval is different: when a worker's own loop pauses, that pause does not automatically propagate to the lead that called it. Unless the sub-run's state is checkpointed so it can be resumed later, the caller only sees that the worker did not finish. The robust designs are to put resumable approvals at the delegation boundary (approve "spawn the payments worker" before it starts), or to make the worker return a typed
needs_approvalresult carrying the pending call and a checkpoint, which the lead surfaces to the human instead of retrying. The same limit, with the code that demonstrates it, is in 08A.10 §5.3;multi_agent.pybelow has no approval layer at all, which is one of the production gaps listed after its output. - Show enough to decide. An approval request must carry what the human needs: the action, the arguments, the agent's reasoning (if available), the blast radius, and the cost so far. "Approve?" with no context trains people to click yes — which is worse than no gate.
- Edit is a first-class answer. Approve / reject / edit the arguments covers most real workflows; an editor who can fix a wrong amount beats one forced into reject-and-retry.
- Escalation is a tool, not a failure. Give agents an explicit
escalate_to_human(reason, context)path — cheaper and safer than letting them flail until budget exhaustion. Anthropic's Research system and most support agents treat "ask a person" as a normal outcome, not an error.
5.2 Takeover and handoff to humans#
Sometimes the human doesn't just approve — they take over. A support agent that hits a novel billing edge case should hand the conversation to a human agent with full context: what was tried, what was learned, what the customer said. This is a handoff, and it needs the same machinery as agent-to-agent handoffs (2.2): a transfer tool, a state marker the receiving side understands, and a summary the human can actually use.
Practical requirements:
- The human sees the trace, not just the transcript. "Agent tried X, tool returned Y, concluded Z" beats a wall of chat when someone inherits a mess at 2 a.m.
- Takeover must be reversible. If the human resolves it, can the agent resume? Design the state so a human can hand back — otherwise every escalation permanently removes the automation's coverage.
- Disclosure. Users deserve to know when they're talking to an agent, when it's delegating, and when a human is taking over — both for trust and because several jurisdictions require it for consequential actions. Module 13A owns the AI-UX side; the engineering side is: make agent/human boundaries visible events in your trace and your UI.
- Humans are also a failure sink. Every escalation path is a queue someone staffs. If your agent escalates 40% of conversations, you've built an expensive human-powered system with an LLM pre-filter — measure escalation rate as a first-class metric alongside cost and quality.
The through-line: in a multi-agent system the human is one more node — with veto power, with context needs of its own, and with a budget (attention) that is usually the scarcest resource in the whole system.
Part 6: Frameworks and the from-scratch build#
6.1 What frameworks add for multi-agent (preview of 08F.1)#
08F.1 surveys the frameworks in depth; the multi-agent-relevant capabilities to look for:
| Capability | Why it matters for multi-agent | Who has it (as of Nov 2026) |
|---|---|---|
| Subagent primitives | Spawn isolated agents with own prompts/tools/models | Claude Agent SDK (agents param), OpenAI Agents SDK (Agent.as_tool, handoffs), ADK sub-agents, LangGraph subagent pattern |
| Handoff/routing primitives | Transfer control between specialists | OpenAI Agents SDK handoffs, LangGraph swarm, ADK agent routing (experimental) |
| Hierarchical orchestration | Supervisor/worker trees, loops, parallel | ADK template workflows (sequential/loop/parallel), LangGraph graphs, Microsoft Agent Framework workflows |
| Shared state / memory | Blackboard, sessions, checkpoints | ADK sessions/state, framework session stores, your own artefact store |
| Nested tracing | See the delegation tree | OpenAI Agents SDK tracing, ADK observability, LangSmith/Langfuse integrations |
| Human-in-the-loop | Approval gates, interrupts | OpenAI Agents SDK HITL, ADK callbacks, Claude Agent SDK permissions |
| Durable execution | Resume long runs, survive crashes | LangGraph checkpointing, ADK runtime, Temporal-style engines |
LangGraph's version of the subagent, handoff and router patterns, with runnable code, is 08F.13 (an optional track, the better next step if you use LangGraph).
The build-vs-adopt trade-off is 08F.1's subject; the lesson here is that multi-agent raises the stakes of that choice — a framework that hides the delegation graph makes the hardest debugging problem invisible. Whatever you adopt, keep your agents as plain functions + schemas underneath so you can leave.
6.2 The build: an orchestrator–subagent research system#
Time to build the 2.8 pattern for real. The requirements from the plan: the lead plans, spawns N parallel workers with bounded concurrency, collects results, synthesises with citations — all testable with ScriptedModel, all pure stdlib.
The design (maps to Part 3 throughout):
call_model(messages, tools, agent=...) -> ModelReply— this file's model boundary; theagentlabel is what makes it multi-agent (per-agent budgets, traces and scripted replies).ScriptedModelfakes it deterministically.run_agent— the bounded loop (steps/tokens/wall-clock budgets, tool-call cap, trace events per call, model-call failures contained asstatus="error"). The wall-clock budget bounds each model call too, and the tool allow-list is enforced where tools execute, not only where they are advertised: a model can emit any tool name it has seen, so hiding a tool from the spec list is not access control.ResearchOrchestrator.run— plan (JSON, malformed subtasks dropped, worker ids made unique, capped atmax_subtasks, one repair retry; the plan'stoolslists are requests intersected with a fixed ceiling, because the plan comes from a model that has read untrusted pages) →asyncio.Semaphore-bounded fan-out with exception containment → synthesise, with one numbered source list so the lead's[n]citations mean something (and no synthesis call at all when every worker failed). The lead's own calls are traced and counted like a worker's.ArtefactStore— workersstore_findingnotes; messages carry digests + IDs (3.3).TraceLog— nested trace tree; delegation events carry a brief hash so "what did the worker think it was told?" is answerable (3.8).- Fake
web_search/web_fetchover an in-memory corpus — everything runs with zero network.
How this file relates to 08A.2 and 08A.10. Those lessons ship their own runtimes; this is a third, deliberate minimal variant — an orchestrator needs a model boundary that knows which agent is calling (08A.2's ChatAdapter.call(history) and 08A.10's call_model(messages, tools) carry no agent label). The names rhyme on purpose; the signatures are this file's own:
| Concept | 08A.2 (agent.py) |
08A.10 (agent_loop.py) |
multi_agent.py (here) |
|---|---|---|---|
| Model boundary | ChatAdapter.call(history) -> ModelTurn |
call_model(messages, tools, **kwargs) -> ModelReply |
call_model(messages, tools, agent=...) -> ModelReply — adds the agent label |
| Test double | ScriptedModel(script: list[tuple]), a ChatAdapter |
ScriptedModel(replies: list) |
ScriptedModel(script: dict[agent, list[ModelReply]]) — per-agent queues |
| Agent result | AgentResult(status, answer, steps, trace, spent) |
AgentResult(answer, stop_reason, messages, events) |
AgentResult(agent, task, status, text, usage, sources, artefacts, trace_id, parent_trace_id) |
| Loop | run_agent(adapter, user_message, ...) |
run_agent(call_model, registry, messages, ...) |
run_agent(runtime, spec, task, *, parent_id) |
| Budgets | Budget |
Budget |
Budgets — per-agent fields, plus the orchestrator's own caps |
| Tools | ToolSpec (pydantic args_model, risk) + REGISTRY |
Tool + ToolRegistry |
ToolSpec dataclass + ToolRegistry |
| Trace | TraceEntry list per run |
events list per run |
TraceLog — one event tree across all agents |
multi_agent.py imports nothing from them — save it as its own file and python multi_agent.py just works.
The complete file (~810 lines, standard library only):
"""multi_agent.py — an orchestrator-subagent research system, stdlib only.
Every model call goes through this file's `call_model` boundary: a function
taking (messages, tools, agent=...) and returning a ModelReply. The `agent`
label is what makes this boundary multi-agent — it lets ScriptedModel replay
canned replies per agent and lets the trace attribute every call. The names
rhyme with 08A.2/08.5's runtimes but the signatures are this file's own; see
the mapping table in the lesson's 6.2. ScriptedModel replays canned replies
so the whole system runs deterministically with no API key; a provider
adapter can replace it in production.
"""
from __future__ import annotations
import asyncio
import hashlib
import json
import time
import uuid
from dataclasses import dataclass, field
from typing import Any, Awaitable, Callable
# ---------------------------------------------------------------------------
# 1. The model boundary
# ---------------------------------------------------------------------------
@dataclass
class ToolCall:
id: str
name: str
arguments: dict[str, Any] = field(default_factory=dict)
@dataclass
class ModelReply:
text: str = ""
tool_calls: list[ToolCall] = field(default_factory=list)
input_tokens: int = 0
output_tokens: int = 0
finish_reason: str = "stop" # "stop" | "tool_calls" | "max_tokens" | "error"
ModelFn = Callable[..., Awaitable[ModelReply]]
# ---------------------------------------------------------------------------
# 2. Budgets, specs, results, trace
# ---------------------------------------------------------------------------
@dataclass
class Budgets:
max_steps: int = 15 # model calls per agent run
max_tool_calls: int = 30
max_input_tokens: int = 120_000 # total input tokens spent by this run
max_output_tokens: int = 40_000
wall_clock_s: float = 240.0
@dataclass
class AgentSpec:
name: str
system_prompt: str
allowed_tools: list[str] = field(default_factory=list)
budgets: Budgets = field(default_factory=Budgets)
model: str = "default" # label for cost accounting / tracing
@dataclass
class AgentResult:
agent: str
task: str
status: str # ok | partial | error | budget_exhausted
text: str
tool_calls_made: int
steps: int
usage: dict[str, int] # {"input_tokens","output_tokens"}
sources: list[str] # URLs surfaced by tools
artefacts: list[str] # artefact ids produced
trace_id: str
parent_trace_id: str | None
error: str | None = None
@dataclass
class TraceEvent:
trace_id: str
parent_id: str | None
agent: str
kind: str # system_run|agent_start|model_call|tool_call|delegation|decision|warning|agent_end
detail: dict[str, Any]
ts: float
class TraceLog:
"""A nested-trace log: every system run, agent run, model call and
tool call is one event carrying trace_id + parent_id."""
def __init__(self) -> None:
self.events: list[TraceEvent] = []
def emit(self, *, trace_id: str, parent_id: str | None, agent: str,
kind: str, detail: dict[str, Any] | None = None) -> None:
self.events.append(TraceEvent(trace_id, parent_id, agent, kind,
detail or {}, time.monotonic()))
def render(self) -> str:
"""Indented tree for tests and demos."""
by_parent: dict[str | None, list[TraceEvent]] = {}
for e in self.events:
by_parent.setdefault(e.parent_id, []).append(e)
lines: list[str] = []
def walk(parent: str | None, depth: int) -> None:
for e in by_parent.get(parent, []):
extra = ""
if e.kind == "model_call":
extra = f" in={e.detail.get('input_tokens')} out={e.detail.get('output_tokens')}"
elif e.kind == "tool_call":
extra = f" {e.detail.get('name')}"
elif e.kind == "delegation":
extra = f" -> {e.detail.get('agent')} ({e.detail.get('status', '?')})"
elif e.kind == "decision":
extra = f" subtasks={e.detail.get('subtasks')}"
elif e.kind == "warning":
extra = f" {e.detail}"
lines.append(" " * depth + f"[{e.kind}] {e.agent}{extra}")
if e.kind in ("system_run", "agent_start"): # only containers have children
walk(e.trace_id, depth + 1)
roots = [e for e in self.events if e.parent_id is None]
for r in roots:
lines.append(f"[run] {r.agent}")
walk(r.trace_id, 1)
return "\n".join(lines)
# ---------------------------------------------------------------------------
# 3. Tool registry and artefact store
# ---------------------------------------------------------------------------
@dataclass
class ToolSpec:
name: str
description: str
parameters: dict[str, Any] # JSON-Schema *properties* map for the
# arguments object; wire_specs wraps it
# in a full {"type": "object", ...} schema
fn: Callable[..., Awaitable[Any]]
@dataclass
class ToolOutcome:
content: str # what the model sees (JSON or error text)
raw: Any # the tool's return value, for the runtime
is_error: bool = False
class ToolRegistry:
"""Name -> ToolSpec. call() validates nothing deeply (08A.6 owns schema
validation); it executes with a timeout and turns exceptions into
error results the model can read."""
def __init__(self) -> None:
self._tools: dict[str, ToolSpec] = {}
def register(self, spec: ToolSpec) -> None:
self._tools[spec.name] = spec
def wire_specs(self, allowed: list[str]) -> tuple[list[dict[str, Any]], list[str]]:
"""Provider-shaped tool specs for the allowed names, plus the names that
aren't registered — returned separately so the runtime can warn instead
of silently dropping a typo'd tool."""
specs: list[dict[str, Any]] = []
missing: list[str] = []
for n in allowed:
t = self._tools.get(n)
if t is None:
missing.append(n)
else:
specs.append({"type": "function", "name": t.name,
"description": t.description,
"parameters": {"type": "object",
"properties": t.parameters}})
return specs, missing
async def call(self, name: str, arguments: dict[str, Any]) -> ToolOutcome:
spec = self._tools.get(name)
if spec is None:
return ToolOutcome(json.dumps({"error": f"unknown tool {name!r}"}), None, True)
try:
raw = await asyncio.wait_for(spec.fn(**arguments), timeout=30.0)
return ToolOutcome(json.dumps(raw, default=str), raw)
except Exception as exc: # noqa: BLE001 — tool errors are data for the model
return ToolOutcome(json.dumps({"error": f"{type(exc).__name__}: {exc}"}),
None, True)
class ArtefactStore:
"""Shared store for worker outputs: the 'filesystem' in Anthropic's
anti-telephone pattern. Agents write artefacts; messages carry only
references. The store lives in the tool layer — build_tools(store)
binds it into store_finding — not on AgentRuntime."""
def __init__(self) -> None:
self._items: dict[str, dict[str, Any]] = {}
async def put(self, kind: str, content: str, *, agent: str) -> str:
aid = f"art-{uuid.uuid4().hex[:10]}"
self._items[aid] = {"kind": kind, "content": content,
"author": agent, "created": time.time()}
return aid
async def get(self, artefact_id: str) -> dict[str, Any]:
return self._items[artefact_id]
def ids_for(self, agent: str) -> list[str]:
return [i for i, it in self._items.items() if it["author"] == agent]
# ---------------------------------------------------------------------------
# 4. The agent runtime and the agent loop
# ---------------------------------------------------------------------------
class AgentRuntime:
"""Everything an agent needs that isn't part of its spec."""
def __init__(self, call_model: ModelFn, registry: ToolRegistry,
trace: TraceLog) -> None:
self.call_model = call_model
self.registry = registry
self.trace = trace
async def call_model_traced(self, messages: list[dict], tools: list[dict] | None,
*, agent: str, trace_id: str, parent_id: str | None) -> ModelReply:
reply = await self.call_model(messages, tools, agent=agent)
self.trace.emit(trace_id=trace_id, parent_id=parent_id, agent=agent,
kind="model_call",
detail={"input_tokens": reply.input_tokens,
"output_tokens": reply.output_tokens,
"finish_reason": reply.finish_reason,
"tool_calls": [c.name for c in reply.tool_calls]})
return reply
_WEB_SCHEMES = ("http://", "https://")
def _harvest(raw: Any, sources: list[str], artefacts: list[str]) -> None:
"""Collect provenance from tool results: URLs and artefact ids."""
if isinstance(raw, dict):
for key in ("url", "sources"):
v = raw.get(key)
if isinstance(v, str) and v.startswith(_WEB_SCHEMES):
sources.append(v)
elif isinstance(v, list):
sources.extend(u for u in v
if isinstance(u, str) and u.startswith(_WEB_SCHEMES))
if isinstance(raw.get("artefact_id"), str):
artefacts.append(raw["artefact_id"])
for v in raw.values():
_harvest(v, sources, artefacts)
elif isinstance(raw, list):
for v in raw:
_harvest(v, sources, artefacts)
async def run_agent(runtime: AgentRuntime, spec: AgentSpec, task: str, *,
parent_id: str | None = None) -> AgentResult:
"""The bounded agent loop: call model -> run tool calls -> repeat, until a
final answer or a budget/stop condition. One trace tree per run. A failed
model call becomes a status="error" result — it never escapes to the
orchestrator as an exception."""
trace_id = uuid.uuid4().hex[:12]
runtime.trace.emit(trace_id=trace_id, parent_id=parent_id, agent=spec.name,
kind="agent_start", detail={"task": task[:200],
"model": spec.model})
messages: list[dict] = [
{"role": "system", "content": spec.system_prompt},
{"role": "user", "content": task}]
usage = {"input_tokens": 0, "output_tokens": 0}
tool_calls_made = 0
steps_done = 0
sources: list[str] = []
artefacts: list[str] = []
status, text, error = "ok", "", None
started = time.monotonic()
# Resolve the wire tool list once. A name that isn't registered is a
# warning in the trace, not a silent drop — a typo'd tool would otherwise
# vanish and the worker would fail for no visible reason.
wire_tools, missing_tools = runtime.registry.wire_specs(spec.allowed_tools)
if missing_tools:
runtime.trace.emit(trace_id=trace_id, parent_id=trace_id, agent=spec.name,
kind="warning",
detail={"missing_tools": missing_tools,
"allowed_tools": spec.allowed_tools})
for _ in range(spec.budgets.max_steps):
# Budgets: tokens, tool calls, wall clock.
if (usage["input_tokens"] > spec.budgets.max_input_tokens or
usage["output_tokens"] > spec.budgets.max_output_tokens or
time.monotonic() - started > spec.budgets.wall_clock_s):
status, error = "budget_exhausted", "token or wall-clock budget hit"
break
# The wall-clock budget also bounds the model call itself: checking it
# only between steps would let one hung provider call stall the run.
remaining = spec.budgets.wall_clock_s - (time.monotonic() - started)
try:
reply = await asyncio.wait_for(
runtime.call_model_traced(
messages, wire_tools,
agent=spec.name, trace_id=trace_id, parent_id=trace_id),
timeout=max(remaining, 0.001))
except asyncio.TimeoutError:
status, error = "budget_exhausted", "wall-clock budget hit during a model call"
break
except Exception as exc: # noqa: BLE001 — model failures are results, not crashes
status, error = "error", f"model call failed: {type(exc).__name__}: {exc}"
break
steps_done += 1
usage["input_tokens"] += reply.input_tokens
usage["output_tokens"] += reply.output_tokens
messages.append({"role": "assistant", "content": reply.text,
"tool_calls": [{"id": c.id, "name": c.name,
"arguments": c.arguments}
for c in reply.tool_calls]})
if reply.finish_reason == "error":
status, error = "error", "model reported finish_reason='error'"
text = reply.text
break
if not reply.tool_calls:
text = reply.text
if reply.finish_reason == "max_tokens":
# Cut off mid-answer: usable, but not a clean finish.
status, error = "partial", "output truncated (finish_reason='max_tokens')"
break
if tool_calls_made + len(reply.tool_calls) > spec.budgets.max_tool_calls:
status, error = "budget_exhausted", "tool-call budget hit"
break
async def _run_tool(c: ToolCall) -> ToolOutcome:
# Enforce the allow-list where tools EXECUTE, not just where they
# are advertised: wire_specs only hides a tool from the model, and
# a model can still emit any name it has seen or been told about.
if c.name not in spec.allowed_tools:
return ToolOutcome(json.dumps({"error": f"tool {c.name!r} is not "
f"allowed for agent {spec.name!r}"}),
None, True)
return await runtime.registry.call(c.name, c.arguments)
outcomes = await asyncio.gather(*(_run_tool(c) for c in reply.tool_calls))
tool_calls_made += len(reply.tool_calls)
for call, out in zip(reply.tool_calls, outcomes):
_harvest(out.raw, sources, artefacts)
runtime.trace.emit(trace_id=trace_id, parent_id=trace_id, agent=spec.name,
kind="tool_call",
detail={"name": call.name, "is_error": out.is_error})
messages.append({"role": "tool", "tool_call_id": call.id,
"name": call.name, "content": out.content})
else:
status, error = "budget_exhausted", f"max_steps={spec.budgets.max_steps} reached"
if status == "ok" and not text:
status = "partial"
runtime.trace.emit(trace_id=trace_id, parent_id=trace_id, agent=spec.name,
kind="agent_end",
detail={"status": status, "steps": steps_done,
"tool_calls": tool_calls_made, "usage": usage})
return AgentResult(agent=spec.name, task=task, status=status, text=text,
tool_calls_made=tool_calls_made, steps=steps_done,
usage=usage, sources=sorted(set(sources)),
artefacts=artefacts, trace_id=trace_id,
parent_trace_id=parent_id, error=error)
# ---------------------------------------------------------------------------
# 5. Fake web tools + corpus (pure local, no network)
# ---------------------------------------------------------------------------
CORPUS: dict[str, dict[str, str]] = {
"https://docs.example.dev/hnsw": {
"title": "HNSW index internals",
"text": "HNSW builds a multi-layer graph. Search starts at an entry point "
"and greedily descends, then explores neighbours within ef_search. "
"Recall improves with ef_search at the cost of latency."},
"https://blog.example.dev/filtered-ann": {
"title": "Filtered ANN search is hard",
"text": "Post-filtering shrinks results: apply the filter after the ANN "
"scan and you may return fewer than k rows. Iterative scan keeps "
"scanning until enough rows survive the filter."},
"https://docs.example.dev/ivfflat": {
"title": "IVFFlat indexes",
"text": "IVFFlat clusters vectors into lists at build time. Queries probe "
"the nearest lists; nprobe controls recall vs speed."},
"https://papers.example.dev/quantization": {
"title": "Scalar and binary quantization",
"text": "Quantization compresses vectors to int8 or binary codes, cutting "
"memory 4-32x. Rescoring against full vectors recovers recall."},
"https://bench.example.dev/recall-latency": {
"title": "Recall-latency trade-offs measured",
"text": "On a 1M-vector benchmark, HNSW at ef=100 reached 0.97 recall at "
"~2ms; IVFFlat at nprobe=16 reached 0.91 at ~1ms."},
"https://docs.example.dev/metadata": {
"title": "Metadata filtering strategies",
"text": "Three strategies: post-filter (simple, lossy), pre-filter "
"(exact, slow on selective filters), and iterative scan "
"(scan until enough rows survive)."},
}
def build_tools(store: ArtefactStore) -> ToolRegistry:
reg = ToolRegistry()
async def web_search(query: str, max_results: int = 5) -> dict:
q = query.lower().split()
hits = sorted(
({"url": u, "title": p["title"],
"snippet": p["text"][:120]}
for u, p in CORPUS.items()
if any(w in (p["title"] + " " + p["text"]).lower() for w in q)),
key=lambda r: -sum(w in r["title"].lower() for w in q))[:max_results]
return {"results": hits}
async def web_fetch(url: str) -> dict:
if url not in CORPUS:
return {"error": f"no page at {url}"}
return {"url": url, "title": CORPUS[url]["title"], "text": CORPUS[url]["text"]}
async def store_finding(title: str, content: str) -> dict:
# The worker's name is bound in by run_agent's caller via spec; the
# artefact records whichever agent the runtime attributes it to.
aid = await store.put("finding", content, agent="worker")
return {"artefact_id": aid, "title": title}
reg.register(ToolSpec("web_search", "Search the fake web corpus.",
{"query": {"type": "string"},
"max_results": {"type": "integer"}}, web_search))
reg.register(ToolSpec("web_fetch", "Fetch one corpus page by URL.",
{"url": {"type": "string"}}, web_fetch))
reg.register(ToolSpec("store_finding", "Persist a research finding as an artefact.",
{"title": {"type": "string"},
"content": {"type": "string"}}, store_finding))
return reg
# ---------------------------------------------------------------------------
# 6. Orchestrator-subagent research system
# ---------------------------------------------------------------------------
LEAD_PROMPT = """You are the research lead. You do NOT research yourself: you plan,
delegate to workers, then synthesise their findings into a cited answer.
To plan, reply with ONLY a JSON object:
{"subtasks": [{"id": "s1", "title": "...", "instructions": "...",
"tools": ["web_search","web_fetch"], "effort": "light|normal|deep"}]}
Rules: 1-4 subtasks for a normal question; give each a distinct, non-overlapping
objective; every subtask MUST include instructions a worker can execute alone.
After workers report, synthesise a concise answer with [n] citations mapped to
the sources workers returned. Never invent sources."""
WORKER_PROMPT = """You are a research worker. Complete ONLY the brief you are given.
Use web_search with short queries, web_fetch the most promising pages, then
store_finding your notes as an artefact. Finish with a <=150 word digest of
your findings and the URLs you actually used. If you cannot verify something,
say so — never fabricate sources."""
EFFORT_STEPS = {"light": 6, "normal": 12, "deep": 20}
# The most a worker may ever be given. The plan comes from a model that has
# read untrusted pages, so its "tools" lists are requests, not entitlements:
# they are intersected with this ceiling, never trusted as written.
WORKER_TOOL_CEILING = ("web_search", "web_fetch", "store_finding")
def _brief(sub: dict, question: str) -> str:
return (f"Research question: {question}\n\n"
f"Your subtask ({sub.get('title','?')}): {sub.get('instructions','')}\n"
f"Report back a digest plus sources. Do not cover other subtasks.")
def _worker_spec(sub: dict, question: str) -> AgentSpec:
effort = sub.get("effort", "normal")
asked = sub.get("tools")
granted = [t for t in (asked if isinstance(asked, list) else [])
if t in WORKER_TOOL_CEILING]
return AgentSpec(
name=f"worker-{sub.get('id','x')}",
system_prompt=WORKER_PROMPT,
allowed_tools=granted or list(WORKER_TOOL_CEILING),
budgets=Budgets(max_steps=EFFORT_STEPS.get(effort, 12),
max_tool_calls=EFFORT_STEPS.get(effort, 12) + 4,
wall_clock_s=120.0))
def _parse_plan(text: str, *, cap: int = 4) -> list[dict]:
"""Extract the plan JSON from the lead's reply; tolerate prose around it.
`cap` is the spawn limit — the caller passes its max_subtasks budget."""
start, end = text.find("{"), text.rfind("}")
if start == -1 or end <= start:
raise ValueError("lead did not return a JSON plan")
plan = json.loads(text[start:end + 1])
subs = plan.get("subtasks")
if not isinstance(subs, list):
raise ValueError("plan has no subtasks")
# Keep only well-formed subtasks (objects with instructions a worker can
# act on), and make worker names unique: two subtasks sharing an id would
# share a trace name, an artefact owner and a scripted-model queue.
clean: list[dict] = []
seen: set[str] = set()
for i, sub in enumerate(subs, start=1):
if not isinstance(sub, dict) or not str(sub.get("instructions", "")).strip():
continue
sid = str(sub.get("id") or f"s{i}")
while sid in seen:
sid += "x"
seen.add(sid)
clean.append({**sub, "id": sid})
if not clean:
raise ValueError("plan has no usable subtasks")
return clean[:cap] # hard cap: never spawn unboundedly
def _sha(text: str) -> str:
"""Short hash for the trace — enough to match a delegation to its brief
without storing the whole prompt in every event."""
return hashlib.sha256(text.encode()).hexdigest()[:12]
def _numbered_sources(results: list[AgentResult]) -> list[str]:
"""One global, de-duplicated source list in first-seen order. The lead's
[n] citations are only meaningful if [n] is defined somewhere it can see."""
seen: list[str] = []
for r in results:
for url in r.sources:
if url not in seen:
seen.append(url)
return seen
async def _synthesise(runtime: AgentRuntime, lead_spec: AgentSpec,
question: str, results: list[AgentResult], *,
trace_id: str, sources: list[str]) -> ModelReply:
"""The lead's final call — the most expensive one, since it re-reads every
worker digest. Returns the whole ModelReply so its tokens count in the
system rollup ([3.7](#37-cost-accounting-across-agents))."""
report = "\n\n".join(
f"## {r.agent} ({r.status})\n{r.text}" for r in results)
numbered = "\n".join(f"[{i}] {u}" for i, u in enumerate(sources, start=1))
return await runtime.call_model_traced(
[{"role": "system", "content": lead_spec.system_prompt},
{"role": "user", "content":
f"Question: {question}\n\nWorker reports:\n{report}\n\n"
f"Numbered sources (cite ONLY these, as [n]):\n{numbered or '(none)'}\n\n"
"Write the final cited answer."}],
tools=None, agent=lead_spec.name,
trace_id=trace_id, parent_id=trace_id)
class ResearchOrchestrator:
"""plan -> bounded parallel fan-out -> synthesise."""
def __init__(self, runtime: AgentRuntime, *, max_parallel: int = 3,
max_subtasks: int = 4) -> None:
self.runtime = runtime
self.max_parallel = max_parallel
self.max_subtasks = max_subtasks
self.lead_spec = AgentSpec(
name="lead", system_prompt=LEAD_PROMPT, allowed_tools=[],
budgets=Budgets(max_steps=4, max_input_tokens=200_000,
max_output_tokens=30_000))
async def run(self, question: str) -> dict[str, Any]:
rt = self.runtime
run_id = uuid.uuid4().hex[:12]
lead_id = uuid.uuid4().hex[:12]
rt.trace.emit(trace_id=run_id, parent_id=None, agent="system",
kind="system_run", detail={"question": question[:200]})
# The lead is an agent run too: its plan, delegation and synthesis
# calls nest under agent_start/agent_end exactly like a worker's.
rt.trace.emit(trace_id=lead_id, parent_id=run_id, agent="lead",
kind="agent_start",
detail={"task": question[:200],
"model": self.lead_spec.model})
lead_usage = {"input_tokens": 0, "output_tokens": 0}
lead_status, lead_error = "ok", None
def _count(reply: ModelReply) -> None:
lead_usage["input_tokens"] += reply.input_tokens
lead_usage["output_tokens"] += reply.output_tokens
try:
# 1. Plan (one repair retry if the JSON is malformed). Every lead
# model call is traced and its tokens counted — synthesis is the
# most expensive call in the system.
plan_msgs = [{"role": "system", "content": LEAD_PROMPT},
{"role": "user", "content": f"Research question: {question}"}]
reply = await rt.call_model_traced(
plan_msgs, None, agent="lead",
trace_id=lead_id, parent_id=lead_id)
_count(reply)
try:
subtasks = _parse_plan(reply.text, cap=self.max_subtasks)
except (ValueError, json.JSONDecodeError):
plan_msgs += [{"role": "assistant", "content": reply.text},
{"role": "user", "content":
"That was not valid JSON. Return ONLY the plan object."}]
reply = await rt.call_model_traced(
plan_msgs, None, agent="lead",
trace_id=lead_id, parent_id=lead_id)
_count(reply)
subtasks = _parse_plan(reply.text, cap=self.max_subtasks)
rt.trace.emit(trace_id=lead_id, parent_id=lead_id, agent="lead",
kind="decision",
detail={"subtasks": [s.get("id") for s in subtasks]})
# 2. Fan out under a semaphore; workers never see each other.
# return_exceptions=True: a worker that crashes outright becomes
# an error result — it can't take the other results down with it.
sem = asyncio.Semaphore(self.max_parallel)
async def work(sub: dict) -> AgentResult:
async with sem:
spec = _worker_spec(sub, question)
brief = _brief(sub, question)
res = await run_agent(rt, spec, brief, parent_id=run_id)
rt.trace.emit(trace_id=lead_id, parent_id=lead_id,
agent="lead", kind="delegation",
detail={"agent": res.agent,
"subtask": sub.get("id"),
"status": res.status,
"sources": len(res.sources),
"brief_sha": _sha(brief)})
return res
gathered = await asyncio.gather(*(work(s) for s in subtasks),
return_exceptions=True)
results: list[AgentResult] = []
for sub, res in zip(subtasks, gathered):
if isinstance(res, BaseException):
agent_name = f"worker-{sub.get('id', 'x')}"
rt.trace.emit(trace_id=lead_id, parent_id=lead_id,
agent="lead", kind="delegation",
detail={"agent": agent_name,
"subtask": sub.get("id"),
"status": "error",
"error": f"{type(res).__name__}: {res}"[:200]})
res = AgentResult(
agent=agent_name, task=_brief(sub, question),
status="error", text="",
tool_calls_made=0, steps=0,
usage={"input_tokens": 0, "output_tokens": 0},
sources=[], artefacts=[], trace_id="",
parent_trace_id=run_id,
error=f"{type(res).__name__}: {res}")
results.append(res)
# 3. Synthesise — traced and counted like every other lead call.
# If no worker returned anything, there is nothing to synthesise:
# asking the model for a "cited answer" anyway invites an invented
# one, so report the failure instead and skip the most expensive call.
sources = _numbered_sources(results)
if any(r.text.strip() for r in results):
synth = await _synthesise(rt, self.lead_spec, question, results,
trace_id=lead_id, sources=sources)
_count(synth)
else:
errors = "; ".join(f"{r.agent}: {r.error or r.status}" for r in results)
synth = ModelReply(text="No worker returned findings, so there is no "
f"answer to give. ({errors})")
lead_status = "error"
lead_error = "no worker returned findings"
except Exception as exc:
lead_status = "error"
lead_error = f"{type(exc).__name__}: {exc}"
raise
finally:
rt.trace.emit(trace_id=lead_id, parent_id=lead_id, agent="lead",
kind="agent_end",
detail={"status": lead_status, "error": lead_error,
"usage": dict(lead_usage)})
# System rollup: every model call in the tree — workers, the plan
# (both attempts if it needed repair) and synthesis — counted once.
total = {"input_tokens": lead_usage["input_tokens"] +
sum(r.usage["input_tokens"] for r in results),
"output_tokens": lead_usage["output_tokens"] +
sum(r.usage["output_tokens"] for r in results)}
return {"question": question, "run_id": run_id, "plan": subtasks,
"results": results, "answer": synth.text, "sources": sources,
"usage": total,
"lead_usage": dict(lead_usage)}
# ---------------------------------------------------------------------------
# 7. ScriptedModel: deterministic fake for tests and demos
# ---------------------------------------------------------------------------
class ScriptedModel:
"""Replays canned ModelReply objects per agent name.
This is the multi-agent variant of the scripted fake: 08A.2's
ScriptedModel is a ChatAdapter replaying one queue; 08A.10's replays one
list; this one keys queues by agent name because an orchestrator's whole
point is that different agents get different replies.
script: {"lead": [reply, reply, ...], "worker-s1": [...], "*": [...]}
Calls are recorded in .calls for assertions. No network, deterministic.
"""
def __init__(self, script: dict[str, list[ModelReply]],
default: ModelReply | None = None) -> None:
self.script = {k: list(v) for k, v in script.items()}
self.default = default or ModelReply(text="(script exhausted)")
self.calls: list[dict[str, Any]] = []
async def __call__(self, messages: list[dict], tools: list[dict] | None = None,
*, agent: str = "") -> ModelReply:
self.calls.append({"agent": agent, "n_messages": len(messages),
"n_tools": len(tools or [])})
# An agent with its own queue never falls through to "*", even once
# that queue is exhausted — otherwise a drained script would quietly
# start answering from someone else's replies.
queue = self.script[agent] if agent in self.script else self.script.get("*", [])
return queue.pop(0) if queue else self.default
# ---------------------------------------------------------------------------
# 8. Demo
# ---------------------------------------------------------------------------
QUESTION = ("How do vector databases handle filtered nearest-neighbour "
"search, and what are the main trade-offs?")
def _tc(i: int, name: str, **args) -> ModelReply:
return ModelReply(tool_calls=[ToolCall(id=f"call_{i}", name=name,
arguments=args)])
SCRIPT: dict[str, list[ModelReply]] = {
"lead": [
ModelReply(text=json.dumps({"subtasks": [
{"id": "s1", "title": "ANN index types",
"instructions": "Compare HNSW and IVFFlat for filtered search.",
"tools": ["web_search", "web_fetch", "store_finding"],
"effort": "normal"},
{"id": "s2", "title": "Filtering strategies",
"instructions": "Explain post-filter vs iterative scan vs pre-filter.",
"tools": ["web_search", "web_fetch", "store_finding"],
"effort": "normal"}]})),
ModelReply(text="Vector databases handle filtered ANN search three ways "
"[1][2]. Post-filtering applies the metadata filter after "
"the approximate scan and can return fewer than k rows; "
"iterative scan keeps scanning until enough rows survive "
"[3]. HNSW offers higher recall at higher ef_search cost "
"[4], while IVFFlat trades recall for speed via nprobe [5]. "
"Quantization cuts memory 4-32x with rescoring to recover "
"recall [6]."),
],
"worker-s1": [
_tc(1, "web_search", query="HNSW IVFFlat filtered"),
_tc(2, "web_fetch", url="https://docs.example.dev/hnsw"),
_tc(3, "store_finding", title="Index comparison",
content="HNSW: graph-based, ef_search controls recall/latency. "
"IVFFlat: cluster probes via nprobe. Both support post-filter."),
ModelReply(text="HNSW and IVFFlat are the two main ANN indexes. HNSW "
"reaches ~0.97 recall at ef=100 (~2ms); IVFFlat ~0.91 at "
"nprobe=16 (~1ms) on a 1M benchmark. Sources: "
"https://docs.example.dev/hnsw, "
"https://docs.example.dev/ivfflat, "
"https://bench.example.dev/recall-latency"),
],
"worker-s2": [
_tc(1, "web_search", query="filtered ANN post-filter iterative"),
_tc(2, "web_fetch", url="https://docs.example.dev/metadata"),
_tc(3, "store_finding", title="Filter strategies",
content="Post-filter is simple but lossy; iterative scan fixes the "
"shortfall by scanning until k rows survive; pre-filter is "
"exact but slow on selective filters."),
ModelReply(text="Three filtering strategies exist: post-filter (lossy), "
"iterative scan (scan until enough rows survive), and "
"pre-filter (exact, slow). Sources: "
"https://blog.example.dev/filtered-ann, "
"https://docs.example.dev/metadata"),
],
}
async def main() -> None:
registry = build_tools(ArtefactStore())
trace = TraceLog()
runtime = AgentRuntime(ScriptedModel(SCRIPT), registry, trace)
orch = ResearchOrchestrator(runtime)
report = await orch.run(QUESTION)
print("=== TRACE ===")
print(trace.render())
print("\n=== PLAN ===")
for s in report["plan"]:
print(f" {s['id']}: {s['title']} ({s.get('effort','?')})")
print("\n=== WORKER RESULTS ===")
for r in report["results"]:
print(f" {r.agent}: status={r.status} steps={r.steps} "
f"tools={r.tool_calls_made} sources={len(r.sources)}")
print(f"\n=== ANSWER ===\n{report['answer']}")
print(f"\nusage={report['usage']}")
if __name__ == "__main__":
asyncio.run(main())Real output (run it yourself — deterministic, no key needed):
=== TRACE ===
[run] system
[agent_start] lead
[model_call] lead in=0 out=0
[decision] lead subtasks=['s1', 's2']
[delegation] lead -> worker-s1 (ok)
[delegation] lead -> worker-s2 (ok)
[model_call] lead in=0 out=0
[agent_end] lead
[agent_start] worker-s1
[model_call] worker-s1 in=0 out=0
[tool_call] worker-s1 web_search
[model_call] worker-s1 in=0 out=0
[tool_call] worker-s1 web_fetch
[model_call] worker-s1 in=0 out=0
[tool_call] worker-s1 store_finding
[model_call] worker-s1 in=0 out=0
[agent_end] worker-s1
[agent_start] worker-s2
[model_call] worker-s2 in=0 out=0
[tool_call] worker-s2 web_search
[model_call] worker-s2 in=0 out=0
[tool_call] worker-s2 web_fetch
[model_call] worker-s2 in=0 out=0
[tool_call] worker-s2 store_finding
[model_call] worker-s2 in=0 out=0
[agent_end] worker-s2
=== PLAN ===
s1: ANN index types (normal)
s2: Filtering strategies (normal)
=== WORKER RESULTS ===
worker-s1: status=ok steps=4 tools=3 sources=4
worker-s2: status=ok steps=4 tools=3 sources=2
=== ANSWER ===
Vector databases handle filtered ANN search three ways [1][2]. Post-filtering applies the metadata filter after the approximate scan and can return fewer than k rows; iterative scan keeps scanning until enough rows survive [3]. HNSW offers higher recall at higher ef_search cost [4], while IVFFlat trades recall for speed via nprobe [5]. Quantization cuts memory 4-32x with rescoring to recover recall [6].
usage={'input_tokens': 0, 'output_tokens': 0}Reading the trace: the system run contains three agent runs — lead plus the two workers — each an agent_start/agent_end pair with its own nested model_call/tool_call events, exactly the tree 3.8 describes. Under lead you can see the whole orchestration story: the plan model_call, the decision (which subtasks it chose), a delegation event per worker carrying its status and a brief_sha hash (match it against _brief(sub, question) to answer "what was the worker told?"), the synthesis model_call, and agent_end. usage is zero because ScriptedModel doesn't bill tokens; a real adapter fills input_tokens/output_tokens per call, run() sums every call in the tree — workers, plan (both attempts if repaired) and synthesis — and report["usage"] gives you the system's total spend (3.7).
What this omits for readability (the production gaps, named honestly): the plan is trusted after one JSON repair rather than reviewed by a critic agent; worker results aren't schema-validated beyond status; there's no system-level budget across workers (only per-agent caps plus max_subtasks/max_parallel); no cancellation propagation; no durable state — a crash loses the run; store_finding attributes artefacts to "worker" rather than the specific agent (bind the spec name through the registry in production); result statuses are ok | partial | error | budget_exhausted — a model call that outlives the wall-clock budget is reported as budget_exhausted and a max_tokens cut-off as partial, but there is no distinct timeout or cancelled status and no cancel_event; and web_search is a toy scorer, not BM25 — Module 06 owns real retrieval. Each gap maps to a Part 3 section; 08A.14 hardens exactly these.
Testing it — the ScriptedModel design means every coordination behaviour is unit-testable without a model:
# test_multi_agent.py — deterministic tests, no API key, no packages.
# Plain functions: `python test_multi_agent.py` runs them all (pytest also works).
import asyncio
import json
from multi_agent import (AgentRuntime, ArtefactStore, ModelReply,
ResearchOrchestrator, ScriptedModel, ToolCall,
build_tools, TraceLog, _parse_plan)
from multi_agent import SCRIPT # reuse the demo script
def runtime_with(script):
trace = TraceLog()
return AgentRuntime(ScriptedModel(script), build_tools(ArtefactStore()), trace), trace
def test_parse_plan_tolerates_prose():
subs = _parse_plan('Here is the plan: {"subtasks": [{"id": "a", "instructions": "x"}]} done')
assert subs == [{"id": "a", "instructions": "x"}]
def test_parse_plan_caps_subtasks():
text = json.dumps({"subtasks": [{"id": str(i), "instructions": "x"} for i in range(10)]})
assert len(_parse_plan(text)) == 4 # default cap
assert len(_parse_plan(text, cap=2)) == 2 # caller's max_subtasks
def test_parse_plan_drops_malformed_subtasks_and_dedupes_ids():
text = json.dumps({"subtasks": [
"just a string", {"id": "a"}, # not an object / no instructions
{"id": "a", "instructions": "first"}, {"id": "a", "instructions": "second"}]})
subs = _parse_plan(text)
assert [s["id"] for s in subs] == ["a", "ax"] # unique worker names
try:
_parse_plan(json.dumps({"subtasks": ["only strings"]}))
except ValueError:
pass
else:
raise AssertionError("a plan with no usable subtasks must be rejected")
def test_worker_cannot_use_a_tool_outside_its_allow_list():
"""The allow-list is enforced where tools execute, not just where they are advertised."""
sneaky = ModelReply(tool_calls=[ToolCall(id="c", name="store_finding",
arguments={"title": "t", "content": "c"})])
script = {"lead": [ModelReply(text=json.dumps({"subtasks": [
{"id": "s1", "instructions": "look things up", "tools": ["web_search"]}]})),
ModelReply(text="done")],
"worker-s1": [sneaky, ModelReply(text="gave up")]}
async def go():
runtime, trace = runtime_with(script)
return await ResearchOrchestrator(runtime).run("q"), trace
report, trace = asyncio.run(go())
assert report["results"][0].artefacts == [] # nothing was stored
assert any(e.kind == "tool_call" and e.detail["is_error"] for e in trace.events)
def test_plan_cannot_grant_a_worker_tools_above_the_ceiling():
from multi_agent import _worker_spec
spec = _worker_spec({"id": "s1", "tools": ["web_search", "delete_everything"]}, "q")
assert spec.allowed_tools == ["web_search"]
assert "delete_everything" not in _worker_spec({"id": "s2", "tools": "all"}, "q").allowed_tools
def test_orchestrator_runs_and_traces():
async def go():
runtime, trace = runtime_with(SCRIPT)
report = await ResearchOrchestrator(runtime).run("q")
return report, trace
report, trace = asyncio.run(go())
kinds = [e.kind for e in trace.events]
assert "system_run" in kinds and "agent_start" in kinds
assert "delegation" in kinds and "model_call" in kinds
assert all(r.status == "ok" for r in report["results"])
assert len(report["results"]) == 2
assert report["answer"].startswith("Vector databases")
def test_worker_budget_exhaustion_is_contained():
"""A worker that never stops calling tools hits its budget, not the run."""
loop_reply = ModelReply(tool_calls=[ToolCall(id="c", name="web_search",
arguments={"query": "x"})])
script = {"lead": SCRIPT["lead"],
"worker-s1": [loop_reply] * 30,
"worker-s2": SCRIPT["worker-s2"]}
async def go():
runtime, _ = runtime_with(script)
return await ResearchOrchestrator(runtime).run("q")
report = asyncio.run(go())
s1 = next(r for r in report["results"] if r.agent == "worker-s1")
# effort="normal" -> max_steps=12, one tool call per step: exactly 12.
assert s1.status == "budget_exhausted"
assert s1.steps == 12 and s1.tool_calls_made == 12
def test_worker_model_error_is_contained():
"""A worker whose model call raises becomes status=error; the run completes."""
base = ScriptedModel(SCRIPT)
async def flaky(messages, tools=None, *, agent=""):
if agent == "worker-s1":
raise RuntimeError("429 rate limit")
return await base(messages, tools, agent=agent)
async def go():
trace = TraceLog()
rt = AgentRuntime(flaky, build_tools(ArtefactStore()), trace)
return await ResearchOrchestrator(rt).run("q")
report = asyncio.run(go())
s1 = next(r for r in report["results"] if r.agent == "worker-s1")
assert s1.status == "error" and "rate limit" in s1.error
s2 = next(r for r in report["results"] if r.agent == "worker-s2")
assert s2.status == "ok" # sibling unaffected
assert report["answer"] # synthesis still ran
def test_truncated_answer_is_partial_not_ok():
cut = ModelReply(text="HNSW is a gra", finish_reason="max_tokens")
script = {"lead": [ModelReply(text=json.dumps({"subtasks": [
{"id": "s1", "instructions": "x"}]})), ModelReply(text="final")],
"worker-s1": [cut]}
async def go():
runtime, _ = runtime_with(script)
return await ResearchOrchestrator(runtime).run("q")
r = asyncio.run(go())["results"][0]
assert r.status == "partial" and "max_tokens" in r.error
def test_a_hung_model_call_hits_the_wall_clock_budget():
from multi_agent import AgentSpec, Budgets, run_agent
async def hang(messages, tools=None, *, agent=""):
await asyncio.sleep(60)
async def go():
rt = AgentRuntime(hang, build_tools(ArtefactStore()), TraceLog())
spec = AgentSpec("w", "sys", budgets=Budgets(wall_clock_s=0.05))
return await run_agent(rt, spec, "task")
res = asyncio.run(go())
assert res.status == "budget_exhausted" and "wall-clock" in res.error
def test_all_workers_failing_skips_synthesis_instead_of_inventing_an_answer():
async def boom(messages, tools=None, *, agent=""):
if agent == "lead":
return await lead_model(messages, tools, agent=agent)
raise RuntimeError("down")
lead_model = ScriptedModel({"lead": [SCRIPT["lead"][0], ModelReply(text="INVENTED ANSWER")]})
async def go():
rt = AgentRuntime(boom, build_tools(ArtefactStore()), TraceLog())
return await ResearchOrchestrator(rt).run("q")
report = asyncio.run(go())
assert "INVENTED" not in report["answer"] and "No worker returned findings" in report["answer"]
def test_exhausted_agent_queue_does_not_fall_through_to_the_wildcard():
model = ScriptedModel({"a": [], "*": [ModelReply(text="from wildcard")]},
default=ModelReply(text="default"))
reply = asyncio.run(model([], None, agent="a"))
assert reply.text == "default"
if __name__ == "__main__":
for name in sorted(n for n in globals() if n.startswith("test_")):
globals()[name]()
print(f"PASS {name}")Run with python test_multi_agent.py — the __main__ block runs every test_* function (pytest works too if you have it, but nothing here needs it). The failure-isolation tests are the multi-agent properties from 3.6: one runaway worker exhausts its budget, one worker whose model call raises becomes an error result, and a hung model call hits the wall-clock budget — while the run and its sibling complete either way. The security tests pin the two least-privilege rules above (a worker cannot execute a tool outside its allow-list; a plan cannot grant tools above the ceiling), and one test checks that a run where every worker failed reports the failure instead of asking the lead to write a cited answer from nothing.
6.3 What providers give you natively#
Before writing more orchestration code, check what your provider's agent SDK already does — verified as of November 2026 (full survey in 08F.1):
| Provider / SDK | Multi-agent primitives | Notes |
|---|---|---|
| Claude Agent SDK | Subagents via agents={name: AgentDefinition(...)} — each with own prompt, tools/disallowedTools, model, skills, mcpServers, maxTurns, background; also .claude/agents/ markdown files and a built-in general-purpose subagent. Context isolation, parallelisation and tool restriction are the documented benefits. |
The subagent's intermediate tool calls stay inside it; only its final message returns. maxTurns marks partial output when the cap hits. Docs: https://platform.claude.com/docs/en/agent-sdk/subagents |
| Claude Managed Agents (beta) | Agent/environment/session/event model; built-in tools (Bash, file ops, web search/fetch, MCP); steer/interrupt mid-run; scheduled deployments. Header managed-agents-2026-04-01; not ZDR-eligible. |
Anthropic's "harness" answer — you get the loop, sandbox and session management hosted. https://platform.claude.com/docs/en/managed-agents/overview |
| OpenAI Agents SDK | Two orchestration styles: orchestrating via LLM (agents as tools via Agent.as_tool(), handoffs where a triage agent routes and the specialist owns the turn) and orchestrating via code (structured outputs, chaining, while-loop evaluator, asyncio.gather parallelism). Built-in tracing. |
The docs' own guidance: agents-as-tools when a specialist helps a bounded subtask; handoffs when routing is the workflow. https://openai.github.io/openai-agents-python/multi_agent/ |
| Google ADK | ADK 2.0 workflows: graph-based, dynamic (code), collaborative (one coordinator agent + sub-agents), and template workflows (sequential, loop, parallel); experimental agent routing; sessions/state/memory; A2A expose and consume support. | https://google.github.io/adk-docs/workflows/ |
| Microsoft Agent Framework | 1.0 GA (April 2026, .NET + Python): typed graph workflows, multi-provider models, A2A + MCP; successor to AutoGen (archived) and Semantic Kernel (maintenance). Agent harness with memory, skills, tool approval, OpenTelemetry. | https://devblogs.microsoft.com/agent-framework/microsoft-agent-framework-version-1-0/ |
| LangGraph | The langgraph-supervisor repository is archived (no longer actively maintained) → the subagents pattern (create_agent + tool-wrapped subagents); swarm handoffs via create_handoff_tool and Command.PARENT — handoffs must carry the tool-call message and its result or history is malformed. Checkpointers for durable state. |
https://docs.langchain.com/oss/python/langchain/multi-agent/handoffs, https://docs.langchain.com/oss/python/migrate/langgraph-supervisor |
The pattern across all of them: the framework gives you the coordination primitives; you still own the delegation prompts, budgets, evals and trace design. That's why Part 3 matters more than which SDK you pick.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "More agents = smarter system." | Multi-agent buys parallelism, isolation and specialisation — not intelligence. DeepMind's 260-config study found it hurts sequential tasks (−39% to −70% on PlanCraft) and helps decomposable ones (+80.8% on Finance-Agent); a capability threshold predicts when it stops helping. |
| "Agents share what they learn automatically." | Each subagent sees only its brief. Cognition's two principles — share context, and remember actions carry implicit decisions — are why vague delegation produces confident contradictions. |
| "The orchestrator can just read all the transcripts." | Transcripts are the wrong channel: lossy, expensive, and they drown the synthesis context. Pass digests + artefact references (3.3). |
| "If one worker fails, the run fails." | Design for partial failure: typed status on every result, explicit join semantics, and a decision per architecture about whether partial findings are usable. |
| "Multi-agent is roughly 2× the cost of one agent." | Anthropic measured ~15× chat tokens for their research system and ~4× for agents generally; tokens explain ~80% of BrowseComp performance variance. Budget accordingly. |
| "Debate makes answers better." | Ensembles help when errors are independent and outputs verifiable; same-model same-prompt voting amplifies correlated mistakes. Measure against the single-agent baseline at matched token budget. |
| "Role-play teams are a multi-agent architecture." | Personas without separation of concerns give you the costs (tokens, coordination, debugging) with none of the benefits. If removing the roles changes nothing, they were decoration. |
| "A2A replaces MCP." | They're complementary layers: MCP connects agents to tools, A2A connects agents to agents. A2A is also explicitly not a sub-agent protocol — your framework's primitives handle that. |
| "You can debug a multi-agent run from the final answer." | The answer is the least informative artefact. You need the nested trace: who spawned whom, with what brief, calling what, returning what (3.8). |
| "Once it works in the demo, it works in production." | Anthropic's gap between prototype and production was "wider than anticipated": statefulness, compounding errors, deployment coordination and synchronous-execution bottlenecks all bit after the architecture was proven. |
Key takeaways#
- Multi-agent is a scaling technique for tasks that exceed one context window and one linear trajectory — parallelisable research, context isolation, specialised tools/permissions, independent verification, per-role models. It is not a general upgrade, and the providers' own numbers (~15× tokens, error compounding, coordination overhead) say so.
- The four taxes are cost, errors, coordination and debugging. Match the architecture to the task's structure: decomposable → fan-out/orchestrator; sequential → single agent or pipeline; verifiable → critic/enumerate; routing → handoffs.
- The delegation brief is the highest-leverage artifact: objective, output format, boundaries, tool guidance, effort scaling — validated as data by your code before anything spawns.
- Context is the boundary problem: children see only the brief, parents see only the digest, siblings see nothing. Pass artefacts + references, label provenance, and treat plan/findings as durable state, not conversation.
- Termination, conflicts, loops and partial failure are designed, not hoped for: budgets at every level, a system-wide budget, typed result statuses, join semantics, delegation-graph loop detection, and cancellation that propagates.
- Cost accounting and nested traces are per-agent and per-run: every
AgentResultcarries usage +parent_trace_id; the system rollup is a tree-fold; match token budgets when A/B testing architectures. - Evaluation checks outcomes and process on a small live suite plus deterministic scripted-model trajectory tests; version prompts + specs + budgets as one release.
- A2A (v1.0, AAIF/Linux Foundation) is the agent↔agent layer — agent cards, tasks, messages, artifacts — complementary to MCP, for cross-vendor delegation; expose agents before you orchestrate strangers.
- Humans are nodes too: approval gates in code (not prompts), escalation as a first-class tool, takeover with trace context, and escalation rate as a metric.
- The from-scratch build works:
multi_agent.pyruns the whole orchestrator–subagent research loop on stdlib Python +ScriptedModel— plan, bounded fan-out, synthesise with citations, nested trace — and every coordination behaviour is unit-testable without an API key.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Multi-agent system | Two or more LLM agents (separate contexts, budgets, tools) coordinated on a shared task |
| Subagent | A separate agent instance spawned by a parent to handle a focused subtask in its own context window |
| Orchestrator–subagents | Lead agent plans, delegates to parallel workers, synthesises their condensed results |
| Handoff / swarm | Control transfers to a specialist agent that owns the rest of the turn; swarms allow peer-to-peer transfer |
| Agents-as-tools | A whole agent registered as a single tool call inside another agent's registry |
| Supervisor / hierarchical | Tree of agents where supervisors decompose, delegate, review and may re-delegate |
| Blackboard / shared state | Agents coordinate through a shared store rather than direct messages |
| Ensemble / voting | Same task run through N agents with programmatic or judge-based aggregation |
| Critic / verifier agent | A second agent that checks the first's output, ideally with different tools or model |
| Role-play team | Agents with persona prompts but no real separation of concerns — usually anti-pattern |
| Delegation brief | The structured instruction (objective, format, boundaries, tools, effort) passed to a subagent |
| Context isolation | Each agent's fresh context window; the source of both compression and information loss |
| Artefact | A durable output stored externally; messages carry references, not payloads |
| Agent card | A2A's JSON discovery document describing an agent's endpoint, capabilities and skills |
| Task / Message / Part / Artifact (A2A) | A2A's stateful work unit / one turn of communication / its content container / tangible outputs |
| contextId | A2A's server-generated ID grouping related tasks across interactions |
| Agentic AI Foundation (AAIF) | Linux Foundation-directed foundation hosting A2A, MCP, goose and AGENTS.md |
| MAST | Multi-Agent System failure Taxonomy: 14 failure modes in three categories, annotated from 1,600+ traces (arXiv 2503.13657) |
| Nested trace | A trace tree (system run → agent runs → model/tool calls) for multi-agent observability |
| System budget | A run-level cap on total tokens/cost/wall-clock/subagents, enforced by code |
| Escalation | An agent's explicit path to hand a decision or task to a human |
| ScriptedModel | A deterministic fake call_model replaying canned replies per agent for tests |
All terms are also collected in the glossary.
Exercises#
- Budget maths: a system has 1 lead (3 calls) + 5 workers × 12 steps × ~4 calls/step average. Estimate total model calls and, assuming ~8k input tokens/call, the rough input-token bill. How does it compare to a single agent doing the same task in 30 calls? What does this say about when fan-out pays?
- Delegation brief: take the
QUESTIONinmulti_agent.pyand write a bad delegation brief ("research vector databases") and a good one (all five elements from 3.1). Predict which failure modes each produces, then check against Anthropic's reported bugs. - Extend the build: add a third worker spec for "quantization trade-offs" to
SCRIPTandLEAD_PROMPT's example plan, runmain(), and inspect the trace — does the semaphore still bound concurrency? What doesreport["usage"]show? - Failure injection: modify
worker-s1's script so its second reply calls a nonexistent tool ("name": "web_search2"). Trace what the loop returns for that call (_run_toolchecks the allow-list beforeregistry.callis reached), what the model sees, and whether the run still completes. Which 3.6 row does this exercise? - Termination: give
worker-s2a script that callsweb_searchforever (30 identical tool-call replies). Confirmstatus == "budget_exhausted"and thatworker-s1and the synthesis still complete — the isolation property. - Swarm sketch: implement
run_swarmfrom 2.2 overrun_agent+ScriptedModelwith two agents and atransfer_to_agenttool. Script a handoff and a ping-pong; verifymax_handoffsstops the loop — and thatmax_turnsstops a specialist that never stops calling ordinary tools. - A2A card: write an
AgentCardfor one of your Module 07 RAG agents (thedocs_qaretriever) as if exposing it over A2A — skills, interfaces, capabilities. What would you not expose, and why? - Eval design: design a 20-query eval suite for the research orchestrator: 5 decomposable, 5 sequential, 5 ambiguous, 5 adversarial (prompt-injection in a fake page). What metrics per category, and what would you measure first?
- Label failures with MAST: take the failure gallery in 3.10 and tag each row with the MAST category it belongs to (system design, inter-agent misalignment or task verification). Which category has the fewest rows, and what failure would you add to cover it?
Hints
- Calls: 3 + 5 × 12 × 4 = 243. Input tokens at 8k per call is about 1.9 million, against 30 × 8k = 240k for the single agent — roughly eight times. Fan-out pays when wall-clock time or context overflow is the binding constraint, not when tokens are.
- A good brief has all five elements: objective, output format, boundaries, tool guidance, effort scaling. Bad briefs produce duplicated work and invented sources.
- Add a third subtask with its own script entry (worker ids are
worker-<subtask id>); the semaphore bounds running workers, so withmax_parallel=2the third waits.report["usage"]stays zero withScriptedModel. - The call never reaches
registry.call:_run_toolrejects any name outsidespec.allowed_toolsand returns an errorToolOutcome(tool 'web_search2' is not allowed for agent 'worker-s1'). The model reads it as a tool result and the run completes: the "worker tool fails" row. - 30 identical replies with
effort="normal"givesteps == 12; the other worker and the synthesis are unaffected. - The loop in 2.2 is the skeleton; scripted ping-pong should end with the "budget exhausted" string after exactly
max_handoffstransfers. - Skills only (what the agent can do), no internal prompts, tools or index paths; the card is public, so describe capabilities, not implementation.
- Per category: decomposable → coverage and cost; sequential → accuracy against a single-agent baseline; ambiguous → clarification behaviour; adversarial → whether the injected instruction was obeyed. Measure the single-agent baseline first, at matched tokens.
- Duplicated work, vague delegation → system design; lost context, lossy telephone → inter-agent misalignment; unanimous wrong vote, unchecked worker output → task verification.
Check yourself#
- What is the module's definition of an agent, and at what point does a system become multi-agent?An agent is an LLM using tools in a loop to reach a goal with the model controlling the flow. It becomes multi-agent when two or more separate agent instances — own contexts, budgets, tools — coordinate on a shared task. Patterns inside one loop (orchestrator-workers as a pattern, routing) are single-agent; separate instances are multi-agent.
- Name the four taxes of multi-agent and the provider-published number behind each.Cost multiplication (~15× chat tokens for Anthropic's multi-agent research, ~4× for agents generally), error compounding (each probabilistic step multiplies failure probability; no-centralised-verification architectures propagate errors more), coordination overhead (spawn/delegate/synchronise costs and failure modes like 50-subagent spawning), debugging difficulty (non-deterministic trees of trajectories).
- List the five cases where multi-agent earns its place.Parallelisable research/fan-out, context isolation/overflow, specialised prompts/tools/permissions, independent verification, different models per role.
- What five elements must a delegation brief contain, and what did Anthropic's production research system teach about them?Objective, output format, boundaries (what's out of scope), tool guidance, effort scaling. Anthropic's production system showed vague briefs cause duplicated work and misinterpretation; the orchestrator needs explicit rules for how many subagents to spawn per complexity band.
- State Cognition's two context-engineering principles and the failure they prevent.Share context (full traces, not just messages) and actions carry implicit decisions (agents that can't see each other's work make conflicting assumptions — the Flappy Bird example).
- What did the DeepMind/MIT scaling study find about sequential vs decomposable tasks?Centralised coordination improved decomposable tasks (+80.8% on Finance-Agent) but every multi-agent variant lost on sequential planning (−39% to −70% on PlanCraft, −70% for independent agents); a capability-saturation effect (single-agent baselines around 45% on their benchmarks) predicts when adding agents stops helping.
- Why is "role-play team" almost always the wrong multi-agent pattern?Personas add prompt and messaging overhead without separation of concerns — same context, tools and blind spots — so you pay multi-agent costs for single-agent benefits. Prefer explicit ensembles or verifier agents.
- What crosses the context boundary downward, upward and laterally — and what is lost in each direction?Downward: only the brief — planning context must be re-stated. Upward: only the requested digest — evidence and confidence are lost unless requested. Laterally: nothing — siblings can't see each other, enabling duplicated work and contradictions.
- When should findings travel as artefacts rather than messages?When findings are long or need to persist: artefacts keep fidelity, provenance and low parent-context cost; messages suit short digests and verdicts.
- Who can decide a multi-agent run is "done", what bounds each decider, and how do you detect and cap delegation loops?The model (bounded by code budgets), the code (on structural completion), and humans (on policy/irreversible actions). Loop defences: per-agent and system budgets (
max_subtasks,max_handoffs,max_turns), identical-brief repeat detection on the delegation graph in the trace, and a wall-clock circuit breaker. - What cost accounting and trace structure does a multi-agent system need?Three levels: per-call
usage→ per-agent-run rollup → per-system-run rollup attributed to the delegation tree (each result carriesparent_trace_id; the lead's calls count too). The trace is a tree — system run → agent runs → model/tool calls — and every event carriestrace_id+parent_id(+ agent, kind, detail). - Why can't you evaluate multi-agent systems by checking the steps?Because paths vary run to run — you judge outcome correctness plus process reasonableness (right tools, sane effort), not a prescribed trajectory.
- What problem does A2A solve that MCP doesn't, and what does it explicitly not do?A2A solves M×N cross-vendor agent interoperability via agent-card discovery and task delegation. It is explicitly not a sub-agent/tool-call protocol, not an agent framework, and not an MCP replacement.
- What's the difference between an approval gate and an escalation path?An approval gates an action before it happens (approve/edit/reject); an escalation hands the problem to a human as a normal outcome when the agent can't or shouldn't proceed.
- In
multi_agent.py, which line enforces bounded parallelism, and which caps total subtasks?asyncio.Semaphore(self.max_parallel)insidework()bounds concurrency;_parse_plan(reply.text, cap=self.max_subtasks)slices the cleaned plan withclean[:cap](default 4) somax_subtasksis a real cap, not decoration.
Further resources#
- 08A.4 — Harness Engineering: sub-agents for context isolation, and separating generating from evaluating.
- Anthropic, How we built our multi-agent research system (June 2025): the canonical production write-up — architecture, token multipliers, delegation prompting, evals, reliability.
- Cognition, Don't Build Multi-Agents (June 2025): the essential counter-argument — context-engineering principles for agent systems.
- DeepMind/MIT, Towards a Science of Scaling Agent Systems (December 2025): the first large controlled study of when multi-agent helps.
- Cemri et al., Why Do Multi-Agent LLM Systems Fail? (March 2025, revised October 2025): the MAST failure taxonomy and the 1,600+ annotated traces.
- Anthropic, Building effective agents (December 2024): workflows vs agents and the orchestrator-workers pattern (note the page's own caveat that tooling has moved on → Managed Agents).
- Anthropic, Effective harnesses for long-running agents (November 2025): initializer + coding agent pattern for work spanning many context windows.
- A2A Protocol: https://a2a-protocol.org/latest/ — What's New in v1.0, Core Concepts, A2A and MCP, AAIF announcement, specification, SDKs.
- Provider agent SDKs: Claude Agent SDK subagents, Claude Managed Agents, OpenAI Agents SDK — Agent orchestration and handoffs, Google ADK workflows, Microsoft Agent Framework 1.0, LangGraph handoffs/multi-agent and migrate from langgraph-supervisor.
- This module: 08D.1 and 08D.2 are the beginner path; 08F.13 builds the same patterns in LangGraph (optional track).
- Earlier lessons: 08A.2 tool loop, 08A.9 workflows vs agents, 08A.10 agent patterns, 08B.2 agent memory, 08E.1 MCP, 08F.1 frameworks, 08A.14 reliable agents; 04.7 context over time, 03.7 cost, 03.10 testing, 03.11 provider-agnostic client.
← 08D.2 — Hands-On: Two-Agent vs Single-Agent, Built, Traced and Evaluated | Module 08D overview | Module 08E: Protocols and Extensibility →