About this notebook

Companion to Module 9: Multi-agent systems. Every cell below was executed with the offline backend, so you can reproduce these outputs exactly with no API key. Download the notebook (.ipynb)

One agent with many tools and a long prompt is the default, and often the right one. This notebook takes a small help-desk task and splits it across several agents in each of the three ways that Hur and Song distinguish, so you can compare who decides what runs next and what each agent gets to see. You will

  1. run a sequential workflow: a researcher, then a writer, in one shared context;
  2. run three checkers in parallel and watch them overlap in time;
  3. run a loop: a drafter and a reviewer, until the reviewer approves;
  4. let a manager call the researcher and the writer as tools, each in a fresh context;
  5. hand a conversation from a triage desk to a specialist with a transfer;
  6. stage two classic failures: lost information and a handoff loop.

Which model answers here?

With no MODEL set, every agent is played by the offline policy model: deterministic rules keyed on a role sentence in each agent’s instructions (“You are the reviewer”). It is not a language model, so the drafts are templates and the routing is word matching. The orchestration code, which is what this notebook is about, is the same for a real model. Set MODEL and re-run to see real agents disagree, wander and recover.

from agentlab.nbsetup import setup
 
nb = setup("09a_workflows_handoffs", packs=["multi"])
llm = nb.llm

LLM backend

offline policy model (deterministic, rule-based, no API key used)

1. The help desk

A small support team has a help centre (five articles) and an account database. Three tools cover both. refund_invoice changes state, so it records each refund in a list you can inspect afterwards.

import json
import re
 
from agentlab.config import repo_root
 
DATA = repo_root() / "fixtures" / "multi"
KB = json.loads((DATA / "kb.json").read_text())
ACCOUNTS = json.loads((DATA / "accounts.json").read_text())
REFUNDS: list[str] = []
 
 
def _words(text: str) -> set[str]:
    return set(re.findall(r"[a-z]+", text.lower()))
 
 
def search_kb(query: str) -> str:
    """Search the help-centre articles and return the two best matches.
 
    Args:
        query: A few words describing the problem.
    """
    def score(article: dict) -> int:
        return len(_words(query) & _words(article["title"] + " " + article["text"]))
 
    ranked = [a for a in sorted(KB, key=lambda a: -score(a)) if score(a) > 0]
    if not ranked:
        return "no matching article"
    return "\n".join(f'{a["id"]} {a["title"]}: {a["text"]}' for a in ranked[:2])
 
 
def get_account(customer_id: str) -> dict:
    """A customer's name, plan and recent invoices.
 
    Args:
        customer_id: The customer id, for example "C-17".
    """
    if customer_id not in ACCOUNTS:
        raise ValueError(f"no customer {customer_id!r}")
    return ACCOUNTS[customer_id]
 
 
def refund_invoice(invoice_id: str) -> str:
    """Refund one invoice in full.
 
    Args:
        invoice_id: The invoice to refund, for example "INV-882".
    """
    amounts = {i["id"]: i["amount_eur"] for a in ACCOUNTS.values() for i in a["invoices"]}
    REFUNDS.append(invoice_id)
    amount = amounts[invoice_id]
    return f"Refund R-{len(REFUNDS)} created for {invoice_id} (EUR {amount:.2f})."
 
 
TICKET = ("Hi, this is Ana (customer C-17). I was charged twice for October. "
          "Can I get my money back?")

Before splitting anything, it is worth asking whether to. The CS329Z lecture on multi-agent systems lists real benefits (parallel work, specialised prompts and tools, a focused context for each agent, broader exploration) and real costs (coordination overhead, information lost between agents, conflicting actions, errors that propagate, and more code to debug), and its advice is to start from a strong single-agent baseline. The three patterns below differ in who decides what happens next and in what each agent sees:

patternwho decides the next agentwhat the next agent seeswho answers
workflowyour codewhatever you pass (here: everything)the last agent
agent as toolthe calling modelonly the request it is giventhe caller
transfer (handoff)the current modelthe whole conversationthe new agent

2. Sequential: a pipeline with one shared context

A researcher gathers facts with the tools; a writer turns them into a reply. In SequentialWorkflow both run on the same ExecutionContext, one after the other, so the writer sees the ticket, every tool call, every result and the researcher’s notes.

from agentlab import Agent, FunctionTool, Message
from agentlab.display import show_trajectory
from agentlab.multi import SequentialWorkflow
 
kb_tool, account_tool, refund_tool = (FunctionTool(f) for f in
                                      (search_kb, get_account, refund_invoice))
researcher = Agent(llm, tools=[kb_tool, account_tool], name="researcher",
                   description="Looks up the customer's account and the relevant help "
                               "article, and returns short notes.",
                   instructions="You are the researcher. Look up the facts a reply needs "
                                "and write them as short notes. Do not write the reply.")
writer = Agent(llm, name="writer",
               description="Writes the customer reply from the researcher's notes.",
               instructions="You are the writer. Write a short, friendly reply to the "
                            "customer using only facts from the notes.")
 
pipeline = SequentialWorkflow([researcher, writer], name="pipeline")
start = len(llm.calls)
result = await pipeline.run(TICKET)
pipeline_calls = llm.calls[start:]
show_trajectory(result, width=84)
print("\nagents, in order:", result.context.state["trace"])
print()
print(result.output)
[user] Hi, this is Ana (customer C-17). I was charged twice for October. Can I get my mo...
[researcher -> search_kb] {"query": "hi ana customer c 17 charged twice october money back"}
[researcher -> get_account] {"customer_id": "C-17"}
    [search_kb ok] KB-101 Refunds for duplicate charges: If a customer was charged twice for the sam...
    [get_account ok] {"name": "Ana Lima", "plan": "Team", "invoices": [{"id": "INV-881", "period": "20...
[researcher] Notes for the writer: - customer: Ana Lima (C-17), plan Team - duplicate: INV-882...
[writer] Hi Ana, you were charged twice for 2026-10: invoice INV-882 repeats INV-881. We a...
--- status: complete, steps: 1

agents, in order: ['researcher', 'writer']

Hi Ana,

you were charged twice for 2026-10: invoice INV-882 repeats INV-881. We are refunding the duplicate, EUR 49.00, in full. Refunds reach your card within 5 working days.

The Support Team

A workflow is the right tool when you already know the steps. It is predictable, easy to test and cheap, because no model spends a call deciding what comes next. Because SequentialWorkflow subclasses Agent, a whole pipeline can itself be a step of another workflow or, as in section 5, a tool.

3. Parallel: independent checks at the same time

Before a reply goes out, three checks can run independently: the tone (greeting and sign-off), the promises it makes, and how it writes amounts. Each checker here is an agent with one tool; in a real system each might be a model acting as a judge. To make the timing visible, each check waits a different amount of time and logs when it starts and ends.

import asyncio
 
from agentlab.multi import ParallelWorkflow
 
timeline: list[str] = []
 
 
async def _timed(label: str, seconds: float) -> None:
    timeline.append(f"start {label}")
    await asyncio.sleep(seconds)
    timeline.append(f"end {label}")
 
 
async def check_tone(text: str) -> str:
    """Check that a reply greets the customer by first name and signs off."""
    await _timed("tone", 0.30)
    problems = []
    if not re.match(r"Hi [A-Z][a-z]+,", text):
        problems.append("greeting: start with 'Hi <first name>,'")
    if not text.rstrip().endswith("The Support Team"):
        problems.append("sign-off: end with 'The Support Team'")
    return "tone: " + ("; ".join(problems) or "ok")
 
 
async def check_promises(text: str) -> str:
    """Check that a reply makes no promise the team does not control."""
    await _timed("promises", 0.10)
    found = [w for w in ("guarantee", "tomorrow", "promise") if w in text.lower()]
    return "promises: " + (f"remove {found}" if found else "ok")
 
 
def _as_eur(amount: str) -> str:
    number = re.search(r"\d+(?:\.\d+)?", amount)
    return f"EUR {float(number.group()):.2f}" if number else "EUR <amount>"
 
 
async def check_amounts(text: str) -> str:
    """Check that amounts are written as the currency code and two decimals (EUR 49.00)."""
    await _timed("amounts", 0.20)
    bad = re.findall(r"\d+(?:\.\d+)? ?(?:euros?|EUR)\b|€", text)
    fixes = [f"rewrite '{b}' as '{_as_eur(b)}'" for b in bad]
    return "amounts: " + ("; ".join(fixes) if fixes else "ok")
 
 
checkers = [Agent(llm, tools=[FunctionTool(f)], name=f.__name__.replace("check_", ""),
                  instructions="You are a checker. Run your check on the text and "
                               "report it.")
            for f in (check_tone, check_promises, check_amounts)]
panel = ParallelWorkflow(checkers, name="panel")
 
loop = asyncio.get_running_loop()
t0 = loop.time()
verdicts = await panel.run(result.output)
elapsed = loop.time() - t0
print(verdicts.output)
print("\ntimeline:", ", ".join(timeline))
print("took about as long as the slowest check, not the sum:", 0.30 <= elapsed < 0.55)
[tone]
tone: ok

[promises]
promises: ok

[amounts]
amounts: ok

timeline: start tone, start promises, start amounts, end promises, end amounts, end tone
took about as long as the slowest check, not the sum: True

All three started before any finished, and they finished in order of their delays, not in the order they were listed. The merged output, on the other hand, is in the listed order: ParallelWorkflow gives each branch its own copy of the context (sharing one would mix their events and race on the step counter) and merges the copies afterwards in a fixed order, so the transcript does not depend on timing. The draft from section 2 passed all three checks; the next section starts from a worse one.

4. Loop: write, review, revise

LoopWorkflow runs its agents in turn, again and again, until a stop condition holds or an iteration limit is reached. A drafter writes, a reviewer checks the draft with a deterministic review_reply tool (the three checks above, in one function) and either approves or lists the issues, and the drafter revises. This is the evaluator-optimizer pattern from the CS329Z lecture on workflows. The offline drafter’s first draft is rough on purpose, so that the loop has something to do.

from agentlab.multi import LoopWorkflow
 
 
async def review_reply(text: str) -> str:
    """Review a draft reply: tone, promises and amounts. Returns the issues found.
 
    Args:
        text: The complete draft.
    """
    found = [await check(text) for check in (check_tone, check_promises, check_amounts)]
    issues = [f.split(": ", 1)[1] for f in found if not f.endswith(": ok")]
    issues = [part for issue in issues for part in issue.split("; ")]
    labels = {"remove": "promise: ", "rewrite": "amount: "}
    lines = [labels.get(i.split()[0], "") + i for i in issues]
    return "no issues" if not lines else "\n".join(f"- {line}" for line in lines)
 
 
drafter = Agent(llm, name="drafter",
                instructions="You are the drafter. Draft the reply to the ticket. When "
                             "the reviewer lists issues, rewrite your last draft to fix "
                             "all of them.")
reviewer = Agent(llm, tools=[FunctionTool(review_reply)], name="reviewer",
                 instructions="You are the reviewer. Run review_reply on the latest draft. "
                              "Reply APPROVED if it has no issues, otherwise list them.")
notes = next(c.content for c in result.context.contents()
             if isinstance(c, Message) and c.content.startswith("Notes for the writer"))
editing = LoopWorkflow([drafter, reviewer], max_iterations=4, name="editing",
                       stop_condition=lambda r, i: str(r.output).startswith("APPROVED"))
edited = await editing.run(f"Ticket: {TICKET}\n\n{notes}")
 
for event in edited.context.events[1:]:
    for item in event.content:
        if hasattr(item, "role"):
            print(f"[{event.author}]\n{item.content}\n")
print("iterations:", edited.context.state["iterations"])
[drafter]
Dear customer, sorry about the double charge on invoice INV-882. We guarantee your 49 euros will be back tomorrow.

[reviewer]
Issues:
- greeting: start with 'Hi <first name>,'
- sign-off: end with 'The Support Team'
- promise: remove ['guarantee', 'tomorrow']
- amount: rewrite '49 euros' as 'EUR 49.00'

[drafter]
Hi Ana, sorry about the double charge on invoice INV-882. We are refunding EUR 49.00 in full; refunds reach your card within 5 working days.

The Support Team

[reviewer]
APPROVED

iterations: 2

Two rounds: four issues, four fixes, approval. The stop condition is ordinary Python, and max_iterations is the guard every loop needs: a reviewer that is never satisfied (or a drafter that never fixes what it is told) would otherwise run until the budget is gone. With a real model, a fixed checker like review_reply is worth having next to any model judge, because it cannot be talked into approving.

5. Agent as tool: a manager with isolated workers

Now let a model decide. AgentTool wraps an agent as a tool with one argument, request. When the manager calls it, the wrapped agent runs from an empty context containing only that request, and the manager gets back only its final answer.

from agentlab.multi import AgentTool
 
manager = Agent(llm, tools=[AgentTool(researcher), AgentTool(writer)], name="manager",
                instructions="You are the support manager. Use the researcher to gather "
                             "facts and the writer to draft the reply, then return the "
                             "reply.")
start = len(llm.calls)
managed = await manager.run(TICKET)
show_trajectory(managed, width=84)
[user] Hi, this is Ana (customer C-17). I was charged twice for October. Can I get my mo...
[manager -> researcher] {"request": "Find the customer's account and the relevant help article for this t...
    [researcher ok] Notes for the writer: - customer: Ana Lima (C-17), plan Team - duplicate: INV-882...
[manager -> writer] {"request": "Write the reply to this ticket: Hi, this is Ana (customer C-17). I w...
    [writer ok] Hi Ana, you were charged twice for 2026-10: invoice INV-882 repeats INV-881. We a...
[manager] Hi Ana, you were charged twice for 2026-10: invoice INV-882 repeats INV-881. We a...
--- status: complete, steps: 3

The manager made three model calls of its own and the two workers ran inside its tool calls. The workers never saw each other’s work directly: the manager copied the notes into the writer’s request. Isolation is the point (each worker reads only what it needs) and also the risk (each worker knows only what it was told). Measure it: for both runs, add up the input tokens of every model call, grouped by the agent that made it.

from agentlab.tracing import usage_of
 
ROLE = {"You are the researcher": "researcher", "You are the writer": "writer",
        "You are the support manager": "manager"}
 
 
def tokens_by_agent(calls) -> dict[str, int]:
    out: dict[str, int] = {}
    for request, response in calls:
        system = " ".join(request.instructions)
        name = next((v for k, v in ROLE.items() if k in system), "other")
        out[name] = out.get(name, 0) + usage_of(request, response)[0]
    return out
 
 
shared = tokens_by_agent(pipeline_calls)
isolated = tokens_by_agent(llm.calls[start:])
for name in ("researcher", "writer", "manager"):
    print(f"{name:<11} shared context {shared.get(name, 0):>5}   "
          f"agent as tool {isolated.get(name, 0):>5}")
researcher  shared context   667   agent as tool   707
writer      shared context   395   agent as tool   146
manager     shared context     0   agent as tool  1215
import matplotlib.pyplot as plt
 
agents = ["researcher", "writer", "manager"]
colours = {"researcher": "#2c5f9e", "writer": "#2c7d54", "manager": "#81796f"}
fig, ax = plt.subplots(figsize=(6.4, 3.2))
for row, (label, data) in enumerate([("agent as tool", isolated),
                                     ("shared pipeline", shared)]):
    left = 0
    for name in agents:
        width = data.get(name, 0)
        if width:
            ax.barh(row, width, left=left, color=colours[name], height=0.5,
                    label=name if row == 0 else None)
            if width > 250:  # label inside the segment, or above it when it is narrow
                ax.text(left + width / 2, row, f"{name}\n{width}", ha="center",
                        va="center", color="white", fontsize=8)
            else:
                ax.text(left + width / 2, row + 0.3, f"{name} {width}", ha="center",
                        va="bottom", color=colours[name], fontsize=8)
        left += width
ax.set_yticks([0, 1], ["agent as tool", "shared pipeline"])
ax.set_xlabel("input tokens (estimated)")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
plt.show()
Input tokens read per agent for the same ticket (estimated). In the shared pipeline the writer reads everything the researcher did; as a tool it reads only its request, but the manager adds calls of its own.

Input tokens read per agent for the same ticket (estimated). In the shared pipeline the writer reads everything the researcher did; as a tool it reads only its request, but the manager adds calls of its own.

For one short ticket the difference is small, and the manager’s own calls make the isolated version more expensive in total. The balance shifts when the research is long (many searches, large results): in a shared context every later agent pays to re-read all of it, while the writer behind a tool reads a few lines of notes. That is the focused context benefit, and the manager’s extra calls are the coordination overhead cost.

6. Handoffs: the conversation moves

A transfer gives the current agent a transfer_to_agent tool whose argument is an enum of agent names. When the model calls it, HandoffAgent stops that agent and continues the run with the target on the same context. The specialist sees the whole conversation, and the next user turn goes straight to it.

from agentlab.multi import HandoffAgent
 
billing = HandoffAgent(llm, tools=[account_tool, refund_tool, kb_tool], name="billing",
                       description="Billing: invoices, wrong or double charges (charged "
                                   "twice), refunds and money back, plan changes.",
                       instructions="You are the billing specialist. Fix billing problems "
                                    "with your tools and tell the customer what you did.")
tech = HandoffAgent(llm, tools=[kb_tool], name="tech",
                    description="Technical: log-in problems, two-factor authentication, "
                                "exports and outages.",
                    instructions="You are the technical specialist. Answer from the help "
                                 "centre articles.")
triage = HandoffAgent(llm, name="triage", handoffs=[billing, tech],
                      instructions="You are the triage desk. Do not solve problems "
                                   "yourself; transfer the customer to the right "
                                   "specialist.")
print(triage.tools[0].description)
print("enum:", triage.tools[0].tool_definition["function"]["parameters"]["properties"]
      ["agent_name"]["enum"])
Hand the conversation to another agent when the request belongs to its specialty. That agent sees the whole conversation and answers the user from then on.
Agents:
  - billing: Billing: invoices, wrong or double charges (charged twice), refunds and money back, plan changes.
  - tech: Technical: log-in problems, two-factor authentication, exports and outages.
enum: ['billing', 'tech']
first = await triage.run(TICKET)
show_trajectory(first, width=84)
print("\n" + first.output)
print("active agent:", first.context.state["active_agent"], "| refunds:", REFUNDS)
[user] Hi, this is Ana (customer C-17). I was charged twice for October. Can I get my mo...
[triage -> transfer_to_agent] {"agent_name": "billing"}
    [transfer_to_agent ok] Transferring to billing.
[billing -> get_account] {"customer_id": "C-17"}
    [get_account ok] {"name": "Ana Lima", "plan": "Team", "invoices": [{"id": "INV-881", "period": "20...
[billing -> refund_invoice] {"invoice_id": "INV-882"}
    [refund_invoice ok] Refund R-1 created for INV-882 (EUR 49.00).
[billing] Hi Ana, you were charged twice for 2026-10. Refund R-1 created for INV-882 (EUR 4...
--- status: complete, steps: 3

Hi Ana, you were charged twice for 2026-10. Refund R-1 created for INV-882 (EUR 49.00).
active agent: billing | refunds: ['INV-882']

The triage desk spent one model call on routing and was then out of the loop. Billing read the customer id from the original message, which it could only do because the context was shared. Now the customer writes again, on the same context:

follow = await triage.run("Thanks! When will I see the money?", context=first.context)
print(follow.output)
print("handoff log:", follow.context.state["handoff_log"])
Refunds reach the card within 5 working days. (help article KB-101)
handoff log: [['triage', 'billing'], ['billing']]

The follow-up went to billing directly (["billing"], with no triage step), and billing answered “when?” without asking which refund: it can see its own earlier turn. A different ticket takes a different route:

other = await triage.run("I changed phones and now I cannot log in to my account.")
print(other.output)
print("handoff log:", other.context.state["handoff_log"])
From help article KB-102: A customer who changed phones and can no longer log in can reset two-factor authentication from the login page with a backup code, or ask support to verify their identity and reset it.
handoff log: [['triage', 'tech']]

Handoffs suit conversations whose topic decides who should handle them. The price is that every agent on the route reads the whole history (the shared-context cost from section 5), and that control is spread across prompts, which makes the system harder to reason about than a workflow.

7. Two ways it goes wrong

Cemri et al. (2025) studied failed runs of several open-source multi-agent frameworks and sorted the failures into three groups: problems in the system’s design or the agents’ specifications, misalignment between agents (lost information, ignored input, agents working against each other), and weak verification of the result. Two of them are easy to stage here with ScriptedLLM, a model that replays a fixed script.

Information lost at a boundary. The manager below calls the researcher without passing the ticket on. The researcher, starting from an empty context, has nothing to look up.

from agentlab.llm.scripted import ScriptedLLM, ToolCallSpec
 
careless = nb.track(ScriptedLLM([
    ToolCallSpec("researcher", {"request": "Look up the account for this ticket."}),
    "I could not find the account.",
]))
research_tool = AgentTool(researcher)
hasty = Agent(careless, tools=[research_tool, AgentTool(writer)], name="manager")
await hasty.run(TICKET)
given = research_tool.runs[-1].context.contents()[0].content
print("what the researcher was given:", given)
print(research_tool.runs[-1].output)
what the researcher was given: Look up the account for this ticket.
Notes for the writer:
- no customer id in the request, so no account was looked up
- no help article matched

Nothing crashed and every agent did its job on what it received. With agents as tools, the request is the interface: write tool descriptions that ask for every detail (“the ticket text, including the customer id”), or pass structured input with an input_schema.

Two agents that keep handing over. Each believes the other should answer. Without a limit this would run until the budget ran out; max_handoffs stops it and returns a status the caller can act on.

to_tech = ScriptedLLM([ToolCallSpec("transfer_to_agent", {"agent_name": "tech_desk"})],
                      repeat_last=True)
to_billing = ScriptedLLM(
    [ToolCallSpec("transfer_to_agent", {"agent_name": "billing_desk"})], repeat_last=True)
billing_desk = HandoffAgent(nb.track(to_tech), name="billing_desk", max_handoffs=4)
tech_desk = HandoffAgent(nb.track(to_billing), name="tech_desk", handoffs=[billing_desk])
billing_desk.set_handoffs([tech_desk])
stuck = await billing_desk.run("My export failed and I was charged for it.")
print("status:", stuck.status)
print(stuck.output)
status: max_handoffs
Stopped: handoff 5 would pass the limit of 4. Route: billing_desk -> tech_desk -> billing_desk -> tech_desk -> billing_desk -> tech_desk

A step budget per agent does not catch this, because each agent stops after one step. The limit has to count handoffs across the whole run, which is why it lives in the run loop that follows the transfers.

Try this

  • Give research_tool an input_schema (a Pydantic model with ticket and customer_id fields) and re-run the careless manager. What changes in the tool’s schema, and why does that help a real model?
  • Add a fourth checker to the panel that waits 0.5 s. How long does the panel take now?
  • Make review_reply also require the invoice id in the reply and re-run the loop. How many iterations does the offline drafter need, and what does max_iterations do?
  • Send the billing ticket to triage with MODEL set and look at the handoff log. Does the real model transfer, answer itself, or ask a question first?
nb.usage()
model callsinput tokensoutput tokenscost
39 (fake: 32, scripted: 7)≈ 11,522≈ 1,119≈ USD 0.0160 (reference price)