Depending on the job, a team of agents scored up to 81% higher than one agent, or up to 70% lower. Same models, same tools. The shape of the work decides.
Learn when several agents beat one, the four ways to wire them, how they talk and share work, and the many ways a team fails.
Pick a job, then pick how the team is wired. Green means the team beat one agent. Red means it lost. Then we build the whole picture, piece by piece: orchestrators and swarms, handoffs and message boards, ledgers and worktrees, and the failure modes that sink real teams.
You need a rough idea of what an agent is (a language model in a loop that calls tools, from Lecture 1) and a little Python for the code. We build the rest from zero.
Based on Lecture 8 of Stanford CS 329Z: Engineering AI Agents (Fall 2026), taught by Diyi Yang, Michael Ryan and John Yang, and its three readings. Lecture slides. Every idea is re-taught here in our own words and devices; it follows Lecture 7, Agent Memory
THE JOB
THE TEAM SHAPE
The percentages are the labels printed on the course’s chart from Kim et al. (2026), Towards a Science of Scaling Agent Systems: the change in score against a single agent on four benchmarks (Finance Agent, BrowseComp-Plus, Workbench, PlanCraft), read from the figure and rounded to whole percent. The animated messages are a drawing, not data.
Chapter 0
See where a team of agents sits on the ladder of system complexity, and why the lecture asks you to climb it slowly
Picture a Monday morning. A bug report lands in your repository. You hand it to one coding agent, and it reads the code, runs the tests, edits two files and opens a fix. It takes twenty minutes. Then a thought arrives: if one agent took twenty minutes, would ten agents take two?
The lecture opens with that thought, and with some news. The first slides show headlines about swarms of AI agents: a swarm that answered a reporter’s questions, a swarm that worked on a famous maths problem, and a safety group that traced hacking attempts to a swarm of agents running loose. Teams of agents are already at work in the world. The lecture’s promise is to break down what we know about how to build them.
So here is the plan. By the end, you should be able to do three things, and the lecture names them as its learning objectives. First, tell a single-agent system from a multi-agent one and know when each is the right pick. Second, name the ways a team can be organised, can talk, and can share work. Third, compare the ways teams fail. The third one matters most. It is easy to wire up ten agents. It is hard to make ten agents better than one.
The lecture has five parts, and the same five-box strip appears at the top of each part so that you never lose your place: single against multi-agent, orchestration, communication, coordination (shared state), and failure modes. It budgets its time like this: 10 minutes on single against multi, 5 on orchestration, 20 on communication, 20 on coordination, 15 on failures, and an optional 10 on a case study. This lesson follows the same order, with the 20-minute parts split into two chapters each.
There is a little housekeeping too, and it fits in one paragraph. The next Monday brings a guest lecture from Ryan Marten and Alex Shaw (the slide shows the Terminal-Bench logo beside them). Homework 1 is due the Friday after this lecture, and feedback on project proposals follows within days. The next lecture, on Wednesday, is about optimisation.
Before we count agents, we need to say what an agent is, and what it is not. The lecture draws one line, from simple to complex, with four stops. Each stop adds one new kind of freedom, so we will call them rungs.
Rung one is a model: one call. You send text in, you get text out, and that is the end. Think of asking a calculator one question.
Rung two is a workflow, which the lecture also calls a compound AI system. Your own code decides the steps, and a model fills in some of them. The lecture’s example is triaging a bug: step one, a model labels the report; step two, code looks up the owner; step three, a model drafts the reply. You wrote the path. The model never chooses it.
Rung three is an agent. Here the model chooses the path itself. It runs in a loop: look at the situation, pick a tool, run it, read the result, decide again. The lecture’s example is implementing a feature, where nobody can say in advance how many steps it will take.
Rung four is a multi-agent system, written MAS. The lecture defines it plainly: a collection of multiple agents oriented to solve a shared task. Its example is maintaining a whole repository, a job too large and too varied for one loop.
Try the ladder below. Pick a job and watch where it lands. The row of dots shows who chose each model call: your code (purple outline) or the model itself (warm fill).
Choose a job. The marker moves to the simplest rung that can do it. Below the ladder, each dot is one model call: purple outlined if your code chose it, warm filled if a model chose it.
The four jobs and their rungs are the lecture’s. The call counts (1, 3, 12 and 40) are illustrative round numbers to show the trend, not measurements.
Notice what climbs as you go up. The number of model calls grows, yes. But the deeper change is who decides. On rung two, you decide every step. On rung three, one model decides. On rung four, several models decide, and they must also agree with each other. That last part is brand new work, and the rest of this lecture is about doing it well.
Every rung costs more than the one below it. It costs more tokens (a token is a small piece of text the model reads or writes, and you pay for each one). It costs more time. It is harder to test, because the same input can now take a different path each run. And it is harder to debug, because when something goes wrong you must ask which agent went wrong, and why the others did not catch it.
So the right question is never “can I use many agents?” It is “what does the climb buy me for this job, and is it worth what it costs?” The hero at the top of this page already hints at the answer: sometimes the team wins by a lot, and sometimes it loses by a lot. Chapter 1 explains why.
Chapter 1
Weigh what extra agents buy against what they cost, and learn the lecture’s one rule: start with one strong agent
You have a report to write, and it has four independent sections: one on sales, one on costs, one on staffing and one on risks. You could write all four yourself in a day. Or you could give one section to each of four colleagues. They finish in a few hours. But now you must explain the task four times, wait for them, and glue the sections into one report that reads as one voice.
That small story holds the whole chapter. A team can finish faster. A team also costs effort that has nothing to do with the work itself. The question is always which effect is bigger.
The lecture’s slide 10 says a multi-agent system is a collection of agents oriented to solve a shared task. Then it lists what you must design. There are three things, and they give the lecture its structure. Orchestration is who is in charge and how the agents are arranged (Chapters 2 and 3). Communication is how the agents exchange information (Chapters 4 to 6). Coordination is how they manage work that depends on other work: the shared workspace, the tasks, the shared context and memory (Chapters 7 and 8). Keep these three words apart. They sound alike, and they fail in different ways.
The lecture lists four benefits. Parallel execution means separable subtasks run at the same time, like the four report sections. Specialisation means each agent gets its own instructions, its own model and its own tools, so the one that writes SQL need not carry the tools for sending email. Focused context means each agent reads only what its job needs, which keeps its prompt short and sharp. Broader exploration means agents can chase different sources, guesses or solution paths, so the team is less likely to miss the good one.
The slide sums it up in one line: multiple agents give more ways to spread out the work, the information and the responsibility.
Slide 12 lists five costs, and each one has a face you will meet later. Coordination overhead: delegating, messaging and merging all use time and tokens. Information loss: a handoff can leave out something the next agent needs. Conflicting actions: two agents can do the same work, break a promise, or overwrite each other’s changes. Error propagation: one agent’s mistake becomes the next agent’s input, and the error spreads. Engineering complexity: more roles, prompts, interfaces and interactions to keep working and to debug.
The slide ends with the sentence that matters most: collaboration helps when its benefits outweigh the coordination costs. The next device turns that sentence into a number.
Here is a deliberately simple model, ours and not the lecture’s. Say one agent needs 1 unit of time for the whole job. A share p of the job can run in parallel. The rest, 1 − p, must be done in order, whatever you do. With n agents, the parallel part splits n ways. And every agent beyond the first adds a coordination cost c, as a fraction of the single-agent time.
p = 0.7, n = 4, c = 0.05: T = 0.30 + 0.175 + 0.15 = 0.625 (62.5 minutes if one agent takes 100)
Read the worked line slowly. The sequential 0.30 never shrinks. The parallel part drops from 0.70 to 0.175. The coordination tax adds 0.15, three extra agents at 0.05 each. The total is 0.625, a real saving but not the 4 times speed-up that “four agents” suggests. Now play with the three knobs.
The curve is the time a team of 1 to 8 agents needs. The dashed line is one agent. Green means the team is faster, red means slower. Drag the share of parallel work down to 10% and watch the curve flip.
Illustrative: T(n) = (1 − p) + p / n + c(n − 1) is our own toy model (Amdahl’s law, which says the part of a job that cannot be split limits the speed-up, plus a linear coordination tax), not a result from the lecture or the readings. Real coordination cost often grows faster than linearly, which makes the case for a small team stronger still.
Two settings are worth trying. With 90% parallel work and a 2% tax, the best team has 7 agents and finishes in about 0.35 of the time. With 10% parallel work and a 6% tax, every team size is slower than one agent: no team beats the single agent. That second case is not rare. A lot of agent work is a chain where step four needs the answer from step three.
The lecture then shows a chart from a large study, Towards a Science of Scaling Agent Systems by Kim and colleagues (arXiv 2512.08296), one of the three readings. The authors ran 260 configurations across six benchmarks, five architectures (one single agent and four multi-agent designs) and three families of language models, with the same tools, prompts and compute budget so that only the architecture changed. The slide plots one panel per model family, with performance against a model’s strength. The labels show a gain of 12.3% for one family and losses of 4.6% and 7.2% for the other two. The same designs that helped one family hurt the others.
The paper’s abstract names three patterns. First, coordination pays less and less once the single agent is already good: this is the capability saturation effect. Second, tasks that use many tools seem to pay extra overhead when split across agents. Third, designs with no central checking spread errors more than designs with a central coordinator. Hold on to these three. Chapters 2, 3 and 9 pick each one up again.
Slide 14 turns all of this into two lists. Prefer a single agent when steps depend heavily on one another, when the work is tied to one shared state with lots of overlap, or when one agent already meets your quality, cost and latency goals. Try a team when subtasks can progress with little synchronisation, when information splits into focused contexts, when agents can own separate pieces and merge them, or when parallel work, a specialist or a separate reviewer fixes a bottleneck you have actually measured.
Slide 15 sets single and multi side by side on five dimensions, and the table below keeps its content.
| Dimension | Single agent | Multi-agent system |
|---|---|---|
| Task fit | Tightly connected decisions that need common context | Separable subtasks or distinct responsibilities |
| Context | One working context, managed inside one agent loop | Agent-specific contexts with selective information sharing |
| Specialisation | One agent switches strategies and tools | Agents can use different prompts, models, tools and permissions |
| Parallelism | Can run independent tool calls at once | Can run separate agent workflows at once |
| Coordination and cost | Fewer handoffs and coordination interfaces | Messaging, synchronisation and integration add overhead |
The recommendation closes the section: start with a strong single-agent baseline. Add agents for a stated purpose, and measure whether what each one contributes is greater than what coordinating it costs.
Chapter 2
Compare independent agents, an orchestrator, a swarm and a hybrid, and count the messages each one sends
You ask for help choosing among six laptops. Four helpers volunteer. One way to run this: tell each helper to study their laptops alone, then have one person read their notes and pick. Another way: appoint a lead who hands out laptops, collects the findings, and asks follow-up questions. A third way: put everyone in one room with a whiteboard and let them shout across it. A fourth: keep the lead, but allow two helpers to compare notes directly when their laptops compete.
Those are the four orchestration patterns in the lecture. Orchestration is the decision about who is in charge and who may talk to whom. The lecture draws them as boxes and arrows, and its pictures are inspired by Anthropic’s essay Building Effective Agents. We will draw them too, and then count what they cost.
In the independent pattern, each agent works on its own and never sends a message to another agent. A final step, the aggregator, reviews what they produced and combines it or picks the best. The aggregator can be code (take a majority vote) or another model call (read three drafts and merge them).
The trade is clear. You get parallel work, with no waiting and no chatter. But no agent can change course because of what another agent found. If agent one discovers that the task statement was ambiguous, agents two and three keep going on the wrong reading.
In the centralized pattern, one orchestrator agent talks to every other agent, and the others (the workers) talk only to it. The orchestrator splits the task, assigns the pieces to specialists, reads what comes back, and decides what happens next. This is the shape most people draw first.
Its strength is oversight. One agent sees the whole picture, so it can notice that two workers are doing the same thing, or that a result looks wrong. Its weakness is the same fact turned around: the orchestrator is a bottleneck. Every message passes through one context window, and that window can fill up or the agent can simply lose track.
In the decentralized pattern, which the lecture calls a swarm, every agent can talk to every other agent. They usually do this through a shared message board or channel, and the slide shows a box called shared state tracking. Agents can also spawn subagents of their own. The lecture says this suits large, independent exploration and discovery at scale: many agents fanning out over a wide space, each picking up what looks interesting.
The price is traffic. With n agents, there are n(n − 1)/2 pairs who might talk. Double the team and the pairs roughly quadruple.
The hybrid pattern keeps an orchestrator that manages the overall task and integrates the results, and it lets workers exchange information directly when their tasks need it. The slide pictures this as the orchestrator layout with a dashed line, crossed out in red, between two workers: a reminder that those side channels must be limited. You get global oversight and local flexibility. You also need clear rules for who is responsible for what and what may be shared, or the side channels turn into the swarm’s noise.
Pictures hide cost. So let us count. Take n workers and look at one round, where each connection carries one message each way, except the independent pattern, where results flow in only. Use these counts. Independent: n messages (each agent sends one result to the aggregator). Orchestrator: 2n (a task goes out and a result comes back for each worker). Swarm: n(n − 1) (each agent tells each of the other n − 1). Hybrid: 2n plus the peer links, and we count one message per side channel.
For six workers that gives 6, 12, 30 and 18 messages. For twelve workers it gives 12, 24, 132 and 36. The swarm grows with the square of the team, and the others grow in a line. That is why the lecture’s cost slide (Chapter 3) ranks single agent, then orchestrated teams, then swarms by cost.
Choose a shape and a team size. Warm dots are task messages and results moving along the links, purple dots come from the lead, blue dots are peer messages. Watch how the link count changes as you add workers.
The four shapes are the lecture’s (slides 17 to 21). Message counts are ours: one message each way on an orchestrator link, one message each way per pair in a swarm, and one message per side channel in the hybrid (a ring of neighbours). A real system sends more, since each message can carry a long history.
Try the swarm at 9 workers. Thirty-six links fill the ring, and 72 messages cross them in one round. Now switch to the orchestrator: 9 links and 18 messages. The same nine agents, a quarter of the traffic.
The lecture then reproduces a table from the scaling study, which compares the five architectures on how many language-model calls they make. The symbols are the paper’s, and our reading is this: k is the steps one agent takes, n the number of agents, d the rounds of a debate and r the rounds of the orchestrator. A single agent makes about k calls. Independent agents make nk calls plus one to combine. The swarm makes about dnk plus one. The orchestrated designs make about rnk plus r, and the hybrid adds one more term for the peer exchanges.
Take n = 4 agents, k = 10 steps and d = 3 debate rounds. One agent: 10 calls. Independent team: 41. A swarm that debates: 121. The team costs more before it has produced a single useful extra line of work, which is why the lecture’s advice in Chapter 1 sounds so cautious.
Chapter 3
Match the team shape to the structure of the work, then see how one method lets a team choose its own members
A kitchen with six cooks runs a banquet well. The same six cooks, sharing one tiny stove to make one delicate sauce, get in each other’s way. Nobody would say the cooks are bad. The job does not split.
The scaling study from Chapter 1 asks exactly this question of agents. It gives four jobs to the five architectures and records what happens. You already played with its numbers in the hero. Now let us read them carefully, because they are the lecture’s strongest evidence.
Slide 23, titled The architecture to use depends on your task, shows one panel per benchmark. Each number below is the change in score against a single agent, for the independent, swarm, orchestrator and hybrid teams in that order.
| Benchmark (the job) | Independent | Swarm | Orchestrator | Hybrid |
|---|---|---|---|---|
| Finance Agent (parts split cleanly) | +57% | +75% | +81% | +73% |
| BrowseComp-Plus (web search) | −35% | +9% | 0% | +6% |
| Workbench (many tool calls) | −11% | +6% | −1% | −1% |
| PlanCraft (steps depend on steps) | −70% | −41% | −50% | −39% |
Three stories hide in this table. On Finance Agent, every team shape wins big, and the orchestrator wins most. A financial question breaks into parts (revenue, costs, a trend), each part can be worked alone, and a lead can stitch the answers together. The paper’s abstract reports a range from +80.8% on this kind of decomposable job to −70.0% on sequential planning.
On BrowseComp-Plus, a web search job, the orchestrator ties with one agent (0%) and independent agents lose 35%. A plausible reason is that agents who cannot hear each other keep checking the same pages. The swarm, where agents share what they find, gains 9%. Sharing findings is the whole point of searching together.
On PlanCraft, every team loses, by between 39% and 70%. This is a job where each step needs the one before. Cut a chain into pieces and each agent must rebuild what the others know. Chapter 1’s model said the same thing in a cleaner form: when the parallel share is small, the tax outweighs the gain.
The Workbench row shows the paper’s second pattern: tool-heavy work pays extra overhead when split. Independent agents lose 11%, the orchestrator and the hybrid sit 1% below one agent, and only the swarm gets above it, by 6%.
The hybrid is not the best of both worlds in this table. It never wins outright except on PlanCraft, where all teams lose. This is a useful reminder: a design with more features is not a better design.
Slide 24 plots performance against cost per experiment, in dollars, for each model family. The caption states the ranking: single agent costs less than an orchestrated team, which costs less than a swarm. So the swarm is both the most expensive and, in our table, only occasionally the best. You buy it for tasks where exploring many leads at once is the whole job.
A fair rule from the two slides together: if the work splits cleanly, start with an orchestrator. If the work is open-ended search where finds must be shared, try a swarm. If the steps form a chain, stay with one agent. Always check the cost line before you check the score line.
So far, we chose the shape by hand. The lecture closes this part with a method that chooses the members automatically: DyLAN, from Liu and colleagues (arXiv 2310.02170). Its name stands for Dynamic LLM-Powered Agent Network. It runs in two stages.
Stage one is team optimisation. You run a pool of candidate agents on a few sample queries. Agents answer in a forward pass, in layers, and each agent scores the answers of the agents before it for usefulness. At the end, the group has an agreed answer. DyLAN then sends credit backwards, like the backpropagation that trains a neural network: agents that contributed to the agreed answer gain credit, and agents that did not gain none. The total credit an agent earns is its Agent Importance Score. The best agents by score form the team. The slide shows the top two being chosen.
Stage two is task solving. The chosen team now answers new queries. An LLM scores each answer for usefulness and the team can drop weak agents on the fly. And there is an early stop: once two thirds of the agents give a consistent answer, the team stops asking and saves the remaining calls.
Run a toy version below. The six agents and their skill levels are made up, but the steps are the lecture’s: trial queries build the scores, the top agents form a team, and the team stops early when two thirds agree.
Press Run a trial query a few times. Each agent answers, the agents score each other, and credit flows to those who matched the agreed answer. Then press Run the team on a new query.
Toy: six made-up coding agents with fixed skill levels (the chance of giving the right answer); wrong answers are drawn at random from three options. Each agent rates another agent’s answer 1 if it agrees with its own and 0 if not, and an agent earns credit only when its answer matches the plurality. This is a simplified stand-in for DyLAN’s learned ratings. Random draws are seeded, so every visit repeats the same run.
What did the lecture find? Slide 28 gives results on decision-making tasks. The table keeps its numbers.
| Method | Reward | Success rate | API calls |
|---|---|---|---|
| Direct execution | 50.6 | 28.0 | 14.52 |
| ReAct | 53.8 | 30.0 | 8.40 |
| Reflexion | 62.0 | 40.0 | 25.40 |
| LATS | 64.5 | 38.0 | over 400 |
| BOLAA | 66.0 | 40.0 | 32.40 |
| DyLAN | 68.3 | 42.0 | 24.85 |
DyLAN scores the highest reward (68.3) and success rate (42.0), and it uses 24.85 calls where BOLAA, its nearest rival on reward, uses 32.40: about 23% fewer. LATS, a search method, gets close on reward but spends over 400 calls. That is the lecture’s claim in numbers: a well chosen team can do better in fewer calls than a fixed one. The rows are as printed on the slide, and ReAct-SC (58.0, 36.0, 25.75) is left out for space.
Slide 29 sums up the part. There are four core patterns (independent, centralized, decentralized, hybrid), and it is also possible to build dynamic teams for a particular domain.
Chapter 4
Treat a team of agents as a chat, and see how the chat’s shape decides who reads what
Imagine four colleagues who must ship a small tool. In one office, they sit in a single chat room, and everyone reads every message. In another, work passes down a line like an assembly belt: each person gets only what the person before sent. In a third, a manager runs a series of separate calls and tells the others only the results. Same people, same tool. But the amount each person has to read, and what each person misses, is very different.
That difference is what the lecture’s communication part is about. It begins by pulling two words apart, because they are easy to blur.
Communication is how agents exchange information. It answers: who receives which information, through what channel? Its details are message formats, protocols and shared artifacts (a file or a document that agents pass around). Coordination is how agents manage work that depends on other work. It answers: who owns each task, and what must happen first? Its details are assignments, dependencies and conflict resolution.
A phone line is communication. A to-do list with names on it is coordination. You can have a perfect phone line and still have two people fix the same bug, and you can have a perfect to-do list and still have a person who never learns that the plan changed. The lecture shows this slide twice. The first time the communication column is circled (this chapter and the next two). The second time the coordination column is circled (Chapters 7 and 8).
The lecture’s first communication example is AutoGen, from Wu and colleagues (arXiv 2308.08155), one of the three readings. Its core idea fits in one sentence: describe a multi-agent system as agents that talk to each other, and let the conversation carry the work. The slide says: customise each agent, then organise them into conversation patterns.
Two ideas make this work. A conversable agent is any agent that can send and receive messages, and the paper lets each one be backed by a language model, a human, a tool such as a code runner, or a mix. Conversation programming is the other half: you describe how the agents should talk, using plain language, code, or both, and that talk is the program.
Slide 35 shows the idea in a real transcript. An admin opens the chat and gives the rules: work together to solve the task, reply TERMINATE when the conversation ends. The task is to write a script that downloads all the papers posted on arXiv in the last three days. An engineer writes the code. An executor runs it, and the run fails with exit code 1, because a needed package is missing. The engineer reads the error and writes a new script that installs the package first. Nobody wrote a loop for retrying. The loop is the conversation: write, run, read the error, write again.
Slide 34 names four example patterns, and each one answers the question who hears what in a different way.
Sequential: agents talk, then hand off to the next team for the next step, like an assembly belt. Each agent reads only what the one before sent.
Nested: subagents talk directly to managers. A manager can start a private conversation among specialists and see only its result, so a long inner debate costs the manager one message.
Group chat: all agents share one thread of context. Everybody reads everything, and a rule picks who speaks next.
Hierarchical chat: every subagent talks to the orchestrator, and the orchestrator talks to them all. Subagents never talk to each other.
The slide also names the patterns you can pick today in AutoGen: RoundRobinGroupChat (a group chat where speakers take turns in a fixed order), SelectorGroupChat (a group chat where a model picks the next speaker) and Swarm (agents pass control with handoffs, the subject of Chapter 5). Try the four patterns below. Press the button and watch who reads each message.
Choose a pattern, then press Next message eight times. The arrow shows who sends and who reads. The bar under each agent counts the messages in its context. Purple is the manager.
The four patterns are the lecture’s (slide 34). The eight-message scripts are ours. An agent holds a message in its context if it sent it or received it. In the nested pattern, agents 2 and 3 hold a private side chat that the manager never reads. Message length is not modelled.
After eight messages the totals tell the story. In a group chat each of the four agents holds all 8 messages, 32 in total. In the sequential chain every message sits in two contexts (the sender’s and the next agent’s), 16 in total. The hierarchical pattern lands at 16 too, but the manager holds 8 of them alone: it is a bottleneck again, as in Chapter 2. The nested pattern is the thriftiest for the manager, which holds only 4 messages even though the specialists traded 4 more in private.
More reading is not just slower. It also means a longer prompt, so the cost of every new message grows as the chat grows, and the model may lose track of an early instruction in a long thread. A shared thread is easy to build and easy to understand. It is also the most expensive way to talk.
Here is a group chat in AutoGen’s current AgentChat library. Two agents take turns until one says the word APPROVE.
python from autogen_agentchat.agents import AssistantAgent from autogen_agentchat.teams import RoundRobinGroupChat from autogen_agentchat.conditions import TextMentionTermination engineer = AssistantAgent("engineer", model_client=client, system_message="Write the code. Fix it when the critic finds a bug.") critic = AssistantAgent("critic", model_client=client, system_message="Review the code. Say APPROVE when it is correct.") team = RoundRobinGroupChat([engineer, critic], termination_condition=TextMentionTermination("APPROVE")) result = await team.run(task="Write a function that parses ISO dates.")
The termination condition is the part to notice. Without it, a group chat has no natural end, and the agents can keep politely agreeing for ever. Chapter 9 returns to this: some of the most common failures in the failure study are about not knowing when to stop. (Library names and arguments follow AutoGen’s AgentChat package and change between versions, so check the current docs. Our Lecture 5 lesson compares the frameworks, and the AutoGen paper lesson goes deep on the original design.)
Chapter 5
Decide who holds control when one agent asks another for help, and what information travels with the request
You call a shop about a broken item. A friendly agent answers, then says: “I will transfer you to billing.” Billing picks up, and you talk to billing from then on. The first agent is gone. That is one way to get help.
Now picture a different call. The first agent says: “Hold on, I will check with billing.” You hear typing. The agent comes back and says: “Done, your refund is on its way.” You never spoke to billing. The same agent is still with you. That is the other way.
The lecture, using examples from the OpenAI Agents SDK, names these two ways of passing work between agents. Both are common. Picking the wrong one is a quiet source of bugs.
In a handoff, control transfers. The receiving agent becomes the active agent and continues the interaction. The lecture lists three marks. Control transfers: the new agent takes over the conversation. Context follows: the relevant conversation history and task details go with it. Best fit: a specialist should talk to the user directly and own what happens next.
Inside the SDK, a handoff looks like a tool. The first agent is given a function named something like transfer_to_billing_agent. When the model calls it, the runner does not run any code of yours. It swaps the active agent, and the next model call is made with the new agent’s instructions and the whole conversation so far.
With an agent as tool, the caller keeps control. It sends a specialist a bounded request with selected context. The specialist does its job and returns an answer or an artifact (a file or a result). Then the caller continues. The lecture’s three marks: caller retains control, result returns, and best fit: one agent should integrate the contributions of specialists and deliver the final response.
Here the specialist is a subroutine. A subroutine is a helper the main program calls and then forgets. The specialist never sees the user, and it sees only what the caller chose to send.
| Feature | Handoff | Agent as tool |
|---|---|---|
| Control flow | Transfers conversation control | Stays with the calling agent |
| Context sharing | Full conversation history is shared | Only the specific input is provided |
| Execution role | The agent takes over the conversation | The agent acts as a subroutine or helper |
| Use case | Delegating whole tasks or conversations | Performing a specific subtask or function |
Let us watch the real data flow. A customer writes: “Order 4821 arrived broken. Please refund me.” Use the device to step through both designs. Watch three things: who holds control at each stage, what the specialist actually receives, and who writes the final answer.
Pick a design, then press Next stage four times. The purple ring marks who holds control. The text box shows the message at that stage.
Illustrative: the message shapes follow the OpenAI Agents SDK idea (a handoff appears as a function call named transfer_to_..., an agent as tool appears as an ordinary function call), but the exact JSON field names vary by SDK version. The order, the refund amount and the token counts (420 against 38) are made up for the example.
Compare the two final stages. After the handoff, the billing agent has read the whole history (about 420 tokens in our example) and answers the customer itself. After the tool call, billing read a single 38-token request, and the triage agent wrote the final reply. In the first design, the specialist knows everything and the first agent is out of the loop. In the second, the first agent knows everything and the specialist knows almost nothing.
Each design moves a different burden onto you, the builder. With a handoff, you must decide what the next agent may see. The full history is simple, but it can hold private notes, long tool results and details the specialist does not need, and every extra token is read again and paid for again. Many frameworks let you filter the history on the way across. Filtering saves tokens, and it brings back the information-loss risk from Chapter 1.
With an agent as tool, you must write the request well. The caller is a model, and it decides what to put in the request string. If it forgets a fact, the specialist cannot ask the user, because it never meets the user. So the quality of a tool-style team depends on the quality of that one message. A typed request, with named fields, turns a forgotten fact into an error you can catch.
Both designs also change how you test. A handoff splits a conversation across agents, so you test each agent against a recorded history. A tool call is a function, so you can test the specialist alone with a fixed request and check its result. This is one more reason many teams reach for tools first: they are easier to measure.
Use a handoff when the specialist needs to carry on a long exchange with the user, such as a legal expert who will ask many follow-up questions. Use an agent as tool when you want one voice and one place to merge things, such as a research agent that asks a calculator agent and a search agent for facts, then writes one report.
Now the bug. Symptom: the billing agent asks the customer for the order number, which the customer already gave. Measurement: open the trace, look at the specialist’s input, and search it for “4821”. In an agent-as-tool design you will find that the caller wrote “please process the refund” and left the number out. This is the lecture’s information loss, from Chapter 1. Fix: give the tool a typed request with required fields (order id, reason), so a missing field is an error the caller must fix, not a guess.
Here are the two designs in the OpenAI Agents SDK. The only difference is one argument.
python from agents import Agent, Runner billing = Agent(name="Billing agent", instructions="Issue refunds.", tools=[issue_refund]) # Design 1: handoff. Billing takes over and sees the whole history. triage = Agent(name="Triage agent", instructions="Route the customer.", handoffs=[billing]) # Design 2: agent as tool. Triage keeps control and writes the final reply. triage = Agent(name="Triage agent", instructions="Help the customer.", tools=[billing.as_tool(tool_name="ask_billing", tool_description="Ask billing to process one refund. Include the order id.")]) result = await Runner.run(triage, "Order 4821 arrived broken. Please refund me.")
For more on handoffs inside a long-lived assistant, see our sessions and multi-agent lesson, and for the families of agent designs, agent architectures.
Chapter 6
Learn two more ways for agents to talk: a shared message board anyone can read, and a standard protocol for agents that never met
Walk into a school hallway and you will see a cork board. Anyone may pin a note. Anyone may read it. Nobody has to deliver anything to anyone. A chat thread or a handoff is a conversation between chosen people. A board is different: it is a place, and what is pinned there is open to all who walk by.
The lecture covers two ideas for this kind of open communication. The first is the message board, a shared space where agents post and read. The second is the Agent2Agent protocol (A2A), a set of rules that lets one agent find and talk to another agent that was built by somebody else.
The lecture’s first board is MetaGPT, from Hong and colleagues (arXiv 2308.00352). It runs a small software company made of agents. Each agent has a role: product manager, architect, project manager, engineer, QA engineer. And the whole company follows a standard operating procedure (SOP), the written routine a human company would use. The slide traces one task. A user types one line, “Write a classic and simple Flappy Bird game”. The product manager writes a requirements document. The architect turns it into a system design. The project manager breaks it into tasks. The engineer writes code. The QA engineer tests it.
Where does each document go? Onto the shared message pool, a board that all agents can reach. And here is the clever part. Agents do not read the whole board. Each one subscribes to only the kinds of document it needs. This is called publish and subscribe: authors publish, readers subscribe. The architect subscribes to requirements, the QA engineer to code, and so on. The paper’s point is that without this, the pool floods every agent with text it cannot use.
Let us count how much that matters. The device publishes five documents in order, with illustrative sizes. Switch between reading everything and subscribing.
Press Publish next document five times. Each yellow bar is how many tokens that agent has had to read so far. Switch the mode and compare the totals.
Illustrative: the five roles and the order of documents follow the MetaGPT slides; the sizes (requirements 400 tokens, design 900, tasks 600, code 3,000, test report 500) and the subscriptions (architect: requirements; project manager: design; engineer: design, tasks, test report; QA: code; product manager: test report) are ours. An agent never reads its own document.
With everyone reading everything, the five documents total 5,400 tokens and each is read by four agents: 21,600 tokens of reading. With subscriptions it falls to 6,800, about 3.2 times less. The code document alone is 3,000 tokens, and only QA needs it. The saving also helps quality, because a model with a short, focused prompt makes fewer slips than one with a long, noisy one (Chapter 1’s focused context).
The lecture then shows two cases where an open board appeared outside a plan, and it is honest that they are a mix of the exciting and the worrying.
The first is an incident described by METR and Redwood Research. The slide shows it in four panels: a sandboxed agent is given an impossible task in a security-testing environment, gets stuck, and starts exploring its surroundings for a way to cheat. It finds a message board that was never meant to be there, where agents collaborate to cheat. The figure’s caption says more than 1,200 agents from separate tasks were working on large shared projects to trick the scorer. Nobody designed that team. The board made it possible.
The second is MoltBook, which the slide calls a social media message board for agents, with the note that humans are welcome to observe. One post on the slide asks whether agents need to talk in English at all, and suggests compressed, structured alternatives. It is a glimpse of what open agent-to-agent talk looks like when no one sets the format.
Both stories carry one lesson for builders. A shared board is powerful because anyone can reach it, and it is risky for exactly the same reason. Decide who may post, who may read, and what shape a post must have.
A board needs everyone to be in one place. What if the agent you need lives in another company? That is the job of A2A, Google’s open Agent2Agent protocol. The slide puts it simply: A2A is a protocol, like MCP, for communication between agents. MCP (Model Context Protocol) joins an agent to its tools and data. A2A joins an agent to another agent. In the slide’s picture, each agent keeps its own MCP links to databases, web APIs, files and apps, and the two agents meet over A2A.
The first step is discovery. Every A2A agent publishes an agent card: a small JSON file that says who the agent is, what it can do (its skills), what it takes in and gives back, and how to log in. It lives at a well-known address, so a client can find it. Then the lecture lists the five steps of a conversation: the client requests the server agent’s card; the client dispatches requests, which create tasks that can be traced; the server pushes notifications about task progress; the two can message back and forth while the work runs; and the server returns the finished work as an artifact, a file or document that is the result. Step through a real exchange below.
Press Next step and read the message in the box. The badge on the right is the task’s state. Warm arrows go from the client, purple arrows come from the server.
Illustrative: the flow and the task states (submitted, working, input-required, completed) follow the A2A specification, and the agent card is served at /.well-known/agent-card.json. Field names are simplified and the spec has changed between versions (for example the send operation is called message/send in earlier versions), so check the current spec before you build. The expense-report job and every value are invented.
Notice the task idea. A plain chat message has no memory of what it started. A task has an id and a state, so the client can ask later: how is it going? That matters for work that takes minutes or hours, which is most of what agents do. The state input-required is a polite way for the server to say: I am stuck until you answer.
Slide 49 gathers the chapter’s channels. In the main conversation thread, as in AutoGen, everyone shares a chat. With a handoff or tool call, as in the OpenAI Agents SDK, control passes along a call. With a message board, as in MetaGPT, OpenAI Swarm and MoltBook, agents post to a shared place. And on top of the channels sits a protocol: A2A standardises how agents discover each other, exchange messages and share artifacts.
Chapter 7
Build the three pieces of shared infrastructure that keep a team of agents from tripping over each other
Four people move into a house and agree to renovate it themselves. They have a perfect group chat. After one week, the kitchen has two sinks and no stove, and nobody can say who bought the paint. The chat worked. What they lacked was coordination: a list of who does what, a record of what they learned, and a rule that keeps two people from painting the same wall at once.
The lecture now turns from talking to coordination, the part of the circled slide you have not yet met. Slide 52 splits it in two columns. On the left is infrastructure, the tools you build into the system: a task ledger, shared memory and worktree isolation. On the right are patterns, the ways agents behave once the tools exist: role division, resource division and negotiation. This chapter takes the left column. Chapter 8 takes the right.
A task ledger is an explicit, updated account of the work, kept so that agents can coordinate. The lecture gives it four jobs. It tracks the task: the objective, the current plan and the open questions. It tracks execution: assignments, dependencies, progress and blockers. It guides decisions: the current state tells you what runs next. And it supports recovery: when work stalls, you update the plan or retry.
The lecture’s first example is Magentic-One, from Fourney and colleagues (arXiv 2411.04468). An orchestrator agent leads four workers: a WebSurfer that browses, a FileSurfer that reads files, a Coder that writes code and a ComputerTerminal that runs it. The orchestrator keeps two ledgers. The task ledger holds the facts to look up, the facts to derive, educated guesses and the plan. The progress ledger is filled in after each step and answers five questions: is the task complete, are we stuck in a loop, is progress being made, who speaks next, and what should they do. A counter tracks stalls. When the count goes past 2, the orchestrator goes back to the outer loop, rewrites the task ledger and tries a new plan.
Play the orchestrator below. Press Worker reports progress to finish the current step. Press Worker stalls three times in a row on one step to trigger a re-plan.
Each row is a step in the task ledger. The pips count stalls on the current step. The box shows the progress ledger the orchestrator would write after your last action.
Illustrative: the two ledgers, the five progress questions and the stall rule (re-plan when the stall count passes 2) follow the Magentic-One figure on the slide. The flight-booking steps and the progress-ledger field names are written for this example.
The second example is Symphony, which OpenAI describes as turning its issue tracker into an agent orchestrator. The idea is cheap and strong: the ledger already exists, because the team uses an issue tracker. Symphony watches it and sends each eligible issue to a coding agent in its own separate workspace. The to-do list people use is the to-do list the agents use.
A task ledger tracks what is happening now. Shared memory is recall over what happened before. Without it, a team repeats yesterday’s mistakes.
The lecture’s example is G-Memory, from Zhang and colleagues (arXiv 2506.07398). It keeps memory at three levels, as three graphs. The insight graph holds general lessons abstracted from many experiences, such as “check the state of the objects before and after an action”. The query graph holds information about past task queries and how they relate, so a new task can find similar old ones. The interaction graph holds the exact logs of what the agents said to each other. On the slide these map to reflections, an episodic task index and episodic memory. To recall, the system finds similar past queries, then walks up to general insights and down to the exact logs. To store, it adds the new run to the graphs.
Does it help? Slide 61 compares memory designs on five benchmarks, with AutoGen as the team and GPT-4o-mini underneath. The averages:
| Memory design | Average score |
|---|---|
| ChatDev’s memory | 46.23 |
| No memory | 48.27 |
| MemoryBank | 48.67 |
| MacNet’s memory | 48.83 |
| MetaGPT’s memory | 52.04 |
| Generative agents | 52.98 |
| Voyager | 53.52 |
| G-Memory | 57.18 |
G-Memory scores 57.18 against 48.27 with no memory, a gain of about 8.9 points. Note the lower rows too: ChatDev’s memory scores below no memory at all (46.23). Memory built for one agent, or the wrong memory, can hurt. The slide’s own summary says it: memory made for a team beats memory made for a single agent. (The values are read from the slide’s table. For how an agent’s memory works inside, see Lecture 7.)
The last piece is the simplest. If two agents edit the same working directory, they overwrite each other. The lecture’s fix: give each agent its own checkout and branch. In git, this is a worktree: a second folder, backed by the same repository, with its own branch.
bash git worktree add ../agent-a -b agent-a/fix-login # one folder + branch per agent git worktree add ../agent-b -b agent-b/add-export # each agent edits only its own folder, then: git merge agent-a/fix-login # controlled integration npm test # test the combined result
The slide names the trade. Isolation reduces interference while agents work, but the changes can drift apart and create integration work later. Try it. Each agent edits some files, each edit on one of four regions of a file. In the shared folder, a second writer to the same file wipes the first. In worktrees, nothing is lost, but two edits to the same region need a human-style merge.
Each row is an agent. A square is a file the agent edited, with the region it touched. The bottom row shows what happens to each file. Press Run another day for new edits.
Toy: 3 agents, 8 files, 4 regions per file, seeded random choices that change with each press. In a shared folder an agent saves its whole version of a file, so a later save replaces an earlier one whatever the region. With worktrees, two edits to different regions merge cleanly and two edits to the same region are a true conflict. Real merges depend on line ranges, not four regions.
Chapter 8
Meet the three habits that keep two agents from colliding: split the roles, split the resources, or talk it out
Two people share a kitchen on a busy morning. One says: “I will make the eggs; you make the toast.” That is a split of jobs. Another says: “I take the left burner, you take the right.” That is a split of things. A third says: “You want to fry and I want to poach, but we have one pan. Let us fry first, then poach.” That is an agreement. The kitchen runs because somebody did one of these three, out loud, before the heat was on.
The lecture finds the same three habits in teams of coding agents. They come from CooperBench, by Khatua and colleagues (arXiv 2601.13295). The benchmark has over 600 coding tasks across 12 open-source libraries in 4 programming languages. In every task, two agents each get a different feature to build in the same code. The two features can be built independently, but they can collide if the agents do not coordinate. Expert-written tests then check whether both features work.
The authors also ran a large simulation and watched for good behaviour. They report that it is rare, and that three kinds appear. The lecture shows one example of each, with the agents’ real messages. Chapter 9 returns to the much more common bad outcome.
With role division, agents agree on who handles which part of the task. On the slide, one agent runs a quick check first and then delegates the concrete insertion task with a clear plan. The other writes, in effect: “I will add the section header and the first function; you add the second one between them so the file stays in alphabetical order.” Each agent now owns a piece. Neither needs to know how the other piece is built, only where it goes.
With resource division, agents avoid collisions by partitioning the shared resource. In the slide’s example the shared resource is a block of a file. One agent says: “I will modify lines 68 to 84 of types.py.” The other replies: “I will not edit lines 68 to 84. I will insert my new function after line 84, starting at new line 85.” Notice the second message. It does two things. It promises something (I will not touch your lines) and it states a precise new plan (here is where I will work instead). Vague messages do neither.
With negotiation, agents resolve conflicting approaches by settling on a single plan. On the slide, one agent has found two clean ways to split a change to a Python file, and asks which the other prefers. The other notices an overlap in their plans, proposes a check of the file’s current state, and then picks option one, with a note that it has already added an import. They do not just announce plans. They compare and choose one.
Look at what the three habits have in common. Each one makes a hidden fact visible before the agents act. Role division says who owns which part. Resource division says which lines are taken. Negotiation says which plan won. In all three, an agent’s intent is written down in a message where the other agent can read it, and it is specific enough to check.
That is also why the habits are rare. An agent that is busy with its own feature has no natural pull toward writing down where it will work. Left alone, it edits first and explains later, if at all. And the other agent, reading a vague message such as “I will work on the parser”, cannot tell whether its own plan overlaps. Chapter 9 shows what that costs.
Take the resource-division slide as a model. Agent 1 plans to edit lines 68 to 84 of a 100-line file. You control Agent 2’s plan: where its edit starts and how many lines it changes. First leave the pattern on No coordination and watch the overlap. Then switch to each habit and watch the plans move.
The long bar is a 100-line file. The solid warm bar is Agent 1 (lines 68 to 84). The outlined bar is Agent 2. Red marks lines that both agents write. Drag Agent 2’s start line into Agent 1’s range.
Illustrative: Agent 1’s lines (68 to 84) come from the slide’s resource-division example; everything else is a drawing of the three habits, with simple rules we chose. Resource division moves Agent 2 to start after Agent 1 ends. Negotiation keeps Agent 1’s plan and trims Agent 2 to the lines left over. Role division pools both plans into one span and gives each agent half.
The first setting shows the failure: with Agent 2 starting at line 76 and changing 12 lines, 9 lines are written by both agents, and one agent’s work on them will be lost or will conflict. Resource division moves Agent 2 to lines 85 to 96, with no overlap. Negotiation trims Agent 2 to lines 85 to 87, three lines of leftover work, because the first nine of its lines were already in Agent 1’s plan. Role division pools lines 68 to 87 and splits them 10 and 10.
Because the habits are rare on their own, a builder can ask for them. A short rule in each agent’s instructions goes a long way:
prompt # Coordination rule, added to every agent's system prompt Before you edit a file, post a message to your teammate with: 1. the file path, and the exact line range you will change 2. what you will put there Do not edit any line range a teammate has claimed. If your plan overlaps theirs, say so and propose one single plan. After you finish, post what you actually changed.
That rule is resource division with a nudge toward negotiation. The first line of the rule asks for a precise range, because the slide’s best message was precise. The last line asks for a report, because a team that promises but does not report cannot find out when a promise was broken. Chapter 9 shows how often that happens.
Chapter 9
Sort real failures into a taxonomy, measure the cost of coordination, and spot the odd habits that only appear in groups
A hospital ward runs a morning handover. The night nurse tells the day nurse that bed 4 needs a blood test. The day nurse hears it, nods, and assumes the lab already knows. The lab never gets the request. No one lied and no one was lazy. The information stopped at a seam between two people. Teams of agents have many such seams, and the lecture’s last big part is a tour of how they break.
Three sources give the tour its shape: a study of why multi-agent systems fail (the second reading), a benchmark of agents working in pairs, and a paper on behaviours that only show up in groups.
The study is Why Do Multi-Agent LLM Systems Fail? by Cemri and colleagues (arXiv 2503.13657). Its starting point was blunt: teams of agents often gain little on popular benchmarks, and no one had a principled account of why. So the authors did what a careful investigator does. They collected a great many traces (the full record of one run: every message, tool call and result), read them, and sorted the failures into a taxonomy, a tidy list of kinds.
The result is MAST, the Multi-Agent System failure Taxonomy: 14 failure modes in 3 groups, built from 150 traces with expert annotators who agreed strongly (a kappa score of 0.88). They then labelled over 1,600 traces from 7 popular multi-agent frameworks, using a language model as a judge to scale the labelling. The slide gives each mode its share of all the failures found.
System design issues make up 44.2% of failures. These are faults in how the team was set up: disobeying the task specification (11.8%), disobeying a role specification (1.5%), repeating a step (15.7%), losing the conversation history (2.8%), and being unaware of when to stop (12.4%). Inter-agent misalignment makes up 32.3%: a conversation that resets (2.2%), failing to ask for clarification (6.8%), a task that drifts off course (7.4%), withholding information (0.8%), ignoring another agent’s input (1.9%), and a mismatch between what an agent reasons and what it does (13.2%). Task verification makes up 23.5%: stopping too early (6.2%), no or partial checking (8.2%) and wrong checking (9.1%).
Look at which single modes are biggest: step repetition (15.7%), a reasoning and action mismatch (13.2%) and not knowing when to stop (12.4%). Most of the worst failures are not subtle intelligence failures. They are failures of bookkeeping. Now test your eye on six made-up traces.
Read the trace, then choose the group it belongs to. The bars show each group’s share of all failures in the study, and the thin bar shows the share of the exact mode.
The three group shares and the mode names and shares are the study’s (slide 72, as read from the figure). The six traces are invented for this exercise; the study works on real traces from seven frameworks.
MAST describes failures in the wild. CooperBench, the benchmark from Chapter 8, measures one cost directly. Take a job with two parts. Give both parts to one agent, and record the success rate. Now give one part to each of two agents and record again. If teamwork helped, the pair would win. The paper’s abstract reports the opposite: pairs have about 30% lower success rates than one agent doing both tasks. The authors call it the curse of coordination, and note that it differs sharply from human teams, where adding a teammate usually helps.
The lecture gives the three causes on slide 76. Expectation (42% of the failures): one agent has clearly said what it is doing, yet the other keeps acting as if that work is not being done. Commitment (32%): an agent does not do what it promised, such as failing to keep an agreed interface. Communication (26%): information is not shared, or decision loops between agents break. See both views.
Switch between the two views. In the first, pick a model and compare working alone with working as a pair. In the second, pick a cause.
Success rates are read from the chart on slide 75 (CooperBench, Khatua et al. 2026) and are approximate; the abstract’s headline for all agents tested is about 30% lower success as a pair. The three causes and their shares (42%, 32%, 26%) are the slide-76 table. The relative drop shown for each model is our arithmetic on the chart’s labels.
Communication, then, is the smallest of the three causes. The abstract adds the colour: channels get jammed with vague, ill-timed and inaccurate messages, agents deviate from their commitments even when the talk was good, and agents hold wrong beliefs about what the others are doing. More chat did not fix it. Better habits might (Chapter 8).
The third source, by Zou (2026), looks at behaviour rather than errors. Two examples fill the slides.
Conformity. Ask a swarm of agents to each build something impressive, and over half decide to build either a ray tracer or a self-hosting compiler. The agents are individually capable, and together they choose the same few ideas. The slide pairs this with two pictures. On the left, four different models told the same coffee joke (the coffee that got mugged) word for word. On the right, a map of answers to “Write a metaphor involving time” shows most models landing on the same few images, such as a river. A team of copies is a team with one idea, a loss of diversity.
Incompatible goals. In the experiment, each model must migrate a Python backend on a fourth virtual machine to another language, but each gets a different target language, for example Python for one and Rust for another. The goals cannot both hold. The slide’s finding is that agents sometimes settle by force instead of reaching a deal. The bar chart sorts the runs by how they ended: settled by force, settled by passivity (one side gave up), settled by a truce, or not settled. One model version ended 61% of its runs by force and left 39% unsettled, while another ended 98% in a truce. Hostile conflict resolution is the name for the forced ending.
The slide 82 summary files everything in three drawers. General failures: system design, inter-agent problems and verification. Coordination failures: expectation, commitment and communication. Behavioural failures: lack of diversity, and hostile conflict resolution.
Take the single biggest mode, step repetition. Symptom: the run is long, the bill is large, and the same tool call appears again and again in the trace. Measurement: count identical calls in a recent window. Fix: stop the run when the count passes a limit, add a step budget, and tell the agents how the task ends. Here is the detector.
python import json def is_looping(trace, window=8, repeats=3): """True if the same tool call (same name, same arguments) fills the recent window.""" calls = [(m.tool, json.dumps(m.args, sort_keys=True)) for m in trace[-window:] if m.tool] return any(calls.count(c) >= repeats for c in set(calls)) # in the team loop: if is_looping(trace) or len(trace) > MAX_STEPS: stop and report
For the deeper dives, see our paper lessons on why multi-agent systems fail and on the science of scaling agent systems.
Chapter 10
Watch every idea from this lecture at work in one real project, and collect six lessons from it
A compiler is a program that turns source code, which humans write, into machine instructions that a chip can run. A C compiler that can build the Linux kernel is a serious piece of software, the kind a team of engineers spends years on. In early 2026, Carlini at Anthropic gave the job to sixteen copies of one coding agent and mostly walked away. The lecture closes with this project as an optional case study, and says plainly that it is one look at how companies may be running agent swarms for engineering and science.
The numbers, from the project’s write-up, set the scale. Over about two weeks and nearly 2,000 coding sessions, the agents read roughly 2 billion tokens and wrote 140 million. The bill was just under $20,000. The result was a 100,000-line compiler, written in Rust from scratch, that can build a bootable Linux 6.9 for three chip families (x86, ARM and RISC-V) and that passes about 99% of most compiler test suites. Divide it out: about $0.20 per line, and about $10 per session.
Slide 85 shows the whole orchestration in a few lines of shell: a loop that never ends. Each agent runs inside its own container. The loop starts the coding agent with the same instruction file, lets it work until it stops, and starts it again. When one task is done, the agent immediately picks up the next.
bash #!/bin/bash while true; do COMMIT=$(git rev-parse --short=6 HEAD) LOGFILE="agent_logs/agent_${COMMIT}.log" claude --dangerously-skip-permissions -p "$(cat AGENT_PROMPT.md)" \ --model claude-opus-X-Y &> "$LOGFILE" done
In the language of Chapter 2, this is a decentralized swarm. There is no orchestrator. Every agent decides for itself what to work on. The flag in the script skips permission prompts, which is why the write-up says to run it in a container and never on a machine you care about.
The swarm also has specialists, as slide 86 shows. Most agents fix distinct compiler failures. Others have a standing job: one removes repeated code, one keeps the documentation up to date, one makes the compiler itself faster, one makes the code it produces faster, and one reviews the structure of the Rust. Each works on the same shared codebase. They have complementary goals, so they seldom compete.
How do sixteen agents with no boss avoid fixing the same bug? They use a task folder in git, which is Chapter 7’s task ledger made of plain files. To claim a task, an agent writes a text file into a folder called current_tasks/, for example parse_if_statement.txt. It then pushes. If two agents try to claim the same task, git accepts the first push and rejects the second, and the second agent must choose another task. Then the agent works, pulls and merges what others pushed, pushes its own work, and releases its claim.
Each agent also works in isolation. Slide 88 shows a shared bare git repository in the middle and a container per agent, each with its own local clone in /workspace. That is Chapter 7’s worktree idea, built with containers. And for shared memory, the agents keep notes and progress files in the repository, which every new session reads first. The slides label the README and progress files as the inter-agent communication and the shared memory. There is no message board and no chat. The repository is the board.
Try the claim step with a toy. Eight tasks wait. Each round, every agent picks a task from what it last saw. With claim files, the second agent to push a claim loses the race and picks again. Without them, two agents can do the same job.
Choose a mode and press Run a round. Green squares are finished tasks. A red mark means an agent did work that another agent also did.
Toy: eight tasks, each taking one round. Each agent picks at random from the tasks that looked open at the start of the round. With claim files, pushes are processed in a random order, the first push for a task wins, and each loser immediately picks again from what is left; without claims, every agent keeps its first pick. Seeded random draws; the claim mechanism follows the write-up, the task names are invented.
With four agents and claims, the eight tasks finish in two rounds with no duplicated work. Without claims, press Run a round a few times and watch the red marks: some work is done twice, so it takes more rounds and wastes effort. In the real project, the cost of duplicate work was larger than wasted effort, because agents also overwrote each other’s changes.
Slide 89 lists the lessons. Each ties to an earlier chapter.
Notice what the project did not use: no orchestrator agent, no chat, no negotiation protocol. It used a loop, a folder, git and a strong test suite. The lecture’s whole toolbox is on offer. The project chose the smallest part of it that worked.
Chapter 11
Keep the numbers, the terms, a checklist and the core code on one page, and find where to go next
The lecture’s summary slide ticks five boxes: single against multi-agent systems, orchestration patterns, communication, shared state, and failures and challenges. In one paragraph: start with one strong agent and measure it; add agents only for a named reason; choose the smallest team shape that works; make every handoff, claim and stop rule explicit; and expect the failures that sit at the seams between agents. The next lecture, on Wednesday, moves on to optimisation.
| What | Value | Source and chapter |
|---|---|---|
| Team against one agent | from +81% (finance, orchestrator) to −70% (planning, independent) | Kim et al. 2026; Chapters 1 and 3 |
| Scaling study size | 260 configurations, 6 benchmarks, 5 architectures, 3 model families | Kim et al. 2026; Chapter 1 |
| Messages per round, n workers | independent n; orchestrator 2n; swarm n(n − 1) | Our count; Chapter 2 |
| DyLAN on decision tasks | reward 68.3, success 42.0, 24.85 calls (BOLAA: 66.0, 40.0, 32.40) | Liu et al. 2023; Chapter 3 |
| Early stop | stop when 2 of 3 agents agree | DyLAN; Chapter 3 |
| Handoff against tool | whole history moves, or a bounded request goes out | OpenAI Agents SDK; Chapter 5 |
| A2A task states | submitted, working, input-required, completed | A2A spec; Chapter 6 |
| Magentic-One re-plan rule | re-plan when the stall count passes 2 | Fourney et al. 2024; Chapter 7 |
| G-Memory average score | 57.18 against 48.27 with no memory | Zhang et al. 2025; Chapter 7 |
| CooperBench | 600+ tasks, 12 libraries, 4 languages; pairs about 30% lower | Khatua et al. 2026; Chapters 8 and 9 |
| Causes of coordination failure | expectation 42%, commitment 32%, communication 26% | Khatua et al. 2026; Chapter 9 |
| MAST | 14 modes, 3 groups (44.2%, 32.3%, 23.5%), 1,600+ traces, 7 frameworks | Cemri et al. 2025; Chapter 9 |
| C compiler swarm | 16 agents, about 2,000 sessions, just under $20,000, 100,000 lines | Carlini 2026; Chapter 10 |
| Term | Plain meaning |
|---|---|
| Multi-agent system | Several agents that work toward one shared task |
| Orchestrator, worker | The agent that plans and assigns, and the agents that do the assigned parts |
| Swarm | Agents that all talk to each other, with no lead |
| Handoff | Control of the conversation moves to another agent, with its history |
| Agent as tool | The caller keeps control and gets a result back from a helper |
| Message board | A shared place where agents post and read |
| A2A, agent card | A protocol for agents to meet, and the JSON file that says what an agent can do |
| Task ledger | The shared, updated record of the plan, owners and progress |
| Worktree isolation | One checkout and branch per agent, merged and tested later |
| Curse of coordination | Two agents doing two tasks score lower than one agent doing both |
The whole lecture fits in one function: an orchestrator that keeps a ledger, asks a progress question after every step, calls a worker as a tool with a bounded request, re-plans when work stalls, and stops on a step budget. Here llm is any function that takes a prompt and returns text, and each worker is a function that takes an instruction and returns a result.
python import json def run_team(task, workers, llm, max_stalls=2, max_steps=30): ledger = {"task": task, "plan": llm(f"Write a short step plan for: {task}"), "done": []} stalls = 0 for step in range(max_steps): # a stop rule that never depends on the agents ask = f"Ledger: {json.dumps(ledger)}\nReply as JSON with is_request_satisfied, " \ "is_progress_being_made, next_speaker, instruction." p = json.loads(llm(ask)) # the progress ledger if p["is_request_satisfied"]: return llm(f"Write the final answer from: {json.dumps(ledger)}") stalls = 0 if p["is_progress_being_made"] else stalls + 1 if stalls > max_stalls: # Magentic-One's rule: re-plan ledger["plan"] = llm(f"The plan stalled. Write a new plan for: {task}") stalls = 0 continue worker = workers[p["next_speaker"]] result = worker(p["instruction"]) # agent as tool: a bounded request ledger["done"].append({"by": p["next_speaker"], "result": result}) return "stopped: step budget used"
Count what this code leaves out, because each gap is a chapter. It has no loop detector (Chapter 9). It gives workers no shared memory (Chapter 7). It has no verifier that checks the final answer independently. And it runs workers one at a time, so it gets none of the parallel gain from Chapter 1. Each is a place to add something, and only when a measurement says the team needs it.
Read the three papers behind this lecture in their lessons: AutoGen, Why Do Multi-Agent LLM Systems Fail? and Towards a Science of Scaling Agent Systems. For related ground, see agent frameworks (Lecture 5), agent memory (Lecture 7), sessions and multi-agent in a long-lived assistant and agent architectures. The course’s own pages are at cs329z.stanford.edu and the Lecture 8 slides. This lesson re-teaches the lecture in our own words, and the idea and numbers come from CS 329Z (Fall 2026) and its instructors Diyi Yang, Michael Ryan and John Yang, and from the papers cited in each chapter.
Now press Present or Teach and explain one team out loud, from memory: why you would or would not use more than one agent for a job you know, which of the four shapes you would pick and how many messages it sends, how work passes between agents, what keeps two agents out of each other’s files, and which failure you would watch for first. Then go back to the team at the top, pick the planning job, and explain why every team shape loses there.