16  Multi-Agent Supervisor

Real work splits: a docs search, a web search, a summary — each a different prompt, each easier to get right on its own. The question this chapter answers is how one graph coordinates several agents without any of them knowing about the others. In Chapter 7 an agent sat at the center of a loop and routed to tools; Chapter 11 showed a whole graph standing in as a single node. Put those together and let the things the agent routes to be other agents. That is the supervisor pattern — no supervisor class, no special library:

A supervisor is just an agent node whose “tools” are other agents. It looks at the task, delegates to a worker, reads what the worker reports back, and decides whether to delegate again or finish.

The pattern is the first half of the chapter. The second half is what the pattern exposes on a first run: a supervisor that decides to finish before any worker has run — and the way to see why a model makes a decision like that instead of guessing at the prompt. (This is serial delegation, not Chapter 10’ fan-out; the Gotcha after the run draws that line.)

16.1 What we’re building

The doc-bot grows a manager. A supervisor node reads the question and delegates to one of two workers — a docs agent that searches the internal knowledge base, or a web agent that falls back to the open web. Each worker does its job, writes a report, and returns to the supervisor. The supervisor reads the reports so far and decides all over again: delegate to the other worker, or finish and write the answer.

%%{init: {'securityLevel': 'loose', 'flowchart': {'diagramPadding': 24}, 'themeCSS': 'foreignObject{overflow:visible}span.bot{display:flex;justify-content:flex-start;align-items:flex-start;width:100%;height:0;overflow:visible;line-height:0}span.bot img{display:block!important;width:18px!important;height:18px!important;padding:2px;background:#fff;border-radius:50%;box-shadow:0 0 0 1px #999}span.bot.r img{margin:0;transform:translate(-24px,-24px)}span.bot.d{justify-content:center}span.bot.d img{margin-top:-50%;transform:translateY(-24px)}'}}%%
flowchart LR
    START(["START"]) --> supervisor{"<span class='bot d'><img src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTIgOFY0SDgiLz48cmVjdCB3aWR0aD0iMTYiIGhlaWdodD0iMTIiIHg9IjQiIHk9IjgiIHJ4PSIyIi8+PHBhdGggZD0iTTIgMTRoMiIvPjxwYXRoIGQ9Ik0yMCAxNGgyIi8+PHBhdGggZD0iTTE1IDEzdjIiLz48cGF0aCBkPSJNOSAxM3YyIi8+PC9zdmc+'/></span>supervisor"}
    supervisor -.->|route = docs_agent| docs("<span class='bot r'><img src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTIgOFY0SDgiLz48cmVjdCB3aWR0aD0iMTYiIGhlaWdodD0iMTIiIHg9IjQiIHk9IjgiIHJ4PSIyIi8+PHBhdGggZD0iTTIgMTRoMiIvPjxwYXRoIGQ9Ik0yMCAxNGgyIi8+PHBhdGggZD0iTTE1IDEzdjIiLz48cGF0aCBkPSJNOSAxM3YyIi8+PC9zdmc+'/></span>docs_agent")
    supervisor -.->|route = web_agent| web("<span class='bot r'><img src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTIgOFY0SDgiLz48cmVjdCB3aWR0aD0iMTYiIGhlaWdodD0iMTIiIHg9IjQiIHk9IjgiIHJ4PSIyIi8+PHBhdGggZD0iTTIgMTRoMiIvPjxwYXRoIGQ9Ik0yMCAxNGgyIi8+PHBhdGggZD0iTTE1IDEzdjIiLz48cGF0aCBkPSJNOSAxM3YyIi8+PC9zdmc+'/></span>web_agent")
    supervisor -.->|route = finish| finish("<span class='bot r'><img src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTIgOFY0SDgiLz48cmVjdCB3aWR0aD0iMTYiIGhlaWdodD0iMTIiIHg9IjQiIHk9IjgiIHJ4PSIyIi8+PHBhdGggZD0iTTIgMTRoMiIvPjxwYXRoIGQ9Ik0yMCAxNGgyIi8+PHBhdGggZD0iTTE1IDEzdjIiLz48cGF0aCBkPSJNOSAxM3YyIi8+PC9zdmc+'/></span>finish")
    docs --> supervisor
    web --> supervisor
    finish --> END(["END"])

Compare it with the agent-tool loop in Chapter 7 and the only difference is what sits at the ends of the spokes: worker agents instead of tool functions. The wiring — the conditional edge out and the back-edges in — is the same.

This is a supervisor that routes one step at a time: it picks the next worker, reads what came back, and decides again. The pattern the literature calls Plan-and-Execute (Appendix C lists it as re-planning) adds one thing we deliberately leave out here: a planner that holds an explicit, revisable plan across turns. That step up is exactly what the Silver challenge at the end of the chapter asks for — a supervisor that plans, delegates, reads, and re-plans until it is satisfied or runs out of budget — and it is the only version that earns the name.

16.2 Connecting the model

The supervisor’s decision is a real model call, so we reuse Chapter 12’s connection block unchanged — with one substitution:

llm = ChatOpenAI(..., model="openai/gpt-oss-20b", temperature=0)

Apart from Chapter 13, Part II runs on Qwen3.8 with its thinking switched off (Chapter 2); this chapter uses gpt-oss-20b on purpose. It is a reasoning model — it keeps its chain-of-thought in a separate channel, and that channel is where this chapter’s one instructive failure comes from (Section 16.9). On Qwen3.8 with the switch off, which then writes no such channel, the same prompt and schema work.

16.3 The state grows a scratchpad

The supervisor decides by reading what the workers have found so far, so the state needs a place to collect their reports. That place is reports, and it carries a reducer — the operator.add from Section 10.3:

import operator
from typing import Annotated, NotRequired, TypedDict


class State(TypedDict):
    question: str                                # input, set by the caller
    route: NotRequired[str]                      # supervisor's pick this step
    reason: NotRequired[str]                     # the supervisor's stated reason
    reports: Annotated[list[str], operator.add]  # workers append; supervisor reads
    answer: NotRequired[str]                     # written by finish

The reducer is here for a different reason than in Chapter 10. There, operator.add stopped two workers writing the same key in one superstep from colliding. Here the writes are serial — one worker per step — but each worker should add its report to the running list, not overwrite the last one. Make reports a plain key and each delegation would clobber the previous report, so the supervisor would only ever see the latest one and lose the history it needs to decide. The reducer turns reports into an accumulating scratchpad: the same operator.add, doing accumulation across serial steps instead of merging parallel ones.

16.4 The supervisor decides who works next

The supervisor is the Chapter 12 agent almost verbatim: read the state, ask the model for a decision, write it, stop. The decision is a structured output, a Delegate whose route is a Literal, so the pick is always one of the three legal targets and never a stray sentence:

from typing import Literal
from pydantic import BaseModel, Field


class Delegate(BaseModel):
    """Pick the next worker for a documentation supervisor, or finish."""

    # reason comes FIRST: fields are emitted in schema order, so this is the only
    # place gpt-oss gets to think under LM Studio's JSON grammar. Move it after
    # `route` and the supervisor mis-routes (see "Look at what it's thinking").
    reason: str = Field(
        description="Think step by step about which rule applies, then decide."
    )
    route: Literal["docs_agent", "web_agent", "finish"] = Field(
        description="Which worker to delegate to next: "
        "docs_agent=search the internal documentation, "
        "web_agent=search the open web, "
        "finish=stop delegating and write the final answer."
    )


router = llm.with_structured_output(Delegate, method="json_schema")

The supervisor node itself hands the model an ordered set of rules — docs first, web only if the docs came back empty, otherwise finish — and returns the pick:

def supervisor_node(state: State) -> dict:
    reports = state.get("reports", [])
1    searched_docs = any(r.startswith("[docs_agent]") for r in reports)
    searched_web = any(r.startswith("[web_agent]") for r in reports)
    reports_text = "\n".join(f"- {r}" for r in reports) or "(none yet)"

    prompt = f"""
        You are the SUPERVISOR of a documentation question-answering team
        with two workers. You delegate to ONE worker at a time, read its report, then
        decide again.

        Question: {state['question']}
        Already delegated to docs_agent: {searched_docs}
        Already delegated to web_agent: {searched_web}

        Worker reports so far:
        {reports_text}

        Read the rules in order and choose the FIRST whose condition is true:
        1. If docs_agent has NOT run yet                                  -> docs_agent
        2. else if the docs came back empty AND web_agent has NOT run yet -> web_agent
        3. otherwise                                                      -> finish

        In `reason`, first repeat the two "Already delegated" values, then state which
2        rule applied."""

    decision = router.invoke(prompt)
    print(f"[supervisor] reports={len(reports)} -> {decision.route}"
          f"  ({decision.reason})")
    return {"route": decision.route, "reason": decision.reason}
1
Which workers have already reported, read off the tagged reports and told to the model in words so it does not re-search an empty result.
2
The last line, what to write in reason, was not in the first draft of this prompt. Section 16.9 is the story of why it is there, and it is the difference between that section’s opening trace and the one under Running it.

This is the ordered-rules prompt from Section 12.5, adapted. The route Literal guarantees the shape of the answer; the rules steer the choice.

16.5 The workers report back — and only back

A worker is not a tool. A tool runs a function and hands back what it computed; a worker reads its raw material and decides what is worth reporting. So each of these two has what an agent has and a tool does not: its own prompt, its own model call, and its own private pile of material that the supervisor never sees.

Both are the same three steps — fetch raw material, have the model read it, return one sentence — so the model call is a shared helper, and only the fetching differs:

WORKER_PROMPT = """You are the {name}. Answer ONLY from the material below.
Write one sentence stating what it says about the question. If the material does
not answer it, reply exactly: nothing useful found.

Question: {q}

Material:
{material}"""


def run_worker(name: str, tag: str, q: str, material: str) -> dict:
    conclusion = llm.invoke(
        WORKER_PROMPT.format(name=name, q=q, material=material)
    ).content.strip()
    print(f"   [{tag}] read {len(material)} chars of raw material, "
1          f"returned {len(conclusion)}")
    return {"reports": [f"[{tag}] {conclusion}"]}


def docs_agent_node(state: State) -> dict:
    q = state["question"]
    hits = [d for t, docs in KNOWLEDGE_BASE.items() if t in q.lower() for d in docs]
    print(f"   [docs_agent] searched internal docs: {len(hits)} hit(s)")
    material = "\n".join(f"- {h}" for h in hits) or "(no internal documents matched)"
    return run_worker("internal-documentation agent", "docs_agent", q, material)


def web_agent_node(state: State) -> dict:
    q = state["question"]
2    results = list(DDGS().text(q, max_results=4))
    print(f"   [web_agent] searched the open web: {len(results)} result(s)")
    material = "\n".join(f"- {r['title']}: {r['body']}" for r in results)
    return run_worker("web-search agent", "web_agent", q, material)
1
The two numbers that make the next section’s point: how much the worker read, how much it handed back.
2
DDGS is the ddgs package (pip install ddgs==9.16.0, the pin in the companion’s requirements.txt) — a metasearch library that queries several engines (its default backend chooses which; DuckDuckGo is one of them), no API key, no bill. This is the only worked example that leaves your machine (Chapter 13’s Gold challenge asks you to build the other), and the reason this chapter’s web results — and so its transcript — will not match yours exactly. KNOWLEDGE_BASE is the same dict as Chapter 7 and is not reprinted.

Notice what each worker does not do. docs_agent doesn’t decide whether to call web_agent; web_agent doesn’t read what docs_agent found and react to it. A worker’s only outward move is to append a report and return to the supervisor — there is no edge from one worker to the other, and there is no shared conversation between them. That is the defining constraint of the supervisor pattern: workers report to the supervisor and nowhere else. The consequence is practical: when a run goes wrong, the [supervisor] lines are the whole decision history, and adding a worker (the Try-it below) touches the supervisor and the wiring, never another worker.

Read those lines in two halves, though, and trust them differently. The route is the decision — a legal enum the graph acts on, and the only half that moves the run. The reason is the model narrating itself: useful when it is good, and no guarantee at all. Section 16.9 is a whole section about a case where the route stayed legal while the reason collapsed to a single stray word. When your trace’s reasons read oddly, check the routes before you conclude anything is broken.

Each worker also tags its report ([docs_agent] ...), which is how the supervisor tells who has already run.

And notice what each worker does not hand over. web_agent pulls four search results — a couple of thousand characters of titles and snippets, most of it irrelevant — reads all of it, and appends one sentence. The rest never reaches the supervisor’s context and never could: the supervisor’s prompt is built from reports, and reports only ever receives a conclusion. The read … / returned … numbers in the trace are the two ends of that boundary, and the ratio between them is what a worker is for.

NoteDeep Dive: this is how a coding agent spins up sub-agents

The supervisor here delegates to two fixed workers, but push the idea one step and you arrive at how a tool like Claude Code actually works.1 Its skeleton is a single capable agent in the loop from Chapter 7 — think, call a tool, read the result, think again. What makes it multi-agent is that one of the “tools” the main agent can reach for is spawn a sub-agent: hand a self-contained task (explore this part of the codebase, draft a plan) to a fresh agent that runs in its own context and reports back only its conclusion. The main agent stays a capable supervisor; the sub-agents are on-demand temporary workers, created when needed rather than standing around as a fixed roster.

Two properties from earlier chapters make this work. The sub-agent runs in an isolated context, the Chapter 11 lesson: it grinds through its own messy middle in its own state space, and only the conclusion crosses back, so the supervisor’s context stays small and focused instead of drowning in the sub-agent’s scratch work. And in the topology this chapter builds, the sub-agents report only to the supervisor, the constraint we just built into the workers. That is this chapter’s simplification, not the product’s rule: Claude Code can hand a sub-agent a roster of named agents and a way to message them, and let one agent resume another. Our reports scratchpad is the plainest version of “return only a conclusion”; a real harness returns a richer summary. The other end of this thread — a single agent editing a repository, and the checks a graph puts between its work and a commit — is the opening chapter of LangGraph in the Wild, the book after this one.

NoteDeep Dive: the pattern we didn’t build — handoffs

LangChain’s multi-agent guide files these designs under five names: subagents (a coordinator calls other agents as tools — this chapter), handoffs (below), and three that recombine pieces you already have — router (a classifier step dispatches to specialists), skills (one agent loads specialized prompts on demand), and custom workflow (a graph you wire yourself). You already own the primitive for the handoff. A handoff is an agent passing control directly to another, with no hub in between. The two layers spell it differently: at the create_agent layer the guide implements a handoff as a tool call, one agent’s tool handing the conversation to the next; at the graph layer, which is where you are, it is one line — the node returns Command(goto="writer_agent", update={...}), the Section 10.6 move, and the runtime runs that agent next, no back-edge to a supervisor. Across subgraphs, the same Command carries graph=Command.PARENT (Chapter 11).

Handoffs beat a supervisor when the agents are peers that own the conversation in turn — triage hands a customer to billing, billing hands back. Ours stays supervised because the workers only ever report a conclusion. Both patterns are plain graph wiring; langgraph-supervisor and langgraph-swarm are older packaging of the two shapes, and the supervisor README now recommends building the pattern directly — via agent-as-tool calls, or, as here, as plain graph wiring.

16.6 Finishing

When the supervisor routes to finish, one last node turns the collected reports into an answer. It’s the generate node from Chapter 12 under a new name: gather every report, hand them to the model, and ask it to answer from them alone.

def finish_node(state: State) -> dict:
    reports = state.get("reports", [])
    reports_text = "\n".join(f"- {r}" for r in reports) or "(no reports)"
    prompt = f"""
        Answer the user's question concisely, using only the worker
        reports below. Do not invent anything.

        Question: {state['question']}

        Worker reports:
        {reports_text}

        Answer:"""
    answer = llm.invoke(prompt).content.strip()
    print("[finish] the supervisor wrote the final answer")
    return {"answer": answer}

16.7 Wiring it

One conditional edge out of the supervisor, a back-edge from each worker, and a single exit. The router is the one-line helper from Chapter 7, read route and return it, and because each route value is already the name of its target node, the mapping is almost an identity:

from langgraph.graph import StateGraph, START, END


def route_after_supervisor(state: State) -> str:
    return state["route"]


builder = StateGraph(State)
builder.add_node("supervisor", supervisor_node)
builder.add_node("docs_agent", docs_agent_node)
builder.add_node("web_agent", web_agent_node)
builder.add_node("finish", finish_node)

builder.add_edge(START, "supervisor")
builder.add_conditional_edges(
    "supervisor",
    route_after_supervisor,
    {
        "docs_agent": "docs_agent",
        "web_agent": "web_agent",
        "finish": "finish",
    },
)
builder.add_edge("docs_agent", "supervisor")
builder.add_edge("web_agent", "supervisor")
builder.add_edge("finish", END)

graph = builder.compile()

%%{init: {'securityLevel': 'loose', 'flowchart': {'diagramPadding': 24}, 'themeCSS': 'foreignObject{overflow:visible}span.bot{display:flex;justify-content:flex-start;align-items:flex-start;width:100%;height:0;overflow:visible;line-height:0}span.bot img{display:block!important;width:18px!important;height:18px!important;padding:2px;background:#fff;border-radius:50%;box-shadow:0 0 0 1px #999}span.bot.r img{margin:0;transform:translate(-24px,-24px)}span.bot.d{justify-content:center}span.bot.d img{margin-top:-50%;transform:translateY(-24px)}'}}%%
flowchart TD
    START(["START"]) --> supervisor{"<span class='bot d'><img src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTIgOFY0SDgiLz48cmVjdCB3aWR0aD0iMTYiIGhlaWdodD0iMTIiIHg9IjQiIHk9IjgiIHJ4PSIyIi8+PHBhdGggZD0iTTIgMTRoMiIvPjxwYXRoIGQ9Ik0yMCAxNGgyIi8+PHBhdGggZD0iTTE1IDEzdjIiLz48cGF0aCBkPSJNOSAxM3YyIi8+PC9zdmc+'/></span>supervisor"}
    supervisor -.->|docs_agent| docs_agent("<span class='bot r'><img src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTIgOFY0SDgiLz48cmVjdCB3aWR0aD0iMTYiIGhlaWdodD0iMTIiIHg9IjQiIHk9IjgiIHJ4PSIyIi8+PHBhdGggZD0iTTIgMTRoMiIvPjxwYXRoIGQ9Ik0yMCAxNGgyIi8+PHBhdGggZD0iTTE1IDEzdjIiLz48cGF0aCBkPSJNOSAxM3YyIi8+PC9zdmc+'/></span>docs_agent")
    supervisor -.->|web_agent| web_agent("<span class='bot r'><img src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTIgOFY0SDgiLz48cmVjdCB3aWR0aD0iMTYiIGhlaWdodD0iMTIiIHg9IjQiIHk9IjgiIHJ4PSIyIi8+PHBhdGggZD0iTTIgMTRoMiIvPjxwYXRoIGQ9Ik0yMCAxNGgyIi8+PHBhdGggZD0iTTE1IDEzdjIiLz48cGF0aCBkPSJNOSAxM3YyIi8+PC9zdmc+'/></span>web_agent")
    supervisor -.->|finish| finish("<span class='bot r'><img src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTIgOFY0SDgiLz48cmVjdCB3aWR0aD0iMTYiIGhlaWdodD0iMTIiIHg9IjQiIHk9IjgiIHJ4PSIyIi8+PHBhdGggZD0iTTIgMTRoMiIvPjxwYXRoIGQ9Ik0yMCAxNGgyIi8+PHBhdGggZD0iTTE1IDEzdjIiLz48cGF0aCBkPSJNOSAxM3YyIi8+PC9zdmc+'/></span>finish")
    docs_agent --> supervisor
    web_agent --> supervisor
    finish --> END(["END"])

docs_agent → supervisor and web_agent → supervisor are what make this a loop rather than a pipeline: a worker never decides what comes next, it returns control to the supervisor, which decides again with one more report in hand. Leave one of those edges out and that worker becomes a dead end; the graph would end after its first report.

16.8 Running it

Two questions, chosen to take the two paths — one the internal docs answer, one they don’t (python code/ch14_supervisor.py):

if __name__ == "__main__":
    for q in [
        "How do I configure Kafka batch consumers?",
        "How do I write a Python decorator?",
    ]:
        print(f"\n===== question: {q} =====")
        result = graph.invoke({"question": q}, {"recursion_limit": 12})
        print("--- answer ---")
        print(excerpt(result["answer"]))

The trace below is one representative run (Chapter 12’s caveat applies), and here even the route can vary on a harder question — what’s fixed is the machine, how each decision is logged and how the graph responds to it. (excerpt: first line only — Chapter 12.)

===== question: How do I configure Kafka batch consumers? =====
[supervisor] reports=0 -> docs_agent  (Already delegated to docs_agent: False, Already delegated to web_agent: False. Rule 1 applied.)
   [docs_agent] searched internal docs: 2 hit(s)
   [docs_agent] read 140 chars of raw material, returned 125
[supervisor] reports=1 -> finish  (Already delegated to docs_agent: True, Already delegated to web_agent: False. Rule 3 applied.)
[finish] the supervisor wrote the final answer
--- answer ---
Set the listener type to batch in your Spring configuration:

===== question: How do I write a Python decorator? =====
[supervisor] reports=0 -> docs_agent  (Already delegated to docs_agent: False, Already delegated to web_agent: False. Rule 1 applied.)
   [docs_agent] searched internal docs: 0 hit(s)
   [docs_agent] read 31 chars of raw material, returned 20
[supervisor] reports=1 -> web_agent  (Already delegated to docs_agent: True, Already delegated to web_agent: False. Rule 2 applied.)
   [web_agent] searched the open web: 4 result(s)
   [web_agent] read 1152 chars of raw material, returned 212
[supervisor] reports=2 -> finish  (Already delegated to docs_agent: True, Already delegated to web_agent: True. Rule applied: 3.)
[finish] the supervisor wrote the final answer
--- answer ---
Define a function that takes another function as an argument and returns a new function (often using closures) that wr ...

Follow the [supervisor] lines. The Kafka question delegates to docs_agent, sees two hits, and on the next decision routes to finish: two supervisor turns, one worker. The Python question delegates to docs_agent, sees 0 hit(s), comes back to the supervisor, which now routes to web_agent, reads its one result, and only then finishes: three supervisor turns, two different workers, in sequence. That sequence — pick one, read the report, pick the next — is serial delegation.

The reason texts are the other half to read. Each one restates the two “Already delegated” facts and then names the rule, which is what the prompt’s last line asked for — and the route that follows is decided on that working. That last line was not in the first draft. Section 16.9 is what the draft did instead, and how to find out what your own stack does rather than guess at it.

Now read the two read … / returned … pairs. On the Kafka question docs_agent read 140 characters and returned 125: the internal knowledge base is already curated, so there is little to filter and the boundary earns little. On the Python question web_agent read 1,152 and returned 212 — four search results in, one sentence out, and the ~940 characters of surrounding web prose never entered the supervisor’s context. Same contract, same graph; what the isolation is worth tracks how noisy the source is. Point the web worker at twenty results instead of four and none of those results reach the supervisor’s prompt: only the worker’s conclusion crosses, and how long that runs is still the model’s to decide. The boundary is what makes this pattern hold when the workers get real, not a guaranteed size.

WarningGotcha: serial delegation is not Chapter 8’s parallel fan-out

It is easy to file “supervisor with workers” next to “Chapter 10 with its Send fan-out” as the same multi-worker idea. They are opposites, and mixing them up will cost you.

Section 10.5 is parallel and one-shot: one orchestrator returns a list of Sends and spawns N identical workers in a single superstep — all at once, no one waiting — a reducer accumulates their results, and the node after them runs when its inputs arrive: a trigger, not a barrier (Chapter 10). You reach for it when the work splits into independent pieces you can do simultaneously (retrieve five sub-questions at the same time).

The supervisor here is serial and adaptive: it delegates to one worker, waits for the report, and only then decides the next move — which may be a different worker, or none. Each decision depends on the last report, so the steps cannot run at once; the supervisor reacts to what each worker found. You reach for it when the next choice depends on the previous result.

Rule of thumb: independent work that can happen simultaneously wants Send (parallel); a decision that has to see the previous result before making the next one wants a supervisor (serial). The trace tells them apart at a glance — a Send fan-out shows N workers between two supervisor-less lines; a supervisor shows a [supervisor] line before every single worker.

TipTry it: add a third worker

Growing the roster is the Chapter 7 move, one level up. Count the places a new worker touches. Write a faq_agent node — search a small FAQ dict, then hand the hits to run_worker("FAQ agent", "faq_agent", q, material) like the other two — then make five edits so the supervisor can see and reach it:

  1. add "faq_agent" to the Literal in Delegate;
  2. register the node: builder.add_node("faq_agent", faq_agent_node);
  3. add "faq_agent": "faq_agent" to the conditional-edge mapping;
  4. add the back-edge builder.add_edge("faq_agent", "supervisor");
  5. teach supervisor_node about it — a searched_faq check off the tagged reports and a rule in the ordered-rules prompt for when to reach for it.

Re-run and watch the [supervisor] line delegate to your new worker on a question the FAQ covers. You touched no existing worker — but a new worker is not free: it’s a new enum value, a new node, a new mapping entry, a new back-edge, and new lines in the supervisor’s detection and prompt. The roster is data and a little logic; the win is that all of it lives in two well-known places — the graph wiring and the supervisor — not scattered across the workers.

On your machine. A fourth Literal value and a fifth rule is more schema and more prompt than this chapter’s supervisor was tuned on, and openai/gpt-oss-20b may answer by delegating to docs_agent over and over instead. That is not your wiring — check the five edits, then read the trace the way Section 16.9 does, and you will find the same story one notch further along: a richer decision is harder for this model to hold. (The Silver challenge hits the ceiling properly and runs its planner on qwen/qwen3.8-27b for exactly this reason; swapping the model is a fair move here too.)

16.9 Look at what it’s thinking

NoteA diagnostic aside — skippable on a first read

The supervisor pattern is built and you have watched it run: workers, a recursion fuse, a route, two traces. This section is a debugging story about one model on one local stack, not a prerequisite for using supervisors — skip to Before moving on if you just want the pattern. The specific behavior below was observed with gpt-oss-20b served by a particular LM Studio build; a different server, backend, or quantization can behave differently, so record your own stack’s versions before treating any of it as fixed.

The supervisor’s prompt (Section 16.4) was first written without its last line — the rules, the two “Already delegated” facts, and nothing about reason. Run that draft and its first decision is

[supervisor] reports=0 -> finish  (analysis)

No worker had run. The model had been asked to pick between a docs search, a web search, and “finish”, with a Literal guaranteeing the pick was one of those three words, and it picked finish on a question it had no reports for. The reason field, which was supposed to hold its thinking, held the single word analysis. A wrong route might be expected to show up late, on the harder question; instead the same {"reason":"analysis","route":"finish"} comes back in every one of four decision states, the easy ones included.

The reflex is to reword the prompt and rerun until the symptom stops. That is guessing. What to understand first is how this particular model writes.

gpt-oss is a reasoning model, and it writes in the Harmony format:2 an analysis channel for its thinking, then a final channel for the answer.

The other half is how a server enforces a schema. Not by checking the reply afterwards, but by constrained decoding: at every token position it masks out every token that would break the schema, so the model cannot emit one — not “will not,” cannot. That mask is what this chapter calls the grammar. The behavior below is consistent with LM Studio applying the json_schema grammar from the first token: the first token the grammar allows is {, so the analysis channel never opens. That is an inference from what the model returns and LM Studio’s documented json_schema handling,3 not something read off the server’s token masks — take it as the best available explanation, not a proven internal. On that reading, the nearest thing to what the model wanted to write next, the channel name, lands in reason, and finish is what a supervisor that has not thought falls back to. The Literal held; it was never asked to do more than keep the route legal.

LM Studio returns the analysis channel as a reasoning key on every response. ChatOpenAI drops it (it is not part of the OpenAI spec), but the openai client underneath keeps every unknown key in message.model_extra, so one raw call gets it back — under the key and in the versions LM Studio chooses:4

GPT_OSS = "openai/gpt-oss-20b"           # reasoning model (Harmony channels)

msg = llm.root_client.chat.completions.create(   # the client ChatOpenAI talks through
    model=GPT_OSS, temperature=0,
    messages=[{"role": "user", "content": prompt}],
    response_format={"type": "json_schema", "json_schema": {...}},   # or tools=[...]
).choices[0].message
extra = msg.model_extra or {}                          # gpt-oss: "reasoning";
reasoning = extra.get("reasoning") or extra.get("reasoning_content")   # Qwen3.x

code/ch14_peek_reasoning.py wraps that in a peek() and sends the original prompt — no last line — through the four decision states of the run above, under six output paths. Run it and read the reasoning next to each answer; it adds up to this:

The original supervisor prompt under six output paths, four decision states each.
Path Reasoning visible? Routes right What the model did
(a) gpt-oss, no constraint yes 4/4 thought (“We need to delegate to docs_agent.”), then answered
(b) gpt-oss, json_schema — the chapter’s path no 2/4 {"reason":"analysis","route":"finish"} in every state; the two finish are luck
(c) json_schema + the scratchpad line no 4/4 reason restates the two facts, then route
(d) gpt-oss, tool calling, tool_choice="required" yes 3/4 thought first; in the state where the reports already justified finishing, answered in prose and called no tool
(e) Qwen3.8 27B, json_schema, thinking off — the book’s default — 4/4 one stream, nothing to starve: reason restates the state, then route
(f) Qwen3.8 27B, json_schema, thinking on yes 0/4 the JSON came back inside the thinking channel — all four routes right in reasoning_content, content empty in every state

Row (b) is the prediction above, caught in the act; (c) and (d) are the two ways out. Rows (e) and (f) are the book’s own model with its thinking channel switched off and on, and that is the only difference: off, there is no channel to starve and the prompt works as written; on, the grammar lands on the thinking channel from token zero and the model writes a legal, correct decision there — which with_structured_output never sees, because it reads content, and content is empty.

On your machine. Re-measured on the same stack, the gpt-oss rows other than (b) came back identical — including (d)’s single miss landing on the same state, Python, both run, with the model writing prose and calling no tool. Row (b) moved, and not in the direction you would guess. Three of its four states answered {"reason":"analysis","route":"finish"} in under two seconds; the fourth stopped answering at all — no response in 120 seconds, and none in 180, across six attempts, while its three siblings kept replying instantly. So the starvation this section describes has a worse mode than a degenerate answer: sometimes nothing comes back, and your 2/4 may read 1/4. It is also why peek() passes an explicit client timeout: ChatOpenAI builds its underlying openai client with timeout=None here (a bare OpenAI() would default to ten minutes), so a hung request otherwise blocks forever, and a probe that hangs teaches you nothing. The general lesson is that you have to know how your model writes. Nothing in the LangGraph layer was broken, and nothing in it could have shown you this — a detail of the model’s own output format surfaced through three abstractions built to hide it (with_structured_output, an OpenAI-compatible endpoint, the graph). That is an abstraction leak,5 and it is why rewording the instruction is the wrong first move here: what row (c) changes is not the persuasion, it is where the model is allowed to put its reasoning.

So this is not “constrained decoding breaks routing”. It is a reasoning model’s channel format meeting where the server applies the grammar. Some hosted reasoning APIs keep the two apart by contract — Claude’s structured-output documentation, for one, excludes the thinking from the output grammar — while a local stack may apply it from token zero, which is the reading that fits what LM Studio returned here. Same model, same schema, different server, different behavior — so look before you reword. Then the fixes, cheapest first:

  • A thinking slot inside the schema — reason (or thinking) as the first field, plus a line saying what goes in it. The chapter’s path, the only row that scored 4/4 with the shape still enforced, portable to any server, harmless on a model that did not need it.

  • An output path where thinking precedes the grammar — tool calling here, or the plain structured-output path on a hosted reasoning API. In Harmony a function call goes out on commentary, which comes after analysis, so the model thinks first and the grammar reaches only the call’s arguments. Ask for it with llm.bind_tools([Delegate], tool_choice="required") (Section 13.2).

    Weigh what you trade, though. json_schema always handed back a legal route, even when the model had not thought. This path reverses that: the thinking comes back, but nothing guarantees a decision arrives at all: on the LM Studio build behind these rows, tool_choice="required" did not force a call. Whether a grammar stands behind it is the server’s business; one missed call shows only that nothing forced it here. That is row (d)’s one miss: having already concluded “finish,” the model called no tool and answered in prose.

  • Two calls — think freely without a constraint, then a constrained call that only extracts the decision.

  • Not this: rewording until it stops wobbling. Under the constraint gpt-oss is prompt-sensitive (a shorter draft of this prompt got the route right with a degenerate reason), so a wording that “works” may be working by accident.

WarningGotcha: constrained decoding can starve a reasoning model’s thinking — it depends on your server

On a reasoning model, where the server applies the json_schema grammar decides whether the model gets to think at all. Applied from the first token — the reading that fits what LM Studio returned here, and what row (f) shows outright — the thinking channel never opens, or opens and swallows the answer: the route comes out legal, fixed, and wrong, with the channel name leaking into your first string field. A Literal cannot catch this — it is a failure of choice, not shape. You will not see it on a non-reasoning model, or on a hybrid model with its thinking switched off, and may not see it on a hosted API. When a structured decision misbehaves, read the reasoning before touching the prompt; if it is absent, give the model somewhere to think inside the shape.

16.9.1 Reasoning models vs. non-reasoning models

Rows (b) and (e) are the same prompt and the same schema; one scores 2/4 by luck and the other 4/4. The difference is the kind of model (or, in (e)’s case, the mode). A non-reasoning model, the instruct models of the Qwen2.5 generation or Qwen3.8 with its thinking switched off, produces one stream, the answer. If you want it to think first, the thinking has to be in that stream (a reason field, “think step by step”). A reasoning model — gpt-oss, the hosted o-series-style models — produces a chain of thought and then the answer, in a place that is not the answer, and is trained to rely on it. gpt-oss makes the two channels explicit; a hosted API hides the chain and bills you for it.

Swap one for the other in a graph and three things change. Cost: a reasoning model spends tokens you don’t see before every structured decision, so the supervisor turn is slower and dearer. Where the grammar bites: on a non-reasoning model it shapes the only stream there is; on a reasoning model it can fall on the thinking channel, and whether it does is the server’s call. What reason-first is for: on a non-reasoning model it is a cheap nudge; on a reasoning model behind a token-zero grammar it is the only thinking the model gets.

A third kind sits between them, and it is where the open-weight models have gone; the book’s own default is one. The hybrid model is one set of weights whose thinking is a switch. Qwen3 through Qwen3.8 all work this way: the chat template takes an enable_thinking variable, on by default, and the request decides. On LM Studio the switch exists only for a model installed from its catalogue (lms get qwen/qwen3.8-27b), which ships the template setting. Then reasoning_effort="none" on the request (the line every Qwen constructor in this book carries) or the model’s Enable Thinking default turns it off. A plain Hugging Face download of the same weights has no switch at all. Rows (e) and (f) are that switch and nothing else. Off, the model is a non-reasoning model and scores 4/4. On, it is the starvation of row (b) in a purer form: the thinking channel opens, the grammar falls on it, and the model fills the channel with the JSON you asked for — right answer, wrong channel, empty content. The first time I saw that empty content I read it as the grammar failing and went through LM Studio’s server log looking for the rejection; the JSON was in reasoning_content the whole time, complete and correct. The fixes above apply unchanged; the cheapest of all is the switch, if you did not want the thinking in the first place — which is why the book’s code leaves it off.

16.10 Before moving on

The pattern cost nothing new: a conditional edge out, a back-edge from each worker, a Literal on the route, and the rule that workers write reports and never talk to each other. What broke was the one-word reason. What to carry out of that:

  • When a structured decision misbehaves, read the model’s reasoning before touching the prompt. If there is none, the grammar may have eaten it; give the model a field to think in, first in the schema, and say what goes there.
  • Whether that starvation happens depends on the model and the server. The same prompt scored 2/4 on gpt-oss under LM Studio’s grammar, and on the book’s Qwen3.8 4/4 with thinking off and 0/4 with it on; a hosted reasoning API may never show it. ch14_peek_reasoning.py is how to find out on your stack.
  • Serial delegation and the Send fan-out of Chapter 10 are opposites: use Send when the pieces are independent and can run at once, a supervisor when the next choice has to see the last result.
  • These workers share the parent State, so their isolation is topological only. The Bronze challenge adds the context isolation of Chapter 11, which is how a coding agent’s sub-agents return a conclusion and no scratch work.
  • LangChain 1.x calls this shape the subagents pattern for create_agent (Chapter 13): a subagent is a tool whose body runs another agent.

The supervisor coordinates a single run, but the moment that run ends the whole graph forgets everything — the reports, the answer, the question. The next chapter gives the doc-bot a memory: short-term conversation history kept per thread (the checkpoints of Chapter 8), and long-term facts that persist across sessions in a Store, so it can remember what you asked last time and who you are.

New pieces in this chapter

Piece Usage
API
ChatOpenAI.root_client The openai.OpenAI client that ChatOpenAI talks through. llm.root_client.chat.completions.create(...); one level down when you need a field LangChain drops
message.model_extra Where the openai SDK parks response keys that are not in the OpenAI spec. msg.model_extra.get("reasoning"); LM Studio’s reasoning channel lives here
ChatOpenAI.bind_tools(tool_choice="required") Request a tool call on every turn; whether it is enforced is the server’s business — on the LM Studio build behind this chapter it was not, and row (d) shows the miss. llm.bind_tools([Delegate], tool_choice="required"); structured output via the tool-call path, where the grammar constrains only the arguments. Send the string — with_structured_output(method="function_calling") sets tool_choice to the tool’s name, which bind_tools then expands to the object form {"type": "function", "function": {"name": …}}, and LM Studio rejects that

Code in this chapter

File What it runs
code/ch14_supervisor.py A supervisor whose tools are other agents: delegate to one worker, read its report, decide whether to delegate again.
code/ch14_peek_reasoning.py Look instead of reword: the supervisor’s own reasoning channel, and what constrained decoding does to it.

Challenge

Two challenges: turn a worker into an isolated sub-agent, then let the supervisor run a real multi-step investigation.

🥉 Bronze — make a worker a real isolated sub-agent

Our workers are plain nodes. Turn docs_agent into a subgraph (Chapter 11): a small two-step pipeline — rewrite the query, then search — with its own RagState that carries a private rewritten field the parent never declares. Wire it in with an adapter node (the Section 11.4 pattern) that maps the supervisor’s question into the subgraph and folds the subgraph’s docs back out as one [docs_agent] ... report.

Verify the isolation the Deep Dive described: print the supervisor’s state keys at finish and confirm rewritten is nowhere in them — the sub-agent’s scratch work stayed sealed in its own context, and only the conclusion crossed back.

office hours Worked solution with tests: code/answers/ch14_subgraph_worker.py.

🥈 Silver — a supervisor that investigates/reflects

Build a supervisor that plans, delegates, reads, and re-plans until it is satisfied or runs out of budget. Give it a compound question and let it choose both which worker and what sub-question each turn, with a max_delegations budget it cannot exceed.

It works when two runs behave: the investigation finishes within budget on a question that needs both workers, and lowering max_delegations forces an earlier finish even where the model would have kept going.

Hints: the budget has to be a guard in your code, checked before the model is called — a number the model is merely told about is a suggestion a confused model can ignore, the same reason Chapter 6’s recursion_limit is enforced by the machine. Feed each turn’s decision a running summary of what has been learned, or the supervisor re-asks what it already knows. And a stack note: the richer three-field plan is harder to route than this chapter’s single decision — openai/gpt-oss-20b mis-sends sub-questions here, so the worked solution runs the planner on the book’s default qwen/qwen3.8-27b.

office hours Worked solution with tests: code/answers/ch14_investigator.py.


  1. Claude Code’s main loop: https://code.claude.com/docs/en/how-claude-code-works; its subagents: https://code.claude.com/docs/en/sub-agents.↩︎

  2. OpenAI’s prompt and response format for the gpt-oss models, which are trained on it — the documentation is blunt that “gpt-oss should not be used without using the harmony format, as it will not work correctly.” It defines three assistant channels: analysis for chain of thought, commentary for function tool calls and preambles, and final for the answer shown to the user. https://developers.openai.com/cookbook/articles/openai-harmony↩︎

  3. LM Studio enforces json_schema with llama.cpp’s grammar sampling for GGUF models and with Outlines for MLX models: https://lmstudio.ai/docs/developer/openai-compat/structured-output.↩︎

  4. LM Studio moved gpt-oss’s reasoning out of content into a separate field in 0.3.23 (https://lmstudio.ai/blog/lmstudio-v0.3.23; API changelog: https://lmstudio.ai/docs/developer/api-changelog). The key depends on the model — reasoning for gpt-oss, reasoning_content for Qwen3.x — so peek() reads both.↩︎

  5. Joel Spolsky’s “Law of Leaky Abstractions” (2002): all non-trivial abstractions, to some degree, are leaky. An abstraction spares you a detail right up until the day that detail decides the outcome — and on that day you need to know the thing the abstraction was hiding. https://www.joelonsoftware.com/2002/11/11/the-law-of-leaky-abstractions/↩︎