▚ The AI Engineer's Field Manual
Module 09b · Act III — The GenAI Core

Multi-Agent Systems — When Many Agents Beat One, and How to Prove It

"A team of agents is a bill you pay on every ticket. Hire it only if it earns more than it costs, and bring the measurement that proves it."

~7 hours Builds on: Module 09 · Module 07 Tools: LangGraph 1.x · Anthropic SDK · Langfuse · CrewAI · Microsoft Agent Framework Job-spec line it unlocks: "design multi-agent systems and justify them with cost and performance data"

01 · The hookA Team of Agents, Because a Blog Post Said So

A multi-agent system is several model-driven programs that pass work to each other. Every hand-off costs money, time and a chance to lose information, so you should add agents only when you can measure that they pay for themselves.

Field report · Client memo

"Priya's refund agent from last quarter works. It is bounded, it is traced, and it handles the easy tickets. Now our CEO has read a blog post that says the future is 'a team of specialist agents, like a real department', and she wants one for refund disputes.

A dispute is harder than a refund. Someone gathers the order data, checks our policy, checks the fraud signals, and drafts a decision. We see about 1,400 a month. When the system gets one wrong, a person spends 25 minutes cleaning it up.

I am not going to say no to the CEO on a feeling, and I am not going to say yes on a blog post. Priya, build it both ways: the plain fixed-order version and the team-of-agents version. Bring me success rate, dollars and seconds per ticket on Thursday. Then procurement will ask whether we build this on a framework or buy a platform, so be ready for that too."

— Maya Okafor, VP Customer Operations at "ClearOps"

Maya is giving Priya Raman, the engineer who built the bounded agent in Module 09, a fair test. Two builds of one task, three numbers, one meeting. Look at the whole assignment before any code.

1 THE TASK: ONE REFUND DISPUTE 1 gather order data 2 check refund policy 3 check fraud signals 4 draft the decision 1,400 tickets a month a failed ticket costs a person 25 minutes to fix 2 TWO BUILDS, SAME TASK A · workflow: fixed order order policy fraud draft 4 model calls, same path every time B · team: a boss picks who speaks supervisor order policy fraud draft a model call for every choice of who speaks next 3 WHAT PRIYA BRINGS THURSDAY % of tickets decided right A: ? | B: ? dollars per ticket A: ? | B: ? seconds per ticket A: ? | B: ? and the question under all three: who pays when it breaks? (leadership already chose B; the numbers have to disagree)
Fig. 9b.0 — The seed of this module: one four-step task, two ways to build it, and the three numbers Priya must bring to Maya's Thursday meeting.
  1. The task. A refund dispute is four steps in a fixed order: read the order, check the refund policy, check the fraud score, write the decision. ClearOps sees about 1,400 a month. If the system is wrong, a person spends 25 minutes fixing the ticket, and that 25 minutes is what makes a wrong answer expensive.
  2. Two builds. Build A is a workflow: your code runs the four steps in the same order every time, four model calls in all. Build B is a team: a supervisor, which is itself a model call, decides who speaks next, so every choice costs one extra call and the path can change per ticket.
  3. The three numbers. Percent of tickets decided right, dollars per ticket and seconds per ticket, each for A and for B. The question under all three is who pays when a build breaks. This page fills every question mark with a measured number.

Notice what Maya did not ask for. She did not ask whether multi-agent systems are good. She asked whether this one beats the boring version on her tickets. That framing is the whole skill. A team of agents is an architecture choice, and architecture choices are defended with measurements.

The market agrees. Employers who list agent frameworks increasingly add a second line: "evaluate and justify". A candidate who can show a workflow and a team side by side, with a cost table, stands apart from the many who can only draw the team.

You already know this

You have chosen between a monolith and microservices. The microservice version is not better. It is a trade: more independent parts, in return for more network calls, more places to lose a message, and harder debugging. A multi-agent system is the same trade with a model at every node. The workflow is your monolith: boring, fast, easy to trace.

Distributed-systems instincts that carry straight over
You know it as…In a multi-agent system it is…
Network hop between servicesA hand-off between agents: one more model call and one more summary
Message queue vs shared databaseMessage passing vs shared state (section 04)
Retry storm / cascading failureA supervisor sending a worker back again and again
Distributed tracing, spansOne trace per ticket, one span per model call (section 06)
"Which service broke it?"Blame assignment: which agent made the wrong call
Build vs buy for a platformFramework vs vendor platform (section 08)

Quick reference — The assignment

Multi-agent system
Several model-driven programs that pass work to each other, often under a supervisor.
Workflow
Your code fixes the order of the steps. A model does the thinking inside a step but never picks the next step.
Agent team
A model picks the next step. More flexible, and each pick is another paid call.
The test
Same task, same cases, three numbers: percent right, dollars per ticket, seconds per ticket.
Honest default
Start with the workflow. Add agents only where a measurement shows the workflow failing.

02 · The intuitionFive Ways to Wire a Team, and What Each One Costs

Maya's memo says "a team of agents" as if it were one design. It is at least five. Before Priya builds anything she needs the menu, because each wiring charges a different number of model calls per ticket, and calls are what the Thursday meeting will count.

A multi-agent pattern is a wiring diagram that says who may talk to whom, and who decides who talks next. Pick the wrong wiring and you pay for conversations nobody needed.

Module 09 already built one pattern, orchestrator–workers, with LangGraph's Send. This section goes wider: the five shapes you will hear named in design reviews, one picture each, and the cost each one adds. The reader's question for every shape is the same: who decides who speaks next?

Shapes where a model is in charge of the order

The first three shapes put a model in the manager's seat. They differ in how often the manager decides, and how many managers there are. Fig. 9b.1 draws all three with the call count each one implies.

1 ORCHESTRATOR-WORKERS orchestrator worker worker worker synthesizer 1 plan + k workers + 1 merge; workers start with fresh context earns it: tasks that split differently every time 2 SUPERVISOR / HIERARCHY supervisor team lead A team lead B worker worker worker worker a boss call before every step; two levels = two boss calls earns it: so many tools that one boss cannot hold them all 3 HANDOFFS (SWARM) triage agent billing agent fraud agent the baton no boss: whoever holds the baton chooses who gets it next earns it: support chats that change topic halfway through
Fig. 9b.1 — Three shapes with a manager or a baton. Orchestrator–workers plans once, a supervisor decides after every result, and a swarm has no manager at all.
  1. Orchestrator–workers. One model call splits the job into k subtasks up front. k workers run, each starting with an empty context, and a final call merges the answers. Total: 1 + k + 1 calls. The plan is made once, so the order cannot adapt to what the workers find.
  2. Supervisor, and the hierarchy above it. The boss is called before every step and reads what has happened so far. It can send a worker back, skip a step or stop. A hierarchy adds team leads, so a boss call happens at every level. This is the shape we build in section 04.
  3. Handoffs (a swarm). No boss exists. The agent holding the baton finishes its part and names the next agent. Only one agent runs at a time. It suits a conversation that wanders, such as a support chat that starts as billing and turns into suspected fraud.

Shapes where your code or a referee decides

The other two shapes remove the model from the manager's seat. They matter because they show how much of a "team" is really just a workflow with a better name.

1 DEBATE / CRITIC writer critic draft objections judge every round = 2 more model calls; stop at 2 rounds or a judge's approval earns it: output you can check and a wrong answer is expensive (legal copy) 2 PIPELINE extract 1 call translate 1 call check 1 call publish 1 call 4 calls, always, in this order fixed order, one specialist per stage; this is the workflow version, drawn earns it: the steps never change, so start here before anything else
Fig. 9b.2 — Two shapes without a free-roaming boss. A critic loop repeats until a judge or a round limit stops it, and a pipeline is a fixed line.
  1. Debate or critic. A writer produces a draft, a critic lists objections, and the writer revises. Each round adds two calls. A judge, or a hard limit of two rounds, ends it. It earns its cost when a human can verify the output and a wrong answer is expensive, such as contract text.
  2. Pipeline. Four stages, one specialist each, in an order your code fixes. Four calls, always. Look closely: this is the workflow version of the refund task, drawn as a team. Most systems sold as multi-agent are this shape.
Decision table: which wiring, and when it earns its extra calls (k = number of workers)
PatternWho picks the next stepCalls addedChoose it whenAvoid it when
PipelineYour codeNone beyond the stagesSteps never changeSteps depend on what earlier steps find
Orchestrator–workersOne model, once, up front2 (plan and merge)The task splits differently each time and the parts are independentParts depend on each other, or the split is always the same
SupervisorA model, every turnk + 1 boss calls at minimumThe path depends on results and you cannot list the casesYou can list the cases: use if-statements
HierarchyModels at two levelsA boss call per level per stepDozens of tools, so one boss cannot hold them allUnder about ten tools
Handoffs / swarmThe current agentNone extra, but one agent at a timeA conversation that changes topicA batch job with a fixed shape
Critic loopA judge or a round cap2 per roundOutput is checkable and errors are costlyLow-stakes text, tight latency

That table has one honest message. Four of the six rows say "when you cannot write the order down". If you can write the order down, you do not need a team, you need a workflow.

Sharpen your pencil

Count the model calls for one ticket, using the rules in Fig. 9b.1 and Fig. 9b.2. Assume every worker runs exactly once and nothing goes wrong. Two rows are done for you.

Pipeline of 4 stages4 calls: one per stage
Orchestrator–workers with k = 3 workers5 calls: 1 plan + 3 workers + 1 merge
Supervisor with 3 workers, each run once, then "done"
Our refund team: supervisor with 4 workers, each run once
Hierarchy: top boss, 2 team leads, 2 workers per lead (each boss speaks once per child, plus one "done")
Critic loop: draft, then 2 rounds of critique and revise
Handoffs: triage, then billing, then fraud
Check your answers
Supervisor with 3 workers7 calls: the boss speaks 4 times (three dispatches and one "done") plus 3 workers.
Our refund team, 4 workers9 calls: 5 boss turns plus 4 workers. The measured average later in this page is 9.9, because some tickets loop.
Hierarchy13 calls: the top boss speaks 3 times (two leads and "done"). Each lead speaks 3 times and runs 2 workers, which is 5 calls, so 10 for both. 3 + 10 = 13.
Critic loop5 calls: 1 draft, then critique and revise twice (4 more).
Handoffs3 calls: each agent's call includes naming its successor, so there is no extra boss call.

If you got the supervisor rows right, you already see why a boss is the expensive part: it is called once more than there are workers. Measuring that cost is the point of section 04.

"Isn't a team of agents just functions calling functions? Why does this get its own page?"

— a nine-year engineer, right about now

Structurally, yes, and that is a useful way to hold it. The difference is that every call is paid per token, takes seconds rather than microseconds, and can return something slightly wrong. The "which function next" decision, in a supervisor design, is also one of those paid and fallible calls.

The honest downside: you lose what your compiler and your tests normally give you. A mis-routed call is not a stack trace. It is a plausible-looking wrong answer, which is why the rest of this page is about measuring.

Fix the order if you can write it down.

Let a model pick only what you cannot predict.

Every hop is a bill, so count the hops.

Line one is the pipeline in Fig. 9b.2. Line two is the supervisor in Fig. 9b.1, used only where the path really varies. Line three is the call count in the pencil table above.

Quick reference — Multi-agent patterns

Pipeline
Fixed stages, one call each. The workflow in disguise. Default choice.
Orchestrator–workers
1 plan + k workers + 1 merge. Splits are decided once, up front.
Supervisor
A boss call before every step; minimum k + 1 boss calls. Adapts to results.
Hierarchy
Bosses of bosses. Only for tool counts one boss cannot hold.
Handoffs / swarm
The current agent names the next. No boss call, one agent at a time.
Critic loop
Two calls per round. Cap the rounds.
The why that is easy to forget
You are choosing who decides the order. Anything your code can decide should not be paid for.

03 · Build it yourselfBuild the Workflow First: Four Fixed Steps

Priya now has the menu from section 02. She has two weeks and a rule of her own: build the boring version first. If the plain workflow is good enough, the team has nothing to prove. If it is not good enough, its failures tell her exactly what the team must fix.

A workflow is the refund dispute written as four fixed steps, in an order your code decides. It is the baseline every team of agents has to beat.

A world to test in: 200 invented tickets and a pretend model

Priya cannot run 200 tickets on the real model a hundred times while she tunes things, and she cannot use real customer disputes in a course. She needs a small fake world: invented tickets with known right answers, and a model stand-in that behaves like a model.

Everything below is simulated, and the page will say so every time. The fake model reads its prompt, answers in a fixed one-line format, slips now and then, and reports token counts and seconds from seeded dice. Same seed, same numbers, every run, with no API key and no bill.

The numbers are therefore not claims about Claude. They are claims about this method: how you count, compare and defend two architectures. The same graphs run on the real API too, as shown in section 07.

The code below uses a dataclass, a seeded random generator and a regular expression. You are not expected to know the exact calls yet. Guess first, then open the answers. Each chunk is explained line by line in the step-by-step list above it.

Sharpen your pencil

Below are ten lines from fake_world.py (the case generator). Three are annotated. Write what you think each other line does before you open the answers.

rng = random.Random(seed)Makes a private dice-roller. The same seed gives the same 200 cases every run.
days = rng.randint(1, 45)
risky = rng.random() < 0.12
fraud = round(rng.uniform(0.60, 0.95), 2) if risky else round(rng.uniform(0.0, 0.40), 2)Risky tickets get a high fraud score, the rest a low one. The two ranges never overlap.
truth = "deny" if days > 30 else "escalate" if fraud >= 0.6 else "approve"
cases.append(Case(i, round(rng.uniform(15, 400), 2), days, fraud, rng.random() < 0.20, truth))
odd: boolA flag on the case: true means a split shipment, where the first order lookup returns half the record.
@dataclass class Case
PRICE_IN, PRICE_OUT = 3.00 / 1_000_000, 15.00 / 1_000_000
return cases
Check your answers
days = rng.randint(1, 45)Picks the days since delivery, a whole number from 1 to 45. The refund window is 30 days, so about a third of tickets are late.
risky = rng.random() < 0.12Rolls a number between 0 and 1 and calls the ticket risky about 12 percent of the time.
truth = "deny" if days > 30 else ...The known right answer. Late means deny. On time but risky means escalate to a person. Otherwise approve. Policy is checked first.
cases.append(Case(...))Builds one ticket: id, an amount between $15 and $400, the days, the fraud score, a 20 percent chance of being a split shipment, and the answer. Then adds it to the list.
@dataclass class CaseA plain record type. @dataclass writes the constructor and the printing for us.
PRICE_IN, PRICE_OUT = ...Dollars per token: $3 per million tokens in, $15 per million out. A "Sonnet-class" price, used for every build so the comparison is fair.
return casesHands back the finished list of 200 tickets.

A "20 percent chance" does not mean exactly 20 percent. With this seed it came out at 56 of 200, which is 28 percent. That is why we always print the counts.

Build it in chunks

We build fake_world.py in three chunks: the tickets, the two tools that read them, and the pretend model. Each chunk runs on its own.

  1. Chunk 1 — make 200 tickets whose right answer we know

    Everything we measure later needs a known right answer to compare against, so the tickets come first.

    Step-by-step: what chunk 1 does, in plain English
    1. Import random and dataclass. Standard library only, so nothing to install.
    2. Set the two token prices. They are used from chunk 3 on.
    3. Define Case, one ticket: its id, amount, days since delivery, fraud score, whether it is a split shipment, and the right answer.
    4. make_cases creates a private dice-roller from a seed. Same seed, same tickets.
    5. For each ticket, roll the days and decide whether it looks risky, then roll a fraud score from the matching range.
    6. Work out the right answer: late means deny, risky means escalate, otherwise approve.
    7. Build the Case, add it to the list, and return the list.
    8. The demo at the bottom prints the first three tickets and counts each right answer.
    fake_world.py — chunk 1runs offline (simulated)
    # fake_world.py: a SIMULATED company and a SIMULATED model, so the whole chapter runs offline.
    # Install: nothing (standard library only).
    # ── chunk 1: 200 invented refund disputes with a known right answer ──
    import random
    from dataclasses import dataclass
    
    PRICE_IN, PRICE_OUT = 3.00 / 1_000_000, 15.00 / 1_000_000   # dollars per token, a "Sonnet-class" price
    
    
    @dataclass
    class Case:
        id: int
        amount: float
        days: int        # days since delivery
        fraud: float     # fraud score, 0 to 1
        odd: bool        # a split shipment: the first lookup returns only half the record
        truth: str       # the decision a careful human would reach
    
    
    def make_cases(n=200, seed=7):
        rng = random.Random(seed)            # same seed, same 200 cases, every run
        cases = []
        for i in range(n):
            days = rng.randint(1, 45)
            risky = rng.random() < 0.12      # about 1 case in 8 looks fraudulent
            fraud = round(rng.uniform(0.60, 0.95), 2) if risky else round(rng.uniform(0.0, 0.40), 2)
            truth = "deny" if days > 30 else "escalate" if fraud >= 0.6 else "approve"
            cases.append(Case(i, round(rng.uniform(15, 400), 2), days, fraud, rng.random() < 0.20, truth))
        return cases
    
    
    if __name__ == "__main__":
        cases = make_cases()
        print(len(cases), "cases; first three:")
        for c in cases[:3]:
            print(" ", c)
        for label in ("approve", "deny", "escalate"):
            print(f"  truth={label}: {sum(c.truth == label for c in cases)}")
        print("  odd (split shipment):", sum(c.odd for c in cases))

    @dataclass for a record type; random.Random(seed) for a private, repeatable dice-roller.

    Run python fake_world.py and you should see:

    output
    200 cases; first three:
      Case(id=0, amount=33.59, days=21, fraud=0.16, odd=False, truth='approve')
      Case(id=1, amount=210.36, days=7, fraud=0.02, odd=True, truth='approve')
      Case(id=2, amount=227.15, days=28, fraud=0.1, odd=True, truth='approve')
      truth=approve: 117
      truth=deny: 62
      truth=escalate: 21
      odd (split shipment): 56
  2. Chunk 2 — two tools that read a ticket, one of which sometimes returns half the record

    Real systems return incomplete data. Split shipments are our stand-in: the first order lookup knows the amount but not the delivery date. This single quirk is what will separate the two builds later.

    Step-by-step: what chunk 2 does, in plain English
    1. lookup_order is the order system. For a normal ticket it returns amount and days since delivery.
    2. For a split-shipment ticket the first call returns only the amount, with a note that the date is on shipment 2.
    3. Asking again with secondary=True returns the full record. Remember this switch.
    4. fraud_signals returns the fraud score as text.
    5. Neither tool involves a model. They are plain deterministic functions.
    6. The demo prints a normal lookup, a half lookup, the full lookup and a fraud reading.
    fake_world.py — chunk 2 (adds to chunk 1)runs offline (simulated)
    # ── chunk 2: the two "tools" (plain deterministic functions, no model involved) ──
    def lookup_order(case, secondary=False):
        """The order system. A split shipment answers with half the record unless you ask for shipment 2."""
        if case.odd and not secondary:
            return f"order #{case.id} amount={case.amount} (shipment 1 of 2; delivery date is on shipment 2)"
        return f"order #{case.id} amount={case.amount} days_since_delivery={case.days} complete"
    
    
    def fraud_signals(case):
        return f"fraud_score={case.fraud}"
    
    
    if __name__ == "__main__":
        plain = next(c for c in make_cases() if not c.odd)
        split = next(c for c in make_cases() if c.odd)
        print(lookup_order(plain))
        print(lookup_order(split))
        print(lookup_order(split, secondary=True))
        print(fraud_signals(plain))

    A keyword argument with a default (secondary=False) as the "ask again, but harder" switch. The new demo block replaces the old one.

    Run it. Case 0 is normal. Case 1 is a split shipment, and the second lookup fills in the date:

    output
    order #0 amount=33.59 days_since_delivery=21 complete
    order #1 amount=210.36 (shipment 1 of 2; delivery date is on shipment 2)
    order #1 amount=210.36 days_since_delivery=7 complete
    fraud_score=0.16
  3. Chunk 3 — the pretend model: it reads its prompt, answers in one line, and sometimes slips

    This is the largest chunk, but it has one idea: a model-shaped function that answers from what is in its prompt, charges tokens for what it reads, and sometimes gets it wrong. If a fact is missing from the prompt, it guesses. That is what makes lost context hurt.

    Step-by-step: what chunk 3 does, in plain English
    1. Three tables per role: the fixed system-prompt size in tokens, the typical answer length in tokens, and the chance of a slip.
    2. Reply is what a call returns: text, tokens in, tokens out, seconds, and whether it slipped.
    3. last finds the last match of a pattern in some text. Later facts override earlier ones.
    4. FakeLLM.ask seeds the dice from the seed, the ticket, the role and the call number. That makes every call repeatable.
    5. It rolls once for "did it slip", builds the answer, and counts tokens in as the system prompt plus a quarter of the prompt's characters.
    6. Tokens out are a bell-curve roll around the role's typical length. Seconds are 0.4 plus output time plus a small input cost, with a 2 percent chance of an 8-second slow call.
    7. _answer handles four roles by reading the prompt: order summarises the record, policy checks the 30-day window, fraud checks the 0.60 line, draft combines policy and fraud. A slip flips or scrambles the answer.
    8. If the date is missing, policy guesses: "ok" 70 percent of the time.
    9. _route is the supervisor role, used from section 04. It reads a transcript and names the next worker, or "done".
    10. price turns token counts into dollars.
    fake_world.py — chunk 3 (adds to chunks 1 and 2)runs offline (simulated)
    # ── chunk 3: the fake model. It reads its PROMPT, answers, and sometimes slips ──
    import re
    
    SYSTEM_TOKENS = {"order": 300, "policy": 450, "fraud": 350, "draft": 500, "supervisor": 600}
    OUT_TOKENS = {"order": 60, "policy": 40, "fraud": 30, "draft": 120, "supervisor": 25}
    SLIP = {"order": 0.02, "policy": 0.04, "fraud": 0.04, "draft": 0.05, "supervisor": 0.05}
    
    
    @dataclass
    class Reply:
        text: str
        tokens_in: int
        tokens_out: int
        secs: float
        slipped: bool = False
    
    
    def last(pattern, text):
        found = re.findall(pattern, text)
        return found[-1] if found else None
    
    
    class FakeLLM:
        def __init__(self, seed=7, slip=None):
            self.seed, self.slip, self.count = seed, slip or SLIP, {}
    
        def ask(self, role, case_id, prompt):
            n = self.count[(case_id, role)] = self.count.get((case_id, role), 0) + 1
            r = random.Random(f"{self.seed}|{case_id}|{role}|{n}")   # the dice for THIS call only
            slipped = r.random() < self.slip[role]
            text = self._answer(role, prompt, r, slipped)
            tin = SYSTEM_TOKENS[role] + int(len(prompt) / 4)         # roughly 4 characters per token
            tout = max(5, int(r.gauss(OUT_TOKENS[role], OUT_TOKENS[role] * 0.2)))
            secs = 0.4 + tout / 70 + tin / 6000 + (8.0 if r.random() < 0.02 else 0.0)   # 2% slow calls
            return Reply(text, tin, tout, round(secs, 2), slipped)
    
        def _answer(self, role, p, r, slipped):
            if role == "order":
                amount, days = last(r"amount=([\d.]+)", p), last(r"days_since_delivery=(\d+)", p)
                if days and slipped:
                    days = str(int(days) + 15)                        # misreads the date
                return f"ORDER amount={amount} days={days or '?'} complete={'yes' if days else 'no'}"
            if role == "policy":
                days = last(r"days=(\d+)", p)
                ok = int(days) <= 30 if days else r.random() < 0.7    # no date? it guesses
                return f"POLICY ok={'yes' if ok != slipped else 'no'}"
            if role == "fraud":
                high = float(last(r"fraud_score=([\d.]+)", p)) >= 0.6
                return f"FRAUD high={'yes' if high != slipped else 'no'}"
            if role == "draft":
                ok = last(r"POLICY ok=(\w+)", p) != "no"              # missing? assume fine
                high = last(r"FRAUD high=(\w+)", p) == "yes"
                d = "deny" if not ok else "escalate" if high else "approve"
                if slipped:
                    d = r.choice([x for x in ("approve", "deny", "escalate") if x != d])
                return f"DECISION {d}"
            return self._route(p, r, slipped)
    
        def _route(self, t, r, slipped):
            if slipped:
                return "NEXT " + r.choice(["order", "policy", "fraud", "draft", "done"])
            if "complete=" not in t:
                return "NEXT order"
            if last(r"complete=(\w+)", t) == "no" and "secondary" not in t:
                return "NEXT order secondary"
            rules = ((r"POLICY ok=", "policy"), (r"FRAUD high=", "fraud"),
                     (r"DECISION (approve|deny|escalate)", "draft"))
            for key, node in rules:
                if not re.search(key, t):
                    return "NEXT " + node
            return "NEXT done"
    
    
    def price(tokens_in, tokens_out):
        return tokens_in * PRICE_IN + tokens_out * PRICE_OUT
    
    
    if __name__ == "__main__":
        cases = make_cases()
        llm = FakeLLM()
        c = next(x for x in cases if not x.odd)
        reply = llm.ask("policy", c.id, lookup_order(c).replace("days_since_delivery", "days"))
        print(reply)
        print("cost of that one call: $%.5f" % price(reply.tokens_in, reply.tokens_out))
        again = FakeLLM().ask("policy", c.id, lookup_order(c).replace("days_since_delivery", "days"))
        print("same seed, same reply:", again == reply)

    re.findall to pull a fact out of text; a seeded Random per call so the "model" is repeatable. You will not see the _route method used until section 04.

    Run it. The same call, made twice with the same seed, gives an equal reply:

    output
    Reply(text='POLICY ok=yes', tokens_in=459, tokens_out=50, secs=1.19, slipped=False)
    cost of that one call: $0.00213
    same seed, same reply: True

The whole program

Chunk 1 is the header, Case and make_cases. Chunk 2 is the two tools. Chunk 3 is everything from SYSTEM_TOKENS down to price. The last rung's demo stays at the bottom; the file is also the importable module the other scripts use.

fake_world.pyruns offline (simulated)
# fake_world.py: a SIMULATED company and a SIMULATED model, so the whole chapter runs offline.
# Install: nothing (standard library only).
# ── chunk 1: 200 invented refund disputes with a known right answer ──
import random
from dataclasses import dataclass

PRICE_IN, PRICE_OUT = 3.00 / 1_000_000, 15.00 / 1_000_000   # dollars per token, a "Sonnet-class" price


@dataclass
class Case:
    id: int
    amount: float
    days: int        # days since delivery
    fraud: float     # fraud score, 0 to 1
    odd: bool        # a split shipment: the first lookup returns only half the record
    truth: str       # the decision a careful human would reach


def make_cases(n=200, seed=7):
    rng = random.Random(seed)            # same seed, same 200 cases, every run
    cases = []
    for i in range(n):
        days = rng.randint(1, 45)
        risky = rng.random() < 0.12      # about 1 case in 8 looks fraudulent
        fraud = round(rng.uniform(0.60, 0.95), 2) if risky else round(rng.uniform(0.0, 0.40), 2)
        truth = "deny" if days > 30 else "escalate" if fraud >= 0.6 else "approve"
        cases.append(Case(i, round(rng.uniform(15, 400), 2), days, fraud, rng.random() < 0.20, truth))
    return cases


# ── chunk 2: the two "tools" (plain deterministic functions, no model involved) ──
def lookup_order(case, secondary=False):
    """The order system. A split shipment answers with half the record unless you ask for shipment 2."""
    if case.odd and not secondary:
        return f"order #{case.id} amount={case.amount} (shipment 1 of 2; delivery date is on shipment 2)"
    return f"order #{case.id} amount={case.amount} days_since_delivery={case.days} complete"


def fraud_signals(case):
    return f"fraud_score={case.fraud}"


# ── chunk 3: the fake model. It reads its PROMPT, answers, and sometimes slips ──
import re

SYSTEM_TOKENS = {"order": 300, "policy": 450, "fraud": 350, "draft": 500, "supervisor": 600}
OUT_TOKENS = {"order": 60, "policy": 40, "fraud": 30, "draft": 120, "supervisor": 25}
SLIP = {"order": 0.02, "policy": 0.04, "fraud": 0.04, "draft": 0.05, "supervisor": 0.05}


@dataclass
class Reply:
    text: str
    tokens_in: int
    tokens_out: int
    secs: float
    slipped: bool = False


def last(pattern, text):
    found = re.findall(pattern, text)
    return found[-1] if found else None


class FakeLLM:
    def __init__(self, seed=7, slip=None):
        self.seed, self.slip, self.count = seed, slip or SLIP, {}

    def ask(self, role, case_id, prompt):
        n = self.count[(case_id, role)] = self.count.get((case_id, role), 0) + 1
        r = random.Random(f"{self.seed}|{case_id}|{role}|{n}")   # the dice for THIS call only
        slipped = r.random() < self.slip[role]
        text = self._answer(role, prompt, r, slipped)
        tin = SYSTEM_TOKENS[role] + int(len(prompt) / 4)         # roughly 4 characters per token
        tout = max(5, int(r.gauss(OUT_TOKENS[role], OUT_TOKENS[role] * 0.2)))
        secs = 0.4 + tout / 70 + tin / 6000 + (8.0 if r.random() < 0.02 else 0.0)   # 2% slow calls
        return Reply(text, tin, tout, round(secs, 2), slipped)

    def _answer(self, role, p, r, slipped):
        if role == "order":
            amount, days = last(r"amount=([\d.]+)", p), last(r"days_since_delivery=(\d+)", p)
            if days and slipped:
                days = str(int(days) + 15)                        # misreads the date
            return f"ORDER amount={amount} days={days or '?'} complete={'yes' if days else 'no'}"
        if role == "policy":
            days = last(r"days=(\d+)", p)
            ok = int(days) <= 30 if days else r.random() < 0.7    # no date? it guesses
            return f"POLICY ok={'yes' if ok != slipped else 'no'}"
        if role == "fraud":
            high = float(last(r"fraud_score=([\d.]+)", p)) >= 0.6
            return f"FRAUD high={'yes' if high != slipped else 'no'}"
        if role == "draft":
            ok = last(r"POLICY ok=(\w+)", p) != "no"              # missing? assume fine
            high = last(r"FRAUD high=(\w+)", p) == "yes"
            d = "deny" if not ok else "escalate" if high else "approve"
            if slipped:
                d = r.choice([x for x in ("approve", "deny", "escalate") if x != d])
            return f"DECISION {d}"
        return self._route(p, r, slipped)

    def _route(self, t, r, slipped):
        if slipped:
            return "NEXT " + r.choice(["order", "policy", "fraud", "draft", "done"])
        if "complete=" not in t:
            return "NEXT order"
        if last(r"complete=(\w+)", t) == "no" and "secondary" not in t:
            return "NEXT order secondary"
        rules = ((r"POLICY ok=", "policy"), (r"FRAUD high=", "fraud"),
                 (r"DECISION (approve|deny|escalate)", "draft"))
        for key, node in rules:
            if not re.search(key, t):
                return "NEXT " + node
        return "NEXT done"


def price(tokens_in, tokens_out):
    return tokens_in * PRICE_IN + tokens_out * PRICE_OUT


if __name__ == "__main__":
    cases = make_cases()
    llm = FakeLLM()
    c = next(x for x in cases if not x.odd)
    reply = llm.ask("policy", c.id, lookup_order(c).replace("days_since_delivery", "days"))
    print(reply)
    print("cost of that one call: $%.5f" % price(reply.tokens_in, reply.tokens_out))
    again = FakeLLM().ask("policy", c.id, lookup_order(c).replace("days_since_delivery", "days"))
    print("same seed, same reply:", again == reply)

Read the output of chunk 1 closely. Of 200 tickets, 117 should be approved, 62 denied and 21 escalated. And 56 are split shipments, about 28 percent, a little more than the 20 percent we asked for. Randomness does that. The count matters later, because those 56 tickets decide the whole comparison.

prompt (38 characters): ORDER amount=210.36 days=? complete=no FakeLLM.ask(role='policy') dice seeded by seed, ticket, role and call number Reply(text='POLICY ok=yes', tokens_in=459, tokens_out=34, secs=0.96, slipped=False) tokens in 450 system prompt + 38 chars / 4 = 9 = 459 1 tokens out bell curve around 40 this call: 34 2 seconds 0.4 + 34/70 + 459/6000 = 0.96 s 3 dollars 459 x $3/M = $0.00138 34 x $15/M = $0.00051 = $0.0019 4 no date in the prompt, so the policy step had to guess (one dice roll, 70 percent ok)
Fig. 9b.3 — One simulated model call, drawn with its real numbers: ticket #1, the policy step of the workflow. Every call the chapter counts is built from these four numbers.
  1. Tokens in. The model is billed for every token it reads. 450 are the fixed system prompt for the policy role. The 38-character prompt adds 38 / 4 = 9 more. The total is 459.
  2. Tokens out. The reply length is a bell-curve roll around 40 tokens. This call drew 34. Output tokens cost five times as much as input tokens.
  3. Seconds. 0.4 seconds of fixed delay, plus the output at 70 tokens a second, plus the input at 6,000 a second. About 2 percent of calls add 8 more seconds, which is what builds the slow tail.
  4. Dollars. $3 per million tokens in, $15 per million out. The one-call bill is $0.0019. compare.py adds this up over every call on every ticket. Note the prompt says days=?: this step had no date, so it guessed, and the guess came up "ok" by luck of the dice.

The workflow itself, in five chunks

The world exists. Priya now builds Build A from Fig. 9b.0: order, policy, fraud, draft, in that order, on LangGraph. Fig. 9b.4 shows the shape she is building on the left and the shape she will build next, for the team, on the right.

1 THE WORKFLOW GRAPH START order policy fraud draft END your code fixes the path 4 nodes, 5 edges, no choices 4 model calls: 1,637 tokens in (sample ticket #1, traced in section 06) 2 THE TEAM GRAPH START supervisor order policy fraud draft END done or 10-turn cap 6 supervisor turns + 5 worker runs 11 model calls: 6,187 tokens in the model decides the path
Fig. 9b.4 — The two LangGraph shapes of this chapter. The workflow is a straight line your code fixes. The team is a hub where a model chooses the path.
  1. The workflow graph. Four work nodes between START and END, five edges, and no choices. LangGraph walks the line in order. On sample ticket #1 it makes 4 model calls and the model reads 1,637 tokens in total.
  2. The team graph. One supervisor node, four workers, and two-headed arrows: every worker reports back to the supervisor, who names the next worker or says "done". On the same ticket it makes 11 calls and reads 6,187 tokens, because the supervisor is called six times.

Two design rules shape the workflow. First, each step is given only what it needs: the policy step sees the order line, not the fraud score. Second, steps pass notes forward by appending to a list. This is message passing, and Fig. 9b.6 in the next section contrasts it with the alternative.

One LangGraph idea in chunk 1 deserves its own picture before you meet it in code: the reducer. When a step returns a list, LangGraph needs a rule for combining it with the list already in the state. Fig. 9b.5 shows both rules on the same two steps.

1 WITH operator.add (what we wrote) notes = [ ] order returns [ORDER] notes = [ORDER] policy returns [POLICY] notes = [ORDER, POLICY] new list is ADDED to the old the draft step can see both lines 2 WITHOUT a reducer (the bug) notes = [ ] order returns [ORDER] notes = [ORDER] policy returns [POLICY] notes = [POLICY] new list REPLACES the old ORDER is gone; draft reads one line
Fig. 9b.5 — The same two steps with two different merge rules. One line of configuration decides whether the notes survive.
  1. With a reducer. operator.add tells LangGraph to append. After the order step the notes hold one line, after the policy step two, so the draft step can read both.
  2. Without one. Each returned list replaces the old list. After the policy step only the POLICY line survives. The ORDER line is gone, and nothing raises an error. This is a quiet bug, which is why chunk 1 sets the rule first.

Build it in chunks

We build refund_workflow.py in five chunks: state, the four steps, the graph, a scorer, and the run over 200 tickets. Each chunk runs on its own, and it needs fake_world.py next to it.

  1. Chunk 1 — the state, and one helper that asks the model and logs the call

    Every later number (tokens, dollars, seconds) comes from the log of model calls, so the logging helper comes first.

    Step-by-step: what chunk 1 does, in plain English
    1. Import operator and typing helpers, plus the pieces of fake_world.py we need.
    2. State is a typed dictionary: the ticket, a list of notes, a list of call records, and a decision.
    3. Annotated[list, operator.add] tells LangGraph how to merge: when a step returns a list, append it instead of replacing the old one. This is called a reducer.
    4. ask calls the model with a role and a prompt and returns the text plus a call record: node, tokens in and out, seconds, and whether it slipped.
    5. The demo calls the order role once on ticket 0 and prints both results.
    refund_workflow.py — chunk 1runs offline (simulated)
    # refund_workflow.py: the deterministic workflow version of the refund dispute, on LangGraph.
    # Install: uv pip install "langgraph>=1.0,<2"       (needs fake_world.py next to it)
    # ── chunk 1: the state, and one helper that asks the model and logs the call ──
    import operator
    from typing import Annotated, TypedDict
    
    from fake_world import Case, FakeLLM, make_cases, lookup_order, fraud_signals, price
    
    
    class State(TypedDict):
        case: Case
        notes: Annotated[list, operator.add]   # each step APPENDS its one-line result
        calls: Annotated[list, operator.add]   # one record per model call: the raw material for cost and latency
        decision: str
    
    
    def ask(llm, state, node, role, prompt):
        reply = llm.ask(role, state["case"].id, prompt)
        call = {"node": node, "role": role, "hop": state.get("hops", 0), "tin": reply.tokens_in,
                "tout": reply.tokens_out, "secs": reply.secs, "slipped": reply.slipped}
        return reply.text, call
    
    
    if __name__ == "__main__":
        case = make_cases()[0]
        state = {"case": case, "notes": [], "calls": [], "decision": ""}
        text, call = ask(FakeLLM(), state, "order", "order", lookup_order(case))
        print(text)
        print(call)

    TypedDict for the shape of the state, and Annotated[..., operator.add] as a "merge by appending" rule.

    Run it. The order step turns the raw lookup into one line, and the call record holds its cost data:

    output
    ORDER amount=33.59 days=21 complete=yes
    {'node': 'order', 'role': 'order', 'hop': 0, 'tin': 313, 'tout': 66, 'secs': 1.4, 'slipped': False}
  2. Chunk 2 — the four steps as plain functions

    Before any graph library, each step is just a function from state to a small update. That keeps the LangGraph part small and the logic testable by hand.

    Step-by-step: what chunk 2 does, in plain English
    1. make_nodes takes the model and returns the four steps, so the same code can later take a real model.
    2. order looks the ticket up with the tool and asks the order role to summarise it.
    3. policy sees only the first note, the ORDER line.
    4. fraud reads the fraud tool's text and asks the fraud role for a verdict.
    5. draft sees only the policy and fraud notes (everything after the first) and returns the decision, the last word of its answer.
    6. Each step returns an update dictionary, not the whole state.
    7. The demo calls the four steps by hand in order and prints each result.
    refund_workflow.py — chunk 2 (adds to chunk 1)runs offline (simulated)
    # ── chunk 2: four steps, each one sees ONLY what it needs ──
    def make_nodes(llm):
        def order(s):
            text, call = ask(llm, s, "order", "order", lookup_order(s["case"]))
            return {"notes": [text], "calls": [call]}
    
        def policy(s):
            text, call = ask(llm, s, "policy", "policy", s["notes"][0])        # only the ORDER line
            return {"notes": [text], "calls": [call]}
    
        def fraud(s):
            text, call = ask(llm, s, "fraud", "fraud", fraud_signals(s["case"]))
            return {"notes": [text], "calls": [call]}
    
        def draft(s):
            text, call = ask(llm, s, "draft", "draft", "\n".join(s["notes"][1:]))   # POLICY and FRAUD lines only
            return {"notes": [text], "calls": [call], "decision": text.split()[-1]}
    
        return {"order": order, "policy": policy, "fraud": fraud, "draft": draft}
    
    
    if __name__ == "__main__":
        case = make_cases()[0]
        state = {"case": case, "notes": [], "calls": [], "decision": ""}
        nodes = make_nodes(FakeLLM())
        for name in ("order", "policy", "fraud", "draft"):          # by hand, before any graph library
            update = nodes[name](state)
            state["notes"] += update["notes"]
            state["calls"] += update["calls"]
            state["decision"] = update.get("decision", state["decision"])
            print(f"{name:7} -> {update['notes'][0]}")
        print("decision:", state["decision"], "| truth:", case.truth)

    Closures: each inner function remembers llm from the outer function. The demo replaces the previous demo.

    Run it. Four steps, one answer, and it matches the invented truth:

    output
    order   -> ORDER amount=33.59 days=21 complete=yes
    policy  -> POLICY ok=yes
    fraud   -> FRAUD high=no
    draft   -> DECISION approve
    decision: approve | truth: approve
  3. Chunk 3 — wire the four steps into a LangGraph graph

    Now the by-hand loop from chunk 2 becomes a graph. The benefit is not this tiny run. It is what LangGraph adds later for free: checkpoints, tracing, and a picture you can draw.

    Step-by-step: what chunk 3 does, in plain English
    1. Import StateGraph, START and END from LangGraph.
    2. build_workflow gets the four step functions.
    3. Create StateGraph(State), which declares the shape of the shared state.
    4. Register each function as a named node.
    5. Add five edges: START to order, order to policy, policy to fraud, fraud to draft, draft to END.
    6. compile() checks the graph and returns something we can invoke.
    7. The demo invokes it on ticket 0 and prints the notes and the number of model calls.
    refund_workflow.py — chunk 3 (adds to chunks 1 and 2)runs offline (simulated)
    # ── chunk 3: wire the four steps into a LangGraph graph ──
    from langgraph.graph import END, START, StateGraph
    
    
    def build_workflow(llm):
        nodes = make_nodes(llm)
        g = StateGraph(State)
        for name, fn in nodes.items():
            g.add_node(name, fn)
        g.add_edge(START, "order")
        g.add_edge("order", "policy")
        g.add_edge("policy", "fraud")
        g.add_edge("fraud", "draft")
        g.add_edge("draft", END)
        return g.compile()
    
    
    if __name__ == "__main__":
        case = make_cases()[0]
        graph = build_workflow(FakeLLM())
        final = graph.invoke({"case": case, "notes": [], "calls": [], "decision": ""})
        print(final["notes"])
        print("decision:", final["decision"], "| truth:", case.truth, "| model calls:", len(final["calls"]))

    StateGraph, add_node, add_edge, compile, invoke. The next anatomy block takes these apart.

    Run it. The graph produces the same four notes as the by-hand loop:

    output
    ['ORDER amount=33.59 days=21 complete=yes', 'POLICY ok=yes', 'FRAUD high=no', 'DECISION approve']
    decision: approve | truth: approve | model calls: 4
  4. Chunk 4 — score one finished run: right answer, tokens, dollars, seconds

    A graph that runs is not yet an experiment. The scorer turns the call log into the three numbers Maya asked for, one row per ticket.

    Step-by-step: what chunk 4 does, in plain English
    1. score takes the ticket and the finished state.
    2. It adds up tokens in and tokens out over every logged call.
    3. It marks the run right if the decision equals the ticket's known answer.
    4. It prices the tokens with price and adds up the seconds. Calls run one after another, so seconds simply add.
    5. The demo runs the first eight tickets and prints one row each.
    refund_workflow.py — chunk 4 (adds to chunks 1 to 3)runs offline (simulated)
    # ── chunk 4: score one finished run: right answer? tokens? dollars? seconds? ──
    def score(case, final):
        calls = final["calls"]
        tin, tout = sum(c["tin"] for c in calls), sum(c["tout"] for c in calls)
        return {"id": case.id, "ok": final["decision"] == case.truth, "odd": case.odd, "calls": len(calls),
                "tin": tin, "tout": tout, "usd": price(tin, tout), "secs": sum(c["secs"] for c in calls)}
    
    
    if __name__ == "__main__":
        graph = build_workflow(FakeLLM())
        print("id  ok     odd    calls  tokens_in  tokens_out  dollars   seconds")
        for case in make_cases()[:8]:
            final = graph.invoke({"case": case, "notes": [], "calls": [], "decision": ""})
            r = score(case, final)
            print(f"{r['id']:<3} {str(r['ok']):6} {str(r['odd']):6} {r['calls']:<6} {r['tin']:<10} "
                  f"{r['tout']:<11} ${r['usd']:.4f}  {r['secs']:.2f}")

    Summing a field across a list of dictionaries with a generator expression.

    Run it. Eight rows. Look at row 2, the one marked False:

    output
    id  ok     odd    calls  tokens_in  tokens_out  dollars   seconds
    0   True   False  4      1632       297         $0.0094  6.12
    1   True   True   4      1637       265         $0.0089  5.66
    2   False  True   4      1636       190         $0.0078  4.58
    3   True   False  4      1633       234         $0.0084  5.22
    4   True   False  4      1633       250         $0.0086  5.43
    5   True   False  4      1632       284         $0.0092  5.93
    6   True   False  4      1633       225         $0.0083  5.10
    7   True   False  4      1633       226         $0.0083  5.10
  5. Chunk 5 — run all 200 tickets and total them up

    The last chunk is a loop and a summary. Success rate, dollars per case, dollars per successful case, mean and 95th-percentile seconds, and calls per case are the columns the comparison table will use.

    Step-by-step: what chunk 5 does, in plain English
    1. run_all invokes the graph on every ticket with a fresh empty state and scores each run.
    2. totals counts the right answers and sorts the seconds.
    3. Success rate is right answers divided by tickets.
    4. Dollars per successful case divides the total bill by the right answers only. A system that is cheap but often wrong looks worse on this line.
    5. The 95th percentile is the seconds value that 95 percent of tickets beat, a measure of the slow tail.
    6. The demo prints the six headline numbers.
    refund_workflow.py — chunk 5 (adds to chunks 1 to 4)runs offline (simulated)
    # ── chunk 5: run all 200 cases and total them up ──
    def run_all(graph, cases):
        return [score(c, graph.invoke({"case": c, "notes": [], "calls": [], "decision": ""})) for c in cases]
    
    
    def totals(rows):
        n, wins = len(rows), sum(r["ok"] for r in rows)
        secs = sorted(r["secs"] for r in rows)
        return {"n": n, "success": wins / n, "usd_per_case": sum(r["usd"] for r in rows) / n,
                "usd_per_success": sum(r["usd"] for r in rows) / max(wins, 1),
                "secs_mean": sum(secs) / n, "secs_p95": secs[int(0.95 * n) - 1],
                "calls": sum(r["calls"] for r in rows) / n}
    
    
    if __name__ == "__main__":
        rows = run_all(build_workflow(FakeLLM()), make_cases())
        t = totals(rows)
        print(f"WORKFLOW over {t['n']} simulated cases")
        print(f"  success rate        {t['success']:.1%}")
        print(f"  dollars per case    ${t['usd_per_case']:.4f}")
        print(f"  dollars per success ${t['usd_per_success']:.4f}")
        print(f"  seconds mean / p95  {t['secs_mean']:.2f} / {t['secs_p95']:.2f}")
        print(f"  model calls         {t['calls']:.1f} per case")

    Percentiles by sorting a list and indexing at 95 percent.

    Run it. This is Build A's report card:

    output
    WORKFLOW over 200 simulated cases
      success rate        77.0%
      dollars per case    $0.0087
      dollars per success $0.0113
      seconds mean / p95  6.02 / 13.08
      model calls         4.0 per case

The whole program

Chunk 1 is the imports, State and ask. Chunk 2 is make_nodes. Chunk 3 is build_workflow. Chunk 4 is score. Chunk 5 is run_all and totals, with the final demo at the bottom.

refund_workflow.pyruns offline (simulated)
# refund_workflow.py: the deterministic workflow version of the refund dispute, on LangGraph.
# Install: uv pip install "langgraph>=1.0,<2"       (needs fake_world.py next to it)
# ── chunk 1: the state, and one helper that asks the model and logs the call ──
import operator
from typing import Annotated, TypedDict

from fake_world import Case, FakeLLM, make_cases, lookup_order, fraud_signals, price


class State(TypedDict):
    case: Case
    notes: Annotated[list, operator.add]   # each step APPENDS its one-line result
    calls: Annotated[list, operator.add]   # one record per model call: the raw material for cost and latency
    decision: str


def ask(llm, state, node, role, prompt):
    reply = llm.ask(role, state["case"].id, prompt)
    call = {"node": node, "role": role, "hop": state.get("hops", 0), "tin": reply.tokens_in,
            "tout": reply.tokens_out, "secs": reply.secs, "slipped": reply.slipped}
    return reply.text, call


# ── chunk 2: four steps, each one sees ONLY what it needs ──
def make_nodes(llm):
    def order(s):
        text, call = ask(llm, s, "order", "order", lookup_order(s["case"]))
        return {"notes": [text], "calls": [call]}

    def policy(s):
        text, call = ask(llm, s, "policy", "policy", s["notes"][0])        # only the ORDER line
        return {"notes": [text], "calls": [call]}

    def fraud(s):
        text, call = ask(llm, s, "fraud", "fraud", fraud_signals(s["case"]))
        return {"notes": [text], "calls": [call]}

    def draft(s):
        text, call = ask(llm, s, "draft", "draft", "\n".join(s["notes"][1:]))   # POLICY and FRAUD lines only
        return {"notes": [text], "calls": [call], "decision": text.split()[-1]}

    return {"order": order, "policy": policy, "fraud": fraud, "draft": draft}


# ── chunk 3: wire the four steps into a LangGraph graph ──
from langgraph.graph import END, START, StateGraph


def build_workflow(llm):
    nodes = make_nodes(llm)
    g = StateGraph(State)
    for name, fn in nodes.items():
        g.add_node(name, fn)
    g.add_edge(START, "order")
    g.add_edge("order", "policy")
    g.add_edge("policy", "fraud")
    g.add_edge("fraud", "draft")
    g.add_edge("draft", END)
    return g.compile()


# ── chunk 4: score one finished run: right answer? tokens? dollars? seconds? ──
def score(case, final):
    calls = final["calls"]
    tin, tout = sum(c["tin"] for c in calls), sum(c["tout"] for c in calls)
    return {"id": case.id, "ok": final["decision"] == case.truth, "odd": case.odd, "calls": len(calls),
            "tin": tin, "tout": tout, "usd": price(tin, tout), "secs": sum(c["secs"] for c in calls)}


# ── chunk 5: run all 200 cases and total them up ──
def run_all(graph, cases):
    return [score(c, graph.invoke({"case": c, "notes": [], "calls": [], "decision": ""})) for c in cases]


def totals(rows):
    n, wins = len(rows), sum(r["ok"] for r in rows)
    secs = sorted(r["secs"] for r in rows)
    return {"n": n, "success": wins / n, "usd_per_case": sum(r["usd"] for r in rows) / n,
            "usd_per_success": sum(r["usd"] for r in rows) / max(wins, 1),
            "secs_mean": sum(secs) / n, "secs_p95": secs[int(0.95 * n) - 1],
            "calls": sum(r["calls"] for r in rows) / n}


if __name__ == "__main__":
    rows = run_all(build_workflow(FakeLLM()), make_cases())
    t = totals(rows)
    print(f"WORKFLOW over {t['n']} simulated cases")
    print(f"  success rate        {t['success']:.1%}")
    print(f"  dollars per case    ${t['usd_per_case']:.4f}")
    print(f"  dollars per success ${t['usd_per_success']:.4f}")
    print(f"  seconds mean / p95  {t['secs_mean']:.2f} / {t['secs_p95']:.2f}")
    print(f"  model calls         {t['calls']:.1f} per case")

Read the output of chunk 5 line by line. The workflow is right on 77 percent of the 200 simulated tickets. It spends about 0.9 of a cent per ticket and about 1.1 cents per successful ticket. A ticket takes six seconds on average, 13 seconds for the slowest 5 percent, and exactly four model calls every time. Those four calls are the reason the numbers are so steady.

One more thing in chunk 4's output deserves a look. Row 2 is wrong, and it is a split shipment. The workflow has no way to ask the order system again, so its policy step guessed. That is a clue, and the pencil exercise below turns it into a prediction.

Anatomy of building a LangGraph graph — the five lines to know by heart
g = StateGraph(State)1
g.add_node("order", order_fn)2
g.add_edge(START, "order")3
graph = g.compile()4
final = graph.invoke(first_state)5
  1. StateGraph(State). Declares the shape of the shared state and the merge rules, such as "append lists". The usual mistake is forgetting the reducer: without it, a step that returns a list overwrites the old list.
  2. add_node(name, function). Registers a step under a name. The function takes the state and returns only the fields it changes. Returning the whole state is the usual mistake.
  3. add_edge(from, to). A fixed arrow. The workflow is only fixed edges. A team uses add_conditional_edges instead, where a function picks the arrow.
  4. compile(). Checks that the graph is wired sensibly and returns a runnable. You can pass a checkpointer here to save state between steps.
  5. invoke(first_state). Runs the graph to END and returns the final state. People forget to fill every field of the first state, then wonder why a step cannot find a key.
Sharpen your pencil

Predict, before the numbers are shown, how well the workflow does on split-shipment tickets. Use only what you know: days since delivery is uniform from 1 to 45, so 30 of 45 days, which is 2 in 3, are inside the 30-day window. The policy step, with no date, says "ok" 70 percent of the time. Ignore slips and fraud.

Chance a split-shipment ticket is truly inside the window30 / 45 = 0.667
If inside the window, chance the guess says "ok" (a right answer)
Chance a split-shipment ticket is truly late
If late, chance the guess says "not ok" (a right answer)
Overall chance the workflow is right on a split shipment
Check your answers
If inside the window, chance the guess says "ok"0.70, straight from the rule.
Chance truly late15 / 45 = 0.333.
If late, chance the guess says "not ok"1 − 0.70 = 0.30.
Overall0.667 × 0.70 + 0.333 × 0.30 = 0.467 + 0.100 = 0.567, about 57 percent.

Section 05 measures 57.1 percent on the real split-shipment tickets. A guess made on paper from two facts predicted the result. That is what it means to understand a failure rather than just see it.

Quick reference — The workflow build

Simulated model
A seeded stand-in that reads its prompt, answers in one line, slips sometimes and reports tokens and seconds. Same seed, same numbers.
State and reducer
The shared dictionary a graph passes along. A reducer such as operator.add says how updates merge.
Node and edge
A step and an arrow. The workflow has only fixed edges.
$ per successful case
Total bill divided by right answers only. Cheap-but-wrong looks worse on this line.
The baseline
77.0 percent right, $0.0087 a ticket, 6.0 s, 4 calls. The workflow's blind spot is the split shipment, about 57 percent right.
Why message passing here
Each step reads only what it needs, which keeps tokens, and therefore the bill, small.

04 · Watch it breakBuild the Team, Then Watch It Break

Build A scored 77 percent, and its misses cluster on split shipments, where its fixed path cannot ask the order system a second question. A supervisor can. So Priya builds Build B, a supervisor with four workers, on the same fake world, and watches what the flexibility costs and what it breaks.

A supervisor team lets a model pick the next step, which fixes cases your fixed path cannot handle. In return it adds a model call per decision, a whiteboard everyone reads, and new ways to fail: lost context, loops and unclear blame.

Shared state: one whiteboard that every agent reads

The workflow passed each step only the line it needed. A supervisor cannot work that way, because it must see the whole story to decide what is missing. So the team shares one transcript, and that choice drives most of the cost.

Two ways to let agents share information exist, and the choice shapes everything. Message passing sends a step only what it needs, like a function argument. Shared state gives every agent the same growing whiteboard, like a global variable. Fig. 9b.6 shows the same ticket both ways.

1 SHARED STATE: THE TEAM VERSION TASK refund dispute #1 NEXT order order #1 amount=210.36 ORDER ... complete=no NEXT order secondary order #1 ... days=7 ORDER ... complete=yes NEXT policy (and so on, all of it) order reads 329 order, 2nd reads 357 policy reads 520 fraud reads 431 draft reads 587 same ticket: 6,187 tokens read in all, 3,963 of them by the supervisor 2 MESSAGE PASSING: THE WORKFLOW order reads 318 policy reads 459 fraud reads 354 draft reads 506 ORDER amount=210.36 POLICY ok=yes FRAUD high=no same ticket: 1,637 tokens read in all, no supervisor, no whiteboard
Fig. 9b.6 — The same ticket under both designs. Shared state lets any agent see everything, at the price of every agent reading everything. Message passing keeps each step small, but each step is blind to the rest.
  1. Shared state (the team). One transcript grows as agents write to it, and every agent reads all of it. The five workers read 329, 357, 520, 431 and 587 tokens, so 2,224 in all. The supervisor reads the whiteboard again before every decision, 3,963 tokens over six turns. Total on this ticket: 6,187 tokens read.
  2. Message passing (the workflow). Each step is handed one line: the order step reads 318 tokens, policy 459, fraud 354 and draft 506. Total: 1,637 tokens read. The price is blindness. The policy step cannot notice that the order record was incomplete, unless an earlier step said so in the one line it passes on.

Neither is better in general. Shared state suits a supervisor who must notice what is missing. Message passing suits a known path. A hybrid is common in real systems: workers receive a summary of what they need, while the supervisor keeps the whole record. The summary step is where context gets lost, which we will measure shortly.

Now the build. multi_agent_refund.py reuses ask, score and totals from the workflow and the pretend model from fake_world.py. It adds a shared whiteboard, a supervisor, and a loop guard.

Build it in chunks

We build multi_agent_refund.py in five chunks: the whiteboard and workers, the supervisor, the graph, blame assignment, and the run over 200 tickets. Each chunk runs on its own.

  1. Chunk 1 — the shared whiteboard and four workers that each read all of it

    Workers come first because they are the part that resembles Build A. The new thing is what they read and what they write back.

    Step-by-step: what chunk 1 does, in plain English
    1. Import what we need, including ask, score and totals from the workflow file.
    2. TeamState is the shared state: the ticket, a transcript string that everyone reads, the call log, the decision, a count of supervisor turns, the supervisor's last instruction, and a flag meaning "fetch shipment 2".
    3. LOSS_P is a simulated 4 percent chance that a worker's hand-off summary comes out garbled.
    4. garbled rolls repeatable dice for that chance.
    5. make_workers builds one worker function per role. Each worker runs its tool, then asks the model with the whole transcript plus the tool output.
    6. If the summary survives, the worker's answer goes on the whiteboard. If it is garbled, only "ROLE [summary lost]" does.
    7. The draft worker also stores the decision, but only when its summary survived.
    8. new_state makes the first whiteboard, and merge applies an update by hand, appending call logs.
    9. The demo drives two workers by hand and prints the whiteboard and how many tokens each worker read.
    multi_agent_refund.py — chunk 1runs offline (simulated)
    # multi_agent_refund.py: the same refund dispute as a supervisor plus four worker agents, on LangGraph.
    # Install: uv pip install "langgraph>=1.0,<2"       (needs fake_world.py and refund_workflow.py next to it)
    # ── chunk 1: the shared whiteboard and four workers that each read all of it ──
    import operator
    import random
    import re
    from typing import Annotated, TypedDict
    
    from fake_world import Case, FakeLLM, make_cases, lookup_order, fraud_signals
    from refund_workflow import ask, score, totals
    
    
    class TeamState(TypedDict):
        case: Case
        transcript: str                        # the shared whiteboard: every agent reads ALL of it
        calls: Annotated[list, operator.add]
        decision: str
        hops: int                              # how many times the supervisor has spoken
        next: str                              # the supervisor's last instruction
        secondary: bool                        # "go and fetch shipment 2"
    
    
    LOSS_P = 0.04    # simulated: chance that a worker's hand-off summary comes out garbled
    
    
    def garbled(seed, case_id, hops, p):
        return random.Random(f"loss|{seed}|{case_id}|{hops}").random() < p
    
    
    def make_workers(llm, loss_p=LOSS_P):
        def worker(role, tool):
            def run(s):
                tool_text = tool(s)
                text, call = ask(llm, s, role, role, s["transcript"] + "\n" + tool_text)
                ok = not garbled(llm.seed, s["case"].id, s["hops"], loss_p)
                note = text if ok else text.split()[0] + " [summary lost]"
                update = {"transcript": s["transcript"] + "\n" + tool_text + "\n" + note, "calls": [call]}
                if role == "draft" and ok:
                    update["decision"] = text.split()[-1]
                return update
            return run
    
        return {"order": worker("order", lambda s: lookup_order(s["case"], s["secondary"])),
                "policy": worker("policy", lambda s: ""),
                "fraud": worker("fraud", lambda s: fraud_signals(s["case"])),
                "draft": worker("draft", lambda s: "")}
    
    
    def new_state(case):
        return {"case": case, "transcript": f"TASK refund dispute for order #{case.id}", "calls": [],
                "decision": "", "hops": 0, "next": "", "secondary": False}
    
    
    def merge(state, update):
        """Apply one node's update by hand. LangGraph does this for us once there is a graph."""
        merged = {**state, **update}
        merged["calls"] = state["calls"] + update.get("calls", [])      # calls are appended, not replaced
        return merged
    
    
    if __name__ == "__main__":
        case = make_cases()[0]
        workers = make_workers(FakeLLM())
        state = new_state(case)
        for name in ("order", "policy"):                      # the supervisor is missing, so we call workers by hand
            state = merge(state, workers[name](state))
        print(state["transcript"])
        print("tokens read by the 1st worker:", state["calls"][0]["tin"], "| by the 2nd:", state["calls"][1]["tin"])

    One function that builds other functions (worker(role, tool)), so four workers share one body.

    Run it. The second worker reads more than the first, because the whiteboard grew:

    output
    TASK refund dispute for order #0
    order #0 amount=33.59 days_since_delivery=21 complete
    ORDER amount=33.59 days=21 complete=yes
    
    POLICY ok=yes
    tokens read by the 1st worker: 321 | by the 2nd: 481
  2. Chunk 2 — the supervisor: one more model call that decides who speaks next

    The supervisor is a model call like the others. It reads the whiteboard and answers "NEXT order", "NEXT policy" and so on, or "NEXT done". Its cost is the reason this page exists.

    Step-by-step: what chunk 2 does, in plain English
    1. make_supervisor returns the supervisor step.
    2. The step asks the model, in the supervisor role, with the whole transcript as the prompt.
    3. It stamps the call record with its turn number, so a trace can group the boss and its worker.
    4. It writes the instruction onto the whiteboard, adds one to the turn count, and records the next worker.
    5. If the instruction contains the word "secondary", it raises the flag that tells the order worker to fetch shipment 2.
    6. The demo drives the supervisor and workers by hand on a split-shipment ticket for three turns.
    multi_agent_refund.py — chunk 2 (adds to chunk 1)runs offline (simulated)
    # ── chunk 2: the supervisor, an extra model call that decides who speaks next ──
    def make_supervisor(llm):
        def supervisor(s):
            text, call = ask(llm, s, "supervisor", "supervisor", s["transcript"])
            call["hop"] = s["hops"] + 1                          # same hop number as the worker it dispatches
            return {"transcript": s["transcript"] + "\n" + text, "calls": [call], "hops": s["hops"] + 1,
                    "next": text.split()[1], "secondary": "secondary" in text}
        return supervisor
    
    
    if __name__ == "__main__":
        case = next(c for c in make_cases() if c.odd)
        llm = FakeLLM()
        supervisor, workers = make_supervisor(llm), make_workers(llm)
        state = new_state(case)
        for _ in range(3):
            state = merge(state, supervisor(state))
            print("supervisor says:", state["next"], "| secondary:", state["secondary"])
            if state["next"] in workers:
                state = merge(state, workers[state["next"]](state))

    An instruction written as plain text on the shared whiteboard, then parsed back out. Real supervisors often use structured output instead.

    Run it. On a split shipment the supervisor sees "complete=no" and sends the order worker back, with the secondary flag:

    output
    supervisor says: order | secondary: False
    supervisor says: order | secondary: True
    supervisor says: policy | secondary: False
  3. Chunk 3 — wire supervisor and workers into a graph, with a cap on turns

    Now the by-hand driving becomes a LangGraph graph with conditional edges. The cap exists because Module 09's pilot looped for six hours, and a supervisor can loop just as happily as an agent.

    Step-by-step: what chunk 3 does, in plain English
    1. Import StateGraph, START and END. Set the cap at 10 supervisor turns.
    2. route is the function that picks the next arrow. It returns END when the supervisor says "done" or the cap is exceeded. Otherwise it returns the worker's name.
    3. build_team adds the supervisor node, then each worker node.
    4. After each worker, a fixed edge goes back to the supervisor. Workers never talk to each other directly.
    5. START goes to the supervisor, and a conditional edge fans out from the supervisor using route.
    6. The demo runs a normal ticket and a split shipment, and prints the path each took.
    multi_agent_refund.py — chunk 3 (adds to chunks 1 and 2)runs offline (simulated)
    # ── chunk 3: wire supervisor and workers into a graph, with a hop cap ──
    from langgraph.graph import END, START, StateGraph
    
    MAX_HOPS = 10
    
    
    def route(s):
        if s["next"] == "done" or s["hops"] > MAX_HOPS:      # the loop guard: stop after 10 supervisor turns
            return END
        return s["next"]
    
    
    def build_team(llm, loss_p=LOSS_P):
        g = StateGraph(TeamState)
        g.add_node("supervisor", make_supervisor(llm))
        for name, fn in make_workers(llm, loss_p).items():
            g.add_node(name, fn)
            g.add_edge(name, "supervisor")                    # every worker reports back to the boss
        g.add_edge(START, "supervisor")
        g.add_conditional_edges("supervisor", route, ["order", "policy", "fraud", "draft", END])
        return g.compile()
    
    
    if __name__ == "__main__":
        graph = build_team(FakeLLM())
        for case in (make_cases()[0], next(c for c in make_cases() if c.odd)):
            final = graph.invoke(new_state(case), {"recursion_limit": 60})
            path = " > ".join(c["role"][:3] for c in final["calls"])        # first 3 letters of each role
            print(f"case {case.id} odd={case.odd}: {path}")
            print(f"   decision={final['decision']} truth={case.truth} calls={len(final['calls'])}")

    add_conditional_edges: an arrow whose destination is chosen by a function at run time.

    Run it. Case 0 visited the fraud worker twice (a repeat caused by a lost summary or a mis-route), and the split shipment, case 1, visited the order worker twice, correctly:

    output
    case 0 odd=False: sup > ord > sup > pol > sup > fra > sup > fra > sup > dra > sup
       decision=approve truth=approve calls=11
    case 1 odd=True: sup > ord > sup > ord > sup > pol > sup > fra > sup > dra > sup
       decision=approve truth=approve calls=11
  4. Chunk 4 — run one ticket and, when it is wrong, say who to blame

    When a team gets a ticket wrong, "the system failed" is not a finding. Blame assignment names the first place the run went off the rails, so you know which part to fix.

    Step-by-step: what chunk 4 does, in plain English
    1. run_team runs the graph from a fresh whiteboard. The recursion limit is raised to 60 so LangGraph's own safety stop does not fire before ours.
    2. blame returns nothing if the answer was right.
    3. If there is no decision at all, the run gave up or looped.
    4. Next, it checks for a worker whose logged call slipped. That is a plain model mistake.
    5. Next, it checks whether the order record was ever complete. If not, the cause is missing data.
    6. Next, a supervisor slip that did not show up anywhere else is a mis-route.
    7. The demo runs the first 40 tickets and prints every wrong one with its blame label.
    multi_agent_refund.py — chunk 4 (adds to chunks 1 to 3)runs offline (simulated)
    # ── chunk 4: run one case and, when it is wrong, say who to blame ──
    def run_team(graph, case):
        s = new_state(case)
        return graph.invoke(s, {"recursion_limit": 60})
    
    
    def blame(case, final):
        if final["decision"] == case.truth:
            return None
        if not final["decision"]:
            return "gave up or looped (no decision)"
        workers = [c["role"] for c in final["calls"] if c["slipped"] and c["role"] != "supervisor"]
        if workers:
            return "model slip in " + workers[0]
        text = final.get("transcript") or " ".join(final.get("notes", []))
        if "complete=yes" not in text:
            return "missing data (split shipment)"
        if any(c["slipped"] for c in final["calls"]):
            return "supervisor mis-route"
        return "other"
    
    
    if __name__ == "__main__":
        graph = build_team(FakeLLM())
        wrong = 0
        for case in make_cases()[:40]:
            final = run_team(graph, case)
            why = blame(case, final)
            if why:
                wrong += 1
                got = final["decision"] or "-"
                print(f"case {case.id:<3} truth={case.truth:8} got={got:8} calls={len(final['calls']):<2} blame: {why}")
        print(f"{wrong} wrong out of 40")

    A short chain of ordered checks that returns the first cause it finds. This is a heuristic and the page says so: it is a first guess for a human to confirm, not a verdict.

    Run it. Eight of the first 40 are wrong, each with a label. Two have calls=1: the supervisor said "done" before anyone worked:

    output
    case 2   truth=approve  got=deny     calls=15 blame: model slip in draft
    case 6   truth=deny     got=-        calls=1  blame: gave up or looped (no decision)
    case 12  truth=deny     got=-        calls=1  blame: gave up or looped (no decision)
    case 15  truth=approve  got=deny     calls=9  blame: model slip in draft
    case 20  truth=approve  got=escalate calls=9  blame: model slip in fraud
    case 22  truth=escalate got=deny     calls=9  blame: model slip in policy
    case 23  truth=approve  got=escalate calls=11 blame: model slip in policy
    case 34  truth=deny     got=escalate calls=11 blame: model slip in draft
    8 wrong out of 40
  5. Chunk 5 — run all 200 tickets and total them up

    The same totals function used for the workflow summarises the team, so the two reports are comparable line for line.

    Step-by-step: what chunk 5 does, in plain English
    1. run_all_team loops over every ticket and runs the team.
    2. For each ticket it scores the run, attaches the blame label, and records the supervisor-turn count.
    3. The demo totals the rows with the workflow's totals and prints six lines in the same layout as Build A.
    multi_agent_refund.py — chunk 5 (adds to chunks 1 to 4)runs offline (simulated)
    # ── chunk 5: run all 200 cases and total them up ──
    def run_all_team(graph, cases):
        rows = []
        for c in cases:
            final = run_team(graph, c)
            row = score(c, final)
            row["blame"] = blame(c, final)
            row["hops"] = final["hops"]
            rows.append(row)
        return rows
    
    
    if __name__ == "__main__":
        rows = run_all_team(build_team(FakeLLM()), make_cases())
        t = totals(rows)
        print(f"MULTI-AGENT over {t['n']} simulated cases")
        print(f"  success rate        {t['success']:.1%}")
        print(f"  dollars per case    ${t['usd_per_case']:.4f}")
        print(f"  dollars per success ${t['usd_per_success']:.4f}")
        print(f"  seconds mean / p95  {t['secs_mean']:.2f} / {t['secs_p95']:.2f}")
        print(f"  model calls         {t['calls']:.1f} per case")

    Reusing a function across two programs (totals) so the comparison cannot drift.

    Run it. This is Build B's report card:

    output
    MULTI-AGENT over 200 simulated cases
      success rate        80.5%
      dollars per case    $0.0226
      dollars per success $0.0280
      seconds mean / p95  12.10 / 21.33
      model calls         9.9 per case

The whole program

Chunk 1 is TeamState, garbled, make_workers, new_state and merge. Chunk 2 is make_supervisor. Chunk 3 is route and build_team. Chunk 4 is run_team and blame. Chunk 5 is run_all_team.

multi_agent_refund.pyruns offline (simulated)
# multi_agent_refund.py: the same refund dispute as a supervisor plus four worker agents, on LangGraph.
# Install: uv pip install "langgraph>=1.0,<2"       (needs fake_world.py and refund_workflow.py next to it)
# ── chunk 1: the shared whiteboard and four workers that each read all of it ──
import operator
import random
import re
from typing import Annotated, TypedDict

from fake_world import Case, FakeLLM, make_cases, lookup_order, fraud_signals
from refund_workflow import ask, score, totals


class TeamState(TypedDict):
    case: Case
    transcript: str                        # the shared whiteboard: every agent reads ALL of it
    calls: Annotated[list, operator.add]
    decision: str
    hops: int                              # how many times the supervisor has spoken
    next: str                              # the supervisor's last instruction
    secondary: bool                        # "go and fetch shipment 2"


LOSS_P = 0.04    # simulated: chance that a worker's hand-off summary comes out garbled


def garbled(seed, case_id, hops, p):
    return random.Random(f"loss|{seed}|{case_id}|{hops}").random() < p


def make_workers(llm, loss_p=LOSS_P):
    def worker(role, tool):
        def run(s):
            tool_text = tool(s)
            text, call = ask(llm, s, role, role, s["transcript"] + "\n" + tool_text)
            ok = not garbled(llm.seed, s["case"].id, s["hops"], loss_p)
            note = text if ok else text.split()[0] + " [summary lost]"
            update = {"transcript": s["transcript"] + "\n" + tool_text + "\n" + note, "calls": [call]}
            if role == "draft" and ok:
                update["decision"] = text.split()[-1]
            return update
        return run

    return {"order": worker("order", lambda s: lookup_order(s["case"], s["secondary"])),
            "policy": worker("policy", lambda s: ""),
            "fraud": worker("fraud", lambda s: fraud_signals(s["case"])),
            "draft": worker("draft", lambda s: "")}


def new_state(case):
    return {"case": case, "transcript": f"TASK refund dispute for order #{case.id}", "calls": [],
            "decision": "", "hops": 0, "next": "", "secondary": False}


def merge(state, update):
    """Apply one node's update by hand. LangGraph does this for us once there is a graph."""
    merged = {**state, **update}
    merged["calls"] = state["calls"] + update.get("calls", [])      # calls are appended, not replaced
    return merged


# ── chunk 2: the supervisor, an extra model call that decides who speaks next ──
def make_supervisor(llm):
    def supervisor(s):
        text, call = ask(llm, s, "supervisor", "supervisor", s["transcript"])
        call["hop"] = s["hops"] + 1                          # same hop number as the worker it dispatches
        return {"transcript": s["transcript"] + "\n" + text, "calls": [call], "hops": s["hops"] + 1,
                "next": text.split()[1], "secondary": "secondary" in text}
    return supervisor


# ── chunk 3: wire supervisor and workers into a graph, with a hop cap ──
from langgraph.graph import END, START, StateGraph

MAX_HOPS = 10


def route(s):
    if s["next"] == "done" or s["hops"] > MAX_HOPS:      # the loop guard: stop after 10 supervisor turns
        return END
    return s["next"]


def build_team(llm, loss_p=LOSS_P):
    g = StateGraph(TeamState)
    g.add_node("supervisor", make_supervisor(llm))
    for name, fn in make_workers(llm, loss_p).items():
        g.add_node(name, fn)
        g.add_edge(name, "supervisor")                    # every worker reports back to the boss
    g.add_edge(START, "supervisor")
    g.add_conditional_edges("supervisor", route, ["order", "policy", "fraud", "draft", END])
    return g.compile()


# ── chunk 4: run one case and, when it is wrong, say who to blame ──
def run_team(graph, case):
    s = new_state(case)
    return graph.invoke(s, {"recursion_limit": 60})


def blame(case, final):
    if final["decision"] == case.truth:
        return None
    if not final["decision"]:
        return "gave up or looped (no decision)"
    workers = [c["role"] for c in final["calls"] if c["slipped"] and c["role"] != "supervisor"]
    if workers:
        return "model slip in " + workers[0]
    text = final.get("transcript") or " ".join(final.get("notes", []))
    if "complete=yes" not in text:
        return "missing data (split shipment)"
    if any(c["slipped"] for c in final["calls"]):
        return "supervisor mis-route"
    return "other"


# ── chunk 5: run all 200 cases and total them up ──
def run_all_team(graph, cases):
    rows = []
    for c in cases:
        final = run_team(graph, c)
        row = score(c, final)
        row["blame"] = blame(c, final)
        row["hops"] = final["hops"]
        rows.append(row)
    return rows


if __name__ == "__main__":
    rows = run_all_team(build_team(FakeLLM()), make_cases())
    t = totals(rows)
    print(f"MULTI-AGENT over {t['n']} simulated cases")
    print(f"  success rate        {t['success']:.1%}")
    print(f"  dollars per case    ${t['usd_per_case']:.4f}")
    print(f"  dollars per success ${t['usd_per_success']:.4f}")
    print(f"  seconds mean / p95  {t['secs_mean']:.2f} / {t['secs_p95']:.2f}")
    print(f"  model calls         {t['calls']:.1f} per case")

Read the two report cards side by side. The team is right 80.5 percent of the time, up from 77.0. But it spends 2.3 cents a ticket instead of 0.9, takes 12.1 seconds instead of 6.0, and makes 9.9 calls instead of 4.0. Better, and several times more expensive. Whether that trade is good is for section 05. First, understand what is happening inside it.

The pretend supervisor follows six rules, checked in order. Fig. 9b.7 lays them out. They are worth studying, because they are the whole of what a boss "knows" in this simulation.

no 'complete=' anywhere on the board? yes NEXT order no last ORDER says complete=no, and 'secondary' not yet written? yes NEXT order secondary no no 'POLICY ok=' on the board? yes NEXT policy no no 'FRAUD high=' on the board? yes NEXT fraud no no 'DECISION approve|deny|escalate' yet? yes NEXT draft no none of the above (everything is written) yes NEXT done 5% of the time the boss slips: it names a random worker, or 'done' (a mis-route) 1 2 3 the rules never change; the wrong picks do
Fig. 9b.7 — The supervisor's rules, first match wins. The rules never change; the wrong picks come from the slip, not from the rules.
  1. Order matters. Rule two only fires after rule one is satisfied, which is why a split shipment sends the order worker out twice: first plain, then with "secondary".
  2. The slip. On 5 percent of calls the boss ignores the rules and names a random worker or "done". That one dial is the whole source of the 8 gave-up tickets and the 5 mis-routes measured below.
  3. "Done" comes last. It fires only when all three lines and a decision exist. A slipped "done" ends the run early with no decision at all.
BE the supervisor

Your turn to play the boss on a split shipment. The rules are the same ones the pretend supervisor uses. Read each whiteboard and say what you would write next, before opening the answers.

  1. The whiteboard holds only: TASK refund dispute for order #1. What next?
  2. It now also holds ORDER amount=210.36 days=? complete=no, and the word "secondary" has never appeared. What next?
  3. It now holds a second ORDER line, ORDER amount=210.36 days=7 complete=yes, and no POLICY line. What next?
  4. It holds POLICY and FRAUD lines but no DECISION line. What next?
  5. It holds a DECISION line of approve. What next?

Then answer: if the order worker's summary came back as ORDER [summary lost] at step 2, what would you write, and what did that mistake cost?

Check your answers

1. NEXT order. No ORDER line exists yet. 2. NEXT order secondary. The record is incomplete, and the secondary lookup has not been tried. 3. NEXT policy. The order is now complete, so the first missing check is policy. 4. NEXT draft. 5. NEXT done.

For the lost summary, no "complete=" text exists, so the rule says NEXT order again. The whole order step is repeated: one extra boss call and one extra worker call, about 0.4 of a cent, plus about two more seconds. Nothing was wrong with the answer. The loss only made the team repeat work. Now you know how lost context turns into cost.

Four ways the team breaks, each one measured

Build B works, and its report card looks fine. But Priya's job is to know how it fails before the CEO's blog-post enthusiasm meets a real queue. She turns each suspected failure mode on and off and reads the change in the numbers.

Four failure modes come up in every multi-agent post-mortem. The simulation lets us switch each on and off, which real systems rarely allow:

The script below runs the team four times with different failure settings, then again with different turn caps. It changes only the dials, never the cases.

Step-by-step: what failure_sweep.py does, in plain English
  1. Import the team module itself, so the script can change its MAX_HOPS cap.
  2. measure builds a fresh team with a given hand-off loss rate, supervisor slip rate and turn cap, and runs all 200 tickets.
  3. It prints success rate, calls per ticket, dollars per ticket, and how many tickets ended with no decision.
  4. First block: the team as built, then with no garbled hand-offs, then with a supervisor that never mis-routes, then with neither.
  5. Second block: the turn cap at 3, 5, 10 and 20.
failure_sweep.pyruns offline (simulated)
# failure_sweep.py: switch each multi-agent failure mode off, one at a time, and measure what it cost.
# Install: uv pip install "langgraph>=1.0,<2"
import multi_agent_refund as team_module
from fake_world import FakeLLM, SLIP, make_cases
from multi_agent_refund import build_team, run_all_team
from refund_workflow import totals

cases = make_cases()


def measure(label, loss_p=0.04, supervisor_slip=SLIP["supervisor"], max_hops=10):
    team_module.MAX_HOPS = max_hops
    rows = run_all_team(build_team(FakeLLM(slip={**SLIP, "supervisor": supervisor_slip}), loss_p), cases)
    t = totals(rows)
    gave_up = sum(r["blame"] == "gave up or looped (no decision)" for r in rows)
    print(f"{label:34} success {t['success']:.1%}  calls {t['calls']:.1f}  "
          f"$/case ${t['usd_per_case']:.4f}  gave-up {gave_up}")


print("-- which failure mode costs what --")
measure("as built")
measure("no garbled hand-offs", loss_p=0.0)
measure("no supervisor mis-routes", supervisor_slip=0.0)
measure("neither (a perfect supervisor)", loss_p=0.0, supervisor_slip=0.0)
print("-- the loop guard: how many supervisor turns are allowed --")
for cap in (3, 5, 10, 20):
    measure(f"max_hops = {cap}", max_hops=cap)
output
-- which failure mode costs what --
as built                           success 80.5%  calls 9.9  $/case $0.0226  gave-up 8
no garbled hand-offs               success 82.0%  calls 9.5  $/case $0.0218  gave-up 7
no supervisor mis-routes           success 86.5%  calls 9.9  $/case $0.0228  gave-up 0
neither (a perfect supervisor)     success 87.5%  calls 9.6  $/case $0.0219  gave-up 0
-- the loop guard: how many supervisor turns are allowed --
max_hops = 3                       success 3.0%  calls 6.9  $/case $0.0147  gave-up 189
max_hops = 5                       success 73.0%  calls 9.6  $/case $0.0219  gave-up 25
max_hops = 10                      success 80.5%  calls 9.9  $/case $0.0226  gave-up 8
max_hops = 20                      success 80.5%  calls 9.9  $/case $0.0226  gave-up 8

Read the output in three parts. First, garbled hand-offs cost only 1.5 points of success (80.5 to 82.0) and 0.4 of a call. They are real, but small. Second, supervisor mis-routes cost 6 points (80.5 to 86.5) and are the entire source of the eight "gave up" tickets. The boss is the weakest link. Third, a perfect supervisor reaches 87.5 percent, the ceiling set by the workers' own slips.

plain workflow 77.0 as built 80.5% calls 9.9 · gave up 8 no garbled hand-offs 82.0% calls 9.5 · gave up 7 no supervisor mis-routes 86.5% calls 9.9 · gave up 0 neither (a perfect boss) 87.5% calls 9.6 · gave up 0 1 2 3 success rate of the team on the same 200 tickets; only the failure dials change
Fig. 9b.8 — Team success with each failure mode switched off, on the same 200 tickets. The vertical line marks the plain workflow.
  1. No garbled hand-offs. +1.5 points and 0.4 fewer calls. Lost summaries cost mostly repeat work, because the boss notices the gap and re-asks.
  2. No mis-routes. +6.0 points, and the 8 gave-up tickets fall to 0. The boss's own mistakes are the most expensive failure by a wide margin.
  3. Neither. 87.5 percent is the ceiling set by the workers' own slips. It happens to equal the score of the workflow with one branch.

The loop guard teaches the opposite lesson. A cap of 3 turns fails almost every ticket, because the minimum path needs five or six turns. A cap of 5 loses 7 points. Past 10 the cap never fires. The right cap is a little above the longest legitimate path, which you learn only by measuring.

3.0% cap = 3 turns 189 gave up 73.0% cap = 5 turns 25 gave up 80.5% cap = 10 turns 8 gave up 80.5% cap = 20 turns 8 gave up 1 2 3 the cap only bites when it is lower than the longest honest path (6 to 8 turns here)
Fig. 9b.9 — The turn cap against success. The cap protects against runaway loops, but a cap below the honest path destroys the system.
  1. Cap 3. The shortest honest run needs five or six boss turns, so 189 of 200 tickets are cut off and success falls to 3.0 percent.
  2. Cap 5. 25 tickets are cut off and 7.5 points are lost. Tight caps look safe and quietly break things.
  3. Caps 10 and 20. Identical results, because no honest run needed more than eight turns. The cap never fires; it exists for the day something loops.

Cost multiplication, shown

The sweep shows quality moving. Cost barely moved in the first block of it, always about 2.2 cents, no matter which failure was removed. That means the cost is structural, so Priya looks at who is getting the bill.

workflow draft 38% policy 23% order 22% fraud 17% $0.0087 a ticket multi-agent supervisor 56% draft 15% order 12% policy 10% fraud 8% $0.0226 a ticket workflow+branch draft 36% order 26% policy 21% fraud 16% $0.0092 a ticket 1 2 3 share of the model bill, 200 simulated tickets (rounded; bars are scaled to 100%)
Fig. 9b.10 — Who gets the model bill, across 200 simulated tickets. In the team, the supervisor alone takes 56 percent.
  1. The supervisor's share. The grey block is the supervisor: 56 percent of the team's bill, more than the four workers combined. The workers' blocks, 15, 12, 10 and 8 percent, are each smaller than any single workflow step.
  2. The workflow's bill. Four steps share the bill fairly evenly, 38, 23, 22 and 17 percent. The draft step is biggest because its answer is longest, and output tokens cost five times more than input tokens.
  3. Dollars per ticket. The workflow costs $0.0087, the team $0.0226, 2.6 times as much. The branch variant on the third bar is introduced in section 05; note only that it costs $0.0092.

"Two and a half times of a fraction of a cent. Who cares? That is $20 a month."

— the CFO, glancing at the bar chart

On this task, at this volume, with these simulated prices, the CFO is right: the model bill is $12 a month for the workflow and $32 for the team. Section 05 shows the real money is elsewhere, in the people who fix wrong tickets.

The honest downside of that argument: costs scale with how much context each step reads. Real tool outputs are hundreds of tokens, not twenty, and the hood below shows the boss's reads growing to about three times the instruction-only bill in that case. Cheap in a toy can be expensive in production.

The math behind the boss's bill — optional depth

Suppose the supervisor speaks n times. Each time it reads a fixed instruction block of S tokens, plus everything on the whiteboard so far. If each completed step adds m tokens to the whiteboard, then before turn k (counting from zero) the whiteboard holds k × m tokens.

Total tokens the supervisor reads: Σk=0..n−1 (S + k × m) = n × S + m × n(n − 1) / 2.

Symbol key: Σ (sigma) means "add up", S is the instruction size, m the tokens added per step, n the number of supervisor turns, k the turn number counting from zero, and n(n − 1)/2 is the sum 0 + 1 + … + (n − 1).

Here, S = 600 and a step adds about 15 tokens, so with n = 6 the boss reads 6 × 600 + 15 × 15 = 3,825, close to the measured 3,963. The instruction block dominates, which is why the boss costs more than any worker. Now let each step add a realistic 500-token tool result: 3,600 + 500 × 15 = 11,100 tokens, about 3.1 times larger. The second term grows with the square of the turn count, so long conversations get expensive fast.

workflow slips 25 missing 21 46 failed multi-agent slips 25 route 5 gave up 8 39 failed workflow+branch slips 25 25 failed 1 2 3 model slip missing data supervisor mis-route gave up or looped failed tickets out of 200, same cases and same dice for every build
Fig. 9b.11 — Why the 200 tickets failed, by cause, for each build. The model's own slips are the same 25 in every bar. The architecture decides what else you add.
  1. The workflow's extra failures. Of its 46 failures, 21 come from missing data: the split shipment it cannot re-query. The other 25 are plain model slips in one step.
  2. The team's new failures. Missing data nearly disappears (1 ticket), but the team adds 5 supervisor mis-routes and 8 tickets that ended with no decision. Those 13 are failures the workflow cannot have, because it has no supervisor to slip.
  3. The 25 slips. Model slips are the same 25 in all three bars because every build uses the same seeded dice for its workers. Architecture does not change how often a worker slips. It changes everything else around it.

That figure is blame assignment, working. A support lead who asked "why did the team fail 39 tickets?" would otherwise hear only "the AI got it wrong". With the labels, the answer is specific: 25 model slips, 13 coordination failures, and one data gap. The 13 are the price of the team, and the 25 slips are the price of using a model at all.

Fireside chat

Tonight's talk: the Workflow and the Supervisor argue over the question, "Who should decide what happens next?"

The Workflow
The Supervisor

I decide next in zero model calls. My order is written in code, I read 1,637 tokens a ticket where you read 6,187, and I never say "done" before anyone has worked, which you did on two of the first forty tickets.

The workflow costs nothing to route and cannot stop early. The figures are the token totals in Fig. 9b.6 and the two calls=1 rows in chunk 4's output.

And I noticed that ticket #1 was missing its delivery date and sent the order worker back for shipment 2. You would have guessed. On the split shipments, you were right 57 percent of the time and I was right 91 percent. Your fixed path cannot ask a second question.

The supervisor's flexibility is real: it repairs incomplete data. The two percentages are measured in section 05.

On the other 144 tickets I beat you, 84.7 percent to 76.4. Every time you are not needed, you are a coin-flip with a 5 percent mis-route rate and a six-hundred-token invoice.

Where the path never varies, the supervisor only adds risk. The two percentages are the normal-ticket slice in section 05.

Fair. Then maybe nobody should be paying me on the normal tickets. We will revisit this when we see what the numbers say about a third option.

Foreshadowing: section 05 tests a workflow with one if-statement for the split-shipment case.

Questions you might be asking now

The shared whiteboard, the boss's bill and the hand-off loss are the three ideas people most often ask to see slowed down. Every answer below uses the same ticket: split shipment #1, amount $210.36, delivered 7 days ago, fraud score 0.02, right answer approve. Its whole run is the table below.

Ticket #1 through the team: eleven model calls (simulated; from the trace saved by compare.py)
CallWhoTokens inTokens out
1supervisor60823
2order32980
3supervisor63820
4order (second lookup)35756
5supervisor66725
6policy52029
7supervisor67426
8fraud43127
9supervisor68411
10draft587124
11supervisor69217
"What exactly is the 'shared state'? Is it a database?"

No. It is one Python dictionary, TeamState, passed from step to step in memory. Its main field, the whiteboard, is just a growing string. It becomes durable only if you attach a checkpointer, which saves it to SQLite or Postgres after each step.

Here is ticket #1's dictionary at the moments that matter. Only three fields change in an interesting way, and the whiteboard is measured in characters:

TeamState on ticket #1 after selected steps
AfterWhiteboard charactershopsnextsecondary
start320(empty)False
boss turn 1431orderFalse
order worker1551orderFalse
boss turn 21762orderTrue
order worker again2702orderTrue
boss turn 63786doneFalse
  1. Start. The whiteboard holds only the task line, 32 characters. Nothing has been decided.
  2. Boss turn 1. The boss appends "NEXT order" and raises hops to 1. The order worker then appends the raw lookup and a summary, jumping the board to 155 characters.
  3. Boss turn 2. The summary says "complete=no", so the boss appends "NEXT order secondary". The word "secondary" flips the flag to True, which tells the order worker to fetch shipment 2.
  4. Boss turn 6. After the draft, the whiteboard is 378 characters, about 95 tokens. The boss writes "NEXT done" and the graph ends.

The honest limit: 378 characters is tiny here. Real whiteboards hold full tool outputs and grow into thousands of tokens. The structure is the same, only the size changes.

Shared state is a dictionary every agent can read and write. It is only as durable as the checkpointer you attach.

"Why does the boss cost more than the workers? It only writes one word."

Because the boss is billed for what it reads, not what it writes. It is called six times on this ticket, each time with a 600-token instruction block plus the whole whiteboard, so it reads more in total than the five workers. Its one-word answers cost almost nothing.

  1. Boss reads. 608 + 638 + 667 + 674 + 684 + 692 = 3,963 tokens in.
  2. Workers read. 329 + 357 + 520 + 431 + 587 = 2,224 tokens in.
  3. Boss dollars. 3,963 tokens × $3 per million = $0.01189. Its 122 output tokens × $15 per million = $0.00183. Total $0.01372.
  4. Worker dollars. 2,224 × $3 per million = $0.00667. Their 316 output tokens × $15 per million = $0.00474. Total $0.01141.
  5. Share. $0.01372 + $0.01141 = $0.02513. The boss's share is 0.01372 / 0.02513 = 54.6 percent.
Boss and workers on ticket #1, side by side
CallsTokens inTokens outDollars
Supervisor63,963122$0.01372
Workers52,224316$0.01141

The honest limit: across all 200 tickets the boss's share is 56 percent, so this ticket is typical. A cheaper model for the boss would shrink the number, and nothing in this simulation prevents you from trying it.

You pay for reading, and the boss reads the whole story every turn.

"How can a model lose its own message? What is a 'garbled hand-off'?"

In the simulation, a worker's summary sometimes comes out as just "POLICY [summary lost]", 4 percent of the time. In real systems it happens when a summary is too short, when the context is trimmed to fit, or when a tool result is dropped. The next reader sees a gap and either guesses or asks again.

  1. The slip. On some ticket the policy worker answers correctly, but the whiteboard receives "POLICY [summary lost]".
  2. The boss's check. It looks for the text "POLICY ok=". It is absent, so the rule says "NEXT policy" again.
  3. The repeat. The boss is called again (about $0.0024 at ~700 tokens in) and the policy worker runs again (about $0.0020). One lost line costs about $0.0044 and about two seconds.

The measured effect: with no garbled hand-offs the team's success rose from 80.5 to 82.0 percent and its calls fell from 9.9 to 9.5 per ticket. Loss is mostly a cost problem here, because the supervisor notices and re-asks.

The honest limit: a real loss often does not announce itself. If a summary silently drops "days=7" instead of the whole line, nothing tells the boss to re-ask, and the next agent guesses. That quieter case is the dangerous one, and the simulation is deliberately kind about it.

A lost fact either costs a repeat call or, worse, a confident guess.

Quick reference — The team and how it breaks

Shared state
One whiteboard every agent reads. Good for a boss that must see everything; the bill grows with it.
Message passing
Each step gets only its input. Cheap and clear; each step is blind to the rest.
Supervisor turn
One extra model call per decision, minimum workers + 1 turns.
Context loss
A summary drops a fact. Measured here: −1.5 points, +0.4 calls.
Mis-route
The boss picks the wrong worker or stops early. Measured: −6 points, all 8 "gave up" tickets.
Loop guard
A cap on boss turns, set a little above the longest legitimate path. Cap 3 fails 189 of 200; cap 10 is enough.
Blame assignment
Name the first step that went wrong. In this run: 25 model slips, 13 coordination failures, 1 data gap.
The why that is easy to forget
The boss costs more than the workers because it re-reads everything each turn.

05 · Defend the winnerDefend the Winner With Numbers

Priya has two report cards: Build A at 77.0 percent and Build B at 80.5, at very different prices. Maya's Thursday meeting needs one honest table. First, Priya applies the rule from Module 07: before comparing, read the failures. Fig. 9b.11 already says that 21 of the workflow's 46 failures share one cause.

Defending an architecture means putting every candidate through the same cases, counting success, dollars and seconds, checking whether the gap is bigger than luck, and then reading the failures. The winner is often not the one the room expected.

Error analysis first: one if-statement for the failure the workflow cannot see

The workflow's biggest single failure is not that it lacks a boss. It lacks a second question. Priya gives it exactly one: if the order record says "complete=no", look the order up again with the secondary flag. No supervisor, no extra model call to decide.

Step-by-step: what workflow_branch.py does, in plain English
  1. Import the workflow's own pieces: its state, its ask helper, its four steps and its runner.
  2. order_again is a new step. It looks the order up with secondary=True, asks the order role to summarise, and appends the result to the notes.
  3. The policy step is rewritten to read the newest ORDER note, not the first, so the second lookup wins when there is one.
  4. needs_second_lookup is ordinary code. If the first note says "complete=no" it returns "order_again", otherwise "policy". No model decides this.
  5. Build the graph as before, but replace the order-to-policy edge with a conditional edge, and add an edge from order_again to policy.
  6. The rest of the line is unchanged: policy, fraud, draft, END.
  7. The demo runs all 200 tickets and prints one summary line.
workflow_branch.pyruns offline (simulated)
# workflow_branch.py: the workflow plus ONE if-statement for the case that beat it (split shipments).
# Install: uv pip install "langgraph>=1.0,<2"       (needs fake_world.py and refund_workflow.py)
from langgraph.graph import END, START, StateGraph

from fake_world import FakeLLM, lookup_order, make_cases
from refund_workflow import State, ask, make_nodes, run_all, totals


def build_workflow_with_branch(llm):
    nodes = make_nodes(llm)

    def order_again(s):                                     # ask the order system for shipment 2
        text, call = ask(llm, s, "order_again", "order", lookup_order(s["case"], secondary=True))
        return {"notes": [text], "calls": [call]}

    def policy(s):                                          # read the NEWEST ORDER line, not the first
        newest = [n for n in s["notes"] if n.startswith("ORDER")][-1]
        text, call = ask(llm, s, "policy", "policy", newest)
        return {"notes": [text], "calls": [call]}

    def needs_second_lookup(s):                             # plain code decides; no supervisor, no model call
        return "order_again" if "complete=no" in s["notes"][0] else "policy"

    g = StateGraph(State)
    for name, fn in {**nodes, "order_again": order_again, "policy": policy}.items():
        g.add_node(name, fn)
    g.add_edge(START, "order")
    g.add_conditional_edges("order", needs_second_lookup, ["order_again", "policy"])
    g.add_edge("order_again", "policy")
    g.add_edge("policy", "fraud")
    g.add_edge("fraud", "draft")
    g.add_edge("draft", END)
    return g.compile()


if __name__ == "__main__":
    t = totals(run_all(build_workflow_with_branch(FakeLLM()), make_cases()))
    print(f"WORKFLOW + ONE BRANCH: success {t['success']:.1%}, ${t['usd_per_case']:.4f} per case, "
          f"${t['usd_per_success']:.4f} per success, {t['secs_mean']:.2f}s mean, {t['calls']:.1f} calls")
output
WORKFLOW + ONE BRANCH: success 87.5%, $0.0092 per case, $0.0105 per success, 6.47s mean, 4.3 calls

Read the output. The workflow with one branch is right on 87.5 percent, better than the team's 80.5, for $0.0092 a ticket instead of $0.0226, and 4.3 calls instead of 9.9. The conditional edge is the same add_conditional_edges call the team used, but the function that picks the arrow is two lines of ordinary code instead of a paid model call.

Be careful with that result, because Priya designed the branch after looking at the 200 tickets it is now scored on. That is the kind of tuning that flatters a number. The honest check, a fresh set of tickets the branch never saw, comes later in this section.

The comparison harness, in three chunks

Three builds now exist. The harness runs all three on the same tickets with the same dice, keeps one trace of each for section 06, and prints the table Maya asked for.

Here is the data flow of the harness before the code, with the real files and numbers of this chapter on it:

make_cases(seed=7) 200 tickets workflow 4.0 calls a ticket multi-agent 9.9 calls a ticket workflow+branch 4.3 calls a ticket score + blame + bill 600 rows (200 x 3) the table (show) results.json traces/*.json 1 2 3 4 chunk 1 builds all of this; chunk 2 prints the table; chunk 3 adds the money and blame lines
Fig. 9b.12 — The comparison harness as data flow: 200 tickets go through three graphs, every run becomes a scored row, and the rows become the outputs Maya sees.
  1. The tickets. make_cases(seed=7) gives all three builds the same 200 tickets. Fairness starts here.
  2. Three graphs. Each build gets its own pretend model on the same seed, so one build cannot use up another's dice. The team makes about 9.9 calls a ticket, the other two about 4.
  3. Rows. Each of the 600 runs becomes one row: right or wrong, tokens, dollars, seconds, a blame label and the bill by role.
  4. Outputs. The printed table, results.json, and one saved call log per build for ticket #1, which section 06 turns into a trace.

Build it in chunks

We build compare.py in three chunks: run all three builds, print the side-by-side table, and add the money and blame lines. Each chunk runs on its own and needs the three files from the earlier ladders plus workflow_branch.py.

  1. Chunk 1 — run all three builds on the same 200 tickets

    Fairness first: same tickets, same seed, same pretend model for every build. If the harness is not fair, no table built on it can be defended.

    Step-by-step: what chunk 1 does, in plain English
    1. Import the three graph builders, the scorer, the blame function and the case generator.
    2. Set two assumptions and label them: a failed ticket costs a person $12.50 (25 minutes at $30 an hour), and ClearOps sees 1,400 tickets a month.
    3. run_both builds the three graphs, each with its own pretend model on the same seed.
    4. For every ticket and every build, it runs the graph, scores the run, labels the failure, and adds up the model bill by role.
    5. When asked to keep a trace, it saves ticket #1's list of model calls as a JSON file for the tracing section.
    6. The demo prints how many tickets each build got right.
    compare.py — chunk 1runs offline (simulated)
    # compare.py: the decision-meeting evidence. Workflow vs multi-agent vs workflow+branch.
    # Install: uv pip install "langgraph>=1.0,<2"
    # Needs fake_world.py, refund_workflow.py, multi_agent_refund.py and workflow_branch.py beside it.
    # ── chunk 1: run all three versions on the same cases and keep one trace each ──
    import json
    import pathlib
    from collections import Counter
    
    from fake_world import FakeLLM, make_cases, price
    from refund_workflow import build_workflow, score, totals
    from multi_agent_refund import build_team, run_team, blame
    from workflow_branch import build_workflow_with_branch
    
    HERE = pathlib.Path(__file__).parent
    HUMAN_FIX_USD = 12.50      # ASSUMPTION: a person fixes each failed ticket: 25 minutes at $30 an hour
    VOLUME = 1400              # refunds a month at ClearOps (module 09)
    
    
    def run_both(cases, seed=7, keep_trace=False):
        graphs = {"workflow": build_workflow(FakeLLM(seed)), "multi-agent": build_team(FakeLLM(seed)),
                  "workflow+branch": build_workflow_with_branch(FakeLLM(seed))}
        rows = {name: [] for name in graphs}
        for c in cases:
            for name, graph in graphs.items():
                if name == "multi-agent":
                    final = run_team(graph, c)
                else:
                    final = graph.invoke({"case": c, "notes": [], "calls": [], "decision": ""})
                row = score(c, final)
                row["blame"] = blame(c, final)
                row["by_role"] = {}
                for call in final["calls"]:
                    usd = price(call["tin"], call["tout"])
                    row["by_role"][call["role"]] = row["by_role"].get(call["role"], 0) + usd
                rows[name].append(row)
                if keep_trace and c.id == 1:                      # keep one split-shipment case as a trace
                    (HERE / "traces").mkdir(exist_ok=True)
                    trace = {"run": name, "case": c.id, "decision": final["decision"], "calls": final["calls"]}
                    (HERE / "traces" / f"{name}_case1.json").write_text(json.dumps(trace, indent=1))
        return rows
    
    
    if __name__ == "__main__":
        rows = run_both(make_cases())
        for name, rs in rows.items():
            print(f"{name:16} right on {sum(r['ok'] for r in rs)} of {len(rs)} cases")

    A loop over a dictionary of graphs, so adding a fourth build means adding one line.

    Run it. Right answers out of 200:

    output
    workflow         right on 154 of 200 cases
    multi-agent      right on 161 of 200 cases
    workflow+branch  right on 175 of 200 cases
  2. Chunk 2 — the side-by-side table, plus the two slices that explain it

    One overall success rate hides the story. Splitting the tickets into normal and split-shipment shows where each build earns its keep, and counting tickets only one build got right shows whether the gap is lopsided.

    Step-by-step: what chunk 2 does, in plain English
    1. show computes the six totals for each build with the same totals function.
    2. It prints one row per metric, with the team-to-workflow ratio in the middle.
    3. Then it prints the success rate for normal tickets and split-shipment tickets separately.
    4. Finally it counts tickets that only the workflow got right and tickets that only the team got right.
    compare.py — chunk 2 (adds to chunk 1)runs offline (simulated)
    # ── chunk 2: the side-by-side table ──
    METRICS = (("success rate", "success", "{:.1%}"), ("$ per case", "usd_per_case", "${:.4f}"),
               ("$ per SUCCESSFUL case", "usd_per_success", "${:.4f}"), ("seconds, mean", "secs_mean", "{:.2f}"),
               ("seconds, p95", "secs_p95", "{:.2f}"), ("model calls per case", "calls", "{:.1f}"))
    
    
    def show(rows):
        w, m, b = (totals(rows[k]) for k in ("workflow", "multi-agent", "workflow+branch"))
        print(f"{'metric (200 simulated cases)':30} {'workflow':>10} {'multi-agent':>12} {'ratio':>7} {'wf+branch':>10}")
        for label, key, fmt in METRICS:
            ratio = m[key] / w[key]
            cells = f"{fmt.format(w[key]):>10} {fmt.format(m[key]):>12} {ratio:>6.1f}x {fmt.format(b[key]):>10}"
            print(f"{label:30} {cells}")
        for name, odd in (("normal cases", False), ("split-shipment cases", True)):
            part = {k: [r for r in rows[k] if r["odd"] == odd] for k in rows}
            cells = "   ".join(f"{k} {sum(r['ok'] for r in v) / len(v):.1%}" for k, v in part.items())
            print(f"{name:22} n={len(part['workflow']):<3} {cells}")
        pairs = list(zip(rows["workflow"], rows["multi-agent"]))
        only_w = sum(a["ok"] and not b["ok"] for a, b in pairs)
        only_m = sum(b["ok"] and not a["ok"] for a, b in pairs)
        print(f"cases only the workflow got right: {only_w}   only the multi-agent got right: {only_m}")
    
    
    if __name__ == "__main__":
        show(run_both(make_cases()))

    Pairing two lists with zip to compare the same ticket across builds.

    Run it. This is the table for the meeting:

    output
    metric (200 simulated cases)     workflow  multi-agent   ratio  wf+branch
    success rate                        77.0%        80.5%    1.0x      87.5%
    $ per case                        $0.0087      $0.0226    2.6x    $0.0092
    $ per SUCCESSFUL case             $0.0113      $0.0280    2.5x    $0.0105
    seconds, mean                        6.02        12.10    2.0x       6.47
    seconds, p95                        13.08        21.33    1.6x      13.58
    model calls per case                  4.0          9.9    2.5x        4.3
    normal cases           n=144 workflow 84.7%   multi-agent 76.4%   workflow+branch 84.7%
    split-shipment cases   n=56  workflow 57.1%   multi-agent 91.1%   workflow+branch 94.6%
    cases only the workflow got right: 15   only the multi-agent got right: 22
  3. Chunk 3 — the money line and the blame lines

    The model bill is tiny. What a finance lead wants is the all-in price of a ticket, including the person who fixes each wrong one. Chunk 3 adds that, the bill by role and the failure labels.

    Step-by-step: what chunk 3 does, in plain English
    1. For each build, all-in cost per ticket is the model bill plus the failure rate times $12.50.
    2. It also prints the monthly model bill and monthly people cost at 1,400 tickets.
    3. It adds each role's dollars across the 200 tickets and prints each role's share of the bill.
    4. It counts the blame labels for each build.
    5. The final demo runs everything, keeps the trace, and saves the totals to results.json.
    compare.py — chunk 3 (adds to chunks 1 and 2)runs offline (simulated)
    # ── chunk 3: the numbers a finance person asks for: all-in cost, who got the bill, who to blame ──
    def show_money_and_blame(rows):
        print("-- all-in cost: model bill + a person fixing every failed ticket --")
        for name, rs in rows.items():
            t = totals(rs)
            failed = 1 - t["success"]
            allin = t["usd_per_case"] + failed * HUMAN_FIX_USD
            model_month = t["usd_per_case"] * VOLUME
            people_month = failed * VOLUME * HUMAN_FIX_USD
            print(f"{name:16} ${allin:.2f} per ticket  | model ${model_month:,.0f} + people ${people_month:,.0f} "
                  f"per month at {VOLUME} tickets")
        for name, rs in rows.items():
            spend = {}
            for r in rs:
                for role, usd in r["by_role"].items():
                    spend[role] = spend.get(role, 0) + usd
            whole = sum(spend.values())
            share = {k: f"{v / whole:.0%}" for k, v in sorted(spend.items(), key=lambda x: -x[1])}
            print(f"bill by role, {name}:", share)
        calls = Counter(r["calls"] for r in rows["multi-agent"])
        print("multi-agent model calls per ticket:", dict(sorted(calls.items())))
        for name, rs in rows.items():
            print(f"blame, {name}:", dict(Counter(r["blame"] for r in rs if r["blame"])))
    
    
    if __name__ == "__main__":
        rows = run_both(make_cases(), keep_trace=True)
        show(rows)
        show_money_and_blame(rows)
        (HERE / "results.json").write_text(json.dumps({k: totals(v) for k, v in rows.items()}, indent=1))

    collections.Counter to tally labels.

    Run it. The first block is the table again. The new lines are below it:

    output (the lines chunk 3 adds)
    -- all-in cost: model bill + a person fixing every failed ticket --
    workflow         $2.88 per ticket  | model $12 + people $4,025 per month at 1400 tickets
    multi-agent      $2.46 per ticket  | model $32 + people $3,412 per month at 1400 tickets
    workflow+branch  $1.57 per ticket  | model $13 + people $2,188 per month at 1400 tickets
    bill by role, workflow: {'draft': '38%', 'policy': '23%', 'order': '22%', 'fraud': '17%'}
    bill by role, multi-agent: {'supervisor': '56%', 'draft': '15%', 'order': '12%', 'policy': '10%', 'fraud': '8%'}
    bill by role, workflow+branch: {'draft': '36%', 'order': '26%', 'policy': '21%', 'fraud': '16%'}
    multi-agent model calls per ticket: {1: 3, 3: 1, 5: 2, 7: 1, 9: 110, 11: 63, 13: 16, 15: 4}
    blame, workflow: {'model slip in draft': 7, 'missing data (split shipment)': 21, 'model slip in fraud': 3, 'model slip in policy': 12, 'model slip in order': 3}
    blame, multi-agent: {'model slip in draft': 7, 'gave up or looped (no decision)': 8, 'model slip in fraud': 2, 'model slip in policy': 14, 'supervisor mis-route': 5, 'missing data (split shipment)': 1, 'model slip in order': 2}
    blame, workflow+branch: {'model slip in draft': 8, 'model slip in fraud': 3, 'model slip in policy': 13, 'model slip in order': 1}

The whole program

Chunk 1 is the imports, the two assumptions and run_both. Chunk 2 is show. Chunk 3 is show_money_and_blame and the final demo that calls everything.

compare.pyruns offline (simulated)
# compare.py: the decision-meeting evidence. Workflow vs multi-agent vs workflow+branch.
# Install: uv pip install "langgraph>=1.0,<2"
# Needs fake_world.py, refund_workflow.py, multi_agent_refund.py and workflow_branch.py beside it.
# ── chunk 1: run all three versions on the same cases and keep one trace each ──
import json
import pathlib
from collections import Counter

from fake_world import FakeLLM, make_cases, price
from refund_workflow import build_workflow, score, totals
from multi_agent_refund import build_team, run_team, blame
from workflow_branch import build_workflow_with_branch

HERE = pathlib.Path(__file__).parent
HUMAN_FIX_USD = 12.50      # ASSUMPTION: a person fixes each failed ticket: 25 minutes at $30 an hour
VOLUME = 1400              # refunds a month at ClearOps (module 09)


def run_both(cases, seed=7, keep_trace=False):
    graphs = {"workflow": build_workflow(FakeLLM(seed)), "multi-agent": build_team(FakeLLM(seed)),
              "workflow+branch": build_workflow_with_branch(FakeLLM(seed))}
    rows = {name: [] for name in graphs}
    for c in cases:
        for name, graph in graphs.items():
            if name == "multi-agent":
                final = run_team(graph, c)
            else:
                final = graph.invoke({"case": c, "notes": [], "calls": [], "decision": ""})
            row = score(c, final)
            row["blame"] = blame(c, final)
            row["by_role"] = {}
            for call in final["calls"]:
                usd = price(call["tin"], call["tout"])
                row["by_role"][call["role"]] = row["by_role"].get(call["role"], 0) + usd
            rows[name].append(row)
            if keep_trace and c.id == 1:                      # keep one split-shipment case as a trace
                (HERE / "traces").mkdir(exist_ok=True)
                trace = {"run": name, "case": c.id, "decision": final["decision"], "calls": final["calls"]}
                (HERE / "traces" / f"{name}_case1.json").write_text(json.dumps(trace, indent=1))
    return rows


# ── chunk 2: the side-by-side table ──
METRICS = (("success rate", "success", "{:.1%}"), ("$ per case", "usd_per_case", "${:.4f}"),
           ("$ per SUCCESSFUL case", "usd_per_success", "${:.4f}"), ("seconds, mean", "secs_mean", "{:.2f}"),
           ("seconds, p95", "secs_p95", "{:.2f}"), ("model calls per case", "calls", "{:.1f}"))


def show(rows):
    w, m, b = (totals(rows[k]) for k in ("workflow", "multi-agent", "workflow+branch"))
    print(f"{'metric (200 simulated cases)':30} {'workflow':>10} {'multi-agent':>12} {'ratio':>7} {'wf+branch':>10}")
    for label, key, fmt in METRICS:
        ratio = m[key] / w[key]
        cells = f"{fmt.format(w[key]):>10} {fmt.format(m[key]):>12} {ratio:>6.1f}x {fmt.format(b[key]):>10}"
        print(f"{label:30} {cells}")
    for name, odd in (("normal cases", False), ("split-shipment cases", True)):
        part = {k: [r for r in rows[k] if r["odd"] == odd] for k in rows}
        cells = "   ".join(f"{k} {sum(r['ok'] for r in v) / len(v):.1%}" for k, v in part.items())
        print(f"{name:22} n={len(part['workflow']):<3} {cells}")
    pairs = list(zip(rows["workflow"], rows["multi-agent"]))
    only_w = sum(a["ok"] and not b["ok"] for a, b in pairs)
    only_m = sum(b["ok"] and not a["ok"] for a, b in pairs)
    print(f"cases only the workflow got right: {only_w}   only the multi-agent got right: {only_m}")


# ── chunk 3: the numbers a finance person asks for: all-in cost, who got the bill, who to blame ──
def show_money_and_blame(rows):
    print("-- all-in cost: model bill + a person fixing every failed ticket --")
    for name, rs in rows.items():
        t = totals(rs)
        failed = 1 - t["success"]
        allin = t["usd_per_case"] + failed * HUMAN_FIX_USD
        model_month = t["usd_per_case"] * VOLUME
        people_month = failed * VOLUME * HUMAN_FIX_USD
        print(f"{name:16} ${allin:.2f} per ticket  | model ${model_month:,.0f} + people ${people_month:,.0f} "
              f"per month at {VOLUME} tickets")
    for name, rs in rows.items():
        spend = {}
        for r in rs:
            for role, usd in r["by_role"].items():
                spend[role] = spend.get(role, 0) + usd
        whole = sum(spend.values())
        share = {k: f"{v / whole:.0%}" for k, v in sorted(spend.items(), key=lambda x: -x[1])}
        print(f"bill by role, {name}:", share)
    calls = Counter(r["calls"] for r in rows["multi-agent"])
    print("multi-agent model calls per ticket:", dict(sorted(calls.items())))
    for name, rs in rows.items():
        print(f"blame, {name}:", dict(Counter(r["blame"] for r in rs if r["blame"])))


if __name__ == "__main__":
    rows = run_both(make_cases(), keep_trace=True)
    show(rows)
    show_money_and_blame(rows)
    (HERE / "results.json").write_text(json.dumps({k: totals(v) for k, v in rows.items()}, indent=1))

Read the table the way Maya will. The team beats the plain workflow on success by 3.5 points (80.5 against 77.0) and costs 2.6 times as much per ticket and 2.0 times as long. The workflow with one branch beats both: 87.5 percent, for about the same money and time as the plain workflow. The ratio column compares the team against the plain workflow only, by design.

1 SUCCESS RATE, higher is better 77.0% workflow 80.5% multi-agent 87.5% wf+branch 2 ALL-IN $ PER TICKET, lower is better $2.88 workflow $2.46 multi-agent $1.57 wf+branch 3 SECONDS PER TICKET, lower is better 6.02s workflow 12.10s multi-agent 6.47s wf+branch whisker: range over 5 dice seeds green bar: best in the panel
Fig. 9b.13 — The three numbers Maya asked for, for all three builds, on the same 200 simulated tickets. Green marks the best bar in each panel.
  1. Success rate. 77.0, 80.5 and 87.5 percent. The black whiskers show the lowest and highest result over five different dice seeds: 75.5 to 81.5, 78.0 to 85.5 and 84.5 to 92.0. The workflow and team whiskers overlap heavily. The branch whisker sits almost entirely above both.
  2. All-in dollars per ticket. $2.88, $2.46 and $1.57, once a person fixing each failed ticket at $12.50 is counted. The team looks better than the plain workflow here, only because it fails less often, and the branch variant is cheapest by a wide margin.
  3. Seconds per ticket. 6.02, 12.10 and 6.47. The team takes twice as long because its calls run one after another and it makes 9.9 of them. The branch adds half a second for the tickets that need a second lookup.
workflow people $4,025 model $12 about $4,037 a month multi-agent people $3,412 model $32 about $3,444 a month workflow+branch people $2,188 model $13 about $2,201 a month 1 2 3 1,400 tickets a month; a failed ticket costs a person $12.50 (assumption)
Fig. 9b.14 — What each build costs ClearOps in a month at 1,400 tickets, counting the people who fix failed tickets at $12.50 each.
  1. Workflow. The model bill is the $12 sliver at the left. People fixing 322 failed tickets cost $4,025.
  2. Team. $32 of model bill, but only 273 failures, so $3,412 of people. Its extra model cost is repaid several times over by fewer failures.
  3. Workflow plus branch. $13 of model bill and 175 failures, $2,188 of people: roughly half the workflow's monthly cost.

Now look at where the team's wins and losses are. On the 144 normal tickets, the workflow gets 84.7 percent and the team 76.4: the boss only adds risk where the path never varies. On the 56 split shipments, the workflow gets 57.1 percent, the team 91.1, and the branch 94.6. The team's whole advantage lives in 28 percent of the tickets, and one if-statement captures it.

1 NORMAL TICKETS (n = 144) 84.7% workflow 76.4% multi-agent 84.7% wf+branch 2 SPLIT SHIPMENTS (n = 56) 57.1% workflow 91.1% multi-agent 94.6% wf+branch green bar: best in the panel
Fig. 9b.15 — Success by ticket type. The team's whole advantage lives in the 28 percent of tickets that are split shipments.
  1. Normal tickets. The workflow gets 84.7 and the team 76.4. Where the path never varies, the boss only adds risk.
  2. Split shipments. Workflow 57.1 (the pencil exercise predicted about 57), team 91.1, workflow with one branch 94.6.

Is the gap real, or luck?

The team's lead over the plain workflow is 3.5 points. Before Priya puts that on a slide, she asks the question Module 07 taught her to ask of any measurement: how much would this move if I ran it again?

Two cheap checks answer it. The first reruns the harness with five different dice seeds on the same tickets. The second runs the three builds on 200 brand-new tickets (seed 99), which the branch's designer never looked at, and computes a paired luck test on the original run.

Step-by-step: what compare_repeat.py and holdout_and_noise.py do, in plain English
  1. compare_repeat.py loops over seeds 7 to 11, runs all three builds with each, and prints the success rate and dollars per success for each.
  2. holdout_and_noise.py first makes 200 new tickets with a different seed and runs all three builds on them.
  3. It then reruns the original tickets and computes the standard error of the team-minus-workflow gap: the square root of the sum of the two variances.
  4. It counts the tickets that only one build got right, then asks how likely a split at least this lopsided would be if the two builds were equally good. That is a coin-flip calculation, an exact binomial tail.
compare_repeat.pyruns offline (simulated)
# compare_repeat.py: how much of the gap is luck? Same 200 cases, five different dice seeds.
# Install: uv pip install "langgraph>=1.0,<2"
from fake_world import make_cases
from compare import run_both
from refund_workflow import totals

cases = make_cases()
print("seed  success: workflow / multi-agent / workflow+branch    dollars per success: same order")
for seed in range(7, 12):
    rows = run_both(cases, seed)
    t = [totals(rows[k]) for k in ("workflow", "multi-agent", "workflow+branch")]
    success = " / ".join(f"{x['success']:.1%}" for x in t)
    dollars = " / ".join(f"${x['usd_per_success']:.4f}" for x in t)
    print(f"{seed:<5} {success}        {dollars}")
output
seed  success: workflow / multi-agent / workflow+branch    dollars per success: same order
7     77.0% / 80.5% / 87.5%        $0.0113 / $0.0280 / $0.0105
8     81.5% / 83.0% / 88.5%        $0.0106 / $0.0270 / $0.0103
9     75.5% / 82.5% / 84.5%        $0.0114 / $0.0271 / $0.0108
10    79.0% / 78.0% / 86.0%        $0.0109 / $0.0285 / $0.0106
11    81.0% / 85.5% / 92.0%        $0.0106 / $0.0265 / $0.0099
holdout_and_noise.pyruns offline (simulated)
# holdout_and_noise.py: two honesty checks. (1) fresh cases the branch was never tuned on. (2) is 22 vs 15 just luck?
# Install: uv pip install "langgraph>=1.0,<2"
from math import comb, sqrt

from compare import run_both
from fake_world import make_cases
from refund_workflow import totals

print("-- 1. held-out: 200 NEW cases (seed 99); the extra branch was designed by looking at seed 7 --")
rows = run_both(make_cases(seed=99))
for name, rs in rows.items():
    t = totals(rs)
    print(f"{name:16} success {t['success']:.1%}   ${t['usd_per_case']:.4f} a case   "
          f"{t['secs_mean']:.2f}s mean")

print("-- 2. noise on the original 200 cases (seed 7) --")
rows = run_both(make_cases())
p_w, p_t = totals(rows["workflow"])["success"], totals(rows["multi-agent"])["success"]
se = sqrt(p_w * (1 - p_w) / 200 + p_t * (1 - p_t) / 200)
print(f"gap team minus workflow = {p_t - p_w:.1%}; its standard error is about {se:.1%}")
only_w = sum(a["ok"] and not b["ok"] for a, b in zip(rows["workflow"], rows["multi-agent"]))
only_t = sum(b["ok"] and not a["ok"] for a, b in zip(rows["workflow"], rows["multi-agent"]))
n = only_w + only_t
tail = sum(comb(n, k) for k in range(max(only_w, only_t), n + 1)) / 2 ** n
print(f"cases that split the two builds: {n} ({only_t} for the team, {only_w} for the workflow)")
print(f"chance of a split at least this lopsided if the builds were equally good: {min(1, 2 * tail):.2f}")
output
-- 1. held-out: 200 NEW cases (seed 99); the extra branch was designed by looking at seed 7 --
workflow         success 78.0%   $0.0087 a case   6.01s mean
multi-agent      success 83.0%   $0.0226 a case   12.19s mean
workflow+branch  success 88.0%   $0.0092 a case   6.47s mean
-- 2. noise on the original 200 cases (seed 7) --
gap team minus workflow = 3.5%; its standard error is about 4.1%
cases that split the two builds: 37 (22 for the team, 15 for the workflow)
chance of a split at least this lopsided if the builds were equally good: 0.32

Read the two outputs. Across five seeds the team beat the plain workflow in four and lost in one (seed 10: 78.0 against 79.0). The branch beat the team in all five, and beat the plain workflow in all five. On fresh tickets the order held: 78.0, 83.0 and 88.0. Fresh tickets matter most, because the branch's 88.0 did not shrink.

The luck test is the sobering part. The team's 3.5-point lead has a standard error of 4.1 points, so it is less than one standard error, which is weak evidence. Of 37 tickets where the builds differed, the team won 22 and the workflow 15. If the builds were equally good, a split that lopsided or more would happen about 32 times in 100. The team's lead over the plain workflow is not established.

70% 75% 80% 85% 90% 95% workflow 1 multi-agent 2 wf+branch 3 one of five dice seeds (seed 7 is the 200-ticket table) square under each row: 200 fresh tickets (seed 99)
Fig. 9b.16 — Success over five dice seeds (circles) and on 200 fresh tickets (square), for each build. Overlap means luck can explain the gap.
  1. Workflow. Seeds range from 75.5 to 81.5; fresh tickets 78.0.
  2. Team. Seeds range from 78.0 to 85.5, overlapping the workflow's range; fresh tickets 83.0.
  3. Workflow plus branch. Seeds range from 84.5 to 92.0. Its worst seed (84.5) beats the team's median (82.5) and the workflow's best (81.5). Fresh tickets 88.0.
Boardroom translation

"We built the team the CEO asked for and the simple version side by side on 200 tickets. The team is no better than the simple version in any way we can prove, and costs 2.6 times as much.

"The simple version plus one extra lookup gets 87.5 percent right, saves about $1.30 a ticket against the plain workflow once fixing mistakes is counted, and costs $13 a month in model fees. We recommend that one. The team stays on the shelf until a task appears where we cannot write the order of steps down."

That last sentence is the useful one. The team did not lose because multi-agent systems are bad. It lost because this task has a known shape with one known exception. Where the shape is genuinely unknown, an open-ended research job or a long chat that changes topic, the table could come out the other way. The method for finding out is exactly what you just ran.

Questions you might be asking now

Four numbers in this section tend to raise eyebrows: the branch that was built after peeking, the "is 3.5 points real" question, dollars per successful ticket, and the $12.50 for a person. Every answer uses the headline numbers of the three builds, shown once here.

Headline numbers on the 200 original simulated tickets (from compare.py)
BuildSuccessModel $ per ticketFailed ticketsAll-in $ per ticket
Workflow77.0%$0.008746$2.88
Team80.5%$0.022639$2.46
Workflow + branch87.5%$0.009225$1.57
"You built the branch after seeing where the workflow failed. Isn't that cheating?"

It is not cheating, because looking at failures and fixing the biggest one is exactly what error analysis is. It does make the 87.5 percent optimistic, because the fix was tuned on the same 200 tickets it is scored on. That is why the fresh-ticket check exists.

  1. The tuned score. On the original 200 tickets the branch scored 87.5 percent.
  2. The fresh score. On 200 new tickets (seed 99) it scored 88.0 percent, against 78.0 for the workflow and 83.0 for the team.
  3. The difference. 88.0 − 87.5 = +0.5 points. No shrinkage.

The honest limit: the fresh tickets come from the same generator, with the same 28-percent split-shipment rate, so this is a weak test. A real held-out set would come from a different month of real tickets, and real fixes do shrink on new data. Keep a held-out set from day one, and never tune on it.

Fixing the biggest failure is good practice; scoring the fix on the data that suggested it is not.

"How do I know 3.5 points isn't just luck? What is a standard error?"

A standard error is the typical size of the wobble you would see if you reran the experiment on fresh tickets. The team's 3.5-point lead is smaller than the wobble, about 4.1 points, so you cannot call it real. You would need roughly 1,100 tickets to see a gap that size clearly.

  1. Each build's wobble. For a success rate p measured on 200 tickets, the variance is p × (1 − p) / 200. Workflow: 0.77 × 0.23 / 200 = 0.000886. Team: 0.805 × 0.195 / 200 = 0.000785.
  2. Add them. The two builds are scored on the same tickets, but this simple version treats them as independent: 0.000886 + 0.000785 = 0.001671.
  3. Square root. √0.001671 = 0.0409, which is 4.1 percentage points. This is the standard error of the gap.
  4. Compare. The gap is 3.5 points, so it is 3.5 / 4.1 = 0.86 standard errors. A gap is usually called clear at about 2.
  5. How many tickets for a clear gap. The wobble shrinks with the square root of the ticket count. To get from 4.1 down to about 1.75 you need 200 × (4.1 / 1.75)² ≈ 1,100 tickets.

The paired view agrees. Of the 37 tickets where the builds disagreed, the team won 22 and the workflow 15. If they were equally good each of those 37 would be a coin flip, and a 22-to-15 split or more lopsided would occur about 32 times in 100.

A difference smaller than its own wobble is a hint, not a result.

"What is 'dollars per successful ticket', and why divide by the right answers only?"

It is the total model bill divided by the number of tickets that came out right. It punishes a system that is cheap but often wrong, because the money spent on wrong tickets is charged to the right ones.

  1. Workflow, per 100 tickets. Bill = 100 × $0.0087 = $0.87. Right answers = 77. $0.87 / 77 = $0.0113 each.
  2. Team. Bill = 100 × $0.0226 = $2.26. Right = 80.5. $2.26 / 80.5 = $0.0281 each.
  3. Branch. Bill = 100 × $0.0092 = $0.92. Right = 87.5. $0.92 / 87.5 = $0.0105 each.

The branch is the cheapest per right answer, even though its bill per ticket is a little higher than the plain workflow's: its extra five cents per hundred tickets buys ten more right answers. The honest limit: this line counts only the model bill. The $12.50 person is the next question.

Divide by what worked, not by what was tried.

"Where did $12.50 per failed ticket come from, and does it change the answer?"

It is an assumption: 25 minutes of a person's time at $30 an hour. It matters a great deal, because the model bill is only cents. Plain arithmetic shows the team beats the plain workflow all-in whenever a failure costs more than about 40 cents.

  1. The person. 25 minutes is 25 / 60 = 0.417 of an hour. 0.417 × $30 = $12.50.
  2. All-in, workflow. $0.0087 + 0.230 failures × $12.50 = $0.0087 + $2.875 = $2.88.
  3. All-in, team. $0.0226 + 0.195 × $12.50 = $0.0226 + $2.4375 = $2.46.
  4. Where the team breaks even. It pays $0.0139 more per ticket in model fees and avoids 3.5 failures in 100, which is 0.035 per ticket. $0.0139 / 0.035 = $0.40. Above that cost per failure the team wins; below it, the workflow does.

The honest limit: the formula assumes every failure is caught and fixed in 25 minutes. Wrong answers that reach a customer cost more, a refund wrongly paid or an angry email. Replace the $12.50 with your own number and rerun compare.py.

The model bill is cents; the failures are dollars. Cost the failures.

Quick reference — Defending an architecture

Same cases, same dice
Every build runs on the same tickets with the same seeded model. Otherwise the comparison cannot be defended.
Three numbers
Success rate, dollars per ticket (and per successful ticket), and seconds per ticket, mean and 95th percentile.
All-in cost
Model bill + failure rate × cost of fixing a failure. Here the assumption is $12.50.
Slice before you conclude
Normal tickets: workflow 84.7, team 76.4. Split shipments: workflow 57.1, team 91.1, branch 94.6.
Noise check
The team's 3.5-point lead has a standard error of 4.1 points. About 1,100 tickets would be needed to see it clearly.
Held-out check
Fresh tickets: workflow 78.0, team 83.0, branch 88.0.
The why that is easy to forget
Read the failures before comparing. They often show a cheaper fix than a bigger architecture.

06 · Tracing a teamSeeing Inside a Team: Traces and Spans

Priya now has numbers but no pictures of a single run. Maya's second question after "which is better?" will be "what happened on the ticket that went wrong?". For a workflow that is a stack of four log lines. For a team it is eleven calls across two kinds of agent, and she needs a way to read them.

A trace is the recorded story of one run. It is split into spans, one per step or model call, each with a start, an end, tokens and cost. Reading a trace is how you find out which agent made a team's mistake.

You know this from distributed tracing: a request enters, calls services, and each hop is a span nested under its parent. A multi-agent run has the same shape. The root span is one ticket. Under it sit the supervisor's turns, and under each turn the model calls for the boss and its worker.

workflow team order policy fraud draft 5.7 s total boss order boss order 2 boss policy boss fraud boss draft boss 11.7 s total 1 2 3 0s 2s 4s 6s 8s 10s 12s one shared clock; calls run one after another, nothing overlaps
Fig. 9b.17 — Ticket #1 on a shared clock. The workflow's four calls take 5.7 seconds. The team's eleven calls, alternating boss and worker, take 11.7. Every grey block is a supervisor call.
  1. The first boss call. Before any work, the team spends 0.83 seconds deciding to start with the order worker. The workflow spent zero seconds on that decision, because the order of steps is in code.
  2. The second order call. The 1.26-second block labelled "order 2" is the extra lookup for shipment 2. The boss noticed the missing date and asked again. This is the call that fixes the split-shipment tickets, and it is also the only part of the long timeline that changed the answer.
  3. The last boss call. After the draft is written, the boss still has to say "done", 0.76 seconds. Six of the eleven blocks are the boss. They add up to 4.8 seconds, which is 41 percent of the ticket's time, spent on deciding rather than doing.

You do not need a server to learn this skill. The script below reads the call log saved by compare.py and prints it as a span tree. The structure is the same one that Langfuse and LangSmith draw in a web page.

Step-by-step: what trace_view.py does, in plain English
  1. Read the JSON file named on the command line: the run name, the ticket, the decision and the list of model calls.
  2. Group the calls by their hop number. A hop is one supervisor turn plus the worker it dispatched.
  3. Add up the dollars and seconds for the whole run and print the root line.
  4. For each hop in order, print a span line with its total seconds.
  5. Under it, print one line per model call: role, tokens in and out, seconds and dollars. Mark any call that slipped.
trace_view.pyruns offline (simulated)
# trace_view.py: print a saved run as a span tree (the shape Langfuse and LangSmith draw). Offline.
# Usage: python trace_view.py traces/multi-agent_case1.json
import json
import sys
from collections import defaultdict

from fake_world import price

trace = json.load(open(sys.argv[1]))
by_hop = defaultdict(list)
for call in trace["calls"]:
    by_hop[call["hop"]].append(call)

total_usd = sum(price(c["tin"], c["tout"]) for c in trace["calls"])
total_secs = sum(c["secs"] for c in trace["calls"])
print(f"TRACE {trace['run']} case {trace['case']} -> {trace['decision']}   "
      f"{len(trace['calls'])} calls  ${total_usd:.4f}  {total_secs:.1f}s")
for hop in sorted(by_hop):
    calls = by_hop[hop]
    print(f"  span hop {hop}  ({sum(c['secs'] for c in calls):.1f}s)")
    for c in calls:
        flag = "   <-- slipped" if c["slipped"] else ""
        usd = price(c["tin"], c["tout"])
        print(f"    llm {c['role']:<10} in={c['tin']:<5} out={c['tout']:<4} {c['secs']:>5.2f}s  ${usd:.4f}{flag}")
output: python trace_view.py traces/multi-agent_case1.json
TRACE multi-agent case 1 -> approve   11 calls  $0.0251  11.7s
  span hop 1  (2.4s)
    llm supervisor in=608   out=23    0.83s  $0.0022
    llm order      in=329   out=80    1.60s  $0.0022
  span hop 2  (2.0s)
    llm supervisor in=638   out=20    0.79s  $0.0022
    llm order      in=357   out=56    1.26s  $0.0019
  span hop 3  (1.8s)
    llm supervisor in=667   out=25    0.87s  $0.0024
    llm policy     in=520   out=29    0.90s  $0.0020
  span hop 4  (1.7s)
    llm supervisor in=674   out=26    0.88s  $0.0024
    llm fraud      in=431   out=27    0.86s  $0.0017
  span hop 5  (2.9s)
    llm supervisor in=684   out=11    0.67s  $0.0022
    llm draft      in=587   out=124   2.27s  $0.0036
  span hop 6  (0.8s)
    llm supervisor in=692   out=17    0.76s  $0.0023
output: python trace_view.py traces/workflow_case1.json
TRACE workflow case 1 -> approve   4 calls  $0.0089  5.7s
  span hop 0  (5.7s)
    llm order      in=318   out=80    1.60s  $0.0022
    llm policy     in=459   out=34    0.96s  $0.0019
    llm fraud      in=354   out=27    0.84s  $0.0015
    llm draft      in=506   out=124   2.26s  $0.0034

Read the two trees. The workflow's trace is one flat span of four calls. The team's trace is six spans, one per supervisor turn, each with a boss call and a worker call except the last, which is the boss alone. The root line carries the totals: 11 calls, $0.0251, 11.7 seconds against 4 calls, $0.0089, 5.7 seconds.

one line of trace_view.py output (ticket 1, team, supervisor turn 3), pulled apart llm 1 kind of span: a model call policy 2 which agent made the call in=520 3 tokens READ: the cost driver out=29 4 tokens WRITTEN: 5x the price 0.90s 5 time this call took (simulated) $0.0020 6 tokens x price in dollars the ticket's cost and time are the sums of these lines; blame starts with the flagged ones
Fig. 9b.18 — One span line from the team's trace, pulled apart. Every dashboard panel in this section is a sum or a count over lines like this.
  1. Kind. "llm" marks a model call, as opposed to a tool call or a node.
  2. Agent. Which role made the call, here the policy worker.
  3. Tokens read. The cost driver. This call read 520 tokens because the whiteboard had grown.
  4. Tokens written. 29 tokens, at five times the per-token price of reading.
  5. Time. 0.90 simulated seconds for this call.
  6. Dollars. 520 in and 29 out at $3 and $15 per million, $0.0020.

Blame assignment is now mechanical. Suppose this ticket had come out wrong. You scan for a <-- slipped flag. If a worker slipped, fix that worker's instructions. If only a boss call slipped, the problem is routing. If no call slipped and the answer is wrong, a fact was missing from the whiteboard, and the span with the second order lookup would be your first suspect.

The next block uses a library, Langfuse, that needs a server you probably do not have running. You are not expected to run it. It is shown so you know how little code the real thing takes, and the offline printer above does the same job for learning.

Step-by-step: what langfuse_tracing.py does, in plain English
  1. Import Langfuse's LangChain callback handler. LangGraph is built on LangChain's callback system, so the same handler works.
  2. Create one handler for this run. It reads its keys from the environment.
  3. Build the team graph and pick ticket #1.
  4. Invoke the graph with the handler in callbacks. Every node, every model call and every tool call becomes a span, nested by step.
  5. Print the decision. The trace itself appears in the Langfuse web page.
langfuse_tracing.pyneeds a Langfuse server or cloud project — not run here
# langfuse_tracing.py: NOT RUN HERE. Needs a Langfuse server or Langfuse Cloud project.
# Install: uv pip install "langfuse>=3,<4" "langgraph>=1.0,<2"
# Needs: LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY and LANGFUSE_HOST in the environment.
from langfuse.langchain import CallbackHandler

from fake_world import FakeLLM, make_cases
from multi_agent_refund import build_team, new_state

handler = CallbackHandler()                         # one handler per run: it opens the trace and the spans
graph = build_team(FakeLLM())
case = make_cases()[1]
final = graph.invoke(new_state(case), {"recursion_limit": 60, "callbacks": [handler]})
print(final["decision"])                            # the trace now shows one span per LangGraph node, nested by step

"My JSON file and a print function did the job. Why would I run a tracing server?"

— the engineer who has never been paged at 3 a.m.

For one run, you wouldn't. A server earns its place when you have thousands of runs a day, want to search for "all tickets where the supervisor took more than 8 turns", compare this week's cost per ticket with last week's, and let a colleague click through a failing run without cloning your repository.

The honest downside: it is another system to host, secure and keep patched, and it receives your prompts, which may hold customer data. Section 08's scorecard applies to it too.

What a dashboard should show for a team

One trace explains one ticket. Maya's operations team will want to know how the whole queue is doing, every day. That is the observability dashboard in the course outline, and for a team it needs a few panels a workflow does not.

A starter dashboard for a multi-agent system, built from the same call log
PanelQuestion it answersWhere the number comes fromExample alert (choose your own)
Success rate on the eval setIs it still right?The nightly run of the scripted casesDown more than 3 points on last week
Dollars per ticket, by roleWho is getting the bill?Tokens per call times price, grouped by roleBoss share above 60 percent
Calls per ticketHas it started looping?Count of call records per traceMean above 1.5 times the baseline (here 9.9)
Supervisor turns, distributionHow close to the cap?Maximum hop per traceAny ticket reaching the cap
Seconds per ticket, p95How slow is the tail?Sum of call seconds per tracep95 above 25 seconds (baseline 21)
Failure mixWhich part to fix first?Blame labels on reviewed failuresAny new label appearing

Read the table once and you will see something. Four of the six panels are cheap to compute from the call log you already keep. The expensive part is the first panel, the evaluation set, because it needs known right answers. That is why Module 07 comes first in the course.

SUCCESS ON THE EVAL SET BILL BY ROLE MODEL CALLS PER TICKET SECONDS PER TICKET FAILURE MIX (39 FAILED) LONGEST RUN 80.5% alert: down more than 3 points 56% 15% 12% 10% boss 56 · draft 15 · order 12 policy 10 · fraud 8 alert: boss share above 60% 7 1-7 110 9 63 11 16 13 4 15 12.10 s mean 21.33 s at the 95th percentile alert: p95 above 25 s slips 25 coord. 13 25 model slips · 13 coordination 1 data gap 8 turns longest run: 15 calls, cap is 10 alert: any run reaching the cap 1 2 3 4 5 6 every panel is a query over the call log kept since day one
Fig. 9b.19 — A six-panel dashboard for the team, filled with the real numbers from the 200-ticket run. Each panel is a query over the call log.
  1. Success. The eval-set pass rate, 80.5 percent. The alert is a drop of more than 3 points on last week.
  2. Bill by role. The boss takes 56 percent. A rise above 60 percent says the whiteboard is growing.
  3. Calls per ticket. Most tickets make 9 calls, 63 make 11, a few make 13 or 15. The early stops on the left (1 to 7 calls) are tickets where the boss said "done" too soon.
  4. Seconds. 12.10 on average, 21.33 at the 95th percentile. The slow tail is what a customer feels.
  5. Failure mix. 25 model slips, 13 coordination failures and 1 data gap, from the blame labels.
  6. Longest run. The longest run was 15 calls, which is 8 boss turns against a cap of 10. A run that reaches the cap is an alert.

Quick reference — Tracing a team

Trace
The recorded story of one run, here one ticket.
Span
One step or model call inside a trace, with start, end, tokens and cost. Spans nest.
Hop
One supervisor turn plus the worker it dispatched. Our trace groups spans by hop.
Reading a trace for blame
Worker slipped: fix that worker. Only the boss slipped: fix routing. Nobody slipped: look for a missing fact on the whiteboard.
Langfuse
Open-source tracing server; LangGraph connects with one callback handler.
Boss time
On ticket #1, six of eleven calls and 41 percent of the seconds.
The why that is easy to forget
Keep the call log from day one. Every dashboard panel is a query over it.

07 · The industry toolsThe Framework Landscape and the Stack, as of October 2026

Priya built both versions on LangGraph. Procurement and the CEO will ask why not CrewAI, why not Microsoft's thing, why not just use the OpenAI SDK. She needs a one-screen answer, and she needs to show that her graphs are not welded to one model vendor.

A multi-agent framework gives you the plumbing: state, routing, retries, tracing hooks. They differ in how much structure they impose, which vendor they favour, and whether they are still actively developed. Pick by the shape of your task and your team's stack, not by the logo.

Six frameworks and plain Python, side by side

Before the table, one fact check that changes real decisions. Tutorials still teach AutoGen as the default multi-agent library. Priya looks up its current status instead of trusting them.

As of October 2026, AutoGen is in maintenance mode. Its repository says it will get critical bug fixes and security patches but no significant new features, and it recommends the Microsoft Agent Framework for new work. That framework combines AutoGen's agent abstractions with Semantic Kernel's enterprise features and a graph-based workflow engine, and Microsoft announced its 1.0 release in April 2026. Existing AutoGen code keeps working; new projects should not start on it.

Multi-agent frameworks, October 2026. Versions and dates are from vendor pages and should be re-checked before you commit.
FrameworkMental modelMulti-agent primitiveHonest weaknessChoose when
LangGraph 1.xState machine: nodes, edges, shared stateConditional edges, Send fan-out, subgraphs, checkpointerMore code to write; a learning curve for graph thinkingYou need resumable runs, human approval gates, or exact control of the path
CrewAI 1.15.xA crew of role-playing agents with tasks; Flows for deterministic controlSequential or hierarchical processes; Crews called from FlowsRole and backstory prompts hide what is actually sent; dependency-heavy installYou want a role-based prototype fast and the tasks fit "a crew with a manager"
Microsoft Agent Framework 1.0Typed graph workflows plus agents, Python and .NETWorkflows with executors and edges; AutoGen-style teamsNewer, so fewer community examples; single-process focus at launchA Microsoft or .NET shop, or you are migrating from AutoGen or Semantic Kernel
AutoGenConversing agents, event-driven coreGroup chats and teamsMaintenance mode: no new featuresOnly to keep existing code alive
OpenAI Agents SDKAgents that hand off to agents, with guardrails and tracing built inHandoffs (replaced the experimental Swarm)Designed around OpenAI models and still before 1.0 in mid-2026, so APIs moveYou are already on OpenAI and the task is routing between specialists
Claude Agent SDKThe Claude Code agent loop as a library, with built-in toolsSubagents that run in their own contextBuilt around Claude; tool-heavy coding-style agents are its home groundYour agents read and edit files or run commands, on Claude
Google ADKAgents composed as sequential, parallel and loop workflowsSub-agents and workflow agents; Python, TypeScript, Go and JavaSmoothest on Google Cloud and GeminiYou are on Google Cloud, or need Go or Java
Plain PythonFunctions calling functionsWhatever you writeYou rebuild retries, checkpoints and tracing yourselfFewer than about five steps, no pauses, no resume: our workflow is nearly this

One pattern in that table is worth saying plainly. CrewAI's guidance, as summarised in several 2026 guides, is to start production applications with a Flow, its name for a deterministic, event-driven workflow, and to call a Crew from inside a Flow step. If that summary is right, the makers of the best-known "team of agents" library also say to use a workflow first, which matches this chapter's result.

Can you write the order of the steps down? yes Plain Python or a LangGraph workflow no Must runs pause, resume, or wait for a human? yes LangGraph with a checkpointer no A .NET shop, or migrating from AutoGen? yes Microsoft Agent Framework no All on OpenAI, and the job is routing? yes OpenAI Agents SDK no Agents edit files or run shell, on Claude? yes Claude Agent SDK no On Google Cloud, or need Go or Java? yes Google ADK no A role-based demo by Friday? yes CrewAI (in its own venv) no None of these? yes LangGraph, then measure 1 2 3
Fig. 9b.20 — A framework chooser. Read down, take the first question you answer yes to. It is a starting point, not a verdict.
  1. The first question. "Can you write the order down?" comes before any framework question. If yes, you do not need a team at all.
  2. The pause question. Runs that must pause for a person, or resume after a crash, are where LangGraph's checkpointer and interrupts are built to help.
  3. CrewAI sits late. It fits a role-based demo well. It is late in the chain here because it is heavy to install and the cost and token accounting are harder to see.

The one CrewAI snippet, and why it is not run here

Priya would like to prove the CrewAI claim by running it. First she checks whether installing it would damage the course environment.

A dry run of uv pip install crewai into the course environment showed it would downgrade three packages the rest of the course relies on: openai from 3.3.0 to 2.54.0, pydantic from 2.13.5 to 2.12.5, and several OpenTelemetry packages. The course environment has to stay intact, so CrewAI was not installed. The snippet below is therefore not run here. Run it in a fresh virtual environment.

Step-by-step: what crew_refund.py does, in plain English
  1. Import CrewAI's four building blocks: Agent, Task, Crew and Process.
  2. Create two agents. Each has a role, a goal, a backstory (extra instructions that shape its voice) and a model string.
  3. Create two tasks. Each says what to do, what shape the answer should take, and which agent does it. The text {ticket} is filled in at kick-off.
  4. Assemble a crew. Process.sequential runs the tasks in order, passing earlier results to later ones. That is the pipeline pattern from Fig. 9b.2.
  5. kickoff runs the crew with the ticket text and returns the final result.
crew_refund.pyneeds API key — not run here (CrewAI conflicts with the course environment)
# crew_refund.py: NOT RUN HERE. CrewAI is not installed in the course environment.
# Install (in a separate virtual environment): uv pip install "crewai>=1.15,<2"
# Needs: a model key, for example ANTHROPIC_API_KEY, and a model string in CrewAI's "provider/model" form.
from crewai import Agent, Crew, Process, Task

MODEL = "anthropic/claude-sonnet-5"

order = Agent(role="Order clerk", goal="Summarise the order record in one line",
              backstory="You read order systems all day.", llm=MODEL)
policy = Agent(role="Policy checker", goal="Say whether the refund window of 30 days is met",
               backstory="You know the refund policy by heart.", llm=MODEL)

t1 = Task(description="Summarise this order: {ticket}", expected_output="ORDER amount=... days=...", agent=order)
t2 = Task(description="Using the order summary, check the 30-day policy", expected_output="POLICY ok=yes|no", agent=policy)

crew = Crew(agents=[order, policy], tasks=[t1, t2], process=Process.sequential)   # a pipeline; hierarchical adds a manager
print(crew.kickoff(inputs={"ticket": "order #1 amount=210.36 days_since_delivery=7"}))

The code looks friendlier than the LangGraph version, and for a first prototype it is. The cost is visibility. The backstory strings become part of every prompt, the routing is internal to the library, and the token counts you need for a comparison like section 05 are harder to extract. Choose it when speed to a demo matters more than control, and expect to measure it the same way.

The same graphs on the real API

The simulation proved a method. Priya still has to show that the method runs against a real model. Her graphs were written to take any object with an ask(role, case_id, prompt) method, so the swap is one file.

Step-by-step: what real_llm.py does, in plain English
  1. Import the Anthropic SDK and the pieces of this chapter: the reply type, both graph builders and the scorer.
  2. SYSTEMS holds one system prompt per role. Each tells the real model to answer in the same one-line format the pretend model imitates, so the graphs' parsing code works unchanged.
  3. RealLLM creates an Anthropic client, which reads ANTHROPIC_API_KEY from the environment, and picks a model name, defaulting to claude-sonnet-5.
  4. ask sends the role's system prompt and the prompt as a Messages API request, with a small output cap. It does not set a temperature, which current models do not take.
  5. It measures wall-clock seconds, reads token counts from the response's usage field, and returns the same Reply type as the pretend model.
  6. The main block refuses to run without a key. With one, it runs the first ten tickets through both builds and prints the same totals as before.
real_llm.pyneeds API key — not run here
# real_llm.py: the SAME two graphs, wired to the real Anthropic API instead of the fake model.
# Install: uv pip install "langgraph>=1.0,<2" "anthropic>=1.0,<2"       Needs: ANTHROPIC_API_KEY
import os
import sys
import time

import anthropic

from fake_world import Reply, make_cases
from multi_agent_refund import build_team, run_team
from refund_workflow import build_workflow, score, totals

SYSTEMS = {   # the same one-line contracts the fake model imitates
    "order": ("Summarise the order record in one line: ORDER amount=<n> days=<n, or ? if missing> "
              "complete=<yes|no>. complete=no when the delivery date is missing."),
    "policy": ("Refund policy: refunds are allowed up to 30 days after delivery. "
               "Reply with one line: POLICY ok=<yes|no>. If days is ?, give your best guess."),
    "fraud": "A fraud score of 0.60 or more is high. Reply with one line: FRAUD high=<yes|no>.",
    "draft": ("Read the POLICY and FRAUD lines. Reply with one line: DECISION <approve|deny|escalate>. "
              "deny if POLICY ok=no, else escalate if FRAUD high=yes, else approve."),
    "supervisor": ("You run a refund team: order, policy, fraud, draft. Read the transcript and reply with "
                   "exactly one line: NEXT <order|order secondary|policy|fraud|draft|done>. Fetch the order "
                   "first; if it says complete=no, ask for 'order secondary' once; then policy, fraud, "
                   "draft; then done."),
}


class RealLLM:
    """Same .ask(role, case_id, prompt) signature as FakeLLM, so both graphs run unchanged."""

    def __init__(self, model=None):
        self.client = anthropic.Anthropic()               # reads ANTHROPIC_API_KEY from the environment
        self.model = model or os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-5")
        self.seed = 0                                      # the team graph reads llm.seed for its simulated hand-off loss

    def ask(self, role, case_id, prompt):
        start = time.perf_counter()
        msg = self.client.messages.create(model=self.model, max_tokens=100, system=SYSTEMS[role],
                                          messages=[{"role": "user", "content": prompt}])
        text = next(b.text for b in msg.content if b.type == "text").strip()
        return Reply(text, msg.usage.input_tokens, msg.usage.output_tokens, round(time.perf_counter() - start, 2))


if __name__ == "__main__":
    if not os.environ.get("ANTHROPIC_API_KEY"):
        sys.exit("Set ANTHROPIC_API_KEY first. Offline? Run compare.py instead.")
    cases = make_cases()[:10]                              # ten cases keeps the bill under a few cents
    for name, graph in (("workflow", build_workflow(RealLLM())), ("multi-agent", build_team(RealLLM()))):
        rows = []
        for c in cases:
            if name == "multi-agent":
                final = run_team(graph, c)
            else:
                final = graph.invoke({"case": c, "notes": [], "calls": [], "decision": ""})
            rows.append(score(c, final))
        t = totals(rows)
        print(f"{name}: success {t['success']:.0%}, ${t['usd_per_case']:.4f}/case, "
              f"{t['secs_mean']:.1f}s, {t['calls']:.1f} calls")

This file was checked two ways without spending anything: it imports, a client can be constructed with a dummy key, and without a key it exits with a clear message. It was not run against the live API in this environment. Ten tickets will cost cents, but ten tickets cannot defend a conclusion. Run more once the shape works, and expect the numbers to differ from the simulation, because real models slip in more varied ways than four dice.

The stack, and why

The stack, and why

The one question that decides it: how much of the path can you write down in advance, and who has to approve the system's data handling?

What this chapter uses, what else you could use, and when to switch (as of October 2026)
LayerWe useAlternativesWhy this oneSwitch when
OrchestrationLangGraph 1.x (1.2 installed here)CrewAI, Microsoft Agent Framework, OpenAI Agents SDK, Claude Agent SDK, Google ADK, plain PythonExplicit graph, so a workflow and a team are the same library and the comparison is fair. Bad at: verbosity, and a learning curve.Fewer than about five steps with no pauses: plain Python. A .NET shop: Microsoft Agent Framework. Pure OpenAI handoff routing: OpenAI Agents SDK.
Model providerAnthropic, claude-sonnet-5 ($3 in, $15 out per million tokens)OpenAI, Google Gemini, open models via Ollama or vLLMStrong tool use and instruction following; the supervisor needs reliable one-line routing. Bad at: single-vendor dependence.Customer data may not leave your cloud: an open model in your own VPC. Boss calls dominate the bill: a cheaper model for the boss only.
State and checkpointsIn-memory (this chapter)SQLite checkpointer, Postgres checkpointerThe simulation runs in seconds and needs no database. Bad at: nothing survives a crash.A run takes more than a minute, or must survive a deploy: SQLite for one process, Postgres for two or more workers.
TracingOwn JSON log plus Langfuse (self-hostable)LangSmith, Arize Phoenix, OpenTelemetry into Datadog or GrafanaOpen source and runs inside your network. Bad at: you operate it.Self-hosting is not allowed or you have no ops capacity: LangSmith cloud. You already run OpenTelemetry: send spans there.
Tool protocolDirect Python functionsModel Context Protocol (Module 10)Two tools, one owner, no ceremony. Bad at: every agent framework wires tools differently.Three or more agents or apps share the same tools, or another team owns them: expose them over MCP.
EvaluationCustom harness (compare.py)DeepEval, promptfoo, Ragas200 cases and three numbers need about 60 lines and show every step. Bad at: no LLM-judge metrics.More than about 50 cases need an LLM judge or must gate every pull request: DeepEval in CI.

The stack is deliberately the smallest one that can run both builds fairly: one library, one model family, memory for state and a JSON log for traces.

Quick reference — Frameworks and the stack

AutoGen
Maintenance mode as of October 2026; new work goes to Microsoft Agent Framework (1.0 in April 2026).
CrewAI
Role-based crews plus Flows; guides summarise its advice as start with a Flow. Not run here: installing it downgrades openai and pydantic.
OpenAI Agents SDK
Handoffs as the primitive; OpenAI-centred; pre-1.0 in mid-2026.
Claude Agent SDK
The Claude Code loop as a library; subagents; coding-style tools.
Google ADK
Sequential, parallel and loop workflow agents; four languages.
LangGraph
Explicit state graph, checkpointer, human gates. Used for both builds.
The swap to a real model
One class with the same ask method; the graphs do not change.
The why that is easy to forget
Pick the framework that fits your task shape and your stack, then measure it the same way as any other.

08 · Build or buyThe Procurement Meeting: Build on a Framework, or Buy a Platform?

Thursday's meeting went the way the numbers pointed: Maya will take the workflow with one branch to production, and the team stays on the shelf. Then the head of procurement raised her hand. The CEO's blog post also named a vendor, "AgentCloud", selling a ready-made platform for agent teams. Should ClearOps build this on a framework, or buy?

Buying an AI platform means renting someone else's orchestration, hosting and tracing, and handing them your customers' data. Buying is sometimes right, but only after you check the contract, the security evidence and how you would leave.

What you are actually choosing between

"Build" does not mean writing everything. It means using an open framework such as LangGraph, running it in your own cloud, and owning the operations. "Buy" means a vendor runs the orchestration and often the hosting, tracing and connectors for you. In between sits a framework with managed hosting. The choice is really about who carries which risk.

you carry the work and the risk the vendor carries the work, you carry the lock-in Build on LangGraph score 88 exit plan 5 of 5 ops work: all yours FrameKit (managed) score 80 exit plan 4 of 5 ops work: shared AgentCloud (platform) score 48 exit plan 1 of 5 ops work: theirs CheapBot (startup) score 52 SOC 2 score 1 OUT: fails the gates 1 2 3 hypothetical vendors, scored by vendor_scorecard.py; the position on the line is the control you keep yearly cost at 1,400 tickets a month: build about $56,500; pay per resolution about $14,500
Fig. 9b.21 — Four hypothetical options on one line, from "you do the work and keep the control" to "the vendor does the work and you keep the lock-in".
  1. Build on LangGraph. Scores 88 with exit plan 5 of 5, but all the operations are yours and the yearly cost at 1,400 tickets is about $56,500.
  2. The full platform. Scores 48. Its exit plan scores 1 of 5, which is the number to worry about.
  3. The startup. Scores 52 on the weights, but fails the SOC 2 and DPA gates, so it is out.

A buyer has seven questions to ask any vendor. Each has a plain meaning, a piece of evidence that answers it and a red flag that should slow the deal down.

Vendor evaluation scorecard: the seven criteria, with weights used in the worked example
Criterion (weight)The plain questionEvidence to requestRed flag
Security review (20)Can they keep our customers' data and our credentials safe?Penetration-test summary, architecture diagram, how prompt injection and tool permissions are handled"We take security very seriously" with no document
Data residency (15)In which country or region is our data stored and processed?A list of regions, and a contract clause pinning oursData may be processed "globally" or by unnamed subprocessors
SOC 2 / ISO 27001 (15)Has an outside auditor checked their security controls?A current SOC 2 Type II report (covers a period of months) or an ISO 27001 certificate with its scopeOnly a Type I report, a report over a year old, or "in progress"
DPA terms (10)What does the data processing agreement, the contract on how they handle personal data, say?A signable DPA, a subprocessor list, breach-notification timingThey will not negotiate it, or it allows training on your data
Model-provider lock-in (15)Can we change the underlying model without rebuilding?Which models are supported, and whether prompts are portableOne model, or a proprietary prompt format
Pricing model (10)What happens to the bill when volume or complexity grows?The price sheet, and a worked quote at 1x, 5x and 20x our volumePer-resolution pricing with a vague definition of "resolved"
Exit plan (15)If we leave, what do we take with us, and how fast?Export formats for agents, prompts, traces and data; the notice period; deletion proof"Export is on the roadmap"

Two of the seven act as gates rather than points: SOC 2 or ISO 27001, and the DPA. A vendor that scores low on either is out, however good its demo was. The other five are weighted and added. The weights are your judgment, and the point of writing them down is to make that judgment arguable instead of invisible.

A worked scoring example

Procurement hands Priya four candidates. AgentCloud is the blog-post vendor. FrameKit is a framework with managed hosting. CheapBot is a seed-stage startup with the lowest price. The fourth is the option already on the table: build on LangGraph in ClearOps' own cloud. Priya scores each from 0 to 5 on each criterion, backed by the evidence column above.

Every vendor, score and price below is hypothetical. The script is small, plain Python, and meant to be copied and edited with your own evidence.

Step-by-step: what vendor_scorecard.py does, in plain English
  1. Write the seven weights. They add up to 100.
  2. Write each candidate's 0-to-5 score on each criterion.
  3. Write the gates: SOC 2 / ISO 27001 and DPA terms must each score at least 3.
  4. For each candidate, the weighted total is the sum of weight times score divided by 5, giving a number out of 100.
  5. Print each total, and mark any candidate that fails a gate as OUT.
  6. Define three yearly cost formulas. Build: 0.3 of an engineer at $180,000, $2,400 of hosting and the model bill at $0.0092 a ticket. Platform: $1,500 a month plus $0.60 per resolved ticket. Pay per resolution: $0.99 per resolved ticket. Resolved means right, at 87.5 percent.
  7. Print the yearly cost at five volumes, then search upward for the volume where build becomes cheaper than each paid option.
vendor_scorecard.pyruns offline (hypothetical numbers)
# vendor_scorecard.py: score four ways to run the refund team, and find where "build" beats "buy".
# Install: nothing (standard library only). Every vendor, score and price here is HYPOTHETICAL.
WEIGHTS = {"Security review": 20, "Data residency": 15, "SOC 2 / ISO 27001": 15, "DPA terms": 10,
           "Model-provider lock-in": 15, "Pricing model": 10, "Exit plan": 15}
# scores are 0 (fails) to 5 (excellent), each backed by evidence in a real review
SCORES = {
    "AgentCloud (full platform)": {"Security review": 3, "Data residency": 2, "SOC 2 / ISO 27001": 4, "DPA terms": 3,
                                   "Model-provider lock-in": 1, "Pricing model": 3, "Exit plan": 1},
    "FrameKit (framework + managed hosting)": {"Security review": 4, "Data residency": 4, "SOC 2 / ISO 27001": 4, "DPA terms": 4,
                                               "Model-provider lock-in": 4, "Pricing model": 4, "Exit plan": 4},
    "CheapBot (seed-stage startup)": {"Security review": 2, "Data residency": 3, "SOC 2 / ISO 27001": 1, "DPA terms": 2,
                                      "Model-provider lock-in": 3, "Pricing model": 5, "Exit plan": 3},
    "Build on LangGraph (our cloud)": {"Security review": 4, "Data residency": 5, "SOC 2 / ISO 27001": 3, "DPA terms": 5,
                                       "Model-provider lock-in": 5, "Pricing model": 4, "Exit plan": 5},
}
GATES = {"SOC 2 / ISO 27001": 3, "DPA terms": 3}      # below this score the vendor is out, whatever the total

print(f"{'vendor':42} {'score /100':>10}  gates")
for vendor, s in SCORES.items():
    total = sum(WEIGHTS[k] * s[k] / 5 for k in WEIGHTS)
    failed = [k for k, floor in GATES.items() if s[k] < floor]
    print(f"{vendor:42} {total:>10.1f}  {'OUT: ' + ', '.join(failed) if failed else 'pass'}")

# pricing models, one year, at three volumes (tickets a month). Resolved = tickets the system gets right.
SUCCESS = 0.875
def build(v):    return 0.3 * 180_000 + 2_400 + 12 * v * 0.0092          # 0.3 engineer + hosting + model bill
def platform(v): return 12 * 1_500 + 12 * v * SUCCESS * 0.60              # monthly fee + per resolved ticket
def per_resolution(v): return 12 * v * SUCCESS * 0.99                    # pay only for resolutions
print()
print(f"{'tickets/month':>14} {'build':>10} {'platform fee+usage':>20} {'per-resolution':>16}")
for v in (1_400, 5_000, 10_000, 20_000, 100_000):
    print(f"{v:>14,} ${build(v):>9,.0f} ${platform(v):>19,.0f} ${per_resolution(v):>15,.0f}")
v = 1
while build(v) > per_resolution(v):
    v += 10
print(f"\nbuild beats pay-per-resolution above roughly {v:,} tickets a month")
v = 1
while build(v) > platform(v):
    v += 10
print(f"build beats fee-plus-usage above roughly {v:,} tickets a month")
output
vendor                                     score /100  gates
AgentCloud (full platform)                       48.0  pass
FrameKit (framework + managed hosting)           80.0  pass
CheapBot (seed-stage startup)                    52.0  OUT: SOC 2 / ISO 27001, DPA terms
Build on LangGraph (our cloud)                   88.0  pass

 tickets/month      build   platform fee+usage   per-resolution
         1,400 $   56,555 $             26,820 $         14,553
         5,000 $   56,952 $             49,500 $         51,975
        10,000 $   57,504 $             81,000 $        103,950
        20,000 $   58,608 $            144,000 $        207,900
       100,000 $   67,440 $            648,000 $      1,039,500

build beats pay-per-resolution above roughly 5,491 tickets a month
build beats fee-plus-usage above roughly 6,211 tickets a month
1 VENDOR SCORECARD, OUT OF 100 AgentCloud 48 FrameKit 80 CheapBot 52 OUT: gates Build (LangGraph) 88 gates: SOC 2 and DPA must each score 3 or more (hypothetical vendors, scores from vendor_scorecard.py) 2 ONE YEAR OF COST VS TICKETS A MONTH 0 5,000 10,000 $0k $50k $100k build: one engineer part-time platform: fee + per ticket pay per resolution 3 tickets a month (hypothetical prices)
Fig. 9b.22 — The scorecard and the price lines for the four hypothetical candidates. Build wins the scorecard, but at ClearOps' size it loses on cost.
  1. The scorecard. Build on LangGraph scores 88, FrameKit 80, AgentCloud 48. CheapBot scores 52 but is crossed out: its SOC 2 score of 1 and DPA score of 2 fail the gates. The CEO's blog-post vendor lands last mainly on two lines: lock-in scores 1 and exit plan scores 1.
  2. The cost lines. Build starts high, about $56,400 a year, because one part-time engineer is the main cost, and then barely rises. The two paid options start lower but climb with every ticket. The per-resolution line starts at zero and climbs fastest.
  3. The crossover. The ring marks where the build line meets the others: about 5,500 tickets a month against pay-per-resolution and about 6,200 against fee plus usage. ClearOps handles 1,400 a month, well to the left, where buying is cheaper.

Read the output carefully, because it contradicts a comfortable story. On the scorecard, building wins at 88 against 80 for the managed framework, because the exit plan, data residency and lock-in lines favour owning it. On cost at 1,400 tickets a month, building costs about $56,500 a year against $14,500 for the pay-per-resolution option. A scorecard and a spreadsheet can point opposite ways, and honest procurement shows both.

So what should Priya recommend? Three honest options remain. Buy the pay-per-resolution product now, with a contractual exit plan, and revisit at 5,500 tickets a month. Or buy the managed framework FrameKit, which scores 80 and keeps the graphs portable. Or build, accepting the premium for control. The scorecard removes AgentCloud and CheapBot, and the spreadsheet says the real argument is about volume and exit rights, not about the CEO's blog post.

Decision table: build or buy, by situation
SituationLean towardsWhyWatch out for
Under about 5,000 tasks a month, and the task is genericBuyThe fixed cost of an engineer dominatesThe exit plan; do not sign a three-year lock
Over about 6,000 a month, or the task is your core productBuildPer-task prices climb linearly; your cost barely doesYou now own security patches and on-call
Regulated data, or residency in a named regionBuild, or buy with a VPC deploymentThe data never leaves your boundaryA vendor that says "VPC" but keeps the control plane abroad
You cannot hire anyone who can run itBuy managed hostingA framework without operators is a liabilityThe vendor's own bus factor
Unsure the use case will survive a yearBuy, short termCheap to stopData left behind; insist on deletion proof

Quick reference — Enterprise AI procurement

SOC 2 Type II
An auditor's report on a vendor's security controls over a period of months. Type I is a single snapshot and weaker.
ISO 27001
A certificate that a company runs a security management system; read the scope statement.
DPA
Data processing agreement: the contract on how personal data is handled, with subprocessors and breach timing.
Data residency
Where data is stored and processed; ask for regions in writing.
Lock-in and exit plan
Can you change the model, and can you export agents, prompts, traces and data, within a notice period?
Gates and weights
Gates (SOC 2, DPA) remove vendors outright. Weights rank the rest.
Worked example
Build 88, FrameKit 80, AgentCloud 48, CheapBot out. At 1,400 tickets a month, buying is cheaper; build wins above about 5,500 to 6,200.
The why that is easy to forget
Everything in the example is hypothetical. The method, not the numbers, is what carries over.

09 · The labDefend the Architecture With Your Own Data

Everything Priya did for the Thursday meeting is a method, and a method is only yours once you have run it on a task you chose. The lab asks you to repeat the whole chain on a different task: two builds, 200 cases, one table, a luck check, a failure sweep, a trace and a scorecard. About 80 percent of the code is already in this page.

LAB 09b — Defend the winning architecture

Mission: choose one multi-step task, build a workflow version and a multi-agent version of it on LangGraph with a deterministic fake model, run both on at least 200 seeded simulated cases, and produce a recommendation a finance lead could sign, backed by cost, latency and success numbers. Suggested tasks: an invoice-dispute triage, a support-ticket router, or a loan-document check. Reuse fake_world.py as a starting point.

  • Two builds of the same task: a workflow (fixed edges) and a supervisor team with at least three workers, both on LangGraph 1.x, both taking the same fake-model interface
  • A case generator with a known right answer for every case and at least one realistic quirk (missing data, ambiguous input) that makes the builds differ
  • A comparison table with success rate, dollars per ticket and per successful ticket, seconds (mean and p95) and calls per ticket, with a ratio column
  • One measured failure sweep: switch off each failure mode (hand-off loss, mis-routes) and a loop-cap sweep, as in failure_sweep.py
  • A luck check: five dice seeds and a held-out set of fresh cases, plus a statement of the standard error of your headline gap
  • Blame labels on every failed case, and a failure chart by cause
  • One saved trace per build and a printed span tree; a six-panel dashboard sketch naming the source of each number
  • A third contender, a "workflow plus one branch" or a critic loop, built from your own error analysis, scored on the held-out set only
  • A vendor scorecard with the seven criteria, two gates and a yearly cost chart, using hypothetical or real quotes
  • README documents: the table, the recommendation in one paragraph, three failure modes found, and the cost of a failure you assumed

Offline path: everything above runs with the pretend model. Needs API key: swap in the RealLLM class from real_llm.py for a 20-case check on the real model and report both sets of numbers side by side. Stretch goal: wire the team to Langfuse (langfuse_tracing.py), attach a Postgres checkpointer, and show a run resuming after a kill.

10 · Interview radarHow This Shows Up in Interviews

Interview radar

Multi-agent questions are judgment questions. The interviewer is grading whether you reach for a team by reflex or by evidence, and whether you can talk about cost and failure in numbers.

"When would you use a multi-agent system instead of a single agent or a fixed workflow?"

The real test Whether you treat multi-agent as a last resort that has to earn its cost.

Strong answer I start with a fixed workflow, because anything my code can order costs no model calls. I add a supervisor only when the path depends on what earlier steps find and I cannot list the cases. I would also consider multiple agents when the tool list is too long for one agent, or when parts must run in isolated contexts. In our refund example, the team beat the plain workflow by 3.5 points at 2.6 times the cost, and an if-statement beat both.

Land it I choose the architecture that wins on a measured table, and I say what the table assumed.

"Design a multi-agent system for handling refund disputes. How would you decide it is worth it?"

The real test System design with a baseline and an evaluation plan, not a box diagram.

Strong answer I would build the plain workflow first, then the team, and run both on the same few hundred labelled cases. I would report success rate, dollars per successful ticket, and p95 latency, and then cost the failures: a person at about $12.50 per wrong ticket in our example. I would slice by case type, because the team's advantage lived in 28 percent of tickets. I would add a luck check, a held-out set, and traces to assign blame.

Land it The design is the evaluation plan; the diagram comes second.

"Your multi-agent system's cost per task doubled after you added a supervisor. How do you investigate?"

Strong answer I look at the call log first.

  • Calls per task: a boss call before every step means at least workers plus one extra calls.
  • Cost by role: in our measurement the supervisor took 56 percent of the bill, because it re-reads the whole whiteboard every turn.
  • Loops: any task near the turn cap, or repeated workers, shows mis-routes or lost context.
  • Context growth: with real tool outputs, the boss's reads grow with the square of the turn count.

Fixes are a cheaper model for the boss, summarised hand-offs, a fixed order for the steps that never vary, and a turn cap.

Land it The bill is a product of calls and context size, and a trace shows both.

"How do agents share information, and what are the trade-offs between shared state and message passing?"

Strong answer With shared state, every agent reads one growing transcript. A supervisor can notice what is missing, but every call re-reads everything: on our sample ticket the team read 6,187 tokens against 1,637 for the workflow.

With message passing, each step gets only what it needs. That is cheap and easy to test, but each step is blind to the rest, so a dropped fact becomes a guess. Real systems often pass summaries to workers and keep the full record for the supervisor, and the summary is where context is lost.

Land it Shared state buys awareness with tokens; message passing buys cheapness with blindness.

"When would you not use LangGraph, and what would you use instead?"

The real test Vendor-agnostic judgment, not framework loyalty.

Strong answer I would avoid it for a very small flow, under about five steps with no pauses or resume, where plain Python is clearer. In a .NET shop I would look at Microsoft Agent Framework, the successor to AutoGen, which is in maintenance mode. For pure handoff routing on OpenAI I might use the OpenAI Agents SDK. For file-and-shell agents on Claude, the Claude Agent SDK. For a quick role-based prototype, CrewAI. I would still measure each against the same cases.

Land it The framework follows the task shape and the stack, and the measurement decides.

"A vendor is pitching an AI agent platform to our company. What do you check before we sign?"

The real test Whether you know enterprise procurement and can say no with reasons.

Strong answer I would run a scorecard. Two gates: a current SOC 2 Type II or ISO 27001 report, and a signable data processing agreement that forbids training on our data. Then weighted lines: security review, data residency, model-provider lock-in, pricing at 1, 5 and 20 times our volume, and an exit plan with export formats and deletion proof. In our example the blog-post vendor scored 48 out of 100 mainly on lock-in and exit, and a seed-stage vendor was out on the gates.

Land it I would rather lose a deal than lose the ability to leave.

"A multi-agent run returned a wrong answer. How do you find which agent was at fault?"

Strong answer I open the trace, one span per model call. If a worker's call is flagged wrong, I fix its instructions. If only the supervisor's call was wrong, it is a routing problem. If no call looks wrong but the answer is, a fact was missing from the shared state, so I look for repeated lookups or a lost summary. I tag each failure with a cause, so over 200 failures I see a mix: in our run, 25 model slips, 13 coordination failures and one data gap.

Land it Without per-call spans and cause labels you are debugging by guessing.

There are no dumb questions

The simulated model is invented. Why should I trust any of these numbers?
Trust the method and the structure, not the decimals. The call counts, the boss's share of the bill and the failure categories follow from how the graphs are built. The success rates depend on four slip rates I chose. Rerun the harness with your real model (real_llm.py) and your own cases before quoting a number to anyone.
Could parallel workers cut the team's latency?
Yes, and the workflow too. Policy and fraud checks do not depend on each other, so a fan-out would roughly halve their time in either build. The simulation ran everything in sequence for both, which keeps the comparison fair but exaggerates absolute seconds.
Is 200 cases enough?
For a gap of 3.5 points, no: you would need about 1,100. For a gap of 10 points or a ranking of cost, 200 is plenty. The right size depends on the difference you need to see, which is why the page computes the standard error.
Does this mean multi-agent systems are overhyped?
It means they are a tool with a price. Where the path really is unknown, such as open-ended research, or a tool list too large for one agent, a team can win. The page's claim is narrower: for a task with a known shape and one known exception, a workflow with one branch beat the team on every number we measured.

11 · RecapWhat You Can Do Now

  • You can name the five multi-agent patterns, draw each, and say what each adds to the call count.
  • You can build a workflow and a supervisor team on LangGraph against a deterministic fake model, and run both on 200 seeded cases.
  • You can show, with a measured run, how context loss, cost multiplication, loops and unclear blame appear in a team.
  • You can produce a defended comparison: success, dollars and seconds, sliced by case type, with an all-in cost that includes fixing failures.
  • You can tell a real gap from luck using five seeds, a held-out set and a standard error.
  • You can read a trace as a span tree and list the panels of a multi-agent dashboard.
  • You can place CrewAI, Microsoft Agent Framework, AutoGen, the OpenAI and Claude SDKs, Google ADK and LangGraph on a decision table, and say AutoGen is in maintenance mode.
  • You can score a vendor with gates, weights and a cost chart, and recommend build or buy with reasons.
🧠 Flex your memory

From this module: without looking, sketch the five patterns as five boxes-and-arrows, and write the call count for each with k = 3 workers. Then say which one you would never pay for if your code could write the order down.

From Module 09: a supervisor can loop just like the 2023 pilot. Name the three bounds Module 09 put on a single agent, and say which of them this page's MAX_HOPS cap is.

Reveal the answer

Pipeline 4, orchestrator–workers 5, supervisor 7, hierarchy 13 for two leads with two workers each, critic loop 5 for two rounds, handoffs 3. The pipeline is the one you never pay for when your code can fix the order. Module 09's three bounds are a cap on turns, a money budget per ticket and a human gate before irreversible actions. MAX_HOPS is the cap on turns. A money budget would be a cap on the running dollar total in the call log, which is a small addition to the supervisor.