◆ AI All-in-One

Level 2 Agentic Coding · Building with AI

Multi-Agent Systems

Several model-driven agents working together, usually a lead agent that hands subtasks to parallel sub-agents. It can beat a single agent on broad, parallel work, at many times the cost. This chapter covers the patterns, the arithmetic of when it pays, and the ways teams of agents fail.

Level
●●●●● Intermediate
Reading
12 min
To learn it well
1 hour to read, an afternoon to experiment
↗ Plan a path here

Read first

AI Agents

This leads to

Running Agents in Parallel and in the Background
The full path from zero — 10 concepts before this one
  1. What Is AI?
  2. Python for AI
  3. How Machines Learn
  4. Large Language Models, Explained Simply
  5. Using LLM APIs
  6. Prompt Engineering
  7. Structured Output and JSON
  8. Chain-of-Thought and Reasoning Prompts
  9. Tool Use and Function Calling
  10. AI Agents
  11. Multi-Agent Systems

Read them roughly in this order. See it on the concept map →

Why it matters

A single agent works through a task one step at a time, in one transcript. That is a problem for some tasks. Researching a market might mean reading 200 web pages. Done one by one, that is slow, and the transcript soon fills the context window with page text, most of it irrelevant by the end.

A multi-agent system splits the work among several agents. Most commonly a lead agent (the orchestrator) plans the job and hands pieces to sub-agents. Each sub-agent works in parallel with its own fresh context and sends back a short report. Anthropic described such a system behind Claude's Research feature (June 2025). On its internal research evaluation, a Claude Opus 4 lead with Claude Sonnet 4 sub-agents beat a single Claude Opus 4 agent by 90.2%.

The same report gives the catch. Agents used about 4 times as many tokens as ordinary chat, and the multi-agent system about 15 times as many. Multi-agent systems are powerful for some tasks and an expensive mistake for others. This chapter is about telling the two apart.

The intuition

Picture a newspaper editor with a big investigative story due. One reporter could do it all, but it would take weeks, and their notebook would become an unreadable mess. Instead the editor sends four reporters out at once: one to the courts, one to the company, one to former employees, one to the regulators. Each comes back with a one-page memo. The editor reads four pages, not four notebooks, and writes the story.

Two things make this work, and they are the two real benefits of multi-agent systems:

  1. Parallelism. Four reporters finish in a quarter of the time.
  2. Context isolation. Each reporter's messy notebook stays with them. Only the condensed memo reaches the editor. This is context isolation: each sub-agent's exploration happens in its own context window, and the lead sees only the results.

The analogy also shows the costs. Four reporters cost four salaries. The memos lose detail. And if two reporters' findings contradict each other, or both chased the same lead, the editor has to sort it out. Coordination is work.

Question “Should we enter market X?” Lead agent (orchestrator) plans subtasks, writes briefs, reads reports, writes the answer Answer with sources lead context ≈ 30k tokens Sub-agent pricing own context ≈ 40k search · read · check Sub-agent competitors own context ≈ 40k search · read · check Sub-agent regulation own context ≈ 40k search · read · check Sub-agent reviews own context ≈ 40k search · read · check solid: brief (objective, format, limits) dashed: short report (~300 words + sources)
Fig. 1 Orchestrator and sub-agents. The lead agent splits the question into subtasks. Each sub-agent runs its own tool loop in a separate context window (tens of thousands of tokens) and returns a short report. The lead reads only the reports and writes the answer.

Key idea Multi-agent systems buy speed and a bigger total working memory by spending many more tokens. They pay off when a task splits into independent pieces that each need a lot of reading. They do badly when the pieces depend on each other or need shared context.

How it works

Pattern 1: orchestrator and parallel sub-agents

This is the most successful pattern in practice, and it is the orchestrator-workers workflow from AI Agents with agents as workers:

  1. The lead agent reads the task and writes a plan: which subtasks, and what each sub-agent should find.
  2. It starts sub-agents with specific briefs. Each brief states the objective, the output format, which tools to use and where the boundaries are. Vague briefs ("research the market") lead to duplicated or missed work.
  3. Each sub-agent runs its own tool loop: searching, reading, checking. Then it returns a compact report.
  4. The lead combines the reports, notices gaps, and may send out another round.

Sub-agents are often a smaller, cheaper model than the lead, because their jobs are narrower. Anthropic's write-up describes the early failures of their system, and they are instructive. The lead spawned 50 sub-agents for simple queries. Sub-agents searched endlessly for sources that didn't exist. Agents distracted each other with excessive updates. The fixes were mostly prompting: tell the lead how much effort different kinds of question deserve, and teach it to write precise briefs.

Pattern 2: handoffs between specialists

Here agents take turns instead of working in parallel. A triage agent talks to the customer and then hands off the whole conversation to a billing agent or a technical agent, each with its own instructions and tools. A handoff transfers control (and usually the transcript) to another agent. OpenAI's Agents SDK is built around this idea. Handoffs are really a form of routing, and they work well when the specialties are clearly separate.

Pattern 3: debate and voting

Several agents answer the same question independently. Then either they read each other's answers and revise over a few rounds (multi-agent debate, Du et al., 2023, which found gains in factual accuracy and maths reasoning), or code takes a majority vote, as in self-consistency. A variant pairs a generator with a separate critic agent, which is the evaluator-optimizer pattern again.

Voting has a mathematical limit that is easy to miss. Suppose each agent is right with probability p=0.7p = 0.7 and the agents' errors are independent. A majority of nn agents is right with probability

P(majority right)=∑k>n/2(nk) pk(1−p)n−kP(\text{majority right}) = \sum_{k > n/2} \binom{n}{k}\, p^k (1-p)^{n-k}

where (nk)\binom{n}{k} ("nn choose kk") counts the ways to pick which kk agents are right. Worked by hand for n=3n = 3: the majority is right if all three are right (0.73=0.3430.7^3 = 0.343) or exactly two are (3×0.72×0.3=0.4413 \times 0.7^2 \times 0.3 = 0.441), so 0.343+0.441=0.7840.343 + 0.441 = 0.784. Five agents give 0.837 and nine give 0.901.

But copies of the same model, given the same prompt, tend to make the same mistakes. Their errors are correlated. Suppose that 60% of the time each agent just repeats a shared "common" answer, which is itself right 70% of the time. Now three agents give 0.730, and nine give only 0.721. Adding voters barely helps, because they mostly agree with each other, right or wrong.

0.7 0.8 0.9 1.0 1 3 5 7 9 11 13 15 17 19 21 independent errors some shared errors (30%) mostly shared errors (60%) each agent alone: right 70% of the time number of voting agents n P(majority is right)
Fig. 2 Majority-vote accuracy as agents are added, each right 70% of the time. With independent errors accuracy climbs steadily. When agents tend to share the same mistakes (correlated errors), the curve flattens and more agents buy almost nothing.

This is why diversity matters in ensembles: different models, different prompts, different evidence. It is the same lesson as Random Forests and Bagging in classical machine learning.

How the agents share information

Agents need some way to pass results around. The main options:

  • Return values. A sub-agent's final message comes back to the lead as a tool result. It is simple, and it is the usual choice.
  • A shared transcript. All agents see one conversation, as in early "group chat" frameworks such as AutoGen. Coordination is easy, but you lose context isolation and costs grow quickly.
  • Shared storage. Agents write findings to files or a database and pass references around. This keeps big outputs out of the lead's context, and it is useful when sub-agents produce code or long documents.

When several agents beat one

Ask four questions:

Question Multi-agent helps when… Single agent is better when…
Can the work be split? subtasks are independent (breadth-first research, checking many files) each step depends on the last (most coding, step-by-step debugging)
Does it overflow one context? total reading far exceeds one context window it fits comfortably
Is it worth the tokens? the answer is valuable (strategy research, due diligence) cost or latency per request matters
Do the parts need shared judgment? parts can be decided separately decisions must stay consistent with each other

Cognition, the company behind the Devin coding agent, argued in "Don't Build Multi-Agents" (June 2025) that splitting work among agents that can't see each other's decisions produces inconsistent results. Two sub-agents might build the background and the character of a game in clashing styles. Anthropic's post agrees on the domain: most coding tasks have fewer truly parallel parts than research does. The two views fit together. Parallel sub-agents are for reading and gathering. For writing one coherent artefact, keep a single agent in charge.

The cost arithmetic

A worked example with made-up but realistic sizes. A single research agent uses 60,000 tokens. A multi-agent version has a lead that uses 30,000 tokens and four sub-agents that each use 40,000: 30,000+4×40,000=190,00030{,}000 + 4 \times 40{,}000 = 190{,}000 tokens, about 3 times as many. At an illustrative price of $3 per million tokens, that is $0.18 against $0.57 per question. If each sub-agent takes 2 minutes and they run in parallel, the multi-agent version might finish in about 3 minutes, where doing the same four investigations one after another would take more than 8. You pay roughly 3 times the money to get a broader answer in about a third of the time. Whether that's a good trade depends on what the answer is worth.

In code

A minimal orchestrator with parallel sub-agents, using asyncio, plus the voting experiment from above. The sub-agent is a stand-in that sleeps instead of calling a model, so the control flow and the arithmetic can be checked offline. Runs as written with NumPy.

import asyncio, time
import numpy as np

async def sub_agent(subtask):
    """Stand-in for a sub-agent: own context, own tool loop, short report back."""
    await asyncio.sleep(0.5)                          # pretend: model + tool time
    return {"report": f"3 key facts about {subtask}", "tokens": 40_000}

async def orchestrator(question):
    subtasks = ["pricing", "competitors", "regulation", "customer reviews"]  # an LLM would plan these
    t0 = time.perf_counter()
    reports = await asyncio.gather(*(sub_agent(s) for s in subtasks))     # in parallel
    tokens = sum(r["tokens"] for r in reports) + 30_000                   # + the lead's own work
    return time.perf_counter() - t0, tokens

wall, tokens = asyncio.run(orchestrator("Should we enter the X market?"))
print(f"wall time {wall:.2f}s for 4 sub-agents (sequential: 2.0s), tokens {tokens:,}")

rng = np.random.default_rng(0)
def vote_accuracy(n, p=0.7, shared=0.0, trials=200_000):
    """Majority vote of n agents. shared = chance an agent copies one common answer."""
    common = rng.random(trials) < p
    own = rng.random((trials, n)) < p
    copy = rng.random((trials, n)) < shared
    right = np.where(copy, common[:, None], own)
    return (right.sum(1) > n / 2).mean()

for n in (1, 3, 5, 9):
    print(f"n={n}: independent {vote_accuracy(n):.3f}   correlated {vote_accuracy(n, shared=0.6):.3f}")
# wall time 0.50s for 4 sub-agents (sequential: 2.0s), tokens 190,000
# n=1: independent 0.699   correlated 0.700
# n=3: independent 0.785   correlated 0.731
# n=5: independent 0.838   correlated 0.732
# n=9: independent 0.901   correlated 0.722

In a real system, sub_agent would run the agent loop from AI Agents with its own system prompt ("You are researching pricing only. Return at most 200 words with sources.") and its own message list. The orchestrator would be a model call that writes the subtask list as structured output. Keep asyncio.gather with a concurrency limit (an asyncio.Semaphore) so you don't exceed the API's rate limits.

Common pitfalls

  • Multi-agent by default. Start with one agent. Add sub-agents only when you have measured that one agent runs out of context or time on your evaluation set.
  • Vague delegation. "Look into competitors" produces overlapping work. Give each sub-agent a precise objective, boundaries and an output format.
  • Over-spawning. Without guidance a lead may start dozens of sub-agents for a simple question. Put effort rules in its prompt ("simple fact-finding: 1 agent, 3 to 10 tool calls") and enforce caps in code.
  • Lossy reports. The lead only knows what sub-agents tell it. Ask for sources and confidence, and allow follow-up questions.
  • Inconsistent outputs. Sub-agents that each write part of one artefact make clashing choices. Gather in parallel, write in one place.
  • Debugging blindness. A failure might be in any agent or in the hand-offs between them. Log every agent's full transcript with a shared trace id.

Watch out A 2025 study of more than 1,600 annotated multi-agent traces across 7 frameworks, "Why Do Multi-Agent LLM Systems Fail?", grouped 14 failure modes into 3 categories: poor system or task specification, misalignment between agents (ignoring each other, withholding information, derailing), and weak verification of the final result. Many failures were design problems, not model problems. Specify roles clearly, and always check the final output with something other than the agents' own agreement.

Where it leads

A bit of history

Multi-agent systems are an old field in AI, from distributed problem solving in the 1980s to multi-agent reinforcement learning and game theory. The language-model version began in 2023. CAMEL and Stanford's Generative Agents ("Smallville", 25 simulated characters in a town) explored role-playing agents. Microsoft's AutoGen framework made multi-agent conversation programmable. Multi-agent debate showed gains from agents critiquing each other. MetaGPT and ChatDev cast agents as software-company roles. The excitement ran ahead of reliability, and by 2025 the mood had become more practical. Anthropic's write-up of its research system showed where multi-agent systems really pay off (breadth-first research), Cognition's essay warned against splitting coherent work, and failure taxonomies like MAST began to catalogue what goes wrong. By 2025 the consensus pattern was a single strong lead with parallel sub-agents for gathering.

Try it

  1. Change sub_agent so each one sleeps a random time between 0.2 and 1.5 seconds. Does total wall time now depend on the average or on the slowest sub-agent? What does that imply for one slow sub-agent?
  2. Add an asyncio.Semaphore(2) so at most two sub-agents run at once. Predict the wall time for four sub-agents, then measure it.
  3. Use vote_accuracy to find the smallest number of independent 70%-accurate voters that reaches 90% accuracy. Then set shared=0.3 and see whether any number of voters gets there.

Hint for 3: with independent voters you need 9 (seven give only 0.874). With shared=0.3 the accuracy levels off below 0.84.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Which task is the best fit for an orchestrator with parallel sub-agents?

  2. A single agent uses 60,000 tokens. A multi-agent version has a 30,000-token lead and four sub-agents of 40,000 tokens each. Roughly how many times more tokens does it use?

  3. You run nine copies of the same model with the same prompt and take a majority vote, but accuracy barely improves over three copies. What is the most likely reason?

  4. What is the main benefit of context isolation in an orchestrator–sub-agent system?

  5. Your lead agent sends 'look into competitors' to three sub-agents, and they return largely overlapping findings. What is the best fix?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

How we built our multi-agent research system

Anthropic · 2025 · Intermediate · Free

An unusually candid engineering write-up of an orchestrator with parallel sub-agents: architecture, prompting lessons, token costs, evaluation and production reliability.

Article

Building Effective Agents

Anthropic · 2024 · Intermediate · Free

A clear, practical essay on agent patterns (workflows vs agents) and when to use each.

Article

Don't Build Multi-Agents

Walden Yan (Cognition) · 2025 · Intermediate · Free

A counterpoint arguing that sub-agents which cannot see each other's context and decisions produce inconsistent work, with principles for context sharing.

Paper

Why Do Multi-Agent LLM Systems Fail?

Cemri et al. (UC Berkeley) · 2025 · Intermediate · Free

Analyses over 1,600 traces from 7 multi-agent frameworks and organises their failures into a taxonomy (MAST) of 14 failure modes in 3 categories.

Tool

OpenAI Agents SDK

OpenAI · Intermediate · Free

A lightweight Python framework for agents with tools, handoffs between agents, guardrails and tracing.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/building/multi-agent-systems.md