08F.13 Subgraphs and Multi-Agent Systems

Agents & multimodalLesson 13 of 1717,743 wordsDeep-dive10 parts
Module 08F · 0 of 10 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17

Lesson 08D.3 taught multi-agent systems as architecture: when a second agent earns its cost, the ten shapes you will meet, and the hard parts (delegation briefs, context boundaries, termination, cost). This lesson is the LangChain and LangGraph half of the same story: what you actually type. Two ideas carry almost everything. A subgraph is a graph used as a node of another graph, which gives you reuse, private state and a clean contract between teams. A multi-agent system in this ecosystem is mostly a handful of agents (each a compiled graph made by create_agent) wired together in one of five documented ways: a main agent that calls the others as tools (subagents), agents that pass control to each other with a Command (handoffs), one agent that loads prompts and knowledge on demand (skills), a classification step that fans work out (router), or a graph you draw yourself (custom workflow).

You will build every one of them here, with scripted stand-ins for the model so that it runs on your laptop with no API key: subgraphs with shared and private state and the three persistence modes, a supervisor whose tools are subagents (the pattern the official docs now recommend), handoff graphs with Command.PARENT and the single-agent-with-middleware variant, a swarm written by hand, a router with Send, parallel branches, and a complete "research desk" that wraps a supervisor in a workflow with a quality gate and a human approval. Then the helper packages langgraph-supervisor (archived upstream) and langgraph-swarm, which you will meet in old tutorials, run for real so that you can read their output; a mapping onto the ten architectures of 08D.3; how to test all of it without a key; and a gallery of the failures that actually happen.

What you'll learn

  • When multi-agent is worth it, in LangChain's own words (context management, distributed development, parallelization), and how the five official patterns map onto the architectures of 08D.3
  • Subgraphs: the two ways to use one (call it inside a node, or add it as a node), shared versus private state keys, nesting, namespaces, and a reducer trap that duplicates your data
  • Subgraph persistence: checkpointer=None, True and False, run side by side, what each does to memory, interrupts and parallel calls, and how to read a subgraph's state
  • Subagents as tools: the supervisor pattern with create_agent, what the supervisor sees and does not see, passing context down (query only versus fork) and results back (text versus Command), a single dispatch tool, parallel subagent calls, per-thread subagents, and interrupts through nested agents
  • Handoffs: tools that return a Command, Command.PARENT, the AIMessage plus ToolMessage rule, active_agent in state, a dispatch node that enforces a handoff budget, and the single-agent state machine built with middleware
  • Swarms written by hand, and why the active agent needs a checkpointer
  • The router pattern with Send, skills, and parallel branches (fan-out edges, reducers, concurrency caps, what a failing branch does)
  • Custom workflows that mix deterministic nodes and agents, with a worked example
  • The helper packages langgraph-supervisor and langgraph-swarm: status, API, a real run, and the migration table to the recommended pattern
  • How to test a multi-agent graph without a model, and a failure gallery with the real behaviour of each trap

What you don't need

  • An API key. Every sample runs with scripted fake chat models, plain Python nodes and in-memory checkpointers, and the outputs shown are the real output of those runs (14 November 2026). Three short sketches (one helper, one per-role-model example that calls providers, one before and after migration) are labelled illustrative.
  • The architectures themselves. 08D.3 owns when to use which, the four taxes, delegation briefs and cost accounting. This lesson says how to build each in LangGraph and does not repeat the argument.
  • The graph basics. 08F.10 owns state, reducers, edges, Command and Send; this lesson uses them. Checkpointers, threads and the store are 08F.11. The full treatment of interrupt, approvals and error handling is 08F.12: here an interrupt appears only to show how it travels through nested agents. All stream modes, and streaming from subgraphs in detail, are 08F.14.
  • create_agent and middleware in depth. 08F.8 owns them, including a first look at agents as tools (its 5.5).

Setup

You need Python 3.11 or newer and uv (08F.4, Part 5). New to uv? The first uv add fails outside a project, so create one first.

bash
uv init multi-agent-lab --bare --python 3.13 && cd multi-agent-lab   # first time only
uv add langgraph langchain
uv add langgraph-supervisor langgraph-swarm                           # only for Part 7 (the helper packages)
# only if you want to run the provider sketch in 3.9 with a real model:
uv add python-dotenv langchain-openai
# or: pip install langgraph langchain langgraph-supervisor langgraph-swarm

No == pins: the lockfile records what uv resolves. Every runnable sample imports one helper file, fakes.py, which holds the scripted chat models built in 08F.8, 1.3. The part of it this lesson uses (the file in 08F.8 also holds a streaming variant that this lesson does not need):

python
# fakes.py: scripted chat models that accept bind_tools (the same file as in 08F.8)
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel


class FakeToolCallingModel(GenericFakeChatModel):
    """Replays the AIMessages you give it, one per model call. It ignores the prompt."""

    def bind_tools(self, tools, **kwargs):
        return self


class RecordingModel(FakeToolCallingModel):
    """Like FakeToolCallingModel, but remembers what each call received and which tools were offered."""

    seen: list = []
    bound: list = []

    def bind_tools(self, tools, **kwargs):
        self.bound.append([getattr(t, "name", t.get("name") if isinstance(t, dict) else t) for t in tools])
        return self

    def _generate(self, messages, *args, **kwargs):
        self.seen.append([(type(m).__name__, m.text) for m in messages])
        return super()._generate(messages, *args, **kwargs)

Put fakes.py in the folder of the samples and run each with uv run python file.py. A scripted model returns the next prepared AIMessage on every call, so each sample "decides" in advance which tool to call; everything else (the real create_agent, tools, graphs, reducers, checkpointers, Command) is the real library. When a script runs out, the next call raises StopIteration: if you copy a sample and see that, you have called an agent more times than it has replies (some samples use itertools.cycle to avoid it).

Versions (current at time of writing, verified 14 and 18 November 2026 by installing them and running every sample marked as run): langgraph 1.2.22, langgraph-prebuilt 1.1.2, langgraph-checkpoint 4.3.2, langchain 1.5.0, langchain-core 1.8.2, langgraph-supervisor 0.0.31 (released 19 November 2025, repository archived), langgraph-swarm 0.1.0 (released 4 December 2025). The samples ran on Python 3.13 with uv run --no-project --python 3.13 --with langgraph --with langchain --with langgraph-supervisor --with langgraph-swarm python sample.py. langgraph ships a patch most weeks: see 08F.4, 5.10 for upgrading on purpose.


What you must be able to do after this lesson#

  • Decide when multi-agent is worth the cost
  • Build a subgraph and share state with a parent graph
  • Build a supervisor with subagents wrapped as tools
  • Write a handoff with Command
  • Test a multi-agent graph without a model

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Should this be one agent or a team?" 1.1 and 1.4
"LangChain has five multi-agent patterns, how do they map to the ten in 08D.3?" 1.2 and Part 8
"Add the compiled graph as a node." / "Call the subgraph in a node." Part 2
"My subgraph's list doubled." 2.3
"Does the subgraph remember the last call?" 2.6
"Wrap each specialist as a tool on the supervisor." Part 3
"The supervisor never sees the specialist's tool calls." 3.2
"A human approval inside a subagent never reaches the user." 3.8
"Hand the customer to the specialist and keep the conversation." Part 4
"Why Command.PARENT? Why a ToolMessage in a handoff?" 4.2 and 4.3
"The two agents keep passing the user back and forth." 4.5
"What is a swarm, and why does it forget?" 4.6
"Classify the request, ask several experts, merge the answers." Part 5
"Wrap the supervisor in a workflow with a quality gate." Part 6
"This tutorial uses create_supervisor / create_swarm." Part 7
"How do we test a team of agents without calling a model?" Part 9

Part 1: The map: what LangChain calls multi-agent#

The concepts behind this map live in 08D: 08D.1 for the one-or-several rule, the roles and the two basic patterns, and 08D.3, Part 2 for the ten architectures. This Part only names LangChain's five patterns and shows how to choose among them; Part 8 maps them onto the ten.

1.1 Why multi-agent, and why often not#

The full treatment of when a second agent earns its cost is in 08D.1, 1.2 and 08D.3, 1.3. This section adds LangChain's own three reasons, including distributed development, which those lessons do not list.

The official multi-agent overview opens with a sentence worth memorizing: not every complex task needs this approach, because "a single agent with the right (sometimes dynamic) tools and prompt can often achieve similar results". It names three reasons to go beyond one agent:

Reason What it means in practice
Context management One agent with forty tools and five domains of instructions picks poorly and fills its window. Specialists each carry only their own tools and knowledge, and report back a summary
Distributed development Different teams own different agents behind a small contract (a tool name and a description, or a state schema), and release independently
Parallelization Independent subtasks run at the same time in separate contexts

and says "at the center of multi-agent design is context engineering": deciding what each agent sees. That is the same conclusion as 08D.3, 3.2, reached from the framework side, and the four taxes of 08D.3, 1.2 (tokens, compounding errors, coordination, debugging) still apply to every sample below. Build the single agent first (08F.8); split when you can name which of the three reasons applies.

1.2 The five official patterns#

The docs describe five patterns. The definitions below are the docs' own, in my words.

Pattern How it works Who talks to the user
Subagents A main agent coordinates other agents that are wrapped as tools. Every routing decision goes through the main agent The main agent, always
Handoffs Behaviour changes with state. A tool call updates a state variable (such as active_agent or current_step) and that triggers a routing or configuration change Whichever agent is active; control really moves
Skills Specialized prompts and knowledge are loaded on demand by one agent that stays in control The one agent
Router A routing step classifies the input and directs it to one or more agents; the results are synthesized The synthesis step
Custom workflow A bespoke flow in LangGraph that mixes deterministic logic and agentic behaviour Whatever you design

Notice what is not in the list: a "supervisor" or a "swarm" as a framework feature. Those are the names the earlier langgraph-supervisor and langgraph-swarm packages gave to two of these patterns (supervisor is subagents with a create_react_agent main agent, swarm is handoffs between peers). Part 7 covers the packages; the patterns are what matters.

1.3 How they compare: the docs' own ratings and call counts#

The docs rate the patterns on four needs. Reproduced as words, from the docs' star ratings (a rough guide, not a measurement):

Need Subagents Handoffs Skills Router
Distributed development (teams own parts) very strong not rated very strong medium
Parallelization very strong not rated medium very strong
Multi-hop (several specialists in sequence) very strong very strong very strong not rated
Direct user interaction (the specialist talks to the user) weak very strong very strong medium

The docs also count model calls for three scenarios. These figures are the docs' illustrative numbers, not measurements by this course, so treat them as the shape of the trade-off:

Scenario Subagents Handoffs Skills Router
One request ("buy coffee") 4 calls 3 3 3
A second, repeat request in the same conversation 4 more (8 total) 2 more (5 total) 2 more (5 total) 3 more (6 total)
A multi-domain question (compare three languages, about 2,000 tokens of docs each) 5 calls, about 9K tokens 7 or more calls, about 14K or more tokens 3 calls, about 15K tokens 5 calls, about 9K tokens

Two lessons from those numbers. First, stateful patterns (handoffs, skills) save roughly 40 to 50 percent of calls on repeat requests because the active specialist already has the context; subagents are stateless by default, so each request pays again. Second, for a multi-domain question, isolation wins on tokens (subagents and router, about 9K) because each specialist reads its own documents and returns a summary, while skills carry every loaded prompt in the one context. This is the cost-versus-isolation trade-off of 08D.3, 1.2 in numbers.

1.4 Choosing a pattern#

The framework-neutral version of this choice is the decision table in 08D.3, 2.11. This section is the same choice as a flowchart over LangChain's five patterns.

flowchart TD
    q0{"Does one agent with the right tools and prompt do the job?"} -- yes --> one["Stay with one create_agent"]
    q0 -- "no: too many tools, too much context, or parallel work" --> q1{"Should one agent stay in control of the whole conversation?"}
    q1 -- yes --> q2{"Is the extra capability mostly prompts and knowledge?"}
    q2 -- yes --> skills["Skills: load_skill tool, one agent"]
    q2 -- no --> sub["Subagents: agents wrapped as tools"]
    q1 -- "no: the specialist should own the turns" --> q3{"Does the user talk to different specialists over time?"}
    q3 -- yes --> hand["Handoffs: Command tools, active_agent in state"]
    q3 -- "no: classify once, then answer" --> router["Router: classify, Send, synthesize"]
    sub --> q4{"Mix fixed code steps with agent steps, or need approvals and loops?"}
    hand --> q4
    router --> q4
    q4 -- yes --> custom["Custom workflow: your own StateGraph"]

The docs' own rule of thumb for the extremes: use a router when you have clear input categories and want deterministic or lightweight classification, and a supervisor (subagents) when you need flexible, conversation-aware orchestration. Part 8 turns this into a table against the ten architectures of 08D.3.


Part 2: Subgraphs#

2.1 What a subgraph is, and what it is for#

The docs define it in one line: a subgraph is a graph that is used as a node in another graph. The parent sees a node; inside, there is a whole compiled graph with its own nodes, edges and (possibly) its own state schema. Three jobs justify the extra structure:

  • Multi-agent systems: each agent made by create_agent is a compiled graph, so adding it to a parent graph is adding a subgraph.
  • Reuse: a validation or enrichment sequence that several workflows share, written and tested once.
  • Distributed development: a team owns the subgraph behind an input and output contract (its schema), and the parent team never touches its internals.
flowchart TD
    subgraph parent ["Parent graph, compiled with the only real checkpointer"]
        n1["node_1"] --> sub
        subgraph sub ["subgraph node: checkpointer None, True or False"]
            a["inner node A"] --> b["inner node B"]
        end
        sub --> n3["node_3"]
    end
    sub -.->|"Command goto other_node graph PARENT"| n3

2.2 Two ways to use one#

There are exactly two communication styles, and the choice is dictated by the state schemas:

Style Use it when What you write
Call the subgraph inside a node The parent and the subgraph have different schemas (no shared keys), or you must transform state on the way in or out A wrapper node: map parent state to the subgraph's input, call subgraph.invoke(...), map the output to a parent update
Add the compiled subgraph as a node Parent and subgraph share state keys Nothing: pass the compiled graph straight to add_node

The sample builds one of each. In style 1 a review subgraph has text and verdict, the parent has body and status, and the wrapper translates. In style 2 the drafting subgraph has keys body and draft, the parent only body: body is shared, draft is private to the subgraph and never appears in the parent.

python
# s01_two_styles.py: the two ways to use a subgraph, with different and with shared state keys
from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph


# ---- Style 1: call the subgraph inside a node (different schemas, you map state yourself) ----
class ReviewState(TypedDict):
    text: str
    verdict: str


def check_length(state: ReviewState):
    return {"verdict": "too long" if len(state["text"]) > 20 else "ok"}


review = StateGraph(ReviewState).add_node(check_length).add_edge(START, "check_length").compile()


class TicketState(TypedDict):
    body: str
    status: str


def run_review(state: TicketState):
    out = review.invoke({"text": state["body"]})        # map parent state -> subgraph input
    return {"status": out["verdict"]}                    # map subgraph output -> parent update


parent1 = StateGraph(TicketState).add_node("review", run_review).add_edge(START, "review").compile()
print("style 1:", parent1.invoke({"body": "Printer on floor 3 is jammed again", "status": ""}))


# ---- Style 2: add the compiled subgraph as a node (shared key `body`, private key `draft`) ----
class DraftState(TypedDict):
    body: str      # shared with the parent
    draft: str     # private to the subgraph


def make_draft(state: DraftState):
    return {"draft": "Re: " + state["body"]}


def polish(state: DraftState):
    return {"body": state["draft"] + " (polished)"}


drafting = (
    StateGraph(DraftState)
    .add_node(make_draft)
    .add_node(polish)
    .add_edge(START, "make_draft")
    .add_edge("make_draft", "polish")
    .compile()
)


class ParentState(TypedDict):
    body: str


parent2 = StateGraph(ParentState).add_node("drafting", drafting).add_edge(START, "drafting").add_edge("drafting", END).compile()
print("style 2 result :", parent2.invoke({"body": "refund request"}))
print("parent keys    :", list(ParentState.__annotations__))
print("subgraph keys  :", list(DraftState.__annotations__))
for chunk in parent2.stream({"body": "refund request"}, stream_mode="updates"):
    print("parent update  :", chunk)
for ns, chunk in parent2.stream({"body": "refund request"}, stream_mode="updates", subgraphs=True):
    print("with subgraphs :", [n.split(":")[0] for n in ns], chunk)
Output8 lines
style 1: {'body': 'Printer on floor 3 is jammed again', 'status': 'too long'}
style 2 result : {'body': 'Re: refund request (polished)'}
parent keys    : ['body']
subgraph keys  : ['body', 'draft']
parent update  : {'drafting': {'body': 'Re: refund request (polished)'}}
with subgraphs : ['drafting'] {'make_draft': {'draft': 'Re: refund request'}}
with subgraphs : ['drafting'] {'polish': {'body': 'Re: refund request (polished)'}}
with subgraphs : [] {'drafting': {'body': 'Re: refund request (polished)'}}

Read the output in order. Style 1 returned the parent's own keys (body, status) and nothing of the subgraph. Style 2 returned body only: the private draft key stayed inside. The parent's plain updates stream shows the subgraph as one node (drafting), with only its result. Passing subgraphs=True to stream reveals what happened inside: each chunk now comes as a (namespace, chunk) pair, where the namespace names the path of subgraph nodes (the real value is drafting:<uuid>; the sample strips the id) and an empty namespace is the parent. 08F.14 owns streaming in full; the one rule to remember now is that a parent's stream does not show a subgraph's inner steps unless you ask.

2.3 The trap: a shared key with an append reducer#

Here is a surprise that costs people an afternoon. When a compiled subgraph is added as a node and a shared key has a reducer that appends, the parent can receive the subgraph's whole value of that key, not only what the subgraph added, and the reducer then appends it to what the parent already had.

python
# s02_shared_reducer.py: a shared key with a reducer, and what the parent receives from the subgraph
import operator
from typing import Annotated

from typing_extensions import TypedDict

from langgraph.graph import END, START, StateGraph


class State(TypedDict):
    log: Annotated[list[str], operator.add]


def inner_a(state: State):
    return {"log": ["inner_a saw " + str(len(state["log"])) + " entries"]}


sub = StateGraph(State).add_node(inner_a).add_edge(START, "inner_a").compile()


def before(state: State):
    return {"log": ["before"]}


parent = StateGraph(State).add_node(before).add_node("sub", sub).add_edge(START, "before").add_edge("before", "sub").add_edge("sub", END).compile()
print(parent.invoke({"log": ["start"]}))
for chunk in parent.stream({"log": ["start"]}, stream_mode="updates"):
    print(chunk)
Output3 lines
{'log': ['start', 'before', 'start', 'before', 'inner_a saw 2 entries']}
{'before': {'log': ['before']}}
{'sub': {'log': ['start', 'before', 'inner_a saw 2 entries']}}

The parent started with ["start"] and before added one entry, so the parent's list was ['start', 'before']. The subgraph received that list as its input, added one entry, and returned ['start', 'before', 'inner_a saw 2 entries']. The parent's reducer (operator.add) appended that to its own list, giving ['start', 'before', 'start', 'before', 'inner_a saw 2 entries']: the two earlier entries are doubled. (The updates stream shows the cause: the sub update carries all three entries.)

Three fixes, all in one sample:

python
# s04_reducer_fixes.py: three ways to avoid duplicated entries when a shared key has an append reducer
import operator
from typing import Annotated

from langchain_core.messages import AIMessage, HumanMessage
from typing_extensions import TypedDict

from langgraph.graph import END, START, MessagesState, StateGraph


class State(TypedDict):
    log: Annotated[list[str], operator.add]


def inner(state: State):
    return {"log": ["inner"]}


sub = StateGraph(State).add_node(inner).add_edge(START, "inner").compile()

# Fix 1: call the subgraph inside a node and return only what is new.
def call_sub(state: State):
    out = sub.invoke(state)
    return {"log": out["log"][len(state["log"]):]}


p1 = StateGraph(State).add_node("sub", call_sub).add_edge(START, "sub").add_edge("sub", END).compile()
print("fix 1 (return only the new entries):", p1.invoke({"log": ["start"]})["log"])


# Fix 2: give the subgraph an output schema that holds only a NEW key; the parent maps it.
class SubOut(TypedDict):
    sub_log: list[str]


class SubState(TypedDict):
    log: list[str]
    sub_log: list[str]


def inner2(state: SubState):
    return {"sub_log": ["inner"]}


sub2 = StateGraph(SubState, output_schema=SubOut).add_node(inner2).add_edge(START, "inner2").compile()


class Parent2(TypedDict):
    log: Annotated[list[str], operator.add]
    sub_log: Annotated[list[str], operator.add]


p2 = StateGraph(Parent2).add_node("sub", sub2).add_edge(START, "sub").add_edge("sub", END).compile()
print("fix 2 (output schema with a new key):", p2.invoke({"log": ["start"], "sub_log": []}))

# Fix 3: messages. add_messages merges by message id, so a shared `messages` key does not duplicate.
def say(state: MessagesState):
    return {"messages": [AIMessage("from the subgraph", id="a1")]}


sub3 = StateGraph(MessagesState).add_node(say).add_edge(START, "say").compile()
p3 = StateGraph(MessagesState).add_node("sub", sub3).add_edge(START, "sub").add_edge("sub", END).compile()
out = p3.invoke({"messages": [HumanMessage("hi", id="h1")]})
print("fix 3 (add_messages merges by id):", [(m.type, m.text) for m in out["messages"]])
Output3 lines
fix 1 (return only the new entries): ['start', 'inner']
fix 2 (output schema with a new key): {'log': ['start'], 'sub_log': ['inner']}
fix 3 (add_messages merges by id): [('human', 'hi'), ('ai', 'from the subgraph')]
Fix How When
1. Call it inside a node and return only the new entries out = sub.invoke(state); return out["log"][len(state["log"]):] The subgraph's list is the parent's list plus additions (an append-only log)
2. Give the subgraph an output schema with a different key StateGraph(SubState, output_schema=SubOut), where SubOut has sub_log; the parent has a sub_log key with its own reducer You want the subgraph's contribution as a separate, explicit field
3. Share only messages (or another id-merged key) add_messages replaces a message with the same id instead of appending a second copy Agents and conversational subgraphs

The deeper rule is the one 08F.10, Part 8 states for any node: a node returns a partial update. A subgraph added as a node returns its final state (limited to keys the parent knows, and to its output schema if it has one), which is rarely a partial update. Shape that return on purpose.

2.4 Nesting, and the namespaces nested subgraphs get#

Subgraphs nest as deeply as you like: a subgraph can contain a subgraph. The sample nests three levels (parent, child, grandchild), each added as a node of the one above.

python
# s03_nested.py: nested subgraphs (parent -> child -> grandchild) and the namespaces they get
from typing_extensions import TypedDict

from langgraph.graph import START, StateGraph


class State(TypedDict):
    text: str


def shout(state: State):
    return {"text": state["text"].upper()}


def exclaim(state: State):
    return {"text": state["text"] + "!"}


def wrap(state: State):
    return {"text": "[" + state["text"] + "]"}


grandchild = StateGraph(State).add_node(shout).add_edge(START, "shout").compile()
child = (
    StateGraph(State)
    .add_node("grandchild", grandchild)
    .add_node(exclaim)
    .add_edge(START, "grandchild")
    .add_edge("grandchild", "exclaim")
    .compile()
)
parent = StateGraph(State).add_node("child", child).add_node(wrap).add_edge(START, "child").add_edge("child", "wrap").compile()

print(parent.invoke({"text": "hello"}))
for ns, chunk in parent.stream({"text": "hello"}, stream_mode="updates", subgraphs=True):
    print([part.split(":")[0] for part in ns], list(chunk))
Output6 lines
{'text': '[HELLO!]'}
['child', 'grandchild'] ['shout']
['child'] ['grandchild']
['child'] ['exclaim']
[] ['child']
[] ['wrap']

Each streamed chunk carries the path of the nodes it came through: ['child', 'grandchild'] is a step of the grandchild, ['child'] a step of the child, and the empty list [] (the last two lines) is the parent itself. The real namespace entries are node_name:uuid; the id is a task id and changes every run, so never match on it. Namespaces matter beyond streaming: the checkpoint of an inner step is stored under its namespace ("" for the parent, "node:uuid" for a child, "outer:uuid|inner:uuid" for a nested one, per the docs), which is how a subgraph's saved state stays separate from its parent's.

2.5 Command.PARENT: leaving a subgraph#

A node inside a subgraph can return Command(goto="some_parent_node", graph=Command.PARENT, update={...}) to jump to a node of the closest parent graph. 08F.10, 6.3 built the minimal example. Two rules carry over, and both reappear in Part 4:

  • If the update writes a key that exists in both schemas, the parent must define a reducer for it (as in 2.3, an overwrite and an append behave differently).
  • The jump skips the rest of the subgraph: the inner node after the one that returned the Command never runs.

2.6 Subgraph persistence: checkpointer=None, True, False#

When a parent graph is compiled with a checkpointer (08F.11), each subgraph decides how to use it, through the checkpointer argument of the subgraph's own compile(). The parent is the one that must have a real checkpointer; the subgraph's setting chooses a mode:

Mode compile(checkpointer=...) Behaviour (per the docs)
Per-invocation (the default, recommended for most uses) None Each call starts with fresh state. It inherits the parent's checkpointer, so interrupts and durable execution work within one call. Parallel calls are fine, and each call gets its own checkpoint namespace
Per-thread True State accumulates across calls on the same thread: the subgraph picks up where it left off. No parallel calls to the same per-thread subgraph (checkpoint conflicts)
Stateless False No checkpointing: it behaves like a plain function. The docs say there are no interrupts and no durable execution: a crash means re-running from the start

The docs' feature table, which the samples below confirm in part:

Feature None True False
Interrupts yes yes no (docs); paused and resumed in the sample below, but the subgraph restarted from its first node
Memory across calls no yes no
Several calls to different subgraphs in one node yes warning (namespace conflicts, see 2.8) yes
Several calls to the same subgraph yes no yes
Reading its state only while it is interrupted yes no

The first sample calls one subgraph three times on the same thread, in each mode. The subgraph remembers every question in a private list and reports how many it has seen.

python
# s05_persistence_modes.py: subgraph checkpointer=None / True / False, same thread, three calls
import operator
from typing import Annotated

from typing_extensions import TypedDict

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph


class SubState(TypedDict):
    question: str
    seen: Annotated[list[str], operator.add]    # what this subgraph remembers
    answer: str


def remember(state: SubState):
    return {"seen": [state["question"]], "answer": f"I have now seen {len(state['seen']) + 1} question(s)"}


def build_sub(checkpointer):
    return StateGraph(SubState).add_node(remember).add_edge(START, "remember").compile(checkpointer=checkpointer)


class State(TypedDict):
    question: str
    answer: str


def build_parent(sub):
    def ask(state: State):
        out = sub.invoke({"question": state["question"]})
        return {"answer": out["answer"]}

    # the PARENT gets a real checkpointer; the subgraph's own setting is the experiment
    return StateGraph(State).add_node(ask).add_edge(START, "ask").add_edge("ask", END).compile(checkpointer=InMemorySaver())


for label, mode in [("None  (per-invocation)", None), ("True  (per-thread)", True), ("False (stateless)", False)]:
    parent = build_parent(build_sub(mode))
    cfg = {"configurable": {"thread_id": "t1"}}
    answers = [parent.invoke({"question": q}, cfg)["answer"] for q in ("q1", "q2", "q3")]
    print(f"{label:24}", answers)
Output3 lines
None  (per-invocation)   ['I have now seen 1 question(s)', 'I have now seen 1 question(s)', 'I have now seen 1 question(s)']
True  (per-thread)       ['I have now seen 1 question(s)', 'I have now seen 2 question(s)', 'I have now seen 3 question(s)']
False (stateless)        ['I have now seen 1 question(s)', 'I have now seen 1 question(s)', 'I have now seen 1 question(s)']

None and False forget: every call sees one question. True accumulates: 1, 2, 3. This is the whole difference between a stateless specialist and one with its own long conversation, and it is also why True forbids parallel calls: two simultaneous calls would write the same thread's subgraph state.

The second sample pauses a subgraph with an interrupt (08F.12 owns interrupt; here it only probes the modes) and then asks the parent for the subgraph's state with get_state(config, subgraphs=True).

python
# s06_interrupt_subgraph.py: an interrupt inside a subgraph, per mode, and viewing the subgraph's state
from typing_extensions import TypedDict

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, interrupt


class State(TypedDict):
    refund: float
    decision: str


def approve(state: State):
    answer = interrupt({"question": f"Approve a refund of {state['refund']}?"})
    return {"decision": answer}


def build(mode):
    sub = StateGraph(State).add_node(approve).add_edge(START, "approve").compile(checkpointer=mode)
    return StateGraph(State).add_node("sub", sub).add_edge(START, "sub").add_edge("sub", END).compile(checkpointer=InMemorySaver())


for label, mode in [("None ", None), ("True ", True), ("False", False)]:
    graph = build(mode)
    cfg = {"configurable": {"thread_id": "t1"}}
    try:
        first = graph.invoke({"refund": 40.0, "decision": ""}, cfg)
        print(label, "paused with:", [i.value for i in first.get("__interrupt__", [])])
        snap = graph.get_state(cfg, subgraphs=True)
        sub_snap = snap.tasks[0].state
        if sub_snap is None:
            print(label, "parent next:", snap.next, "| subgraph state: None (not available)")
            print(label, "resumed  :", graph.invoke(Command(resume="approved"), cfg))
            continue
        print(label, "parent next:", snap.next, "| subgraph state values:", sub_snap.values, "| subgraph next:", sub_snap.next)
        print(label, "resumed  :", graph.invoke(Command(resume="approved"), cfg))
    except Exception as e:  # noqa: BLE001
        print(label, "FAILED   :", type(e).__name__, str(e)[:110])
Output9 lines
None  paused with: [{'question': 'Approve a refund of 40.0?'}]
None  parent next: ('sub',) | subgraph state values: {'refund': 40.0, 'decision': ''} | subgraph next: ('approve',)
None  resumed  : {'refund': 40.0, 'decision': 'approved'}
True  paused with: [{'question': 'Approve a refund of 40.0?'}]
True  parent next: ('sub',) | subgraph state values: {'refund': 40.0, 'decision': ''} | subgraph next: ('approve',)
True  resumed  : {'refund': 40.0, 'decision': 'approved'}
False paused with: [{'question': 'Approve a refund of 40.0?'}]
False parent next: ('sub',) | subgraph state: None (not available)
False resumed  : {'refund': 40.0, 'decision': 'approved'}
python
# s07_false_mode_rerun.py: what checkpointer=False costs when a subgraph pauses after earlier work
from typing_extensions import TypedDict

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, interrupt

calls = {"prepare": 0}


class State(TypedDict):
    refund: float
    decision: str


def prepare(state: State):
    calls["prepare"] += 1            # stands in for an expensive or side-effecting step
    return {}


def approve(state: State):
    return {"decision": interrupt("approve?")}


def build(mode):
    sub = (
        StateGraph(State)
        .add_node(prepare)
        .add_node(approve)
        .add_edge(START, "prepare")
        .add_edge("prepare", "approve")
        .compile(checkpointer=mode)
    )
    return StateGraph(State).add_node("sub", sub).add_edge(START, "sub").add_edge("sub", END).compile(checkpointer=InMemorySaver())


for label, mode in [("None ", None), ("False", False)]:
    calls["prepare"] = 0
    graph = build(mode)
    cfg = {"configurable": {"thread_id": "t1"}}
    graph.invoke({"refund": 1.0, "decision": ""}, cfg)
    graph.invoke(Command(resume="yes"), cfg)
    print(label, "prepare ran", calls["prepare"], "time(s) across pause and resume")
Output2 lines
None  prepare ran 1 time(s) across pause and resume
False prepare ran 2 time(s) across pause and resume

With None, the work done before the interrupt (prepare) ran once, because the subgraph's own progress was saved. With False, it ran twice: on resume, the whole subgraph started again from its first node, and only the interrupt returned immediately. So treat False as "no durability inside this subgraph": it may appear to work, but anything before the pause repeats, which is a duplicated charge or email if it has side effects. I have not verified how the docs' claim and this behaviour fit together in every graph shape (for example False subgraphs called inside tools); do not build on interrupts inside a False subgraph.

2.7 Reading a subgraph's state, and when you cannot#

graph.get_state(config, subgraphs=True) returns the parent's StateSnapshot, and snapshot.tasks[0].state is the subgraph's snapshot (its values, its next). In the sample it showed the subgraph's refund key and next == ('approve',) for the None and True modes, and None for False. For None you get the state only while the subgraph is interrupted (it is the current invocation); for True it is the accumulated state.

One rule decides whether this works: LangGraph must be able to discover the subgraph statically. A subgraph that is a node, or is called inside a node function, is discovered. A subgraph called from inside a tool is not, which is exactly the subagents-as-tools pattern, and Part 3 shows that get_state(subgraphs=True) then returns nothing for it. If you need to inspect a subagent's state while it is paused, invoke it from a node of a custom graph instead (Part 6).

2.8 Namespaces when you call several subgraphs inside one node#

When you call subgraphs inside a node function (style 1), the namespaces that store their checkpoints are assigned in call order. With checkpointer=True subgraphs, that has a sharp edge, in the docs' words about the "same subgraph, different position": if you reorder the calls, the subgraph that used to be first now loads the state of whichever one is first, and per-thread memory is mixed up. The documented remedy is to wrap each agent in its own StateGraph with a unique node name, so its namespace is stable and name-based:

python
from langgraph.graph import MessagesState, StateGraph


def create_sub_agent(model, *, name, **kwargs):
    """Wrap an agent in its own graph with a fixed node name, so its checkpoint namespace is stable."""
    from langchain.agents import create_agent

    agent = create_agent(model=model, name=name, **kwargs)
    return StateGraph(MessagesState).add_node(name, agent).add_edge("__start__", name).compile()

This helper follows the shape the docs use. It is illustrative (not run here, and it needs a model to be useful): a sketch for the case "several per-thread agents inside one node", and I have not run the reordering scenario, so test it against your own graph. Subgraphs added as nodes already get name-based namespaces, which is one more reason to prefer style 2 when you can.

2.9 Other things that cross (or do not cross) the boundary#

From the docs, and worth knowing before you debug at 2 a.m.:

  • Time travel. With the default mode, a subgraph is one parent super-step: you cannot fork between its inner nodes. With checkpointer=True the inner checkpoints exist, and you fork from parent_state.tasks[0].state.config. 08F.11 owns time travel.
  • Node defaults are not inherited. Retry policies and timeouts set as defaults on the parent (set_node_defaults, 08F.12) do not apply inside a subgraph; set them on the subgraph's own nodes.
  • Errors surface to the parent node. An exception inside a subgraph reaches the parent's node handling for the node that holds the subgraph.
  • Token streaming. A parent's stream_mode="messages" will not emit the LLM tokens of an agent that is a subgraph unless you pass subgraphs=True (08F.14).

Part 3: Subagents: agents wrapped as tools#

3.1 The pattern, built#

This is the pattern the LangChain docs recommend for a "supervisor" today: a main agent made with create_agent whose tools are the subagents, each itself a create_agent wrapped in a function decorated with @tool. 08F.8, 5.5 showed the smallest version; this one has two specialists, one with its own tool, and prints what each side saw.

flowchart LR
    U["User message"] --> S["supervisor: create_agent"]
    S -->|"tool call: ask_billing(question)"| B["billing_agent<br/>own prompt, own tools, own context"]
    S -->|"tool call: ask_policy(question)"| P["policy_agent<br/>own prompt, own tools, own context"]
    B -.->|"final message only"| S
    P -.->|"final message only"| S
    S --> A["Answer to the user"]
python
# s10_subagents_as_tools.py: a supervisor create_agent whose tools are two subagents (scripted models)
from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool

from fakes import FakeToolCallingModel, RecordingModel


@tool
def lookup_order(order_id: str) -> str:
    """Look up an order by id."""
    return f"Order {order_id}: laptop, delivered 2026-10-02, paid 1299.00 EUR"


# --- subagent 1: billing. It has its own tool, its own prompt and its own (scripted) model.
billing_model = RecordingModel(messages=iter([
    AIMessage(content="", tool_calls=[ToolCall(name="lookup_order", args={"order_id": "A-1007"}, id="b1")]),
    AIMessage(content="Order A-1007 was paid 1299.00 EUR and is eligible for a refund until 2026-11-01."),
]))
billing_agent = create_agent(
    billing_model,
    tools=[lookup_order],
    system_prompt="You are the billing specialist. Answer in two sentences and include the order id.",
    name="billing_agent",
)

# --- subagent 2: policy, no tools
policy_agent = create_agent(
    FakeToolCallingModel(messages=iter([AIMessage(content="Laptops can be returned within 30 days of delivery.")])),
    tools=[],
    system_prompt="You answer questions about the returns policy. Be brief.",
    name="policy_agent",
)


@tool("ask_billing", description="Ask the billing specialist about an order, a payment or a refund. Pass a complete, self-contained question.")
def ask_billing(question: str) -> str:
    result = billing_agent.invoke({"messages": [{"role": "user", "content": question}]})
    return result["messages"][-1].text


@tool("ask_policy", description="Ask the policy specialist about returns and refunds rules. Pass a complete, self-contained question.")
def ask_policy(question: str) -> str:
    result = policy_agent.invoke({"messages": [{"role": "user", "content": question}]})
    return result["messages"][-1].text


supervisor_model = RecordingModel(messages=iter([
    AIMessage(content="", tool_calls=[
        ToolCall(name="ask_billing", args={"question": "What did order A-1007 cost, and is it still refundable?"}, id="s1"),
        ToolCall(name="ask_policy", args={"question": "What is the laptop return window?"}, id="s2"),
    ]),
    AIMessage(content="Order A-1007 cost 1299.00 EUR. Laptops can be returned within 30 days of delivery, so the window closed on 2026-11-01."),
]))
supervisor = create_agent(
    supervisor_model,
    tools=[ask_billing, ask_policy],
    system_prompt="You are a support lead. Delegate to the specialists, then answer the customer.",
    name="supervisor",
)

result = supervisor.invoke({"messages": [HumanMessage("I want to return my laptop, order A-1007. Can I?")]})

print("supervisor message trail:")
for m in result["messages"]:
    extra = f" tool_calls={[c['name'] for c in m.tool_calls]}" if getattr(m, "tool_calls", None) else ""
    print(f"  {m.type:5} {m.text[:70]!r}{extra}")

print("\nWhat the billing subagent's model saw on its 1st call:")
for kind, text in billing_model.seen[0]:
    print(f"  {kind:14} {text[:80]!r}")
print("\nDid the supervisor see the billing subagent's tool call? ",
      any("lookup_order" in str(getattr(m, "tool_calls", "")) for m in result["messages"]))
Output12 lines
supervisor message trail:
  human 'I want to return my laptop, order A-1007. Can I?'
  ai    '' tool_calls=['ask_billing', 'ask_policy']
  tool  'Order A-1007 was paid 1299.00 EUR and is eligible for a refund until 2'
  tool  'Laptops can be returned within 30 days of delivery.'
  ai    'Order A-1007 cost 1299.00 EUR. Laptops can be returned within 30 days '

What the billing subagent's model saw on its 1st call:
  SystemMessage  'You are the billing specialist. Answer in two sentences and include the order id'
  HumanMessage   'What did order A-1007 cost, and is it still refundable?'

Did the supervisor see the billing subagent's tool call?  False

Four things happened that are the whole pattern:

  1. The supervisor's model asked for two tools in one reply (ask_billing and ask_policy); the tool node ran both and appended two ToolMessages. That is parallel delegation for free (3.6).
  2. The billing subagent ran its own loop: its model called lookup_order, got a result, and answered. None of that is in the supervisor's trail.
  3. The subagent's model saw only a system message (its own prompt) and one human message: the question the supervisor wrote. It did not see the customer's conversation. That is context isolation (08D.3, 3.2) made literal.
  4. The supervisor's history holds the subagents' final text, nothing else (False on the last line: it never saw lookup_order).

3.2 What the supervisor sees, and what it does not#

The supervisor sees exactly what your wrapper returns, and nothing about how the subagent got there. The docs say it plainly: the supervisor only sees the final output. That is the point (small context, clean separation) and the main way this pattern fails.

You return The supervisor can Failure to watch for
result["messages"][-1].text Use the subagent's final answer The subagent's final message omitted the facts you needed (it did the work, then said "Done!")
A formatted summary you build from the whole result See sources, status, a confidence note You must write and maintain the formatting; it replaces the old output_mode of the helper package
A Command with extra state Receive more than text (a sources list, a flag) You must also return the matching ToolMessage (3.3)

So: prompt the subagent to put what the supervisor needs in its last message (the answer, the evidence, any caveat), and treat what the subagent returns as untrusted text if it ever read outside content (a web page, an uploaded file): the supervisor will act on it. 08D.3, 3.1 has the delegation-brief checklist; in this pattern the tool description and the tool's argument names are the brief.

3.3 Context down, results back: query only versus fork, text versus Command#

Two design decisions from the docs' table, shown together.

What goes in. Query only: the wrapper passes just the question, so the subagent is isolated and cheap. Fork: the wrapper passes the parent's messages as well, so the subagent shares the context (and the cost). A tool can read the parent's messages through ToolRuntime (08F.8, Part 3).

What comes out. Text: the return value becomes the ToolMessage. A Command: the tool updates parent state (a sources key, say) and must include a ToolMessage for its own call in update["messages"], as 08F.8, 3.3 explains.

python
# s11_outputs_and_inputs.py: what goes into a subagent (query only vs the parent's messages) and what comes back
from langchain.agents import AgentState, create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall, ToolMessage
from langchain.tools import ToolRuntime, tool
from langgraph.types import Command
from typing_extensions import NotRequired

from fakes import FakeToolCallingModel, RecordingModel


class SupportState(AgentState):
    sources: NotRequired[list[str]]     # extra key the supervisor keeps


researcher_model = RecordingModel(messages=iter([
    AIMessage(content="Found the answer in the returns policy."),
    AIMessage(content="Found the answer in the returns policy."),
]))
researcher = create_agent(researcher_model, tools=[], name="researcher", system_prompt="You research policy questions.")


@tool("research_isolated", description="Research a self-contained question.")
def research_isolated(question: str, runtime: ToolRuntime) -> Command:
    """Query only: the subagent sees nothing but the question. It returns text AND a state update."""
    result = researcher.invoke({"messages": [{"role": "user", "content": question}]})
    return Command(update={
        "sources": ["returns-policy.md"],                                  # extra state flows back
        "messages": [ToolMessage(result["messages"][-1].text, tool_call_id=runtime.tool_call_id)],  # required
    })


@tool("research_forked", description="Research using the whole conversation so far as context.")
def research_forked(question: str, runtime: ToolRuntime) -> str:
    """Fork: the subagent sees the parent's messages up to the delegating AI message, plus the question."""
    history = runtime.state["messages"][:-1]            # drop the AI message that holds this very tool call
    result = researcher.invoke({"messages": [*history, {"role": "user", "content": question}]})
    return result["messages"][-1].text


def run(tool_fn, tool_name):
    researcher_model.seen.clear()
    sup = create_agent(
        FakeToolCallingModel(messages=iter([
            AIMessage(content="", tool_calls=[ToolCall(name=tool_name, args={"question": "Is a 45-day-old laptop returnable?"}, id="c1")]),
            AIMessage(content="No: the window is 30 days."),
        ])),
        tools=[tool_fn],
        state_schema=SupportState,
        name="supervisor",
    )
    out = sup.invoke({"messages": [HumanMessage("My name is Dana. I bought a laptop 45 days ago.")]})
    print(f"{tool_name}: subagent saw {[k for k, _ in researcher_model.seen[0]]}")
    print(f"{tool_name}: supervisor state has sources = {out.get('sources')}")


run(research_isolated, "research_isolated")
run(research_forked, "research_forked")
Output4 lines
research_isolated: subagent saw ['SystemMessage', 'HumanMessage']
research_isolated: supervisor state has sources = ['returns-policy.md']
research_forked: subagent saw ['SystemMessage', 'HumanMessage', 'HumanMessage']
research_forked: supervisor state has sources = None

The isolated tool's subagent saw two messages (its system prompt and the question); the forked one saw one more (the customer's introduction, "My name is Dana..."). The isolated tool also wrote sources into the supervisor's state through a Command, so the application can show citations without putting file names into the prompt. Choose by what the subagent needs to know, not by habit: a policy lookup needs the question; a drafting agent that must keep the customer's tone needs the conversation. The docs' name for the forked variant is exactly "fork", and Deep Agents expose the same choice as a subagent mode (1.4).

Run-time context goes down too. A subagent that needs the caller's identity (a user id, a tenant, permissions) does not need it copied into the prompt. The parent's run-time context (08F.10, Part 9; ToolRuntime.context in 08F.8) is inherited by a subagent invoked inside a tool, and the wrapper can replace it by passing context= explicitly. Run, with a subagent whose tool reports runtime.context.user_id:

python
# s16_context_to_subagent.py: does the parent's run-time context reach a subagent called inside a tool, and can the wrapper replace it?
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import ToolRuntime, tool

from fakes import FakeToolCallingModel


@dataclass
class Ctx:
    user_id: str


@tool
def whoami(runtime: ToolRuntime[Ctx]) -> str:
    """Report which user this run is for (reads run-time context)."""
    ctx = runtime.context
    return f"user_id={ctx.user_id if ctx else None}"


def build_billing():
    return create_agent(
        FakeToolCallingModel(messages=iter([
            AIMessage(content="", tool_calls=[ToolCall(name="whoami", args={}, id="w1")]),
            AIMessage(content="done"),
        ])),
        tools=[whoami],
        context_schema=Ctx,
        name="billing",
    )


def seen_by_subagent(mode: str) -> str:
    billing = build_billing()

    @tool("ask_billing", description="Ask the billing specialist.")
    def ask_billing(question: str, runtime: ToolRuntime[Ctx]) -> str:
        kwargs = {"context": Ctx(user_id="u-override")} if mode == "override" else {}
        result = billing.invoke({"messages": [{"role": "user", "content": question}]}, **kwargs)
        return next(m.text for m in result["messages"] if m.type == "tool")

    supervisor = create_agent(
        FakeToolCallingModel(messages=iter([
            AIMessage(content="", tool_calls=[ToolCall(name="ask_billing", args={"question": "who am I?"}, id="s1")]),
            AIMessage(content="ok"),
        ])),
        tools=[ask_billing],
        context_schema=Ctx,
        name="supervisor",
    )
    out = supervisor.invoke({"messages": [HumanMessage("hi")]}, context=Ctx(user_id="u-42"))
    return next(m.text for m in out["messages"] if m.type == "tool")


print("nothing passed         :", seen_by_subagent("inherit"))
print("context=Ctx(u-override):", seen_by_subagent("override"))
Output2 lines
nothing passed         : user_id=u-42
context=Ctx(u-override): user_id=u-override

With nothing passed the subagent's tool saw the parent's u-42; with context=Ctx(user_id="u-override") it saw the override. So a wrapper only needs context= when it wants the subagent to run as a different identity or scope. The subagent must declare the same context_schema to read it. Not verified for this lesson: the same inheritance for the store, and for async runs on older Python versions; check the docs before relying on either.

3.4 One tool per subagent, or one dispatch tool#

With two specialists a tool each is natural. With twenty, the tool list itself becomes the context-management problem the pattern was meant to solve. The docs offer a second design: a single task tool that takes the specialist's name and the task, with the available specialists described in the tool's description (or discovered on demand).

python
# s15_dispatch_tool.py: ONE `task` tool for many subagents instead of one tool per subagent
from typing import Literal

from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool

from fakes import FakeToolCallingModel

SUBAGENTS = {
    "billing": create_agent(FakeToolCallingModel(messages=iter([AIMessage(content="billing: invoice 204 unpaid")])), tools=[], name="billing"),
    "shipping": create_agent(FakeToolCallingModel(messages=iter([AIMessage(content="shipping: parcel in transit")])), tools=[], name="shipping"),
}
DESCRIPTIONS = {"billing": "invoices, payments, refunds", "shipping": "parcels, delivery, tracking"}


@tool("task", description="Delegate a self-contained task to a specialist. Specialists: "
      + "; ".join(f"{k} ({v})" for k, v in DESCRIPTIONS.items()))
def task(specialist: Literal["billing", "shipping"], description: str) -> str:
    """The Literal type becomes an enum in the schema, so the model cannot invent a specialist name."""
    agent = SUBAGENTS[specialist]
    return agent.invoke({"messages": [{"role": "user", "content": description}]})["messages"][-1].text


print("schema enum:", task.args["specialist"].get("enum"))
sup = create_agent(
    FakeToolCallingModel(messages=iter([
        AIMessage(content="", tool_calls=[ToolCall(name="task", args={"specialist": "shipping", "description": "Where is parcel 99-1?"}, id="1")]),
        AIMessage(content="Your parcel is in transit."),
    ])),
    tools=[task],
)
out = sup.invoke({"messages": [HumanMessage("Where is my parcel?")]})
print([m.text for m in out["messages"] if m.type == "tool"], "->", out["messages"][-1].text)
Output2 lines
schema enum: ['billing', 'shipping']
['shipping: parcel in transit'] -> Your parcel is in transit.

Because the parameter is a Literal, it becomes an enum in the tool's schema, so the model cannot call a specialist that does not exist. The trade-off:

One tool per subagent One task tool
Model sees Each specialist as its own tool with its own description and argument names One tool; specialists listed in its description or discovered
Adding a specialist Add a tool (and its description competes with the rest) Add a dictionary entry
Per-specialist arguments Natural (each tool has its own schema) Awkward (one shared schema, or free text)
Good for A handful of specialists with distinct inputs Many specialists, plug-in teams, dynamic registries

3.5 Names, and what you can see in a trace#

Give every agent a name= (create_agent(..., name="billing_agent")): names label the nodes in traces and, as the later parts show, are required and must be unique by the helper packages. The @tool name and description are the supervisor's view; the agent's name is yours. For streaming a supervisor's run, the event streaming API from 08F.8, 10.3 has a subagents projection (currently marked experimental by the package); 08F.14 covers what the stream modes show from inside a tool-called agent. 11A.5 covers the trace tree that LangSmith builds from these nested calls.

3.6 Parallel subagent calls#

When the supervisor's reply holds several tool calls, the tool node runs them concurrently. The sample runs two subagent-like tools that each take 0.4 seconds, in one turn:

python
# s12_parallel_and_limits.py: parallel subagent calls in one turn; ToolCallLimitMiddleware signature
import inspect
import time

from langchain.agents import create_agent
from langchain.agents.middleware import ToolCallLimitMiddleware
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool

from fakes import FakeToolCallingModel


@tool
def ask_a(q: str) -> str:
    """Slow specialist A."""
    time.sleep(0.4)
    return "A done"


@tool
def ask_b(q: str) -> str:
    """Slow specialist B."""
    time.sleep(0.4)
    return "B done"


sup = create_agent(
    FakeToolCallingModel(messages=iter([
        AIMessage(content="", tool_calls=[ToolCall(name="ask_a", args={"q": "x"}, id="1"), ToolCall(name="ask_b", args={"q": "y"}, id="2")]),
        AIMessage(content="both finished"),
    ])),
    tools=[ask_a, ask_b],
)
t0 = time.perf_counter()
sup.invoke({"messages": [HumanMessage("go")]})
elapsed = time.perf_counter() - t0
print("two 0.4 s subagent calls in one turn finished in under 0.7 s:", elapsed < 0.7)

print(inspect.signature(ToolCallLimitMiddleware.__init__))

# run_limit=1 on one tool: the second call in the same run is blocked, the run does not crash
limited = create_agent(
    FakeToolCallingModel(messages=iter([
        AIMessage(content="", tool_calls=[ToolCall(name="ask_a", args={"q": "1"}, id="1")]),
        AIMessage(content="", tool_calls=[ToolCall(name="ask_a", args={"q": "2"}, id="2")]),
        AIMessage(content="done"),
    ])),
    tools=[ask_a],
    middleware=[ToolCallLimitMiddleware(tool_name="ask_a", run_limit=1)],
)
out = limited.invoke({"messages": [HumanMessage("go")]})
for m in out["messages"]:
    if m.type == "tool":
        print("tool message:", m.status, "|", m.text[:100])
Output4 lines
two 0.4 s subagent calls in one turn finished in under 0.7 s: True
(self, *, tool_name: 'str | None' = None, thread_limit: 'int | None' = None, run_limit: 'int | None' = None, exit_behavior: 'ExitBehavior' = 'continue') -> 'None'
tool message: success | A done
tool message: error | Tool call limit exceeded. Do not call 'ask_a' again.

The first line is true because both finished within the time of one (if they had run one after the other it would have taken 0.8 seconds or more). Parallel subagents are the whole gain of the research fan-out of 08D.3, 2.8, and its whole risk: nothing bounds how many a model asks for in one turn. Bound it yourself: describe the cap in the supervisor's prompt (08D.3 shows effort-scaling bands), cap calls per tool with ToolCallLimitMiddleware, and cap the whole run with the model-call limit from 08F.8, 7.5.

The sample's second half shows the limiter: ToolCallLimitMiddleware(tool_name="ask_a", run_limit=1) lets the first call run, and on the second the model gets an error ToolMessage ("Tool call limit exceeded. Do not call 'ask_a' again.") instead of a crash, because exit_behavior defaults to "continue". The printed signature shows the knobs: tool_name, thread_limit, run_limit and exit_behavior.

3.7 Do subagents remember? Stateless by default, per-thread on request#

By default a subagent is stateless: each call starts from only the messages the wrapper passes. The docs give the reason (strong context isolation) and the price (a repeated request pays full cost again). To give a subagent a persistent history on the same thread, create it with checkpointer=True, which is the subgraph mode of 2.6 applied to an agent. Only the outermost agent gets a real checkpointer:

python
# s13_subagent_memory.py: does a subagent remember across supervisor turns? checkpointer None versus True
from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool
from langgraph.checkpoint.memory import InMemorySaver

from fakes import FakeToolCallingModel, RecordingModel


def build(sub_checkpointer):
    sub_model = RecordingModel(messages=iter([AIMessage(content="answer 1"), AIMessage(content="answer 2")]))
    sub = create_agent(sub_model, tools=[], name="expert", checkpointer=sub_checkpointer)

    @tool("ask_expert", description="Ask the expert.")
    def ask_expert(question: str) -> str:
        return sub.invoke({"messages": [{"role": "user", "content": question}]})["messages"][-1].text

    sup = create_agent(
        FakeToolCallingModel(messages=iter([
            AIMessage(content="", tool_calls=[ToolCall(name="ask_expert", args={"question": "first question"}, id="1")]),
            AIMessage(content="turn 1 done"),
            AIMessage(content="", tool_calls=[ToolCall(name="ask_expert", args={"question": "second question"}, id="2")]),
            AIMessage(content="turn 2 done"),
        ])),
        tools=[ask_expert],
        checkpointer=InMemorySaver(),          # only the OUTERMOST agent gets a real checkpointer
    )
    cfg = {"configurable": {"thread_id": "t1"}}
    sup.invoke({"messages": [HumanMessage("turn 1")]}, cfg)
    sup.invoke({"messages": [HumanMessage("turn 2")]}, cfg)
    return sub_model


for label, mode in [("default (None)", None), ("checkpointer=True", True)]:
    m = build(mode)
    second_call = [text for kind, text in m.seen[1] if kind == "HumanMessage"]
    print(f"{label:18} on the 2nd call the expert saw these user messages: {second_call}")
Output2 lines
default (None)     on the 2nd call the expert saw these user messages: ['second question']
checkpointer=True  on the 2nd call the expert saw these user messages: ['first question', 'second question']

With the default, the expert's second call saw only the second question. With checkpointer=True it saw both: its conversation accumulated across supervisor turns on the same thread. Three consequences follow from the table in 2.6:

  • No parallel calls to a per-thread subagent. Two calls in one turn would write the same thread state. Limit that tool to one call per run (run_limit=1, 3.6) or turn off parallel tool calls for the model.
  • Its state grows without bound: add summarization (08F.8, 8.8) or a trimming step.
  • It is harder to reason about: the supervisor's behaviour now depends on a hidden conversation. Prefer passing the needed context explicitly (3.3) until you have measured that the repeated cost matters.

3.8 Interrupts through nested agents#

A subagent that needs a human decision (a refund above a limit, a risky delete) can call interrupt() from one of its tools, even though the subagent itself is called from a tool of another agent. The docs give two requirements: compile only the outermost graph with a checkpointer (leave the subagents without checkpointer=), and pass the thread_id in the outer call's config. Then the interrupt travels up through every layer, shows up on the outer result as __interrupt__, and Command(resume=...) on the outer graph resumes it.

python
# s14_nested_interrupt.py: an interrupt() in a tool of a subagent that is itself called from a tool
from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command, interrupt

from fakes import FakeToolCallingModel


@tool
def issue_refund(order_id: str, amount: float) -> str:
    """Issue a refund. Needs a human decision first."""
    decision = interrupt({"action": "issue_refund", "order_id": order_id, "amount": amount})
    return f"refund {decision}"


# the subagent has NO checkpointer of its own
refund_agent = create_agent(
    FakeToolCallingModel(messages=iter([
        AIMessage(content="", tool_calls=[ToolCall(name="issue_refund", args={"order_id": "A-1007", "amount": 40.0}, id="r1")]),
        AIMessage(content="Refund handled."),
    ])),
    tools=[issue_refund],
    name="refund_agent",
)


@tool("ask_refunds", description="Hand a refund task to the refunds specialist.")
def ask_refunds(task: str) -> str:
    return refund_agent.invoke({"messages": [{"role": "user", "content": task}]})["messages"][-1].text


supervisor = create_agent(
    FakeToolCallingModel(messages=iter([
        AIMessage(content="", tool_calls=[ToolCall(name="ask_refunds", args={"task": "Refund 40 on A-1007"}, id="s1")]),
        AIMessage(content="The refund was processed."),
    ])),
    tools=[ask_refunds],
    checkpointer=InMemorySaver(),            # ONLY the outermost graph is compiled with one
)

cfg = {"configurable": {"thread_id": "support-1"}}                # and the thread id goes on the OUTER call
first = supervisor.invoke({"messages": [HumanMessage("Please refund order A-1007")]}, cfg)
print("paused, interrupt value:", [i.value for i in first["__interrupt__"]])

snap = supervisor.get_state(cfg, subgraphs=True)
print("outer next:", snap.next)
print("subagent state visible through get_state(subgraphs=True)?", snap.tasks[0].state is not None)

final = supervisor.invoke(Command(resume="approved"), cfg)
print("final answer:", final["messages"][-1].text)
Output4 lines
paused, interrupt value: [{'action': 'issue_refund', 'order_id': 'A-1007', 'amount': 40.0}]
outer next: ('tools',)
subagent state visible through get_state(subgraphs=True)? False
final answer: The refund was processed.

The run paused with the subagent's interrupt payload on the outer result; get_state(..., subgraphs=True) returned no state for the subagent (the discovery rule of 2.7: it was called inside a tool); and resuming from the outer graph finished the whole chain. On resume the tool wrapper ran again from its first line and the subagent continued from its own saved step rather than starting over, because it inherited the outer checkpointer.

3.9 Hierarchies, background work and per-role models#

  • Nested supervisors. A subagent may itself be a supervisor with subagent tools; flatten if you can (one supervisor with one tool per leaf), because every level adds a lossy summary and a failure point (08D.3, 2.3).
  • "Async" in the docs. When the docs list "sync versus async" as a subagent design choice, async means a background job in a separate process or service whose result arrives later, not Python's async def. Python async works with agents too, but it is a different topic (08F.8, 2.6).
  • A model per role. Each create_agent takes its own model, so a cheap fast model can triage and a stronger one can synthesize (08D.3, 1.3). The sketch below uses the course's model table for the provider strings; swap the strings for the provider you use.
python
from langchain.agents import create_agent
from langchain.tools import tool

# one cheap model for a narrow specialist, a stronger one for the agent that talks to the user
lookup_agent = create_agent("openai:gpt-6-luna", tools=[], name="lookup_agent",
                            system_prompt="You answer order-status questions. Be brief.")


@tool("ask_lookup", description="Ask the order-status specialist a self-contained question.")
def ask_lookup(question: str) -> str:
    return lookup_agent.invoke({"messages": [{"role": "user", "content": question}]})["messages"][-1].text


lead = create_agent("anthropic:claude-sonnet-5-5", tools=[ask_lookup], name="support_lead",
                    system_prompt="You are the support lead. Delegate lookups, then answer the customer.")

This sketch is illustrative: it needs a provider key and the matching langchain-openai and langchain-anthropic packages (08F.4), and the model ids follow the course's table as of November 2026, so check the providers' pages for current ids. The wiring (a tool wrapper per specialist, a model per agent) is the part that does not change.


Part 4: Handoffs: control moves with a Command#

4.1 The mechanism#

In the subagents pattern the main agent stays in charge: a specialist answers and control returns. In a handoff, control moves. A tool call changes a state variable (the active agent, or the current step), and the system reads that variable to decide who speaks next. The docs credit OpenAI with the term. The mechanism in LangGraph is a tool that returns a Command (08F.8, 3.3, 08F.10, Part 6): an update that sets the variable and, in the multi-agent form, a goto that names the next agent.

The docs describe two ways to build it, and they trade flexibility for simplicity:

Implementation One agent or many How the switch happens Choose it when
Single agent with middleware (the docs' recommendation for most cases) One create_agent A wrap_model_call hook changes the system prompt and the offered tools according to current_step Your "agents" are really steps of one conversation with different instructions and tools (collect warranty status, then classify, then resolve)
Multiple agent subgraphs Several create_agents as nodes of a parent graph Handoff tools return Command(goto=..., graph=Command.PARENT) and a router reads active_agent The agents are genuinely distinct (own model, own tools, own owners) and the specialist should own the next turns

4.2 builds the second form, 4.4 the first. Both avoid the supervisor's per-turn relay cost, which is why handoffs are the cheaper pattern on repeat requests (1.3).

4.2 Handoff tools between agent nodes#

The sample is a small customer-support graph: a sales agent and a support agent, each with one handoff tool to the other.

flowchart TD
    st["START"] -->|"route_initial reads active_agent"| sales["sales_agent node"]
    st -->|"route_initial reads active_agent"| support["support_agent node"]
    sales -->|"tool: transfer_to_support returns Command goto support_agent graph PARENT"| support
    support -->|"tool: transfer_to_sales returns Command goto sales_agent graph PARENT"| sales
    sales -->|"no tool calls: route_after_agent returns end"| en["END"]
    support -->|"no tool calls: route_after_agent returns end"| en
python
# s20_handoff_graph.py: two agents as nodes of a parent graph, handing off with Command.PARENT
from typing import Literal

from langchain.agents import AgentState, create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall, ToolMessage
from langchain.tools import ToolRuntime, tool
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command
from typing_extensions import NotRequired

from fakes import FakeToolCallingModel, RecordingModel


class MultiAgentState(AgentState):
    active_agent: NotRequired[str]


@tool
def transfer_to_sales(runtime: ToolRuntime) -> Command:
    """Transfer the customer to the sales agent (pricing, quotes, new orders)."""
    last_ai = next(m for m in reversed(runtime.state["messages"]) if isinstance(m, AIMessage))
    ack = ToolMessage(content="Transferred to the sales agent", tool_call_id=runtime.tool_call_id)
    return Command(
        goto="sales_agent",
        update={"active_agent": "sales_agent", "messages": [last_ai, ack]},   # exactly these two, not the whole history
        graph=Command.PARENT,
    )


@tool
def transfer_to_support(runtime: ToolRuntime) -> Command:
    """Transfer the customer to the support agent (faults, returns, refunds)."""
    last_ai = next(m for m in reversed(runtime.state["messages"]) if isinstance(m, AIMessage))
    ack = ToolMessage(content="Transferred to the support agent", tool_call_id=runtime.tool_call_id)
    return Command(
        goto="support_agent",
        update={"active_agent": "support_agent", "messages": [last_ai, ack]},
        graph=Command.PARENT,
    )


sales_model = RecordingModel(messages=iter([
    AIMessage(content="", tool_calls=[ToolCall(name="transfer_to_support", args={}, id="t1")]),
]))
support_model = RecordingModel(messages=iter([
    AIMessage(content="I can help with the return. What is the order number?"),
]))

sales_agent = create_agent(sales_model, tools=[transfer_to_support], state_schema=MultiAgentState,
                           system_prompt="You are the sales agent. Hand faults and returns to support.", name="sales_agent")
support_agent = create_agent(support_model, tools=[transfer_to_sales], state_schema=MultiAgentState,
                             system_prompt="You are the support agent. Hand pricing questions to sales.", name="support_agent")


def call_sales(state: MultiAgentState):
    return sales_agent.invoke(state)


def call_support(state: MultiAgentState):
    return support_agent.invoke(state)


def route_initial(state: MultiAgentState) -> Literal["sales_agent", "support_agent"]:
    return state.get("active_agent") or "sales_agent"                # default entry point


def route_after_agent(state: MultiAgentState) -> Literal["sales_agent", "support_agent", "__end__"]:
    last = state["messages"][-1]
    if isinstance(last, AIMessage) and not last.tool_calls:
        return "__end__"                                              # the agent answered the user: stop
    return state.get("active_agent") or "__end__"


builder = StateGraph(MultiAgentState)
builder.add_node("sales_agent", call_sales)
builder.add_node("support_agent", call_support)
builder.add_conditional_edges(START, route_initial, ["sales_agent", "support_agent"])
builder.add_conditional_edges("sales_agent", route_after_agent, ["sales_agent", "support_agent", END])
builder.add_conditional_edges("support_agent", route_after_agent, ["sales_agent", "support_agent", END])
graph = builder.compile()

out = graph.invoke({"messages": [HumanMessage("My new laptop arrived with a cracked screen.")]})
print("active_agent at the end:", out["active_agent"])
print("final message:", out["messages"][-1].text)
print("\nmessage trail:")
for m in out["messages"]:
    extra = f" tool_calls={[c['name'] for c in m.tool_calls]}" if getattr(m, "tool_calls", None) else ""
    print(f"  {m.type:5} {m.text[:60]!r}{extra}")
print("\nWhat the support agent's model received:")
for kind, text in support_model.seen[0]:
    print(f"  {kind:14} {text[:60]!r}")
Output14 lines
active_agent at the end: support_agent
final message: I can help with the return. What is the order number?

message trail:
  human 'My new laptop arrived with a cracked screen.'
  ai    '' tool_calls=['transfer_to_support']
  tool  'Transferred to the support agent'
  ai    'I can help with the return. What is the order number?'

What the support agent's model received:
  SystemMessage  'You are the support agent. Hand pricing questions to sales.'
  HumanMessage   'My new laptop arrived with a cracked screen.'
  AIMessage      ''
  ToolMessage    'Transferred to the support agent'

How it works, in the order it ran:

  1. START consults route_initial: no active_agent yet, so sales_agent runs (the default entry point). The node is a wrapper, sales_agent.invoke(state), because the parent's state and the agent's state are the same schema (MultiAgentState, an AgentState plus active_agent).
  2. The sales agent's model asked for transfer_to_support. The tool returned a Command with graph=Command.PARENT, so the jump is to the node named support_agent in the parent graph, not inside the sales agent's own graph, and the sales agent's loop ended there.
  3. The tool's update wrote active_agent, and two messages into the shared history: the AIMessage that held the tool call, and a ToolMessage that answers it (4.3).
  4. The support agent started with the customer's message, the (empty) handoff AIMessage and the acknowledgement. Its model's input is printed: the system prompt of the support agent, then the shared conversation. It answered with no tool calls, and route_after_agent returned "__end__".

Two details deserve a sentence each. The handoff tool reads runtime.state and runtime.tool_call_id from ToolRuntime (08F.8, Part 3), which is also why the tool needs the runtime parameter and the tool node of create_agent (it propagates a returned Command; a hand-written tool node must too). And the type hints on the routers (Literal[...]) are what let the drawing show the edges (08F.10, 5.2).

Run it: one agent whose handoff tool jumps to b, and a conditional edge after it that records each call and returns whatever it is told to.

python
# s52_router_cannot_veto.py: does an edge after a node run after a Command.PARENT jump, and can it cancel the jump?
from langchain.agents import AgentState, create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall, ToolMessage
from langchain.tools import ToolRuntime, tool
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command
from typing_extensions import NotRequired

from fakes import FakeToolCallingModel


class S(AgentState):
    active_agent: NotRequired[str]


@tool
def go_b(runtime: ToolRuntime) -> Command:
    """Hand the conversation to agent b."""
    last_ai = next(m for m in reversed(runtime.state["messages"]) if isinstance(m, AIMessage))
    return Command(
        goto="b",
        graph=Command.PARENT,
        update={"active_agent": "b", "messages": [last_ai, ToolMessage("ok", tool_call_id=runtime.tool_call_id)]},
    )


def make_agent(name, script, tools, ran):
    agent = create_agent(FakeToolCallingModel(messages=iter(script)), tools=tools, state_schema=S, name=name)

    def node(state):
        ran.append(name)
        return agent.invoke(state)

    return node


def run(router_returns):
    ran, router_calls = [], []
    handoff = AIMessage(content="", tool_calls=[ToolCall(name="go_b", args={}, id="1")])
    builder = StateGraph(S)
    builder.add_node("a", make_agent("a", [handoff], [go_b], ran))
    builder.add_node("b", make_agent("b", [AIMessage(content="b here")], [], ran))
    builder.add_node("c", make_agent("c", [AIMessage(content="c here")], [], ran))

    def router(state):
        router_calls.append(1)
        return router_returns

    builder.add_edge(START, "a")
    builder.add_conditional_edges("a", router, ["b", "c", END])
    builder.add_edge("b", END)
    builder.add_edge("c", END)
    try:
        builder.compile().invoke({"messages": [HumanMessage("hi")]})
        outcome = "ok"
    except Exception as exc:
        outcome = type(exc).__name__
    print(f"router returns {router_returns!r:9} -> router calls: {len(router_calls)}, nodes run: {ran}, outcome: {outcome}")


run("b")
run(END)
run("c")
Output3 lines
router returns 'b'       -> router calls: 1, nodes run: ['a', 'b'], outcome: ok
router returns '__end__' -> router calls: 1, nodes run: ['a', 'b'], outcome: ok
router returns 'c'       -> router calls: 1, nodes run: ['a', 'b', 'c'], outcome: InvalidUpdateError

The router ran once in every case (so "edges are skipped" is wrong). Returning "b" agrees with the jump; returning END still ran b, so the edge could not veto it; returning "c" ran b and c and failed, because the two agents both wrote active_agent in one step.

4.3 The messages a handoff must carry#

The docs' rule has a reason you can reproduce. When a model emits a tool call, the provider's API expects the conversation to contain a result for it. A history with an AIMessage that has a tool_call but no ToolMessage with the same tool_call_id is malformed, and providers reject it. The docs' prescription for a handoff: update messages with exactly the AIMessage that contained the tool call and a ToolMessage that acknowledges it (id from runtime.tool_call_id), and nothing else, so the receiving agent gets a small, valid history. Put what it needs to know in the acknowledgement's text if you want to pass a summary.

What the three possible mistakes actually do, run:

python
# s21_missing_toolmessage.py: a handoff tool that forgets the ToolMessage, and a validator for message history
from typing import Literal

from langchain.agents import AgentState, create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import ToolRuntime, tool
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command
from typing_extensions import NotRequired

from fakes import FakeToolCallingModel


class S(AgentState):
    active_agent: NotRequired[str]


@tool
def transfer_bad(runtime: ToolRuntime) -> Command:
    """Transfer without acknowledging the tool call (BUG)."""
    return Command(goto="b", update={"active_agent": "b"}, graph=Command.PARENT)   # no ToolMessage, no AIMessage


@tool
def transfer_bad_messages(runtime: ToolRuntime) -> Command:
    """Transfer that puts a plain AI message in instead of the pair (BUG)."""
    return Command(goto="b", update={"active_agent": "b", "messages": [AIMessage("handing off")]}, graph=Command.PARENT)


@tool
def transfer_ai_only(runtime: ToolRuntime) -> Command:
    """Transfer that copies the AI message with the call but no ToolMessage (BUG)."""
    last_ai = next(m for m in reversed(runtime.state["messages"]) if isinstance(m, AIMessage))
    return Command(goto="b", update={"active_agent": "b", "messages": [last_ai]}, graph=Command.PARENT)


def build(tool_fn, name):
    a = create_agent(
        FakeToolCallingModel(messages=iter([AIMessage(content="", tool_calls=[ToolCall(name=name, args={}, id="t1")])])),
        tools=[tool_fn], state_schema=S, name="a",
    )
    b = create_agent(FakeToolCallingModel(messages=iter([AIMessage(content="b here")])), tools=[], state_schema=S, name="b")
    g = StateGraph(S)
    g.add_node("a", lambda s: a.invoke(s))
    g.add_node("b", lambda s: b.invoke(s))
    g.add_edge(START, "a")
    g.add_edge("b", END)
    return g.compile()


def check_history(messages):
    """Every AI tool call must be answered by a ToolMessage with the same id (what providers require)."""
    answered = {m.tool_call_id for m in messages if m.type == "tool"}
    return [c["id"] for m in messages if m.type == "ai" for c in m.tool_calls if c["id"] not in answered]


for tool_fn, name in [(transfer_bad, "transfer_bad"), (transfer_bad_messages, "transfer_bad_messages"), (transfer_ai_only, "transfer_ai_only")]:
    try:
        out = build(tool_fn, name).invoke({"messages": [HumanMessage("hi")]})
        print(f"{name:22} ran; history = {[m.type for m in out['messages']]}; unanswered tool calls: {check_history(out['messages'])}")
    except Exception as e:  # noqa: BLE001
        print(name, "->", type(e).__name__, str(e)[:160])
Output3 lines
transfer_bad           ran; history = ['human', 'ai']; unanswered tool calls: []
transfer_bad_messages  ran; history = ['human', 'ai', 'ai']; unanswered tool calls: []
transfer_ai_only       ran; history = ['human', 'ai', 'ai']; unanswered tool calls: ['t1']

Read this carefully, because it is subtler than "forgetting the ToolMessage breaks everything":

  • transfer_bad (no messages update at all) and transfer_bad_messages (a plain AIMessage instead of the pair) both run, and both leave a valid history. The reason: when a tool leaves the agent with Command.PARENT, the agent's own messages (including the AIMessage with the call) are not copied to the parent unless you put them in the update. The receiving agent just never sees the handoff, which loses information (it does not know a transfer happened) but breaks nothing.
  • transfer_ai_only (the AIMessage with the call, no ToolMessage) leaves the call t1 unanswered in the shared history. LangGraph raises nothing; the history is silently malformed, and the next real provider call is where it fails. That is the dangerous one, because nothing fails in tests that use a fake model.

So the rule is "if you copy the AIMessage, you must add the matching ToolMessage", and the docs' recommendation of copying both is what keeps the receiving agent informed. The check_history function in the sample is worth keeping: Part 9 turns it into an assertion for your tests.

4.4 The single-agent variant: a state variable and a middleware#

If the "agents" are steps of one conversation, you do not need several agents. One create_agent, with every tool registered up front, and a wrap_model_call middleware (08F.8, 8.4) that picks the system prompt and the visible tools by current_step. Tools move the conversation along by returning a Command that updates current_step.

python
# s22_middleware_handoff.py: handoffs inside ONE agent: a state variable decides the prompt and the tools
from langchain.agents import AgentState, create_agent
from langchain.agents.middleware import ModelRequest, wrap_model_call
from langchain.messages import AIMessage, HumanMessage, SystemMessage, ToolCall, ToolMessage
from langchain.tools import ToolRuntime, tool
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command
from typing_extensions import NotRequired

from fakes import RecordingModel


class SupportState(AgentState):
    current_step: NotRequired[str]      # "triage" until the agent hands off
    issue_type: NotRequired[str]


@tool
def record_issue_type(issue_type: str, runtime: ToolRuntime) -> Command:
    """Record whether the issue is 'hardware' or 'billing', then move to the specialist step."""
    return Command(update={
        "issue_type": issue_type,
        "current_step": "specialist",
        "messages": [ToolMessage(f"Issue recorded as {issue_type}", tool_call_id=runtime.tool_call_id)],   # required
    })


@tool
def start_repair(order_id: str) -> str:
    """Open a repair case for a hardware fault."""
    return f"repair case opened for {order_id}"


@tool
def go_back_to_triage(runtime: ToolRuntime) -> Command:
    """Return to triage if the customer's issue is not what was recorded."""
    return Command(update={
        "current_step": "triage",
        "messages": [ToolMessage("Back to triage", tool_call_id=runtime.tool_call_id)],
    })


STEPS = {
    "triage": {"prompt": "You are the triage step. Find out the issue type and record it.", "tools": ["record_issue_type"]},
    "specialist": {"prompt": "You are the hardware specialist. Open a repair case.", "tools": ["start_repair", "go_back_to_triage"]},
}


@wrap_model_call(state_schema=SupportState)
def step_config(request: ModelRequest, handler):
    step = request.state.get("current_step", "triage")
    cfg = STEPS[step]
    allowed = [t for t in request.tools if t.name in cfg["tools"]]
    return handler(request.override(system_message=SystemMessage(cfg["prompt"]), tools=allowed))


model = RecordingModel(messages=iter([
    AIMessage(content="", tool_calls=[ToolCall(name="record_issue_type", args={"issue_type": "hardware"}, id="c1")]),
    AIMessage(content="", tool_calls=[ToolCall(name="start_repair", args={"order_id": "A-1007"}, id="c2")]),
    AIMessage(content="Repair case opened for A-1007."),
    AIMessage(content="Anything else I can do for the repair?"),       # turn 2
]))
agent = create_agent(
    model,
    tools=[record_issue_type, start_repair, go_back_to_triage],      # ALL tools are registered up front
    middleware=[step_config],
    state_schema=SupportState,
    checkpointer=InMemorySaver(),
)
cfg = {"configurable": {"thread_id": "t1"}}
out = agent.invoke({"messages": [HumanMessage("My screen is cracked, order A-1007")]}, cfg)
print("final:", out["messages"][-1].text, "| current_step =", out["current_step"])
print()
for i, (call, tools) in enumerate(zip(model.seen, model.bound), 1):
    print(f"model call {i}: prompt={call[0][1]!r:70} tools offered={tools}")

out = agent.invoke({"messages": [HumanMessage("Thanks. Is it covered?")]}, cfg)
print("\nturn 2 started in step:", model.seen[-1][0][1][:30], "| tools offered:", model.bound[-1])
Output7 lines
final: Repair case opened for A-1007. | current_step = specialist

model call 1: prompt='You are the triage step. Find out the issue type and record it.'      tools offered=['record_issue_type']
model call 2: prompt='You are the hardware specialist. Open a repair case.'                 tools offered=['start_repair', 'go_back_to_triage']
model call 3: prompt='You are the hardware specialist. Open a repair case.'                 tools offered=['start_repair', 'go_back_to_triage']

turn 2 started in step: You are the hardware specialis | tools offered: ['start_repair', 'go_back_to_triage']

Read the three model calls: the first saw the triage prompt and the single record_issue_type tool; after the tool wrote current_step = "specialist" the second and third calls saw the specialist prompt and a different pair of tools. The second turn on the same thread started in the specialist step, because current_step lives in the checkpointed state: that persistence is what makes this a handoff rather than a one-off prompt switch. go_back_to_triage shows that the machine can also move backwards.

4.5 A dispatch node and a handoff budget#

Two agents that can transfer to each other can transfer forever: the customer's question is "not my department" to both (08D.3, 2.2 calls this ping-pong and caps it with max_handoffs). Left alone, LangGraph stops it only at the recursion limit, which is 10,007 steps by default (08F.10, Part 11), so you pay for thousands of model calls first. The sample scripts two models that always ask to transfer, and shows both the default failure and a fix.

The fix follows from the warning in 4.2 (an edge after the agent cannot veto a handoff): route every handoff through a node you own. The handoff tools use goto="dispatch" instead of naming the target; dispatch reads active_agent and either forwards or ends the run when the count is exhausted.

python
# s60_pingpong.py: two agents that keep handing off to each other, the default failure, and a dispatch node with a budget
import itertools
from typing import Literal

from langchain.agents import AgentState, create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall, ToolMessage
from langchain.tools import ToolRuntime, tool
from langgraph.errors import GraphRecursionError
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command
from typing_extensions import NotRequired

from fakes import FakeToolCallingModel


class S(AgentState):
    active_agent: NotRequired[str]
    handoffs: NotRequired[int]


def handoff_tool(target: str, via: str | None):
    """`via` is the node every handoff passes through; None means jump straight to the target agent."""

    @tool(f"transfer_to_{target}", description=f"Transfer to {target}.")
    def _t(runtime: ToolRuntime) -> Command:
        last_ai = next(m for m in reversed(runtime.state["messages"]) if isinstance(m, AIMessage))
        ack = ToolMessage(content=f"Transferred to {target}", tool_call_id=runtime.tool_call_id)
        return Command(goto=via or target, graph=Command.PARENT, update={
            "active_agent": target, "messages": [last_ai, ack], "handoffs": runtime.state.get("handoffs", 0) + 1})

    return _t


def forever(target: str):
    """A scripted model that ALWAYS asks to transfer to `target`, with a fresh id each time."""
    return FakeToolCallingModel(messages=(
        AIMessage(content="", tool_calls=[ToolCall(name=f"transfer_to_{target}", args={}, id=f"{target}-{i}")])
        for i in itertools.count()))


def build(max_handoffs=None):
    via = "dispatch" if max_handoffs is not None else None
    a = create_agent(forever("b"), tools=[handoff_tool("b", via)], state_schema=S, name="a")
    b = create_agent(forever("a"), tools=[handoff_tool("a", via)], state_schema=S, name="b")

    def dispatch(state: S) -> Command[Literal["a", "b", "__end__"]]:
        if state.get("handoffs", 0) >= (max_handoffs or 0):
            return Command(goto=END)                         # the budget lives in ONE place
        return Command(goto=state["active_agent"])

    g = StateGraph(S)
    g.add_node("a", lambda s: a.invoke(s))
    g.add_node("b", lambda s: b.invoke(s))
    g.add_node("dispatch", dispatch)
    g.add_edge(START, "a")
    return g.compile()


try:
    build().invoke({"messages": [HumanMessage("hi")]}, config={"recursion_limit": 12})
except GraphRecursionError as e:
    print("no budget  :", type(e).__name__, "-", str(e).splitlines()[0][:70])

out = build(max_handoffs=3).invoke({"messages": [HumanMessage("hi")]}, config={"recursion_limit": 50})
print("with budget: stopped after", out["handoffs"], "handoffs; last active agent =", out["active_agent"])
Output2 lines
no budget  : GraphRecursionError - Recursion limit of 12 reached without hitting a stop condition. You ca
with budget: stopped after 3 handoffs; last active agent = b

Without the budget the run only stopped at the (here deliberately low) recursion limit with GraphRecursionError. With the dispatch node it stopped after exactly three handoffs and ended cleanly. In a real system the same node is where you also write the audit log line, check that the target agent is allowed for this user, and escalate to a human after the cap instead of ending silently. The handoffs counter lives in state, so it survives a checkpoint; reset it at the start of each user turn if the cap is per turn.

4.6 A swarm, by hand#

A swarm is handoffs between peers with no supervisor, plus one more thing: the system remembers which agent was last active, so the next user message resumes with that agent. You already have all of it. The graph from 4.2 has the active_agent key and a conditional edge from START; what remains is a checkpointer so that the key survives between calls. The sample builds a two-agent swarm (a maths expert and a pirate) with one factory for the handoff tools, so the AIMessage plus ToolMessage pair is written in exactly one place, and runs two turns with and without a checkpointer.

python
# s23_swarm_by_hand.py: a swarm is the s20 graph plus a checkpointer: the active agent survives between turns
from typing import Literal

from langchain.agents import AgentState, create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall, ToolMessage
from langchain.tools import ToolRuntime, tool
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command
from typing_extensions import NotRequired

from fakes import FakeToolCallingModel


class SwarmState(AgentState):
    active_agent: NotRequired[str]


def handoff_tool(target: str, description: str):
    """One factory for every handoff tool, so the AIMessage + ToolMessage pair is written in exactly one place."""

    @tool(f"transfer_to_{target}", description=description)
    def _transfer(runtime: ToolRuntime) -> Command:
        last_ai = next(m for m in reversed(runtime.state["messages"]) if isinstance(m, AIMessage))
        ack = ToolMessage(content=f"Transferred to {target}", tool_call_id=runtime.tool_call_id)
        return Command(goto=target, update={"active_agent": target, "messages": [last_ai, ack]}, graph=Command.PARENT)

    return _transfer


def build_swarm(checkpointer):
    alice = create_agent(
        FakeToolCallingModel(messages=iter([
            AIMessage(content="", tool_calls=[ToolCall(name="transfer_to_bob", args={}, id="h1")]),
            AIMessage(content="Alice here again. 5 + 7 = 12."),
        ])),
        tools=[handoff_tool("bob", "Transfer to Bob, who speaks like a pirate.")],
        state_schema=SwarmState, system_prompt="You are Alice, a maths expert.", name="alice",
    )
    bob = create_agent(
        FakeToolCallingModel(messages=iter([AIMessage(content="Arr, Bob be here. What be yer question?"), AIMessage(content="Arr, Bob answers again.")])),
        tools=[handoff_tool("alice", "Transfer to Alice for maths.")],
        state_schema=SwarmState, system_prompt="You are Bob. You speak like a pirate.", name="bob",
    )

    def route_start(state: SwarmState) -> Literal["alice", "bob"]:
        return state.get("active_agent") or "alice"          # the saved active agent, else the default

    def route_after(state: SwarmState) -> Literal["alice", "bob", "__end__"]:
        last = state["messages"][-1]
        if isinstance(last, AIMessage) and not last.tool_calls:
            return "__end__"
        return state.get("active_agent") or "__end__"

    g = StateGraph(SwarmState)
    g.add_node("alice", lambda s: alice.invoke(s))
    g.add_node("bob", lambda s: bob.invoke(s))
    g.add_conditional_edges(START, route_start, ["alice", "bob"])
    g.add_conditional_edges("alice", route_after, ["alice", "bob", END])
    g.add_conditional_edges("bob", route_after, ["alice", "bob", END])
    return g.compile(checkpointer=checkpointer)


for label, saver in [("with a checkpointer", InMemorySaver()), ("without one", None)]:
    app = build_swarm(saver)
    cfg = {"configurable": {"thread_id": "1"}}
    t1 = app.invoke({"messages": [HumanMessage("I'd like to speak to Bob")]}, cfg)
    print(f"[{label}] turn 1: active_agent={t1['active_agent']!r}, reply={t1['messages'][-1].text!r}")
    t2 = app.invoke({"messages": [HumanMessage("What's 5 + 7?")]}, cfg)
    print(f"[{label}] turn 2: active_agent={t2.get('active_agent')!r}, reply={t2['messages'][-1].text!r}, messages in history={len(t2['messages'])}")
Output4 lines
[with a checkpointer] turn 1: active_agent='bob', reply='Arr, Bob be here. What be yer question?'
[with a checkpointer] turn 2: active_agent='bob', reply='Arr, Bob answers again.', messages in history=6
[without one] turn 1: active_agent='bob', reply='Arr, Bob be here. What be yer question?'
[without one] turn 2: active_agent=None, reply='Alice here again. 5 + 7 = 12.', messages in history=2

Turn 1 handed the user to Bob in both runs. On turn 2 the checkpointed swarm resumed with Bob and the six messages of history. The one without a checkpointer lost both: active_agent was None, the router fell back to the default (Alice), and the history held only the new exchange. That is the surprise behind "my swarm forgets who I was talking to": the active agent is state, and state without a checkpointer lives for one call (08F.11).

4.7 Choosing between the handoff forms, and returning control#

Question Single agent + middleware (4.4) Agent nodes + Command.PARENT (4.2)
Different models or owners per specialist? Awkward (one create_agent, one model, unless the middleware swaps it) Natural
Different tool sets per specialist? Yes, by filtering per step (not enforcement) Yes, each agent has its own tools
Shared history size One history, as long as the conversation One shared history unless you trim at the handoff
Tests One agent with a scripted model One graph, several scripted models
Streaming and tracing One agent, one trace Several nodes, readable names

Returning control to the user. An agent that has the answer simply finishes with an AIMessage without tool calls; the router then returns "__end__" and the turn ends, with active_agent still set so that the next turn resumes there. To escalate to a human, add a node or a tool that calls interrupt() (08F.12); the human's reply becomes the next message. Custom handoff arguments (a task_description the transferring agent writes for the receiver, a priority) are plain tool parameters of the handoff tool; write them into the acknowledgement or into a state key the receiver's prompt reads. The upstream swarm package passes the full history on every handoff by default and lets you override that with a custom tool (Part 7).


Part 5: Router, skills and parallel branches#

Deep-dive

5.1 The router: classify, fan out, synthesize#

A router is not an agent that decides turn by turn: it is a step that classifies the input and sends it to one or more specialists, usually in parallel, followed by a step that combines their answers. The docs' recipe uses the two routing tools you met in 08F.10: Command(goto=agent) when exactly one specialist should answer, and a list of Send objects (one per chosen specialist, each with its own input) when several should.

flowchart TD
    cl["classify"] -->|"route returns a list of Send"| b["billing agent"]
    cl -->|"route returns a list of Send"| s["shipping agent"]
    cl -->|"route returns a list of Send"| h["hr agent"]
    b --> syn["synthesize"]
    s --> syn
    h --> syn
    syn --> en["END"]

The sample classifies with a small rule-based function (a stand-in: a real router calls a model with structured output here, 08F.6), fans out with Send, runs each specialist as a node that wraps a create_agent, collects the answers through a reducer, and synthesizes.

python
# s30_router.py: the router pattern: classify, fan out with Send to agent nodes, synthesize
import itertools
import operator
from typing import Annotated

from langchain.agents import create_agent
from langchain.messages import AIMessage
from langgraph.graph import END, START, StateGraph
from langgraph.types import Send
from typing_extensions import TypedDict

from fakes import FakeToolCallingModel


class ClassificationResult(TypedDict):
    agent: str
    query: str


class RouterState(TypedDict):
    query: str
    classifications: list[ClassificationResult]
    results: Annotated[list[dict], operator.add]     # every branch appends; order is not guaranteed
    final_answer: str


def make_agent(name: str, reply: str):
    # itertools.cycle: the scripted model can answer any number of calls
    return create_agent(FakeToolCallingModel(messages=itertools.cycle([AIMessage(content=reply)])), tools=[], name=name,
                        system_prompt=f"You are the {name} specialist. Answer briefly.")


AGENTS = {
    "billing": make_agent("billing", "Invoice INV-204 is unpaid since 3 November."),
    "shipping": make_agent("shipping", "Parcel 99-1 left the depot this morning."),
    "hr": make_agent("hr", "Unused here: HR is never classified for this query."),
}


def classify(state: RouterState):
    """A rule-based stand-in for a classifier model. A real router would call a model with structured output here."""
    q = state["query"].lower()
    picks = []
    if "invoice" in q or "pay" in q:
        picks.append({"agent": "billing", "query": "What is the status of the customer's invoice?"})
    if "parcel" in q or "delivery" in q:
        picks.append({"agent": "shipping", "query": "Where is the customer's parcel?"})
    return {"classifications": picks}


def route(state: RouterState):
    return [Send(c["agent"], {"query": c["query"]}) for c in state["classifications"]]    # one task per pick


def agent_node(name: str):
    def node(state: dict):
        reply = AGENTS[name].invoke({"messages": [{"role": "user", "content": state["query"]}]})["messages"][-1].text
        return {"results": [{"agent": name, "answer": reply}]}
    return node


def synthesize(state: RouterState):
    parts = sorted(state["results"], key=lambda r: r["agent"])     # sort: branch order is not guaranteed
    return {"final_answer": " ".join(f"[{r['agent']}] {r['answer']}" for r in parts)}


g = StateGraph(RouterState)
g.add_node("classify", classify)
for name in AGENTS:
    g.add_node(name, agent_node(name))
g.add_node("synthesize", synthesize)
g.add_edge(START, "classify")
g.add_conditional_edges("classify", route, list(AGENTS))
for name in AGENTS:
    g.add_edge(name, "synthesize")
g.add_edge("synthesize", END)
router = g.compile()

if __name__ == "__main__":
    out = router.invoke({"query": "Has my invoice been paid, and where is my parcel?", "results": []})
    print("routed to:", [c["agent"] for c in out["classifications"]])
    print("answer   :", out["final_answer"])
    print("one topic:", router.invoke({"query": "Where is my delivery?", "results": []})["final_answer"][:60])
Output3 lines
routed to: ['billing', 'shipping']
answer   : [billing] Invoice INV-204 is unpaid since 3 November. [shipping] Parcel 99-1 left the depot this morning.
one topic: [shipping] Parcel 99-1 left the depot this morning.

The query mentioned an invoice and a parcel, so two Sends went out and the hr agent never ran; the second query matched one topic and only the shipping agent ran. Four details matter in production:

  • Each worker gets its own input. Send("billing", {"query": ...}) is the worker's whole state; the classifier rewrote the customer's sentence into a question for that specialist. That rewrite is the router's delegation brief (08D.3, 3.1).
  • Results merge through a reducer (results uses operator.add), and arrival order is not guaranteed, which is why synthesize sorts before joining. If you need the original order, carry an index in the worker input and sort by it (08F.10, 7.2).
  • An empty classification skips the workers entirely. With no Send, the reduce node may not run (08F.10, Part 7), so handle "nothing matched" explicitly (a fallback general agent, or a polite refusal) rather than trusting the join.
  • The synthesis step is the weak point. The docs give no code for it; it is a model call that merges specialist text, with the usual risk that it drops the minority finding or smooths a disagreement away. Instruct it to keep each specialist's claim attributed, as the sample's [billing] ... tags do.

5.2 Routers are stateless: make them a tool for multi-turn#

The docs are direct about the limit: a router treats each request independently. For a conversation, they offer two routes. The light one: wrap the whole router as a tool of a conversational agent, so the agent holds the memory and the router stays stateless. The heavy one: persist history inside the router and pass chosen messages to the specialists, which needs custom history management, and switching specialists between turns can feel disjointed to the user (the docs suggest handoffs or subagents instead).

python
# s32_router_as_tool.py: a stateless router wrapped as a tool of a conversational agent (the docs' recipe for multi-turn)
from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool
from langgraph.checkpoint.memory import InMemorySaver

from fakes import FakeToolCallingModel
from s30_router import router        # the compiled router graph from the previous sample


@tool("ask_the_desks", description="Ask the billing and shipping desks. Pass the customer's full question.")
def ask_the_desks(query: str) -> str:
    result = router.invoke({"query": query, "results": []})     # the router stays stateless
    return result["final_answer"]


assistant = create_agent(
    FakeToolCallingModel(messages=iter([
        AIMessage(content="", tool_calls=[ToolCall(name="ask_the_desks", args={"query": "invoice status and parcel location"}, id="1")]),
        AIMessage(content="Your invoice is unpaid, and the parcel is on its way."),
        AIMessage(content="Anything else about the invoice?"),                       # turn 2: answered from the conversation
    ])),
    tools=[ask_the_desks],
    checkpointer=InMemorySaver(),                                  # memory lives in the conversational agent
)
cfg = {"configurable": {"thread_id": "c1"}}
r1 = assistant.invoke({"messages": [HumanMessage("Has my invoice been paid, and where is my parcel?")]}, cfg)
print("turn 1:", r1["messages"][-1].text)
r2 = assistant.invoke({"messages": [HumanMessage("Thanks!")]}, cfg)
print("turn 2:", r2["messages"][-1].text, "| messages kept:", len(r2["messages"]))
Output2 lines
turn 1: Your invoice is unpaid, and the parcel is on its way.
turn 2: Anything else about the invoice? | messages kept: 6

The conversational agent (with the only checkpointer) remembered the first exchange and answered turn 2 from it, without calling the router again. A router wrapped as a tool is also, structurally, the single dispatch tool of 3.4 with a graph behind it.

5.3 Skills: one agent, prompts on demand#

The skills pattern is the lightest of the five: no second agent at all. A skill is a specialized prompt (instructions, a schema, a style guide, a runbook), and one agent loads the ones it needs through a tool. The docs describe it as load_skill: the tool's docstring lists the available skills, the system prompt tells the agent to use it, and the tool returns the chosen skill's text. Skills therefore load progressively, and the context holds only what the current task needed.

python
# s33_skills.py: the skills pattern: ONE agent, prompts loaded on demand through a load_skill tool
from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool

from fakes import RecordingModel

SKILLS = {
    "sql_style": "SQL style guide: uppercase keywords, one clause per line, never SELECT *, always qualify columns.",
    "invoice_schema": "Tables: invoices(id, customer_id, total, paid_at), customers(id, name). paid_at IS NULL means unpaid.",
}


@tool
def load_skill(skill_name: str) -> str:
    """Load a specialized skill prompt. Available skills: sql_style (how to write SQL here), invoice_schema (the invoice tables)."""
    if skill_name not in SKILLS:
        return f"Unknown skill {skill_name!r}. Available: {', '.join(SKILLS)}"
    return SKILLS[skill_name]


model = RecordingModel(messages=iter([
    AIMessage(content="", tool_calls=[ToolCall(name="load_skill", args={"skill_name": "invoice_schema"}, id="1")]),
    AIMessage(content="SELECT invoices.id FROM invoices WHERE invoices.paid_at IS NULL"),
]))
agent = create_agent(
    model, tools=[load_skill], name="sql_assistant",
    system_prompt="You write SQL for the invoicing database. Use load_skill to get the schema or the style guide before you write a query.",
)
out = agent.invoke({"messages": [HumanMessage("List unpaid invoices")]})
print("tool result :", out["messages"][2].text[:70])
print("1st call saw:", [t for _, t in model.seen[0]][0][:40], "...", "| skill text in the 1st prompt?", any("paid_at" in t for _, t in model.seen[0]))
print("2nd call saw:", "skill text in the 2nd prompt?", any("paid_at" in t for _, t in model.seen[1]))
Output3 lines
tool result : Tables: invoices(id, customer_id, total, paid_at), customers(id, name)
1st call saw: You write SQL for the invoicing database ... | skill text in the 1st prompt? False
2nd call saw: skill text in the 2nd prompt? True

The first model call's prompt did not contain the schema; after the agent called load_skill, the second call did. That is the whole mechanism. (The docs show the tool's shape and leave the skill store to you; the dictionary here stands in for files or a database.)

Skills Subagents
Isolation None: loaded text joins the one conversation Strong: a separate context per call
Cost shape Cheap to load, but every loaded skill stays in context A full agent run per call
Enforce constraints between specialties No: it is prompt-driven Yes: separate tools, permissions and loops
Teams develop independently Yes: a skill is a document Yes: an agent is a package
Risk The agent may never call load_skill, or may load the wrong skill A vague tool description or brief

The docs also describe three extensions: loading a skill can register tools as well (database backup tools appear once the database skill is loaded), skills can be hierarchical (a skill that lists sub-skills loaded separately), and a skill can point at files or templates and say when to read them. The dynamic-tools extension needs the two-hook technique of 08F.8, 9.3 (offer the tool and execute it). The docs link a tutorial that builds a SQL assistant with on-demand skills; I have not read it, so read it before you rely on details beyond the shape shown here.

5.4 Parallel branches in a graph#

There are three ways work becomes parallel in this lesson, and they differ in who decides how many branches there are:

Mechanism Who decides the branch count Where it appears
Several tool calls in one reply The model, each turn Subagents (3.6)
Several edges out of one node (or a conditional edge returning a list of names) You, at build time This section
Send objects Your routing function, at run time The router (5.1)

With fan-out edges, every branch runs in the same super-step, on the same snapshot of the state, and their updates are applied together; they cannot see each other (08F.10, 1.3). Branches that write one key need a reducer on it, and the order of their updates is not guaranteed. To wait for all of them, join with the list form add_edge([...], "join") for unconditional branches, or defer=True for conditional and dynamic ones (08F.10, 5.4). The sample fans a draft out to three reviewer nodes (each stands in for a slow agent run), joins them, makes one branch fail, and then caps concurrency.

python
# s31_parallel_branches.py: static fan-out to agent nodes, a reducer, a join, and one branch that fails
import operator
import threading
import time
from typing import Annotated

from langgraph.graph import END, START, StateGraph
from typing_extensions import TypedDict


class State(TypedDict):
    draft: str
    reviews: Annotated[list[str], operator.add]
    verdict: str


peak = {"now": 0, "max": 0}
lock = threading.Lock()


def reviewer(name: str, fail: bool = False):
    def node(state: State):
        with lock:
            peak["now"] += 1
            peak["max"] = max(peak["max"], peak["now"])
        time.sleep(0.2)                                    # stands in for a slow agent run
        with lock:
            peak["now"] -= 1
        if fail:
            raise RuntimeError(f"{name} reviewer crashed")
        return {"reviews": [f"{name}: ok"]}
    return node


def build(fail_legal=False):
    g = StateGraph(State)
    for n in ("security", "style", "legal"):
        g.add_node(n, reviewer(n, fail=(fail_legal and n == "legal")))
        g.add_edge(START, n)                              # fan-out: three branches in ONE super-step
    g.add_node("verdict", lambda s: {"verdict": f"{len(s['reviews'])} reviews: " + ", ".join(sorted(s["reviews"]))})
    g.add_edge(["security", "style", "legal"], "verdict")  # fan-in: wait for all three, run once
    g.add_edge("verdict", END)
    return g.compile()


t0 = time.perf_counter()
print(build().invoke({"draft": "v1", "reviews": []})["verdict"])
print("three 0.2 s reviewers in under 0.5 s:", time.perf_counter() - t0 < 0.5, "| peak concurrency:", peak["max"])

try:
    build(fail_legal=True).invoke({"draft": "v1", "reviews": []})
except RuntimeError as e:
    print("one branch failed, the whole run raised:", e)

# a cap on concurrency: 6 branches, at most 2 at a time
peak.update(now=0, max=0)
g = StateGraph(State)
for i in range(6):
    g.add_node(f"w{i}", reviewer(f"w{i}"))
    g.add_edge(START, f"w{i}")
    g.add_edge(f"w{i}", END)
g.compile().invoke({"draft": "v1", "reviews": []}, config={"max_concurrency": 2})
print("peak concurrency with max_concurrency=2:", peak["max"])
Output4 lines
3 reviews: legal: ok, security: ok, style: ok
three 0.2 s reviewers in under 0.5 s: True | peak concurrency: 3
one branch failed, the whole run raised: legal reviewer crashed
peak concurrency with max_concurrency=2: 2
  • The three reviewers took about one reviewer's time, and the peak concurrency was 3: they really ran together. The verdict sorts the reviews before joining, because their order is not deterministic.
  • When one branch raised, the whole run raised. A super-step is transactional: the updates of the branches that succeeded in that step are discarded with it, and a retry policy re-runs only the failing branch (08F.12 owns retries). Design reviewer nodes so that a failure becomes a result ("legal: could not review, reason") if the run should continue with the others.
  • config={"max_concurrency": 2} capped six branches at two at a time. It is a top-level config key. Always set it when the branches call a rate-limited provider or a shared tool.

Part 6: A custom workflow around a team: the research desk#

Deep-dive

The fifth pattern, custom workflow, is what you reach for when the fixed shapes of Parts 3 to 5 are not enough: some steps are plain code (validation, a quality check, a permission test), some are agents or whole teams, and the flow has loops and a human gate. The docs describe it as using a create_agent agent directly as a node (or inside a node function that maps state to the agent's input), and mixing it with deterministic nodes and model nodes. This part builds one end to end. It uses everything so far: a supervisor with a subagent as its tool (Part 3), an agent added as a node of a parent graph with a shared messages key (Part 2), Command for routing (Part 4), and one checkpointer on the outermost graph so an approval can pause the run (3.8).

flowchart TD
    st["START"] --> intake["intake: validate"]
    intake -->|"ok"| team["research_team: supervisor agent as a node"]
    intake -->|"empty topic"| en["END"]
    team --> gate["quality_gate"]
    gate -->|"no Source line, attempts left"| team
    gate -->|"good or out of attempts"| pub["publish_review: interrupt"]
    pub --> en

The design, in the five-step method of 08F.10, Part 13: the steps are intake, the research team, quality_gate and publish_review; the state is the conversation (messages) plus a topic, an attempts counter and a status; the deterministic parts are everything except the team; the loop is gate back to team, bounded by attempts; the human gate is the last node.

python
# s50_research_desk.py: a custom workflow around a supervisor: validate, research team, quality gate, human approval
from typing import Literal

from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, MessagesState, StateGraph
from langgraph.types import Command, interrupt

from fakes import FakeToolCallingModel

# ---------- the research team: a supervisor agent whose tools are subagents ----------
policy_agent = create_agent(
    FakeToolCallingModel(messages=iter([AIMessage(content="Laptops: 30-day returns. Source: policy.md")])),
    tools=[], name="policy_agent", system_prompt="You answer from the returns policy and name your source.",
)


@tool("ask_policy", description="Ask the policy specialist. Pass a complete, self-contained question.")
def ask_policy(question: str) -> str:
    return policy_agent.invoke({"messages": [{"role": "user", "content": question}]})["messages"][-1].text


team = create_agent(
    FakeToolCallingModel(messages=iter([
        AIMessage(content="", tool_calls=[ToolCall(name="ask_policy", args={"question": "What is the laptop return window?"}, id="t1")]),
        AIMessage(content="Laptops can be returned within 30 days."),                    # pass 1: forgot the source
        AIMessage(content="Laptops can be returned within 30 days. Source: policy.md"),   # pass 2: after the gate's nudge
    ])),
    tools=[ask_policy], name="research_team",
    system_prompt="You lead a research team. Delegate, then answer and cite the source.",
)


# ---------- the workflow around it ----------
class DeskState(MessagesState):
    topic: str
    attempts: int
    status: str


def intake(state: DeskState) -> Command[Literal["research_team", "__end__"]]:
    if not state["topic"].strip():
        return Command(update={"status": "rejected: empty topic"}, goto=END)
    return Command(update={"messages": [HumanMessage(state["topic"])], "attempts": 0}, goto="research_team")


def quality_gate(state: DeskState) -> Command[Literal["research_team", "publish_review"]]:
    answer = state["messages"][-1].text
    if "Source:" in answer or state["attempts"] >= 2:
        return Command(goto="publish_review")
    return Command(update={"attempts": state["attempts"] + 1,
                           "messages": [HumanMessage("Your answer has no 'Source:' line. Add one.")]}, goto="research_team")


def publish_review(state: DeskState):
    decision = interrupt({"draft": state["messages"][-1].text, "question": "Publish this answer?"})
    return {"status": "published" if decision == "yes" else "held back"}


g = StateGraph(DeskState)
g.add_node("intake", intake)
g.add_node("research_team", team)          # a compiled agent as a node: a subgraph sharing the `messages` key
g.add_node("quality_gate", quality_gate)
g.add_node("publish_review", publish_review)
g.add_edge(START, "intake")
g.add_edge("research_team", "quality_gate")
g.add_edge("publish_review", END)
desk = g.compile(checkpointer=InMemorySaver())      # one checkpointer, on the outermost graph

cfg = {"configurable": {"thread_id": "desk-1"}}
paused = desk.invoke({"topic": "Can customers return laptops?", "messages": []}, cfg)
print("quality-gate loops used:", paused["attempts"])
print("paused for approval with draft:", paused["__interrupt__"][0].value["draft"])
done = desk.invoke(Command(resume="yes"), cfg)
print("status:", done["status"])
print("rejected case:", desk.invoke({"topic": "  ", "messages": []}, {"configurable": {"thread_id": "desk-2"}})["status"])
Output4 lines
quality-gate loops used: 1
paused for approval with draft: Laptops can be returned within 30 days. Source: policy.md
status: published
rejected case: rejected: empty topic

Walk through what the output proves:

  • The team's first answer had no Source: line, so quality_gate added a nudge message and sent the run back to the team; the second answer had one. One loop was used (attempts is 1), and the cap of two would have stopped a model that never complied (it then goes to review anyway: a gate that blocks forever is a hang, so decide what happens at the limit).
  • The run paused at publish_review with the draft in the interrupt payload, and Command(resume="yes") on the same thread finished it. The only checkpointer is on the parent; the team (a create_agent as a node) and its subagent inherit it, as 3.8 requires.
  • A blank topic never reached an agent: intake returned a Command straight to END with a status. Cheap deterministic checks go first, because a model call is the most expensive way to say no.

Because the team is added as a node (not called inside a function), LangGraph can see it, so the drawing and the state views work. The sample below prints the drawn edges and the team's inner nodes:

python
# s51_desk_edges.py: the desk graph from s50, drawn: do the Command annotations show up as edges?
import contextlib
import io

with contextlib.redirect_stdout(io.StringIO()):
    exec(open("s50_research_desk.py").read())       # builds `desk`, prints nothing we want here

drawn = desk.get_graph()
print(sorted((e.source, e.target) for e in drawn.edges))
print("xray=1 nodes:", sorted(desk.get_graph(xray=1).nodes))
Output2 lines
[('__start__', 'intake'), ('intake', '__end__'), ('intake', 'research_team'), ('publish_review', '__end__'), ('quality_gate', 'publish_review'), ('quality_gate', 'research_team'), ('research_team', 'quality_gate')]
xray=1 nodes: ['__end__', '__start__', 'intake', 'publish_review', 'quality_gate', 'research_team:__end__', 'research_team:__start__', 'research_team:model', 'research_team:tools']

Every edge of the diagram is there, including the two that are only declared by Command[Literal[...]] return annotations (intake and quality_gate). With xray=1 the drawing also lists the inner model and tools nodes of research_team, confirming that an agent is a subgraph. Note what the drawing cannot show: the subagent behind the ask_policy tool. It is called inside a tool, so it is invisible to the graph (2.7).


Part 7: The helper packages, and how to read old tutorials#

Reference

Legacy. This part is the marked "legacy and how to read old tutorials" part of the lesson. Everything above is the recommended path. Read this so that you can read old tutorials and maintain code that uses the packages; do not start new work with langgraph-supervisor.

7.1 Two packages, two statuses#

Before create_agent existed, LangChain published two small packages that wrapped the supervisor and swarm shapes. Their status on 14 November 2026:

langgraph-supervisor langgraph-swarm
Version on PyPI 0.0.31 (released 19 November 2025) 0.1.0 (released 4 December 2025)
Repository langchain-ai/langgraph-supervisor-py, archived (read-only; last push 15 July 2026) langchain-ai/langgraph-swarm-py, not archived (last push 28 October 2026)
Maintenance The docs say it is no longer actively maintained and recommend the supervisor pattern directly via tools (Part 3), because tool calling "gives you more control over context engineering" Maintained, and updated for LangChain 1 (its handoff tool imports from langchain.messages and langchain.tools; its docs examples use create_agent)
Documentation A migration page in the LangChain docs A README and an API reference page; no guide in the LangGraph docs
Builds the supervisor with langgraph.prebuilt.create_react_agent, which is deprecated Your agents, which can be create_agent
Install uv add langgraph-supervisor uv add langgraph-swarm

My recommendation follows the status: do not start new code on langgraph-supervisor; use Part 3. For handoffs and swarms, the hand-built forms of Part 4 are about thirty lines and use only public, documented APIs; langgraph-swarm is a reasonable convenience if you accept an undocumented-in-the-docs dependency, and the maintainers' own docs steer most cases to handoffs by state and middleware. Both packages also still need a provider package for real models.

7.2 langgraph-supervisor, run#

The signature (from the package source), abbreviated:

text
create_supervisor(agents: list[Pregel], *, model, tools=None, prompt=None, response_format=None,
                  pre_model_hook=None, post_model_hook=None, parallel_tool_calls=False,
                  state_schema=None, context_schema=None,
                  output_mode="last_message",            # or "full_history"
                  add_handoff_messages=True, handoff_tool_prefix=None, add_handoff_back_messages=None,
                  supervisor_name="supervisor", include_agent_name=None) -> StateGraph   # NOT compiled

The rules that surprise people: every worker needs a unique name (not None and not the default "LangGraph"), or you get a ValueError; the function returns an uncompiled StateGraph, so you must call .compile(checkpointer=...) yourself; the supervisor gets one auto-generated handoff tool per worker, named transfer_to_<agent_name> (or <handoff_tool_prefix>_<agent_name>); parallel_tool_calls defaults to False and only has an effect on OpenAI and Anthropic models (per the source docstring); and include_agent_name="inline" wraps names into the message text because only some providers honour a message's name field. The sample runs it with create_agent workers and scripted models, and records any warnings.

python
# s40_supervisor_pkg.py: the legacy langgraph-supervisor package, run with scripted models
import warnings

from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool

from fakes import FakeToolCallingModel

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    from langgraph_supervisor import create_supervisor

    @tool
    def add(a: float, b: float) -> float:
        """Add two numbers."""
        return a + b

    math_agent = create_agent(
        FakeToolCallingModel(messages=iter([
            AIMessage(content="", tool_calls=[ToolCall(name="add", args={"a": 5, "b": 7}, id="m1")]),
            AIMessage(content="5 + 7 = 12"),
        ])),
        tools=[add], name="math_expert", system_prompt="You are a maths expert.",
    )
    research_agent = create_agent(
        FakeToolCallingModel(messages=iter([AIMessage(content="unused")])),
        tools=[], name="research_expert", system_prompt="You research facts.",
    )

    supervisor_model = FakeToolCallingModel(messages=iter([
        AIMessage(content="", tool_calls=[ToolCall(name="transfer_to_math_expert", args={}, id="s1")]),
        AIMessage(content="The answer is 12."),
    ]))
    workflow = create_supervisor([math_agent, research_agent], model=supervisor_model, prompt="You manage a maths expert and a research expert.")
    print("create_supervisor returned:", type(workflow).__name__, "(not compiled)")
    app = workflow.compile()
    out = app.invoke({"messages": [HumanMessage("what is 5 + 7?")]})

print("nodes:", [n for n in app.get_graph().nodes])
print("message trail:")
for m in out["messages"]:
    extra = f" tool_calls={[c['name'] for c in m.tool_calls]}" if getattr(m, "tool_calls", None) else ""
    print(f"  {m.type:5} name={getattr(m, 'name', None)!s:15} {m.text[:50]!r}{extra}")
print("warnings:", sorted({f"{w.category.__name__}: {str(w.message)[:110]}" for w in caught}))
Output11 lines
create_supervisor returned: StateGraph (not compiled)
nodes: ['__start__', 'supervisor', 'math_expert', 'research_expert', '__end__']
message trail:
  human name=None            'what is 5 + 7?'
  ai    name=supervisor      '' tool_calls=['transfer_to_math_expert']
  tool  name=transfer_to_math_expert 'Successfully transferred to math_expert'
  ai    name=math_expert     '5 + 7 = 12'
  ai    name=math_expert     'Transferring back to supervisor' tool_calls=['transfer_back_to_supervisor']
  tool  name=transfer_back_to_supervisor 'Successfully transferred back to supervisor'
  ai    name=supervisor      'The answer is 12.'
warnings: ['LangGraphDeprecatedSinceV10: create_react_agent has been moved to `langchain.agents`. Please update your import to `from langchain.agents i']

What this tells you, from a real run:

  • It works with create_agent workers on langgraph 1.2.22 and langchain 1.5.0 (the fact sheet could not confirm this without running it).
  • The warning is real: LangGraphDeprecatedSinceV10: create_react_agent has been moved to langchain.agents is emitted when the package is used, because the supervisor itself is a deprecated create_react_agent. It comes from inside the package, so you cannot fix it in your code.
  • The default history is not the workers' full history. The math expert's own tool call (add) is gone; what remains is the worker's final message, plus two synthetic messages the package adds when control returns ("Transferring back to supervisor" and its ToolMessage).

The knobs that control that history, measured on the same scenario (a supervisor, one worker that calls one tool):

python
# s41_supervisor_output_mode.py: output_mode, handoff messages and what ends up in the history
import warnings

warnings.simplefilter("ignore")

from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool
from langgraph_supervisor import create_supervisor

from fakes import FakeToolCallingModel


@tool
def add(a: float, b: float) -> float:
    """Add two numbers."""
    return a + b


def run(**kwargs):
    math_agent = create_agent(
        FakeToolCallingModel(messages=iter([
            AIMessage(content="", tool_calls=[ToolCall(name="add", args={"a": 5, "b": 7}, id="m1")]),
            AIMessage(content="5 + 7 = 12"),
        ])),
        tools=[add], name="math_expert",
    )
    sup_model = FakeToolCallingModel(messages=iter([
        AIMessage(content="", tool_calls=[ToolCall(name="transfer_to_math_expert", args={}, id="s1")]),
        AIMessage(content="The answer is 12."),
    ]))
    app = create_supervisor([math_agent], model=sup_model, **kwargs).compile()
    out = app.invoke({"messages": [HumanMessage("what is 5 + 7?")]})
    return [m.type + (":" + m.name if getattr(m, "name", None) else "") for m in out["messages"]]


print("default (last_message)          :", len(run()), run())
print("output_mode='full_history'      :", len(run(output_mode="full_history")), run(output_mode="full_history"))
print("add_handoff_back_messages=False :", len(run(add_handoff_back_messages=False)))
print("add_handoff_messages=False      :", len(run(add_handoff_messages=False)))
Output4 lines
default (last_message)          : 7 ['human', 'ai:supervisor', 'tool:transfer_to_math_expert', 'ai:math_expert', 'ai:math_expert', 'tool:transfer_back_to_supervisor', 'ai:supervisor']
output_mode='full_history'      : 9 ['human', 'ai:supervisor', 'tool:transfer_to_math_expert', 'ai:math_expert', 'tool:add', 'ai:math_expert', 'ai:math_expert', 'tool:transfer_back_to_supervisor', 'ai:supervisor']
add_handoff_back_messages=False : 5
add_handoff_messages=False      : 3
Setting Messages in the final history What it does
default (output_mode="last_message") 7 Worker's last message only, plus the handoff and hand-back pairs
output_mode="full_history" 9 Also the worker's tool call and tool result
add_handoff_back_messages=False 5 Drops the synthetic "back to supervisor" pair
add_handoff_messages=False 3 Drops handoff messages as well (the shortest history)

This is what the migration guide means by "output_mode becomes formatting in the tool wrapper": in Part 3 you decide what text to return, which is simpler and explicit. The package's create_forward_message_tool adds a forward_message tool that lets the supervisor pass a worker's reply to the user unchanged (saves tokens and avoids paraphrase loss); in Part 3 the equivalent is return_direct=True on a tool whose output should be the answer (08F.8, 2.7), with the caveat that every tool call in that step must have it.

7.3 Migrating off langgraph-supervisor#

The official migration page maps each feature to the hand-built pattern:

langgraph-supervisor Replacement
create_supervisor with workers as graph nodes create_agent with each worker wrapped as an @tool (3.1)
output_mode Format the subagent's output in the tool wrapper: return the last message or a built summary (3.2)
create_handoff_tool and custom routing A custom @tool that calls subagent.invoke(...) (3.1), or a handoff tool with Command.PARENT if the specialist should own the turns (4.2)
Nested supervisors A subagent tool that calls other subagents, or flatten to one supervisor with one tool per leaf (3.9)
prompt= system_prompt= (the create_react_agent to create_agent rename)
config_schema= context_schema= (deprecated name, per the source)

A before and after, as the docs show it:

python
# before (legacy): the supervisor is a deprecated create_react_agent built for you
from langgraph_supervisor import create_supervisor

workflow = create_supervisor([research_agent, math_agent], model=model,
                             prompt="You are a team supervisor.")
app = workflow.compile(checkpointer=checkpointer)

# after (recommended): the supervisor is a create_agent whose tools are the workers
from langchain.agents import create_agent
from langchain.tools import tool


@tool("research_expert", description="Research a question and return the findings.")
def call_research_agent(query: str) -> str:
    result = research_agent.invoke({"messages": [{"role": "user", "content": query}]})
    return result["messages"][-1].content


@tool("math_expert", description="Solve a maths problem and return the result.")
def call_math_agent(query: str) -> str:
    result = math_agent.invoke({"messages": [{"role": "user", "content": query}]})
    return result["messages"][-1].content


supervisor = create_agent(model=model, tools=[call_research_agent, call_math_agent],
                          system_prompt="You are a team supervisor.", checkpointer=checkpointer)

This before and after is illustrative: research_agent, math_agent, model and checkpointer are defined elsewhere in the docs' example, so it shows the shape of the change and does not run on its own. Part 3's samples are the runnable version. The migration page's own advice on when to use a hand-written StateGraph instead: when you need to mix deterministic and agentic steps, static subgraph discovery (2.7), per-tier checkpoint namespaces, or shared state keys between levels. That is Part 6.

7.4 langgraph-swarm, run#

text
create_swarm(agents: list[Pregel], *, default_active_agent: str, state_schema=SwarmState, context_schema=None) -> StateGraph   # NOT compiled
create_handoff_tool(*, agent_name: str, name: str | None = None, description: str | None = None) -> BaseTool
add_active_agent_router(builder: StateGraph, *, route_to: list[str], default_active_agent: str) -> StateGraph
class SwarmState(MessagesState):  active_agent: str | None

It is the graph of 4.6 packaged: an active_agent key, a conditional edge from START that reads it, each agent as a node, and a handoff tool that returns Command(goto=agent, graph=Command.PARENT, update={...}). Differences from the hand-built version that you can rely on (from the source and the run below): the handoff tool passes the full message history plus a ToolMessage ("Successfully transferred to "), each agent's name must match the agent_name used in the handoff tools, and create_swarm raises a ValueError for a missing active_agent key in a custom schema, an empty agents list, or a default agent that is not among the names. Compile with a checkpointer for multi-turn use, as in 4.6; compile(checkpointer=..., store=...) also accepts a store for long-term memory (08F.11).

python
# s42_swarm_pkg.py: the langgraph-swarm package, run with scripted models
import warnings

from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool
from langgraph.checkpoint.memory import InMemorySaver

from fakes import FakeToolCallingModel

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    from langgraph_swarm import SwarmState, create_handoff_tool, create_swarm

    @tool
    def add(a: float, b: float) -> float:
        """Add two numbers."""
        return a + b

    alice = create_agent(
        FakeToolCallingModel(messages=iter([
            AIMessage(content="", tool_calls=[ToolCall(name="transfer_to_bob", args={}, id="h1")]),
            AIMessage(content="Alice: 5 + 7 = 12"),
        ])),
        tools=[add, create_handoff_tool(agent_name="Bob", description="Transfer to Bob")],
        system_prompt="You are Alice, an addition expert.", name="Alice",
    )
    bob = create_agent(
        FakeToolCallingModel(messages=iter([AIMessage(content="Arr, Bob here."), AIMessage(content="Arr, still Bob.")])),
        tools=[create_handoff_tool(agent_name="Alice", description="Transfer to Alice, she can help with math")],
        system_prompt="You are Bob, you speak like a pirate.", name="Bob",
    )
    workflow = create_swarm([alice, bob], default_active_agent="Alice")
    print("create_swarm returned:", type(workflow).__name__, "| state keys:", list(SwarmState.__annotations__))
    app = workflow.compile(checkpointer=InMemorySaver())
    cfg = {"configurable": {"thread_id": "1"}}
    t1 = app.invoke({"messages": [HumanMessage("i'd like to speak to Bob")]}, cfg)
    t2 = app.invoke({"messages": [HumanMessage("what's 5 + 7?")]}, cfg)

print("turn 1 active agent:", t1["active_agent"], "->", t1["messages"][-1].text)
print("turn 2 active agent:", t2["active_agent"], "->", t2["messages"][-1].text)
print("handoff tool message:", [m.text for m in t1["messages"] if m.type == "tool"])
print("handoff tool name for agent 'Bob':", create_handoff_tool(agent_name="Bob").name)
print("warnings:", sorted({f"{w.category.__name__}: {str(w.message)[:100]}" for w in caught}))
Output6 lines
create_swarm returned: StateGraph | state keys: ['messages', 'active_agent']
turn 1 active agent: Bob -> Arr, Bob here.
turn 2 active agent: Bob -> Arr, still Bob.
handoff tool message: ['Successfully transferred to Bob']
handoff tool name for agent 'Bob': transfer_to_bob
warnings: []

Turn 1 switched to Bob, and turn 2 resumed with Bob, as in 4.6. Two details a real run exposed:

To customize (the README's two routes): write your own handoff tool (to add LLM-filled arguments such as task_description, or to pass less than the full history), and bring your own agent implementation with private state keys, converting between the swarm state and the agent's state in a wrapper node and wiring it with add_active_agent_router. If a custom handoff tool returns a Command, the agent needs a tool node that propagates it (the prebuilt one does), and both the swarm state and the agent state must contain the keys in Command.update. At that point you are writing 4.2 by hand, which is a sign to drop the package.

7.5 Reading old multi-agent tutorials#

You see It means Use now
from langgraph_supervisor import create_supervisor The archived package (7.2) Subagents as tools (Part 3)
create_react_agent(model, tools, prompt=...) langgraph.prebuilt, deprecated create_agent(model, tools, system_prompt=...) (08F.8, Part 13)
config_schema= on create_supervisor or create_swarm Deprecated name context_schema=
MessageGraph as the multi-agent graph Deprecated StateGraph with MessagesState (08F.10, 14.2)
A handoff that sets a flag in state with no ToolMessage Pre-1.0 style A Command handoff tool with the AIMessage plus ToolMessage pair (4.3)
create_handoff_tool from langgraph_supervisor The package's helper Your own @tool that calls the subagent, or a Command.PARENT handoff tool

One more caution about JavaScript: the JS packages were named @langchain/langgraph-supervisor and @langchain/langgraph-swarm; I did not verify their current status, so check before relying on them.


Part 8: The five patterns against the ten architectures of 08D.3#

Deep-dive

Lesson 08D.3 has ten architectures; LangChain's docs have five patterns. They are two different cuts of the same territory, so the mapping is many to many. Use 08D.3 to decide what shape the task has, and this table to find how to build it.

08D.3 architecture LangChain and LangGraph form Where in this lesson Notes
Orchestrator–subagents Subagents: a main create_agent with subagents as tools Part 3 The default. The lead's plan is the model's tool calls; for a plan your code validates first, put a node before the agent (Part 6)
Handoffs and swarm Handoffs: Command tools, active_agent or current_step in state; a swarm is handoffs plus a checkpointer Part 4, 7.4 08D.3's max_handoffs and max_turns become the dispatch node of 4.5 and the model-call limit
Supervisor and hierarchical Subagents, nested (a subagent tool that calls subagents). langgraph-supervisor was the packaged form 3.9, Part 7 Flatten when you can; depth is a lossy summary per level
Agents as tools Subagents. The same thing under the docs' name Part 3 08D.3 draws a line between "as tools" and "orchestrator–subagents"; LangChain's docs do not, because in code both are a tool wrapper
Peer debate, ensembles and voting No named pattern. Custom workflow: fan-out edges to the same task, a reducer, an aggregator node 5.4, Part 6 Give the agents different models or prompts, or the errors correlate
Pipeline and assembly line Custom workflow: sequential edges (or add_sequence) between agent nodes Part 6 If the sequence is fixed it is a workflow (08A.9); the "agents" are stages
Blackboard and shared state Shared state keys in a StateGraph with reducers; the Store for state that outlives a thread 2.2, 2.3, 08F.11 Subgraphs with shared keys are a blackboard with a schema; 2.3 is its concurrency trap
Parallel research fan-out Subagents with parallel tool calls, or a router with Send 3.6, 5.1 Bound the count: prompt bands, ToolCallLimitMiddleware, max_concurrency
Critic and verifier Custom workflow: a verifier agent or deterministic check as a node, with a loop back bounded by a counter Part 6 (quality_gate) Give the verifier different evidence (tools), not just the draft
Role-play teams None, and the docs do not suggest one none 08D.3's verdict stands: personas without separate tools, context or checks are decoration

Two patterns have no clean counterpart on the other side. The docs' skills pattern is, in 08D.3's terms, not multi-agent at all: it is one agent with progressive disclosure of context (the single-agent techniques of 08A.9 and 08B.2). The docs' router is the routing workflow of 08A.9 and 08A.10 with agents as the destinations.

The deepest difference is who holds the history, which is the real axis of 08D.3's "context isolation versus sharing" (3.2):

Pattern History each specialist sees Persistence of specialist context Typical cost shape
Subagents Only the brief the wrapper passes (isolated), or a fork None by default; checkpointer=True for per-thread Pay per call; isolation keeps each call small
Handoffs The shared conversation (full, or the handoff pair) In the checkpointed state Cheap on repeats; history grows
Skills The one conversation, with loaded text added In the conversation Cheap to load; loaded skills stay in context
Router Only what Send carries None (stateless) Parallel; synthesis step adds a call
Custom workflow Whatever you pass between nodes Whatever you checkpoint You design it

A decision table in 08D.3's style. The meta-rule of 08D.3 still wins: default to the simplest architecture that meets the task's structure.

You need... Use Avoid
One agent is picking badly among many tools Subagents with a dispatch tool (3.4), or skills if the difference is knowledge A swarm: it adds coordination you do not need
A specialist to talk to the user for several turns Handoffs (4.2), or the single-agent state machine (4.4) Subagents: the user would be talking to a relay
Independent questions answered in parallel, then merged Router with Send (5.1) or parallel subagent tool calls (3.6) A sequential supervisor loop
Many teams contributing capabilities independently Subagents (a package per team) or skills (a document per team) Shared mutable state between teams
Code steps, agents, loops and an approval in one flow Custom workflow (Part 6) langgraph-supervisor; stacking agents and hoping
Reliability on checkable output A verifier node with a bounded loop (Part 6) The same model with the same context voting with itself
A multi-turn router A router as a tool of a conversational agent (5.2) A router that keeps its own history

Part 9: Testing multi-agent graphs without a key#

Deep-dive

Everything in this lesson ran with scripted models, which is also how you should test it. 08F.8, Part 12 and 08F.10, 13.3 own the tools; a multi-agent system adds four assertions worth writing down:

Assert How Why
The path, not the wording List the tool calls in result["messages"], or the node names from stream_mode="updates"; compare with the expected sequence A model's phrasing changes; the route is the behaviour
The history is valid Every AIMessage tool call has a ToolMessage with the same tool_call_id A dangling call is invisible to fake models and fatal to providers (4.3)
Isolation held Give the subagent's model a recorder and assert on the messages it received The point of a subagent is what it did not see
Budgets hold Script a model that never stops, set a low recursion_limit or a dispatch cap, and assert the failure or the clean stop The loops fail only when the model misbehaves (4.5)
python
# s70_tests.py: testing multi-agent graphs without a key: assert the PATH, the history and the budget
from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool

from fakes import FakeToolCallingModel, RecordingModel


def unanswered_tool_calls(messages):
    """Every AI tool call needs a ToolMessage with the same id, or a provider will reject the history."""
    answered = {m.tool_call_id for m in messages if m.type == "tool"}
    return [c["id"] for m in messages if m.type == "ai" for c in m.tool_calls if c["id"] not in answered]


def tools_called(result):
    return [c["name"] for m in result["messages"] if m.type == "ai" for c in m.tool_calls]


def test_supervisor_delegates_to_billing_only():
    billing = RecordingModel(messages=iter([AIMessage(content="Invoice 204 is unpaid.")]))
    tax = RecordingModel(messages=iter([AIMessage(content="never called")]))
    billing_agent = create_agent(billing, tools=[], name="billing_agent")
    tax_agent = create_agent(tax, tools=[], name="tax_agent")

    @tool("ask_billing", description="Ask billing.")
    def ask_billing(q: str) -> str:
        return billing_agent.invoke({"messages": [{"role": "user", "content": q}]})["messages"][-1].text

    @tool("ask_tax", description="Ask tax.")
    def ask_tax(q: str) -> str:
        return tax_agent.invoke({"messages": [{"role": "user", "content": q}]})["messages"][-1].text

    sup = create_agent(
        FakeToolCallingModel(messages=iter([
            AIMessage(content="", tool_calls=[ToolCall(name="ask_billing", args={"q": "status of invoice 204?"}, id="1")]),
            AIMessage(content="Invoice 204 is unpaid."),
        ])),
        tools=[ask_billing, ask_tax],
    )
    result = sup.invoke({"messages": [HumanMessage("Is invoice 204 paid?")]})
    assert tools_called(result) == ["ask_billing"]              # the PATH, not the wording
    assert unanswered_tool_calls(result["messages"]) == []      # the history is valid
    assert billing.seen and not tax.seen                        # the tax agent's model was never called
    assert [k for k, _ in billing.seen[0]] == ["HumanMessage"]  # isolation: it saw only the brief (no system prompt set here)


test_supervisor_delegates_to_billing_only()
print("test_supervisor_delegates_to_billing_only: passed")
print("dangling call detected:", unanswered_tool_calls([AIMessage(content="", tool_calls=[ToolCall(name="x", args={}, id="9")])]))
Output2 lines
test_supervisor_delegates_to_billing_only: passed
dangling call detected: ['9']

Move each test into a test_*.py file and run uv run pytest: the function is already in pytest's shape (a test_ name, plain assert). Three practical notes. Scripts run out: a scripted model raises StopIteration when asked for a reply it does not have, which usually means your graph made more model calls than you planned, so read it as a test failure, not a nuisance. Use fresh models per test: the scripted iterators are consumed (several samples build the agents inside a function for exactly that reason; itertools.cycle is the alternative for stateless specialists). Tool-call ids must be unique across a script, or the history validator and add_messages will confuse two calls (the ping-pong sample generates ids with a counter).

What fake models cannot test: whether the real model chooses the right specialist from your tool descriptions, writes a good brief, or follows "include the evidence in your final message". That is an evaluation problem, with a dataset of requests and the expected specialist (10A.12, 3.2 grades routing as a classification problem with confusion matrices; Module 10A has the rest, and 11A.5 for LangSmith datasets and experiments). The scripted tests protect your wiring; evaluations protect your prompts.


Part 10: Pitfalls, real behaviour and a checklist#

Reference

Most rows were reproduced by a sample in the section they cite. Rows marked "docs" are stated by the official docs or the package source and were not run; the row about paraphrased subagent output is general advice, and the create_supervisor compile row follows from the return type (a StateGraph has no invoke).

Symptom Cause Fix
A shared list in state is doubled after a subgraph runs Subgraph added as a node returns its whole value; an append reducer adds it again 2.3: return only new entries, use an output schema with a new key, or share messages
The subgraph "forgets" between calls Default mode is per-invocation (checkpointer=None) 2.6: checkpointer=True if you really want memory, or pass context in
Parallel calls to a checkpointer=True subagent conflict Two writers on one thread's subagent state 3.7: ToolCallLimitMiddleware(run_limit=1) or disable parallel tool calls
A checkpointer=False subgraph repeats work after a pause It restarts from its first node on resume 2.6: use None unless the subgraph is pure
get_state(subgraphs=True) returns nothing for a subagent The subagent is called inside a tool, so it is not discoverable 2.7, 3.8: call it from a node if you need its state
A nested approval never reaches the user No thread_id on the outer call, or no checkpointer on the outermost graph (a subagent's own checkpointer= is against the docs' rule but did not break the sample) 3.8: one checkpointer on the outermost graph, thread_id on the outer call
The supervisor ignores the specialist's evidence It only sees the specialist's final message 3.2: prompt the specialist to include evidence, or return a built summary
A handoff gives a provider error on the next call An AIMessage with a tool call was copied without its ToolMessage 4.3: always copy the pair; validate history in tests
A budget check on an edge after the agent does not stop handoffs The edge runs but cannot veto a Command.PARENT jump 4.2, 4.5: route handoffs through a dispatch node
Two agents pass the user back and forth No handoff budget; the default stop is the recursion limit 4.5
The swarm forgets the active agent No checkpointer, so active_agent lives for one call 4.6
transfer_to_Bob is an unknown tool langgraph-swarm lower-cases the name and turns whitespace runs into underscores 7.4: print tool.name or pass name=
ValueError from create_supervisor about names Workers without unique names 7.2: name= on every agent
create_supervisor(...).invoke fails: no such method It returns an uncompiled StateGraph 7.2: .compile() it
One failing parallel branch loses the others' results A super-step is transactional 5.4: turn failures into results inside the node
A tool hidden from a step still runs Hiding is not enforcing 4.4: check the step inside the tool
Subagent output is a paraphrase of what you needed Wrapper returned a model's summary of a summary 3.2: return the evidence verbatim, or an artefact reference (08D.3, 3.3)
The parent's stream_mode="messages" shows no tokens from the inner agent Subgraph streams are off by default (docs) 2.9, 08F.14: subgraphs=True
Retry and timeout defaults do not apply inside a subgraph Node defaults are not inherited (docs) 2.9: set them on the subgraph's nodes

10.2 A pre-flight checklist#

  1. Can one agent with better tools and a better prompt do this? If yes, stop.
  2. Which of the three reasons applies: context, ownership or parallelism? Which of the five patterns follows (1.4)?
  3. Does every agent have a unique name=, a clear tool description (the brief) and its own model choice?
  4. Is there one checkpointer, on the outermost graph? Is the thread_id on the outer call?
  5. What does each specialist return, and does the supervisor get the evidence it needs? Is untrusted text treated as data?
  6. Is every loop bounded: model calls per agent, tool calls per subagent, handoffs per turn, gate retries, max_concurrency, recursion limit?
  7. Are handoff messages a matched AIMessage and ToolMessage pair, and is there a test that asserts a valid history?
  8. Do shared keys have the right reducer, and have you checked what a subgraph returns for them (2.3)?
  9. Which tests fail if the route changes? Is there an evaluation for the choice of specialist?
  10. Can you read a trace of a failed run and say which agent did what? (11A.5)

10.3 JavaScript, in one note#

The same ideas exist in @langchain/langgraph (subgraphs, Command, Send) and langchain for JavaScript (createAgent). I did not verify the JavaScript API names or the status of its supervisor and swarm packages for this lesson; read the JavaScript tabs of the same documentation pages.


Common misconceptions#

Misconception Reality
"More agents is more capable." A single agent with the right tools and prompt often does as well; each agent adds tokens, errors and coordination (1.1, 08D.3, 1.2).
"LangChain has a supervisor feature and a swarm feature." The docs have five patterns (subagents, handoffs, skills, router, custom workflow). "Supervisor" and "swarm" are the names of two helper packages for two of them (1.2, Part 7).
"langgraph-supervisor is the way to build a supervisor." Its repository is archived, it is built on the deprecated create_react_agent, and the docs recommend a create_agent with subagents as tools (7.1).
"A subgraph returns only what it changed." A subgraph added as a node returns its final state for the keys the parent knows; with an append reducer on a shared key that duplicates entries (2.3).
"Private subgraph keys are hidden from everything." They are absent from the parent's state, but a subgraphs=True stream shows them (2.2).
"A subgraph remembers its earlier calls." Not by default: checkpointer=None starts fresh on each call; True accumulates (2.6).
"checkpointer=False means no interrupts." The docs say so, but in a run the interrupt still paused and resumed; what changed is that the subgraph restarted from its first node (2.6).
"The supervisor sees what its subagents did." It sees only what the tool wrapper returns, usually the final message (3.2).
"I can inspect a subagent with get_state(subgraphs=True)." Only if LangGraph can discover it statically. A subagent called inside a tool cannot be (2.7, 3.8).
"Every agent that can pause needs its own checkpointer." Only the outermost graph gets one (the docs' rule). The 3.8 sample ran with a subagent checkpointer too, but a private one gives the subagent a second, separate state (3.8).
"A handoff tool just sets active_agent." It must also return a Command with graph=Command.PARENT and, when it copies the AIMessage with the call, the matching ToolMessage (4.2, 4.3).
"A router after each agent node will stop runaway handoffs." An edge after the node runs but cannot veto a Command.PARENT jump (END does not cancel it); use a dispatch node (4.5).
"A swarm remembers who is active by itself." active_agent is state; without a checkpointer it lasts one call (4.6).
"Hiding a tool from a step stops the agent calling it." It only changes what the model is offered (4.4).
"A router can hold a conversation." It is stateless; wrap it as a tool of a conversational agent (5.2).
"If one parallel branch fails, the others' results are kept." The super-step is transactional; the run raises and the step's updates are discarded (5.4).
"Parallel agents are free speed." They cost one agent run each; cap them (5.4).
"The handoff tool for agent Bob is transfer_to_Bob." In langgraph-swarm it is transfer_to_bob (lower-cased, whitespace runs become underscores) (7.4).

Key takeaways#

  1. Start with one agent. Multi-agent earns its place for context management, distributed development or parallelization; every extra agent adds the four taxes of 08D.3.
  2. LangChain has five patterns: subagents (agents as tools, all routing through a main agent), handoffs (state variable plus Command), skills (prompts loaded on demand), router (classify, fan out, synthesize) and custom workflow (your own graph). Stateful patterns save about 40 to 50 percent of calls on repeat requests, and isolating patterns win on tokens for multi-domain questions (the docs' illustrative figures).
  3. A subgraph is a graph used as a node. Call it inside a node when the schemas differ, add it as a node when they share keys; private keys stay inside. A shared key with an append reducer can duplicate entries, so return only new entries, use an output schema or share messages.
  4. Subgraph persistence has three modes. None (default): fresh per call, interrupts work inside a call. True: accumulates per thread, no parallel calls. False: stateless, restarts from its first node on resume. Only the outermost graph needs a real checkpointer.
  5. The recommended supervisor is a create_agent whose tools are subagents. The supervisor sees only what the wrapper returns, so prompt the specialist to include evidence, return a summary you build, and treat returned text as untrusted.
  6. Choose what crosses the boundary on purpose: query only (isolated) or the parent's messages (fork) going down; text or a Command (with its ToolMessage) coming back. For many specialists use one dispatch tool with a Literal argument.
  7. Subagents are stateless by default and safe in parallel; checkpointer=True gives per-thread memory and forbids parallel calls (limit the tool to one call per run). Bound parallel work with prompts, ToolCallLimitMiddleware and max_concurrency.
  8. Nested interrupts need one checkpointer on the outermost graph and a thread_id on the outer call. Subagents called inside tools cannot be inspected with get_state(subgraphs=True).
  9. A handoff is a tool that returns Command(goto=..., graph=Command.PARENT, update=...). Copy the AIMessage with the call and a matching ToolMessage together or neither; LangGraph will not stop a dangling call, the provider will.
  10. Route handoffs through a node you own (dispatch) for budgets, audit and authorization: edges after the agent node cannot veto a Command.PARENT jump. A swarm is handoffs plus active_agent plus a checkpointer.
  11. For steps of one conversation, use one agent with middleware that swaps the prompt and tools by current_step; hiding tools is not enforcement.
  12. Router, skills and branches: a router is stateless (make it a tool for multi-turn), a skill is trusted prompt text, parallel branches need reducers, sorted joins and a concurrency cap, and one failing branch fails the step.
  13. Custom workflows mix deterministic nodes, agents and a human gate in one graph; cheap checks go first, loops get counters, and the approval interrupt needs a durable checkpointer in production.
  14. langgraph-supervisor is legacy (archived, deprecated internals); langgraph-swarm still works but lacks a guide in the docs. Migrate to Part 3 and Part 4 forms.
  15. Test the path, the history validity, the isolation and the budgets with scripted models; evaluate the real model's choice of specialist separately.

Terms introduced in this lesson#

Term One-line definition
Multi-agent system Two or more agents, each with its own instructions, tools and context, coordinated by code, by another agent or by state
Subgraph A compiled graph used as a node of another graph, with shared keys (added as a node) or a state mapping (called inside a node)
Shared and private state (subgraph) Keys present in both parent and subgraph schemas (shared) versus keys only the subgraph has (private, never in the parent)
Subgraph persistence mode The checkpointer setting of a subgraph's compile(): None (per-invocation), True (per-thread) or False (stateless)
Checkpoint namespace The path (node:uuid, nested levels joined with a pipe character) under which a subgraph's checkpoints are stored
Subagent An agent wrapped as a tool and called by a main agent, which sees only the final output and controls all routing
Subagents pattern The supervisor design recommended by the LangChain docs: a create_agent whose tools are create_agent subagents
Fork (subagent input) Passing the parent's messages to the subagent as well as the question, so it shares context (and cost)
Dispatch tool One tool (often task) that takes a specialist name and a task, instead of one tool per subagent
Handoff Moving control to another agent or step by updating a state variable, usually from a tool that returns a Command
Handoff tool A tool that returns Command(goto=..., graph=Command.PARENT, update=...) with the AIMessage plus ToolMessage pair
Active agent The state key (active_agent) naming which agent handles the next turn; persisted by a checkpointer
Dispatch node A node every handoff passes through, where budgets, logging and authorization are enforced
Swarm Peer agents handing off to each other with no supervisor, with the last active agent remembered across turns
Skills pattern One agent that loads specialized prompts and knowledge on demand through a load_skill tool
Router pattern A classification step that sends the input to one or more agents (with Command or Send) and synthesizes their results
Custom workflow A hand-built StateGraph mixing deterministic nodes, model nodes and agents
Quality gate A deterministic or agentic node that checks a result and routes back, onward or to a human, with a bounded loop
langgraph-supervisor The archived helper package whose create_supervisor builds a supervisor from a deprecated create_react_agent
langgraph-swarm The helper package whose create_swarm and create_handoff_tool package the swarm pattern

Exercises#

All of these run with no API key, with the scripted models of fakes.py. Each has an answer to compare with after you try it.

  1. Fix the doubled log. Take s02_shared_reducer.py. Make the final list equal to ['start', 'before', 'inner_a saw 2 entries'] using each of the three fixes of 2.3 in turn.
  2. Three modes, one table. Extend s05_persistence_modes.py to call the subgraph twice inside the same parent node, in each mode, and report what happens. Which mode would the docs forbid for this, and why?
  3. A third specialist behind a dispatch tool. Add a tax specialist to s15_dispatch_tool.py, make the supervisor script call two specialists in one turn, and assert (as in s70_tests.py) that exactly those two ran.
  4. Fork with a window. Change research_forked in s11_outputs_and_inputs.py to pass only the last two messages of history. Why is that a reasonable middle ground, and what can go wrong with a window that starts in the middle of a tool exchange?
  5. A per-turn handoff budget. In s60_pingpong.py the counter never resets. Reset it at the start of each user turn (a node before the first agent) and test two turns on one thread with a checkpointer.
  6. A verifier agent. Replace the "Source:" in answer test in s50_research_desk.py with a verifier create_agent node that returns pass or fail: reason, with a scripted model. Keep the loop bounded.
  7. An ensemble. Fan one question out to three scripted agents that give answers A, A, B, join with a reducer and an aggregator node that returns the majority. Then make the three agents identical and explain what voting now buys you.
  8. Migrate the supervisor. Rewrite s40_supervisor_pkg.py using Part 3 (no langgraph-supervisor). Compare the message trails: which messages disappeared, which did you gain, and how would you reproduce output_mode="full_history"?
  9. Guard the handoff history. Write a pytest that builds the handoff graph of 4.2 with a deliberately broken handoff tool (transfer_ai_only) and fails because of the dangling call.
  10. A skill that does not exist. Run s33_skills.py with a script whose first tool call asks for skill_name="regex". What does the agent get back, and what does a good load_skill return so that a real model can recover?
Answers
  1. Fix 1: call the subgraph inside a node and return out["log"][len(state["log"]):]. Fix 2: give the subgraph an output_schema with a new key such as sub_log and give the parent that key (the parent's log then stays ['start', 'before'] and the contribution is in sub_log, so decide which representation you want). Fix 3 does not apply to a plain string list; convert the entries to messages with ids and use add_messages, which merges by id.
  2. Build two wrappers that call sub.invoke(...) twice in one node. None and False give two independent fresh calls. With True the two calls share per-thread state and the docs warn about checkpoint conflicts and call-order namespaces for the same subgraph (2.6, 2.8), so the docs forbid calling the same per-thread subgraph twice in parallel and advise unique node names when you call different ones.
  3. Add a dictionary entry and extend the Literal; script two task tool calls in one AIMessage; assert that the recorded models of exactly those two specialists have seen entries and the third's is empty.
  4. A window keeps cost down while preserving recent context, which is cheaper than a full fork. The risk is starting the window on a ToolMessage or between an AIMessage with tool calls and its results, leaving a dangling or orphaned message that a provider rejects; start the window at a human message, or use trim_messages (08F.11).
  5. Add reset_turn as the first node (return {"handoffs": 0}) and route START to it, then to the active agent. With a checkpointer the counter would otherwise carry over from the last turn, and a long conversation would eventually trip the cap without any ping-pong.
  6. The verifier node calls the agent and returns a Command to research_team or publish_review by parsing the verdict; keep attempts in state and stop at the cap. Give the verifier tools or evidence the generator did not have, otherwise it tends to approve what it just read.
  7. With answers A, A, B the aggregator returns A. With three identical agents all three give the same answer, so voting adds cost and no information: the errors are perfectly correlated (08D.3, 2.5). Different models, prompts or evidence are what make votes independent.
  8. The tool-based trail has no synthetic "Transferring back to supervisor" messages and no transfer_to_* tool messages: the history is the user's message, the supervisor's tool call, the specialist's final text as a ToolMessage, and the answer. You gain a formatting responsibility in the wrapper. To reproduce full_history, return a built string of the subagent's tool calls and results from result["messages"] (at a token cost) rather than only [-1].
  9. Build the graph with the broken tool, invoke it, and assert unanswered_tool_calls(out["messages"]) == []; the test fails with ['t1']. Then fix the tool to add the ToolMessage and watch it pass.
  10. The tool returns Unknown skill 'regex'. Available: sql_style, invoice_schema. A good load_skill returns the list of valid names (as the sample does) so the model can self-correct; raising instead would stop the run unless you configured tool error handling (08F.8, Part 4).

Check yourself#

  1. In LangChain's own words, what are the three reasons to use more than one agent, and what is the first thing to try instead?
  2. Name the five multi-agent patterns in the docs and say which one keeps one agent in control and loads prompts on demand.
  3. When do you call a subgraph inside a node, and when do you add it as a node?
  4. A shared list key with operator.add doubles after a subgraph runs. Why, and what are three fixes?
  5. Describe checkpointer=None, True and False for a subgraph in one line each. Which one forbids parallel calls?
  6. Which graph needs a real checkpointer when you nest subagents, and what two things must you do for an interrupt to reach the user?
  7. What does the supervisor see of a subagent's run, and how do you give it more?
  8. Why can get_state(config, subgraphs=True) not show a subagent called inside a tool?
  9. What is a handoff tool, and what does graph=Command.PARENT do?
  10. A handoff tool copies the AIMessage that contains the tool call but no ToolMessage. What happens, and when do you find out?
  11. Why did a conditional edge after the agent node not stop a runaway handoff loop, and what is the fix?
  12. Why does a swarm forget the active agent without a checkpointer?
  13. How is a router different from a supervisor, and how do you make a router work across turns?
  14. What happens to the other branches when one parallel branch raises, and what caps concurrency?
  15. What is the status of langgraph-supervisor, what is its replacement, and what is the surprise in langgraph-swarm's handoff tool name?

Further resources#

Official sources only. The LangChain and LangGraph documentation is larger and moves faster than this lesson (there are tutorials for a personal assistant with subagents and a customer-support bot with handoffs that this lesson does not repeat); where it is more complete, read it. 08F.17 maps the whole documentation.


← 08F.12: Human-in-the-Loop and Control Flow | Module 08F overview | 08F.14: The Functional API and Streaming →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close