TAI BUI
Back to curriculum
LearnTypeScript

Why Multi-Agent?

One agent eventually hits a wall. Past that point, the fix is usually more agents, not a bigger one.

TIME: ~60 minutesPREREQUISITES: Phase 14 (Agent Engineering)

Learning Objectives

  • Identify the single-agent ceiling (context overflow, mixed expertise, sequential bottleneck) and explain when splitting into multiple agents is the right move
  • Compare orchestration patterns (pipeline, parallel fan-out, supervisor, hierarchical) and select the right one for a given task structure
  • Design a multi-agent system with clear role boundaries, shared state, and a communication contract
  • Analyze the tradeoffs of multi-agent complexity (latency, cost, debugging difficulty) versus single-agent simplicity

The Problem

You built a single agent in Phase 14. It works. It can read files, run commands, call APIs, and reason about results. Then you point it at a real codebase: 200 files, three languages, tests that depend on infrastructure, and a requirement to research external APIs before writing code.

The agent chokes. Not because the LLM is dumb, but because the task exceeds what one agent loop can handle. The context window fills up with file contents. The agent forgets what it read 40 tool calls ago. It tries to be a researcher, a coder, and a reviewer all at once, and does all three poorly.

This is the single-agent ceiling. You hit it every time a task requires:

  • More context than fits in one window: reading 50 files blows past 200k tokens
  • Different expertise at different stages: research requires different prompting than code generation
  • Work that can happen in parallel: why read three files sequentially when you can read them simultaneously?
Warm-up0/3
1. A single agent loop has made 40 tool calls on a large codebase, and its context window is nearly full of file contents and command output. What is the most likely effect?Warm-up
A context window bar filled about 92 percent, split into file contents, command output and earlier turns, labelled 40 tool calls in. Below it a dashed box asks about the quality of the next decision.
Illustrative; the stem gives the call count, not exact token figures.
2. An agent loop makes one LLM call, runs one tool, then makes the next LLM call. The task needs three independent file reads. How does this loop handle them?Warm-up
A loop of an LLM call then one tool run, with an arrow looping back to the start. To the right, three unconnected file boxes labelled File A, B and C are waiting to be read. A dashed box asks how many calls the three reads take.
Typed schematic of the loop described in the stem.
3. Two independent network requests each take about 2 seconds. Roughly how long does the pair take when run one after the other, and when run at the same time?Warm-up
Two boxes, Request A and Request B, each about 2 seconds. Below, two dashed rows ask for the total time when they run one after another and when they run at the same time.
Everyday setup; no specific service or numbers beyond the stem's 2 seconds.
Check: The Problem0/1
1. What is the single-agent ceiling?Define
A single agent box next to a wall line, with three labelled boxes on the other side: more context than fits, different expertise per stage, and work that could run in parallel.
The three symptoms are named directly in the lesson's Problem section.

The Concept

The Single-Agent Ceiling

A single agent is one loop, one context window, one system prompt. Picture it:

┌─────────────────────────────────────────┐
│            SINGLE AGENT                 │
│                                         │
│  ┌───────────────────────────────────┐  │
│  │         Context Window            │  │
│  │                                   │  │
│  │  research notes                   │  │
│  │  + code files                     │  │
│  │  + test output                    │  │
│  │  + review feedback                │  │
│  │  + API docs                       │  │
│  │  + ...                            │  │
│  │                                   │  │
│  │  ██████████████████████ FULL ███  │  │
│  └───────────────────────────────────┘  │
│                                         │
│  One system prompt tries to cover       │
│  research + coding + review + testing   │
│                                         │
│  Result: mediocre at everything         │
└─────────────────────────────────────────┘

Three things break:

  1. Context saturation: tool results pile up. By turn 30, the agent has consumed 150k tokens of file contents, command outputs, and prior reasoning. Critical details from turn 5 get lost.

  2. Role confusion: a system prompt that says "you are a researcher, coder, reviewer, and tester" produces an agent that half-researches, half-codes, and never finishes reviewing.

  3. Sequential bottleneck: the agent reads file A, then file B, then file C. Three serial LLM calls. Three serial tool executions. No parallelism.

The Multi-Agent Solution

Split the work. Give each agent one job, one context window, and one system prompt tuned for that job:

┌──────────────────────────────────────────────────────────┐
│                    ORCHESTRATOR                          │
│                                                          │
│  "Build a REST API for user management"                  │
│                                                          │
│         ┌──────────┬──────────┬──────────┐               │
│         │          │          │          │               │
│         ▼          ▼          ▼          ▼               │
│   ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐  │
│   │RESEARCHER│ │  CODER   │ │ REVIEWER │ │  TESTER  │  │
│   │          │ │          │ │          │ │          │  │
│   │ Reads    │ │ Writes   │ │ Checks   │ │ Runs     │  │
│   │ docs,    │ │ code     │ │ code     │ │ tests,   │  │
│   │ finds    │ │ based on │ │ quality, │ │ reports  │  │
│   │ patterns │ │ research │ │ finds    │ │ results  │  │
│   │          │ │ + spec   │ │ bugs     │ │          │  │
│   └─────┬────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘  │
│         │           │            │             │         │
│         └───────────┴────────────┴─────────────┘         │
│                          │                               │
│                     Merge results                        │
└──────────────────────────────────────────────────────────┘

Each agent has:

  • A focused system prompt ("You are a code reviewer. Your only job is finding bugs.")
  • Its own context window (not polluted by other agents' work)
  • A clear input/output contract (receives research notes, outputs code)

Real Systems That Do This

Claude Code subagents: when Claude Code spawns a subagent with Task, it creates a child agent with a scoped task. The parent keeps its context clean. The child does focused work and returns a summary.

Devin: runs a planner agent, a coder agent, and a browser agent. The planner breaks work into steps. The coder writes code. The browser researches documentation. Each has separate context.

Multi-agent coding teams (SWE-bench): top-performing systems on SWE-bench use a researcher that reads the codebase, a planner that designs the fix, and a coder that implements it. Single-agent systems score lower.

ChatGPT Deep Research: spawns multiple search agents in parallel, each exploring a different angle, then synthesizes results.

The Spectrum

Multi-agent is a spectrum, not a switch:

SIMPLE ──────────────────────────────────────────── COMPLEX

 Single        Sub-         Pipeline      Team         Swarm
 Agent         agents

 ┌───┐       ┌───┐        ┌───┐───┐    ┌───┐───┐    ┌─┐┌─┐┌─┐
 │ A │       │ A │        │ A │ B │    │ A │ B │    │ ││ ││ │
 └───┘       └─┬─┘        └───┘─┬─┘    └─┬─┘─┬─┘    └┬┘└┬┘└┬┘
               │                │        │   │       ┌┴──┴──┴┐
             ┌─┴─┐          ┌───┘───┐    │   │       │shared │
             │ a │          │ C │ D │  ┌─┴───┴─┐    │ state │
             └───┘          └───┘───┘  │  msg   │    └───────┘
                                       │  bus   │
 1 loop      Parent +      Stage by    │       │    N peers,
 1 context   child tasks   stage       └───────┘    emergent
                                       Explicit      behavior
                                       roles

Single agent: one loop, one prompt. Good for simple tasks.

Subagents: a parent spawns children for focused subtasks. The parent maintains the plan. Children report back. This is what Claude Code does.

Pipeline: agents run in sequence. Agent A's output becomes Agent B's input. Good for staged workflows: research -> code -> review -> test.

Team: agents run in parallel with a shared message bus. Each has a role. An orchestrator coordinates. Good when different skills are needed simultaneously.

Swarm: many identical or near-identical agents with shared state. No fixed orchestrator. Agents pick up work from a queue. Good for high-throughput parallel tasks.

The Four Multi-Agent Patterns

Pattern 1: Pipeline

Input ──▶ Agent A ──▶ Agent B ──▶ Agent C ──▶ Output
          (research)  (code)      (review)

Each agent transforms the data and passes it forward. Simple to reason about. Failure in one stage blocks the rest.

Pattern 2: Fan-out / Fan-in

                ┌──▶ Agent A ──┐
                │              │
Input ──▶ Split ├──▶ Agent B ──├──▶ Merge ──▶ Output
                │              │
                └──▶ Agent C ──┘

Split work across parallel agents, then merge results. Good for tasks that decompose into independent subtasks.

Pattern 3: Orchestrator-Worker

                    ┌──────────┐
                    │  Orch.   │
                    └──┬───┬───┘
                  task │   │ task
                 ┌─────┘   └─────┐
                 ▼               ▼
           ┌──────────┐   ┌──────────┐
           │ Worker A │   │ Worker B │
           └──────────┘   └──────────┘

A smart orchestrator decides what to do, delegates to workers, and synthesizes results. The orchestrator is itself an agent with tools for spawning workers.

Pattern 4: Peer Swarm

         ┌───┐ ◄──── msg ────▶ ┌───┐
         │ A │                  │ B │
         └─┬─┘                  └─┬─┘
           │                      │
      msg  │    ┌───────────┐     │ msg
           └───▶│  Shared   │◄────┘
                │  State    │
           ┌───▶│  / Queue  │◄────┐
           │    └───────────┘     │
      msg  │                      │ msg
         ┌─┴─┐                  ┌─┴─┐
         │ C │ ◄──── msg ────▶ │ D │
         └───┘                  └───┘

No central orchestrator. Agents communicate peer-to-peer. Decisions emerge from interaction. Harder to debug, but scales to many agents.

When NOT to Use Multi-Agent

Multi-agent adds complexity. Each message between agents is another place for something to fail. Debugging goes from "read one conversation" to "trace messages across five agents."

Stay single-agent when:

  • The task fits in one context window (under ~100k tokens of working data)
  • You do not need different system prompts for different stages
  • Sequential execution is fast enough
  • The task is simple enough that splitting it adds more overhead than value

The complexity cost:

  • An agent boundary is a lossy compression step: agent A's full context gets summarized into a message for agent B
  • Coordination logic (who does what, when, in what order) is its own source of bugs
  • Latency increases: N agents means at least N serial LLM calls, and more if they need to talk back and forth
  • Cost multiplies: each agent burns tokens independently

Rule of thumb: if a task takes fewer than 20 tool calls and fits in 100k tokens, keep it single-agent.

Check: The Concept0/23
1. What is the Orchestrator-Worker pattern in multi-agent systems?Define
A Task box feeds a dashed region labelled Orchestrator-Worker, containing three faint unlabeled circles, which feeds a Result box. The inner workings are left blank.
Typed schematic; only the pattern's name and its place between task and result are shown.
2. In the Peer Swarm pattern, how do agents coordinate their work?Define
Four unconnected agent circles labelled A through D. A dashed box below asks how they coordinate their work.
No connections are drawn between the four agents.
3. What is the order from simplest to most complex in The Spectrum section?Define
Five boxes named Team, Single agent, Swarm, Pipeline and Subagents, scattered with no left-to-right order. A dashed box asks for their order from simplest to most complex.
The five names are placed in a non-sequential scatter on purpose.
4. In multi-agent vocabulary, what is a coordinator?Define
A card titled Key Term, Coordinator, with a note that the lesson calls it easy to confuse with Orchestrator, and a question mark where its meaning would go.
The confusion with Orchestrator is stated directly in the lesson's Key Terms table.
5. What is consensus in a multi-agent system?Define
Two boxes, Agent A output X and Agent B output Y marked as conflicting. A dashed box below asks what happens before the system moves on.
Illustrative placeholder outputs; no real values are given for this term.
6. What does emergent behavior mean in a multi-agent system?Define
Five small agent circles connected by thin lines in a loose cluster, with no overall shape labelled. A dashed box asks for the name of the system-level pattern this produces.
Generic interaction diagram; no specific pattern shape is asserted.
7. What do fan-out and fan-in describe?Define
A Task input box feeds a dashed region labelled fan-out slash fan-in, which feeds a Combined output box. The inner mechanism is left blank.
Typed schematic; the region between input and output is left open.
8. In a multi-agent system, what is message passing?Define
Two separate agent boxes, each with its own context window drawn inside it, connected by a dashed line marked with a question mark. The windows are not merged.
Typed schematic; what crosses between the two windows is left open.
9. When is a pipeline (sequential) multi-agent pattern better than a parallel fan-out pattern?Explain
Two named boxes, Pipeline and Fan-out slash fan-in, each above a dashed strip asking what kind of stages it fits, dependent or independent. No internal structure of either pattern is drawn.
Only the two pattern names are shown; their internal wiring is left out.
10. Devin runs separate planner, coder, and browser agents. Why does giving the browser agent its own context help the coder?Explain
Three boxes for Devin's planner, coder and browser agents. A dashed line with a question mark sits between the coder and browser boxes. Below, a dashed strip asks what the coder's window ends up holding.
Names and roles are as given in the lesson's Real Systems section.
11. What is the primary tradeoff of multi-agent systems compared to single agents?Explain
A balance beam with Single agent on one side and Multi-agent, several agents, on the other. Below, a line of question marks for cost, latency, complexity and debugging.
A balance-scale schematic; no specific numbers are given in the stem.
12. Why does a prompt saying "you are a researcher, coder, reviewer, and tester" produce weak results?Explain
A single system prompt text naming four roles: researcher, coder, reviewer and tester. Below, four short progress bars, one per role, each filled only a little.
Prompt text quoted from the question stem; the bars show partial progress with no cause stated.
13. A parent agent delegates a file-heavy subtask to a subagent, as Claude Code does with Task. Why does the parent stay effective afterward?Explain
A parent agent box with a light, mostly empty context window, connected by an arrow labelled Task to a subagent box whose context window is filling with file icons. A dashed return path is marked with a question mark.
Typed schematic of the Task delegation described in the lesson's Real Systems section.
14. Why is an agent boundary called a lossy compression step?Explain
Agent A's context panel lists research notes, docs read and earlier reasoning. An arrow leads to a dashed box with a question mark, then to Agent B's context box. The dashed box's size is smaller than Agent A's panel.
Generic two-agent setup; no specific message content is shown.
15. Why does each agent in a multi-agent design need a clear input/output contract?Explain
Agent A and Agent B on either side of a dashed box labelled contract, with receives and returns each marked as a question mark.
Typed schematic; the contract's purpose is left open.
16. What is the main cost of a peer swarm compared with an orchestrator-worker design?Explain
Two named boxes, Orchestrator-Worker and Peer Swarm, each above a dashed strip asking for its main cost. No internal structure of either pattern is drawn.
Only the two pattern names are shown; their internal wiring is left out.
17. A task needs about 12 tool calls and 60k tokens of working data, and one system prompt suits every step. What should you do?Apply
Two bars: tool calls at 12 against a threshold line at 20, and tokens at 60 thousand against a threshold line at 100 thousand. A dashed box below asks whether to stay single-agent or split.
Numbers and thresholds are the ones given in the stem and the lesson's rule of thumb.
18. An agent has read 150k tokens of files and output over 30 turns. It now misremembers a function signature it read at turn 5. Which failure is this?Analyze
A context window bar nearly full, marked with the turn 5 reading point near the start and the current turn 30-plus point near the end. A dashed box asks what the agent now believes.
Illustrative fill; the stem gives the token count and turn numbers, not exact proportions.
19. A team splits a 10-tool-call task with 40k tokens of data into four agents. The run is slower, costs more, and a bug takes an hour to trace. What does this show?Analyze
Four agent boxes, with two bars below for tool calls at 10 against a threshold of 20 and tokens at 40 thousand against a threshold of 100 thousand, next to a note that the result was slower, cost more and a bug took an hour to trace. A dashed box asks what the split added.
Numbers and outcomes are the ones given in the stem.
20. In a research, code, review pipeline, the coder ignores a rate-limit rule that the researcher found in the docs. The rule is in the researcher's full transcript. Where is the likely fault?Analyze
A Researcher's full transcript box containing a rate-limit rule, an arrow through a dashed box marked with a question mark, then an arrow to a Coder box. The dashed box's contents are not shown.
The rate-limit rule is named directly in the stem; whether it crosses to the coder is masked.
21. In a five-stage pipeline, the third agent crashes on malformed input. What happens to the run?Analyze
Five stages in a row. Stage 3 is marked with a crash. Stages 4 and 5 are drawn as dashed boxes with question marks for their status.
Typed schematic of the five-stage pipeline described in the stem.
22. Your team needs a code-review bot. For each pull request it must run a security scan, a style check, and a test-gap analysis. The three do not depend on each other. Which design fits best?Design
A pull request box next to three independent check boxes: security scan, style check and test-gap analysis. A note says none depends on the others. A dashed box below asks for the design.
The three checks and their independence are given directly in the stem.
23. You must process thousands of independent support tickets an hour. Any agent can take any ticket, and no agent needs the full picture. Which design fits?Design
A queue of ticket icons feeding three unlabeled worker circles marked with question marks. A note says any agent can take any ticket and none needs the full picture. A dashed box asks for the design.
The ticket volume and constraints are given directly in the stem.

Build It

Step 1: The Overloaded Single Agent

Here is a single agent trying to do everything. It has one massive system prompt and one context window holding research, code, and reviews:

typescript
type AgentResult = {
  content: string;
  tokensUsed: number;
  toolCalls: number;
};
 
async function singleAgentApproach(task: string): Promise<AgentResult> {
  const systemPrompt = `You are a full-stack developer. You must:
1. Research the requirements
2. Write the code
3. Review the code for bugs
4. Write tests
Do ALL of these in a single conversation.`;
 
  const contextWindow: string[] = [];
  let totalTokens = 0;
  let totalToolCalls = 0;
 
  const research = await fakeLLMCall(systemPrompt, `Research: ${task}`);
  contextWindow.push(research.output);
  totalTokens += research.tokens;
  totalToolCalls += research.calls;
 
  const code = await fakeLLMCall(
    systemPrompt,
    `Given this research:\n${contextWindow.join("\n")}\n\nNow write code for: ${task}`
  );
  contextWindow.push(code.output);
  totalTokens += code.tokens;
  totalToolCalls += code.calls;
 
  const review = await fakeLLMCall(
    systemPrompt,
    `Given all previous context:\n${contextWindow.join("\n")}\n\nReview the code.`
  );
  contextWindow.push(review.output);
  totalTokens += review.tokens;
  totalToolCalls += review.calls;
 
  return {
    content: contextWindow.join("\n---\n"),
    tokensUsed: totalTokens,
    toolCalls: totalToolCalls,
  };
}

Problems with this approach:

  • The context window grows with every stage. By the review step, it contains research notes, code, and prior reasoning.
  • The system prompt is generic. It cannot be tuned for each stage.
  • Nothing runs in parallel.

Step 2: Specialist Agents

Now split it. Each agent gets one job:

typescript
type SpecialistAgent = {
  name: string;
  systemPrompt: string;
  run: (input: string) => Promise<AgentResult>;
};
 
function createSpecialist(name: string, systemPrompt: string): SpecialistAgent {
  return {
    name,
    systemPrompt,
    run: async (input: string) => {
      const result = await fakeLLMCall(systemPrompt, input);
      return {
        content: result.output,
        tokensUsed: result.tokens,
        toolCalls: result.calls,
      };
    },
  };
}
 
const researcher = createSpecialist(
  "researcher",
  "You are a technical researcher. Read documentation, find patterns, and summarize findings. Output only the facts needed for implementation."
);
 
const coder = createSpecialist(
  "coder",
  "You are a senior TypeScript developer. Given requirements and research notes, write clean, tested code. Nothing else."
);
 
const reviewer = createSpecialist(
  "reviewer",
  "You are a code reviewer. Find bugs, security issues, and logic errors. Be specific. Cite line numbers."
);

Each specialist has a focused prompt. Each gets a clean context window with only the input it needs.

Step 3: Coordinate Through Messages

Wire the specialists together with explicit message passing:

typescript
type AgentMessage = {
  from: string;
  to: string;
  content: string;
  timestamp: number;
};
 
async function multiAgentApproach(task: string): Promise<AgentResult> {
  const messages: AgentMessage[] = [];
  let totalTokens = 0;
  let totalToolCalls = 0;
 
  const researchResult = await researcher.run(task);
  messages.push({
    from: "researcher",
    to: "coder",
    content: researchResult.content,
    timestamp: Date.now(),
  });
  totalTokens += researchResult.tokensUsed;
  totalToolCalls += researchResult.toolCalls;
 
  const coderInput = messages
    .filter((m) => m.to === "coder")
    .map((m) => `[From ${m.from}]: ${m.content}`)
    .join("\n");
 
  const codeResult = await coder.run(coderInput);
  messages.push({
    from: "coder",
    to: "reviewer",
    content: codeResult.content,
    timestamp: Date.now(),
  });
  totalTokens += codeResult.tokensUsed;
  totalToolCalls += codeResult.toolCalls;
 
  const reviewerInput = messages
    .filter((m) => m.to === "reviewer")
    .map((m) => `[From ${m.from}]: ${m.content}`)
    .join("\n");
 
  const reviewResult = await reviewer.run(reviewerInput);
  messages.push({
    from: "reviewer",
    to: "orchestrator",
    content: reviewResult.content,
    timestamp: Date.now(),
  });
  totalTokens += reviewResult.tokensUsed;
  totalToolCalls += reviewResult.toolCalls;
 
  return {
    content: messages.map((m) => `[${m.from} -> ${m.to}]: ${m.content}`).join("\n\n"),
    tokensUsed: totalTokens,
    toolCalls: totalToolCalls,
  };
}

Each agent receives only the messages addressed to it, so the researcher's 50k tokens of documentation reading never enter the reviewer's context. What crosses the boundary is whatever the researcher chose to write down.

Step 4: Compare

typescript
async function compare() {
  const task = "Build a rate limiter middleware for an Express.js API";
 
  console.log("=== Single Agent ===");
  const single = await singleAgentApproach(task);
  console.log(`Tokens: ${single.tokensUsed}`);
  console.log(`Tool calls: ${single.toolCalls}`);
 
  console.log("\n=== Multi-Agent ===");
  const multi = await multiAgentApproach(task);
  console.log(`Tokens: ${multi.tokensUsed}`);
  console.log(`Tool calls: ${multi.toolCalls}`);
}

Both versions make three LLM calls here. The difference is what each call sees: the single agent re-sends its accumulated context at every stage, while each specialist gets only its own input. In this toy, the stubbed fakeLLMCall (see single_vs_multi.ts) estimates tokens from string length plus 500 per call and returns a placeholder string, so the numbers show how input size moves, not whether quality improves. With real models, a specialized prompt should help each stage, but you have to measure that.

Check: Build It0/5
1. In the Build It code, what do the `AgentMessage` type and the `.filter((m) => m.to === "coder")` line accomplish together?Apply
A code card for the AgentMessage type, with fields from, to, content and timestamp, next to a card quoting the filter line m dot to equals coder. A dashed box asks what these two pieces accomplish together.
Both snippets are quoted directly from the lesson's single_vs_multi.ts.
2. In `singleAgentApproach`, what does the review call receive as its prompt?Apply
An empty contextWindow array has the research output pushed in, then the code output pushed in, then a dashed box asks what the review call's input is.
Structure quoted from the lesson's single_vs_multi.ts, not invented.
3. In `multiAgentApproach`, what does the reviewer receive as its input?Apply
Two message cards. Message 1 is from the researcher with its to field marked as a question mark. Message 2 is from the coder, also with its to field marked as a question mark. Below, a dashed box asks for the reviewer's inbox.
Message structure quoted from single_vs_multi.ts; the to fields are masked.
4. Step 4 runs `compare()` with the stubbed `fakeLLMCall`. What is the real difference between the two approaches' three calls?Apply
Two rows of three dashed boxes each, one row labelled single agent and one labelled multi-agent. Each box is marked with a question mark. A note says both rows make 3 calls.
Call count of 3 is stated directly in the lesson text; what each call receives is masked.
5. A researcher reads 50k tokens of documentation for a coder. What should its message to the coder contain?Design
A researcher box with five stacked document icons labelled about 50 thousand tokens of docs, an arrow to a dashed box marked with a question mark, then an arrow to a coder box.
The 50,000-token figure is given directly in the stem.

Use It

This lesson produces a reusable prompt for deciding when to go multi-agent. See outputs/prompt-multi-agent-decision.md.

Author's Note

I'd run single_vs_multi.ts before trusting any number in it. fakeLLMCall returns a placeholder string, estimates tokens as input length divided by four plus 500, and picks a random tool-call count between one and five. What the output shows is how input size changes between designs, not how good the result is. The file also goes a step past the Build It snippets: multiAgentFanOut runs the researcher and a requirements analyst under Promise.all, which is the shape Exercise 3 asks for. The file also calls the Step 3 function multiAgentPipeline rather than multiAgentApproach.

My bet is that the line worth rereading is the .filter((m) => m.to === "coder") that builds each agent's input. That filter is the whole context-isolation story. The coder sees what was addressed to it and nothing else, and anything the researcher left out of its message is gone, which is the lossy handoff from the concept section.

I'd also read the tail of the fan-out version with suspicion. The reviewer runs on codeResult.content directly and its message is never pushed onto messages, so the returned transcript has no review in it, while the pipeline version does log one. Fix that when you do Exercise 3.

Exercises

  1. Add a fourth specialist: a "tester" agent that receives code from the coder and review feedback from the reviewer, then writes tests
  2. Modify the pipeline so the reviewer can send feedback back to the coder for a revision loop (max 2 rounds)
  3. Convert the sequential pipeline into a fan-out: run the researcher and a "requirements analyzer" agent in parallel, then merge their outputs before passing to the coder

Key Terms

TermWhat people sayWhat it actually means
Swarm"A hive mind of AI agents"A set of peer agents with shared state and no fixed leader. Behavior emerges from local interactions.
Orchestrator"The boss agent"An agent whose tools include spawning and managing other agents. It plans and delegates but may not do the actual work.
Coordinator"The traffic cop"A non-agent component (often just code, not an LLM) that routes messages between agents based on rules.
Consensus"The agents agree"A protocol where multiple agents must reach agreement before proceeding. Used when conflicting outputs need resolution.
Emergent behavior"The agents figured it out themselves"System-level patterns that arise from agent interactions but were not explicitly programmed. Can be useful or harmful.
Fan-out / fan-in"Map-reduce for agents"Splitting a task across parallel agents (fan-out), then combining their results (fan-in).
Message passing"Agents talk to each other"The communication mechanism between agents: structured data sent from one agent to another, replacing shared context windows.

Further Reading

Code

Ships With