19 · Multi-agent systems

Run it in Colab View the .ipynb

You are reading this notebook. To run it, open it in Colab with the button above - no install, no GPU needed for most of them - or clone the repository and open it in Jupyter.

  1. 19.1 · When a team is actually justified
    1. 1. Different tools, and the sets must not mix
    2. 2. Different context, and one window will not hold it
    3. 3. Adversarial roles
    4. Reasons that are not reasons
    5. In plain terms
  2. 19.2 · The domain: planning a trip
  3. 19.3 · Pattern 1: the router
    1. Why the choice is a model call and not an if
    2. Routers fail by inventing specialists
  4. 19.4 · Pattern 2: the orchestrator
    1. Count the cost honestly
    2. The dependency trap
  5. 19.5 · Pattern 3: the critic loop
  6. 19.6 · How teams fail
  7. 19.7 · So: do you need a team?
  8. Checkpoint

Agents track · ~90 minutes · no server needed

Let’s start with the conclusion, because the field does not:

Most multi-agent systems should have been one agent with more tools.

Every handoff is a lossy summary. Agent A knows things it did not write down; agent B gets the summary instead of the knowledge. You have replaced a function call with a game of telephone and you pay a model call per round.

That said, there are three situations where several agents genuinely win, and one of them is a security property nothing else provides. By the end you will be able to:

  1. name the three cases that justify a team, and reject the rest;
  2. build the four patterns — router, orchestrator, pipeline, critic loop;
  3. measure the handoff cost instead of assuming it away;
  4. recognise the failures that only appear with multiple agents;
  5. decide, for a given task, whether to use a team at all.

Everything runs with scripted specialists. The working example is a trip-planning assistant — a new domain, chosen because it genuinely splits into independent pieces, which is exactly the shape a team suits.

# --- Setup: works on your laptop AND in Google Colab ------------------------
import os
import subprocess
import sys
from pathlib import Path

if "google.colab" in sys.modules:
    if not Path("/content/ROBT407LLM").exists():
        subprocess.run(["git", "clone", "--depth", "1",
                        "https://github.com/berdakh/ROBT407LLM.git",
                        "/content/ROBT407LLM"], check=True)
    os.chdir("/content/ROBT407LLM")
    subprocess.run([sys.executable, "-m", "pip", "install", "-q",
                    "-r", "requirements.txt"], check=True)

REPO_ROOT = next(p for p in [Path.cwd(), *Path.cwd().parents]
                 if (p / "src" / "qwen_workshop").is_dir())
sys.path.insert(0, str(REPO_ROOT / "src"))
print("repo root:", REPO_ROOT)
from qwen_workshop.agent import Agent
from qwen_workshop.multiagent import CriticLoop, Orchestrator, Router, Specialist, Team
from qwen_workshop.scripted import ScriptedModel, calls, says
from qwen_workshop.tools import ToolError, ToolRegistry, tool

19.1 · When a team is actually justified

Three reasons. If yours is not on this list, you want functions.

1. Different tools, and the sets must not mix

The agent that reads your email must not be the agent that can spend money. This is a security boundary, and it is the only item on this list that nothing else can provide. Capability separation is enforced by construction: a specialist cannot misuse a tool it was never given.

2. Different context, and one window will not hold it

Four specialists each reading a different 50-page document is four context windows. One agent reading all four is a truncation bug waiting to happen (notebook 17.5 has the arithmetic).

3. Adversarial roles

A critic that has not seen the writer’s reasoning catches what the writer cannot — precisely because it lacks the context. Here the information loss is the mechanism rather than the cost.

Reasons that are not reasons

“We need multiple agents because…” What you actually want
“it mirrors how our team works” functions with good names
“each agent has a clear responsibility” functions with good names
“it’s more modular” functions. With good names.
“agents can specialise in a domain” a better system prompt, usually
“it’s easier to debug” the opposite is true — see 19.6

What is genuinely new is only three things: routing (who handles this), a handoff format (what crosses the boundary), and a termination rule (when the exchange stops). That is why the module behind this notebook is short.

In plain terms

The pattern names are the most confusing jargon in this workshop, and every one of them is an everyday job you already understand:

Pattern Think of it as And so
Router The receptionist at a clinic. Ten seconds of listening, then “third door on the left”. Decides once, then steps aside. Two model calls.
Orchestrator A wedding planner. Asks the florist, the caterer and the photographer each for their piece, then assembles the day. You pay all three whether or not you use what they say.
Pipeline A passport office. Desk 1 → desk 2 → desk 3. Nobody sees your whole case, so nobody can explain the outcome.
Critic loop A writer and an editor. Draft, red pen, revise, signed off. Only works if the editor can say no — and if you cap the rounds.
Handoff Repeating a story to the next person. Each retelling loses detail. This is the cost nobody counts.

Hold on to the wedding planner in particular. It explains the cost (three suppliers, three bills), the benefit (the florist does not need to know about catering), and the failure (the planner assumes the caterer checked the dietary requirements, and the caterer assumed the planner did).

19.2 · The domain: planning a trip

Three specialists with genuinely different tools. Note what each one cannot do — that is the design, not an omission.

PRICES = {"Almaty->Istanbul": 185_000, "Almaty->Dubai": 210_000,
          "Almaty->Tbilisi": 160_000}
VISA = {"Istanbul": "visa-free for 90 days", "Dubai": "visa-free for 30 days",
        "Tbilisi": "visa-free for 1 year"}
WEATHER = {"Istanbul": "14-19C, rain likely", "Dubai": "24-33C, dry",
           "Tbilisi": "8-15C, cool and wet"}


@tool
def flight_price(destination: str) -> int:
    """Return the return flight price from Almaty in tenge.

    Args:
        destination: City name, e.g. Istanbul.
    """
    key = f"Almaty->{destination}"
    if key not in PRICES:
        raise ToolError(f"no route to {destination!r}. Known: "
                        + ", ".join(k.split('->')[1] for k in PRICES))
    return PRICES[key]


@tool
def visa_rules(destination: str) -> str:
    """Return visa requirements for a Kazakhstani passport.

    Args:
        destination: City name.
    """
    if destination not in VISA:
        raise ToolError(f"no visa data for {destination!r}")
    return VISA[destination]


@tool
def forecast(destination: str) -> str:
    """Return the expected weather for the travel month.

    Args:
        destination: City name.
    """
    if destination not in WEATHER:
        raise ToolError(f"no forecast for {destination!r}")
    return WEATHER[destination]


@tool
def book_flight(destination: str, confirmed: str = "no") -> str:
    """Book a flight. SPENDS MONEY. Requires confirmed='yes'.

    Args:
        destination: City name.
        confirmed: Must be 'yes' to actually book.
    """
    if confirmed != "yes":
        return f"DRAFT: would book Almaty->{destination}. Re-call with confirmed='yes'."
    return f"BOOKED Almaty->{destination}"

Now wrap agents as specialists. A Specialist is just a name, a description and a task -> result callable — which means it can be an Agent, a plain function, or another whole team.

def scripted_specialist(name: str, description: str, registry: ToolRegistry,
                        turns: list) -> Specialist:
    """A Specialist backed by a scripted Agent, so runs are reproducible."""

    def run(task: str) -> str:
        return Agent(*ScriptedModel(turns).as_client(), registry, max_steps=5).run(task).answer

    return Specialist(name, description, run, tools=registry.names())


budget = scripted_specialist(
    "budget",
    "Flight prices and totals from Almaty. Use for anything about cost.",
    ToolRegistry().add(flight_price),
    [calls("flight_price", {"destination": "Istanbul"}),
     says("Istanbul is 185,000 tenge return.")],
)

paperwork = scripted_specialist(
    "paperwork",
    "Visa rules for a Kazakhstani passport. Use for entry requirements.",
    ToolRegistry().add(visa_rules),
    [calls("visa_rules", {"destination": "Istanbul"}),
     says("Istanbul: visa-free for 90 days.")],
)

weather = scripted_specialist(
    "weather",
    "Expected weather at the destination. Use for what to pack or when to go.",
    ToolRegistry().add(forecast),
    [calls("forecast", {"destination": "Istanbul"}),
     says("Istanbul: 14-19C, rain likely.")],
)

team = Team().add(budget, paperwork, weather)
print(team.roster())
print("\ntools each one holds:")
for member in team.members:
    print(f"  {member.name:<10} {member.tools}")

Notice what nobody has. book_flight was defined above and given to no one. No specialist in this team can spend money, and that is enforced by construction rather than by a prompt asking nicely. Compare that with one agent holding all four tools, where the only thing between a bad decision and a booking is the model’s judgement.

Router, orchestrator, pipeline and critic loop side by side, with the model-call cost of each

19.3 · Pattern 1: the router

The cheapest useful pattern, and the one most teams actually need. One model call picks a specialist; that specialist does the work. Two model calls total, and only the relevant specialist is paid for.

def choose(task: str, roster: str) -> str:
    """Stands in for a model call. A real one is given `roster` and the task."""
    lowered = task.lower()
    if any(w in lowered for w in ("cost", "price", "how much", "flight", "afford", "budget")):
        return "budget"
    if any(w in lowered for w in ("visa", "passport", "entry")):
        return "paperwork"
    return "weather"


router = Router(team, choose, fallback="weather")
for question in ["How much is a flight to Istanbul?",
                 "Do I need a visa for Istanbul?",
                 "What should I pack?"]:
    print(f"{question:<38} -> {router.run(question)}")

The roster is what the router reads, which makes the description field the routing signal — not documentation. “Handles data” routes nothing. This is exactly the lesson from notebook 10.5 about tool descriptions, applied one level up.

Why the choice is a model call and not an if

choose above is keywords, because this notebook has to be reproducible. Keyword routing is also genuinely brittle, and it fails silently — which is the worst way to fail.

for question in ["Will this blow my savings?",          # cost, no cost keyword
                 "Can I get in with my passport?",      # visa, and it does say passport
                 "Is 185,000 tenge reasonable?"]:       # cost, no keyword either
    print(f"{question:<34} -> routed to {choose(question, '')!r}")

Two of those three went to the weather specialist, which will answer confidently about the weather. Nothing raised, nothing logged, and the user gets a fluent non-answer.

A model reads the roster and gets these right, which is the actual argument for spending a model call on the routing decision: not that it is smarter, but that it degrades more gracefully on phrasings you did not anticipate.

Routers fail by inventing specialists

Models produce plausible names that do not exist. Routine, not exceptional, so handle it rather than crashing.

confused = Router(team, lambda t, r: "TravelExpertAgent", fallback="weather")
print("answer :", confused.run("Do I need a visa?"))
print("\ntranscript:")
print(confused.team.trace().splitlines()[-3])

The fallback kept it running, and the error is in the transcript so you can count how often it happens. A router that silently guesses is a router whose accuracy you can never measure.

Exercise 1. The fallback above sent a visa question to the weather specialist, which will answer confidently and wrongly. Change Router so an invalid choice is retried once with the roster and the invalid name fed back, before falling back. Then argue the other side: when is answering with the wrong specialist worse than returning an error to the user?

19.4 · Pattern 2: the orchestrator

What people usually mean by “multi-agent”. Fan the subtasks out, gather, synthesise. It earns its keep when the subtasks are independent.

def synthesise(goal: str, results: dict[str, str]) -> str:
    """Stands in for the final model call."""
    lines = [f"Re: {goal}", ""]
    lines += [f"- {name}: {text}" for name, text in results.items()]
    return "\n".join(lines)


team2 = Team().add(budget, paperwork, weather)
answer = Orchestrator(team2, synthesise).run(
    "Should I go to Istanbul next month?",
    [("budget", "cost of Almaty-Istanbul return"),
     ("paperwork", "visa rules for Istanbul"),
     ("weather", "weather in Istanbul next month")],
)
print(answer)
print("\n" + team2.trace())
print(f"\nhandoffs: {team2.n_handoffs}")

Count the cost honestly

Three specialists, each an agent in its own right.

one_agent = 3   # think, call three tools in one turn, answer
team_cost = 1 + (3 * 2) + 1  # route/plan + (think+answer per specialist) + synthesise
print(f"one agent with three tools : ~{one_agent} model calls")
print(f"orchestrator + 3 specialists: ~{team_cost} model calls")
print(f"\nhandoff messages: {team2.n_handoffs}, each one a lossy summary")

Roughly three times the model calls for the same answer. You are buying context separation and tool separation. On this task — three tiny tool calls that would comfortably fit one window — you are buying nothing, and the right design is one agent with three tools.

Swap in three specialists that each read a 40-page document and the arithmetic reverses completely. The pattern is not the question; the context budget is.

The dependency trap

Orchestration assumes the subtasks are independent. The moment subtask 2 needs what subtask 1 found, you have a plan, and notebook 18 already models that properly. Forcing it into an orchestrator means either running them in the wrong order or passing results by hand.

sequential = Team().add(budget, paperwork)
Orchestrator(sequential, synthesise).run(
    "Can I afford the trip after visa fees?",
    [("paperwork", "visa cost"), ("budget", "flight cost minus visa cost")],
)
print(sequential.trace())
print("\n^ the budget specialist was asked to subtract a number it was never given.")

Exercise 2. Fix the cell above by building a Plan (notebook 18) whose budget task depends on the paperwork task, with a runner that dispatches each task to a specialist and passes the dependency results into the task description. Then say in one sentence what Orchestrator is still good for once you have a planner.

19.5 · Pattern 3: the critic loop

The one pattern where losing context is the point. A critic that has not seen the writer’s reasoning judges the output the way a reader will.

DRAFTS = iter([
    "You should go to Istanbul. It's lovely.",
    "Istanbul is a good choice: flights are 185,000 tenge and no visa needed.",
    "Istanbul: 185,000 tenge return, visa-free for 90 days, 14-19C with rain "
    "likely - pack a coat. Total before accommodation: 185,000 tenge.",
])


def writer(task: str) -> str:
    return next(DRAFTS)


def critic(draft: str) -> str:
    """Checks the draft against a rubric. Must say APPROVED, or it is not."""
    missing = [need for need, token in
               [("a price", "185,000"), ("visa status", "visa"), ("weather", "C")]
               if token not in draft]
    if missing:
        return f"Not yet. Missing: {', '.join(missing)}."
    return "APPROVED"


pair = Team().add(
    Specialist("writer", "Writes the recommendation.", writer),
    Specialist("critic", "Checks it against the rubric. Replies APPROVED or a list.", critic),
)
outcome = CriticLoop(pair, "writer", "critic", max_rounds=4).run(
    "Recommend a destination for next month.")

print(pair.trace())
print(f"\naccepted after {outcome['rounds']} rounds: {outcome['accepted']}")
print("\nFINAL:\n" + outcome["draft"])

Two rules make this work, and both were learned the hard way:

A round cap. Without one the pair trades refinements forever, sounding productive the whole time. This is the characteristic multi-agent failure and it is expensive because every round is two model calls.

An explicit accept token. “Looks good to me, although…” is not an acceptance, and prose gives you no reliable way to tell. The critic must emit APPROVED and nothing else counts.

polite = Team().add(
    Specialist("writer", "writes", lambda t: "Here is my draft."),
    Specialist("critic", "reviews", lambda d: "Looks good to me, although the tone is off."),
)
stuck = CriticLoop(polite, "writer", "critic", max_rounds=3).run("write something")
print(f"accepted: {stuck['accepted']} after {stuck['rounds']} rounds "
      f"({polite.n_handoffs} handoff messages = {polite.n_handoffs // 2} "
      f"specialist calls, all wasted)")
print("last critique:", stuck["last_critique"])

Without the token check, “Looks good to me” would have been read as approval and a draft with the wrong tone would have shipped. With it, the loop correctly reports failure — which is the right outcome, because the critic never actually approved anything.

Exercise 3. The critic here is a Python function with a rubric, which makes it deterministic and free. Replace it with a scripted model critic and keep the rubric in its system prompt. Which is better for CI, and which is better for catching the problems you did not think of? Then say what happens to the critic loop when the writer and critic are the same model — and why that is not a hypothetical.

19.6 · How teams fail

Everything from notebook 10.9 still applies to each member. These are the failures that only exist once there is more than one.

def demo(label, build):
    print(f"--- {label} ---")
    build()
    print()


# 1. Telephone: each handoff is a summary, and summaries compound.
vague = Team().add(
    Specialist("budget", "costs", lambda t: "It's affordable."),
    Specialist("planner", "plans", lambda t: "Affordable" if "afford" in t else "unclear"),
)
demo("1. telephone - detail lost at each boundary", lambda: (
    print("   specialist said :", vague.dispatch("orchestrator", "budget", "cost?")),
    print("   what reached the next agent: a word, not 185,000 tenge")))

# 2. Diffusion of responsibility: everyone assumes someone else checked.
demo("2. nobody owns correctness", lambda: print(
    "   budget assumes paperwork checked the visa; paperwork assumes budget\n"
    "   checked the dates; the synthesiser assumes both were careful."))

# 3. Infinite politeness, already seen in 19.5.
demo("3. loops that sound productive", lambda: print(
    f"   {stuck['rounds']} rounds, {polite.n_handoffs} handoffs, nothing agreed"))

# 4. The hallucinated specialist, already seen in 19.3.
demo("4. routing to someone who does not exist", lambda: print(
    "   model picks 'TravelExpertAgent'; without a fallback the run dies"))

Failure 2 deserves more than a line. In a single agent, one transcript holds every fact and every decision, and you can read it. In a team, the only record of what they told each other is the message log — which is why Team records every handoff, and why building a team without that log is a system you cannot debug.

This is the real answer to “multi-agent is easier to debug”. It is not. It is easier to draw.

print("the full handoff log for the orchestrator run:\n")
print(team2.trace())

Exercise 4. Write audit(team) that flags any specialist whose result was never used in the final answer, and any handoff whose content was under 20 characters (a suspiciously lossy summary). Run it on team2 and vague. Then say which of the four failures above your audit cannot detect, and what you would need to record to catch it.

19.7 · So: do you need a team?

Work down this list and stop at the first yes.

  1. Must two capability sets be kept apart for safety? → yes, a team. Nothing else gives you this.
  2. Does the context genuinely not fit in one window? → yes, a team. Measure it first (notebook 17.5); people assume this far more often than it is true.
  3. Do you want an independent critic? → yes, a critic loop. Just two roles, not a committee.
  4. Are the subtasks independent and slow? → maybe an orchestrator. Compare against one agent with more tools first.
  5. Anything else? → one agent, more tools. Or a chain. Or a function.

And if you do build one, start with a router: it is two model calls, it gives you the capability separation from reason 1, and it is the only pattern here whose cost is comparable to a single agent.

Checkpoint

  1. Give the three cases where a team is genuinely justified.
  2. Which of them can nothing else provide, and why?
  3. Name three bad reasons for multiple agents and what each really wants.
  4. What are the only three new mechanisms a team introduces?
  5. Why is the description field the most important part of a Specialist?
  6. What is the handoff cost of an orchestrator with three specialists?
  7. Why does the critic loop need both a round cap and an accept token?
  8. Why is a team harder to debug than one agent, not easier?

➡️ Next: 20_evaluating_agents.ipynb — how to tell whether any of this actually works.


Back to top

ROBT407LLM workshop materials. Code is MIT licensed; prose is CC BY 4.0. Model weights are governed by their own licences - check each model card.