flowchart TD
START(["START"]) --> agent("agent")
agent --> rag
rag --> generate("generate")
generate --> END(["END"])
subgraph rag [rag subgraph]
direction LR
rw("rewrite") --> se("search") --> rr("rerank")
end
11 Subgraphs

The doc-bot’s retrieval side has become a little machine of its own: rewrite the query, search, rerank. That is a flow, and flows are graphs — so make it one, and use it the way you’d use any other piece:
A whole compiled graph can be used as a single node inside another graph. The parent doesn’t see the subgraph’s internals — only its inputs and outputs.
There is no new API. Build a small StateGraph, compile() it, and hand the compiled object to add_node. The parent calls it like a plain node — state in, update out — and never learns that “one node” was three steps of its own.
11.1 What we’re building
We package the retrieval logic — rewrite → search → rerank — as a self-contained retrieval-augmented generation (RAG) subgraph, then drop it into a parent that orchestrates around it: agent decides to look something up, the subgraph does the lookup, generate writes the answer.
The parent graph has three nodes: agent, rag, generate. That middle one is an entire graph. From the parent’s point of view there is no rewrite and no rerank, just a node called rag that takes a question and returns docs.
11.2 Building the subgraph
A subgraph is an ordinary StateGraph with its own State, nodes, and edges. Here the State carries the question in, a rewritten query only the subgraph cares about, and the docs it hands back.
from typing import NotRequired, TypedDict
from langgraph.graph import StateGraph, START, END
class RagState(TypedDict):
question: str # input, shared with the parent
1 rewritten: NotRequired[str] # internal only: the rewritten query
docs: NotRequired[list[str]] # output, shared with the parent- 1
-
The parent has no
rewrittenfield and never will; it is scratch space the subgraph uses between its own steps, and it disappears at the boundary.
The three nodes are subgraph-local stubs, and each stands in for one job a real retrieval pipeline does: rewrite turns the user’s question into the query a search index answers best, search pulls a handful of candidate documents for that query, and rerank orders the candidates by how well they actually answer the question and keeps the top few. The parent then writes an answer from what survives. Query-rewriting is new here, and what earlier chapters retrieved with search_docs is vector_search inside this subgraph — both details nothing outside needs to know. All three stay hard-coded in Part I; Part III’s RAG chapters make them real.
def query_rewrite_node(state: RagState) -> dict:
q = state["question"]
rewritten = f"{q} (rewritten: + synonyms/context)"
print(f" [rag/rewrite] rewrote query: {rewritten}")
return {"rewritten": rewritten}
def vector_search_node(state: RagState) -> dict:
rewritten = state["rewritten"]
print(f" [rag/search] searching with: {rewritten}")
return {"docs": ["coarse doc 1", "coarse doc 2", "coarse doc 3"]}
def rerank_node(state: RagState) -> dict:
docs = state["docs"]
top = docs[:2] # pretend the reranker keeps the top 2
print(f" [rag/rerank] reranked, kept top-{len(top)}")
return {"docs": top}We wire and compile them just like any graph. One detail of that compile() matters only once the graph becomes a node. With no checkpointer passed (the default, checkpointer=None), a subgraph inherits the parent’s, so Chapter 8’s checkpointer and Chapter 9’s interrupt() survive the seam with no extra wiring. checkpointer=False opts out; checkpointer=True gives the subgraph memory of its own across calls on the same thread.
rag_builder = StateGraph(RagState)
rag_builder.add_node("rewrite", query_rewrite_node)
rag_builder.add_node("search", vector_search_node)
rag_builder.add_node("rerank", rerank_node)
rag_builder.add_edge(START, "rewrite")
rag_builder.add_edge("rewrite", "search")
rag_builder.add_edge("search", "rerank")
rag_builder.add_edge("rerank", END)
rag_subgraph = rag_builder.compile() # the compiled subgraphflowchart TD
START(["START"]) --> rewrite("rewrite") --> search("search") --> rerank("rerank") --> END(["END"])
11.3 Using it as a node
Now the parent. Its State shares two keys with the subgraph — question and docs — and adds a third, answer, of its own.
class MainState(TypedDict):
question: str
docs: NotRequired[list[str]] # shared: subgraph writes, parent reads
answer: NotRequired[str]
def agent_node(state: MainState) -> dict:
print("[agent] decided to do RAG")
return {}
def generate_node(state: MainState) -> dict:
docs = state["docs"]
print(f"[generate] generating an answer from {len(docs)} reranked doc(s)")
return {"answer": f"final answer (used {len(docs)} curated docs): {docs}"}Because parent and child agree on those key names, LangGraph can map data across the boundary automatically, and you get to pass the compiled subgraph straight to add_node — the second argument is a whole graph, not a function.
main_builder = StateGraph(MainState)
main_builder.add_node("agent", agent_node)
main_builder.add_node("rag", rag_subgraph) # a whole graph as one node
main_builder.add_node("generate", generate_node)
main_builder.add_edge(START, "agent")
main_builder.add_edge("agent", "rag")
main_builder.add_edge("rag", "generate")
main_builder.add_edge("generate", END)
main_graph = main_builder.compile()flowchart TD
START(["START"]) --> agent("agent") --> rag("rag") --> generate("generate") --> END(["END"])
When the parent reaches rag, it hands the subgraph the shared keys from its own state, the subgraph runs its three steps, and its updates flow back through the channels the parent’s schema declares. The filter works in both directions:
- On the way in, the child receives only the keys its own schema declares; it never sees
answer. - On the way out, the child’s final state is written to every parent channel its output schema names: the
ragnode writes bothdocsandquestion, whilerewrittenis dropped. The child does returnrewritten— invokerag_subgraphalone and you get it back — butMainStatenever declares it, so in the parent it has nowhere to land.
When you add a compiled graph directly, the update it returns is the child’s entire final state, written to every channel the parent also declares. For plain keys that’s harmless — docs replaces docs. For a key with a list reducer like Chapter 10’ operator.add, the child’s list already contains what the parent passed in, so the parent appends its own items a second time. Share log: Annotated[list[str], operator.add] on both sides and the parent’s log comes back as ['parent-step', 'parent-step', 'child-step'].
“Harmless for plain keys” holds because this parent runs its subgraph serially. Run two subgraphs in the same superstep and even a shared read-only key collides. Returning it counts as a write, so two children handing back the same question raise InvalidUpdateError on question — identical values and all. Two deliberate fixes: have an adapter return only the child’s own new keys (a delta), or give the child an output schema that omits the shared input.
(add_messages in Section 14.5 de-duplicates by message id, which is why sharing messages across the seam works in Part II.)
If parent and child share an accumulating key, wrap the subgraph in a node and return only the new items.

11.4 When the schemas don’t line up
That mapping worked because both graphs happened to call the question question and the docs docs. Neither graph enforces it. Suppose the parent calls them query and sources instead:
class MismatchState(TypedDict):
query: str # the question, under a different name
sources: NotRequired[list[str]] # the docs, under a different name
answer: NotRequired[str]LangGraph maps data across the boundary by matching key names, and when the names don’t match nothing crosses. Fields do not line up by position, by type, or by intent — only by name. When schemas differ, you transform explicitly.
The fix is a small wrapper node: a function that maps the parent’s state to the child’s input, invokes the subgraph, and maps the output back.
def rag_adapter_node(state: MismatchState) -> dict:
# Map parent -> child on the way in.
child_input = {"question": state["query"]}
# Invoke the compiled subgraph like any runnable graph.
child_output = rag_subgraph.invoke(child_input)
# Map child -> parent on the way out.
return {"sources": child_output["docs"]}Then wire rag_adapter_node as the rag node. The subgraph itself doesn’t change; it still speaks question and docs. The general pattern: share keys and add the subgraph directly for the easy case; wrap it in a mapping node the moment the two schemas disagree.
Everything so far returns through the seam. The subgraph runs to its END, its output maps back, and the parent’s wiring decides what’s next. The Command from Section 10.6 has one more trick — a node inside the subgraph can jump straight to a node of the parent:
from langgraph.types import Command
def query_rewrite_node(state: RagState):
# A stand-in for a real small-talk detector: just peek at the opening word.
if state["question"].lower().startswith(("hi", "hello", "thanks")):
# Nothing to retrieve — skip the rest of the subgraph and hand control
# straight to the parent's `generate`.
1 return Command(goto="generate", graph=Command.PARENT)
return {"rewritten": f"{state['question']} (rewritten)"}- 1
-
graph=Command.PARENTaddresses thegototo the parent’s node names instead of the subgraph’s own — heregenerate, which is where the parent’srag → generateedge already leads.
There is a contract to honor. The greeting path skipped search and rerank, so it never wrote docs — but generate above opens with docs = state["docs"], and lands there with the key absent. Run it as written and the greeting question raises KeyError: 'docs'. A new control path still has to satisfy its target’s input contract, the same dependency rule from Chapter 5. Make generate tolerate the no-retrieval case rather than pretend it summarized zero documents:
def generate_node(state: MainState) -> dict:
docs = state.get("docs", [])
if not docs: # arrived via the small-talk hand-off
return {"answer": "Hi! Ask me a documentation question and I'll dig in."}
return {"answer": f"final answer (used {len(docs)} curated docs): {docs}"}Now it runs both ways. "Hi there!" reaches generate with no docs and answers directly, while a real question still flows rag → search → rerank → generate with its two curated docs.
Use hand-offs sparingly — the clean habit is still “subgraph returns a conclusion, the parent decides.” But this is the mechanism they are built on: one agent passing control directly to another instead of reporting back. That pattern returns with Part II’s multi-agent designs (Chapter 16).
11.5 Running it
We run one question through the parent and print the final state keys, so you can see what crossed the boundary and what didn’t.
if __name__ == "__main__":
print("========== parent graph run ==========")
question = "How do I configure batch consumers in Kafka?"
result = main_graph.invoke({"question": question})
print("\n=== final answer ===")
print(result["answer"])
# `rewritten` never crossed back: it is not in the parent's state.
print("\nparent state keys:", sorted(result))========== parent graph run ==========
[agent] decided to do RAG
[rag/rewrite] rewrote query: How do I configure batch consumers in Kafka? (rewritten: + synonyms/context)
[rag/search] searching with: How do I configure batch consumers in Kafka? (rewritten: + synonyms/context)
[rag/rerank] reranked, kept top-2
[generate] generating an answer from 2 reranked doc(s)
=== final answer ===
final answer (used 2 curated docs): ['coarse doc 1', 'coarse doc 2']
parent state keys: ['answer', 'docs', 'question']
The indented [rag/...] lines are the subgraph’s three steps, inside a node the parent wired as one. The final state is ['answer', 'docs', 'question'] — no rewritten. The parent got the conclusion, and only that.
Add print("[generate] full state:", sorted(state)) to the top of generate_node and run again: rewritten is not in the state it receives.
Then break the easy case on purpose. Rename the parent’s docs field to results (in MainState and generate_node) but leave add_node("rag", rag_subgraph) alone. The run blows up with KeyError: 'results' — the subgraph still writes docs, the parent no longer declares that channel, so nothing maps into results. The fix is the wrapper node above.
11.6 What we learned
- A whole compiled graph can be a node. Pass the compiled object to
add_nodeand the parent runs it like any other node — seeing its inputs and outputs, never its internals. Private fields likerewrittendon’t cross. - Shared keys map automatically, by name. But the child hands back its whole final state, so an accumulating reducer on a shared key will double-count.
- Mismatched schemas need an explicit transform. Wrap the subgraph in a function node that maps parent → child in and child → parent out.
- A subgraph gives you a sub-agent’s isolation — minus the autonomy. It decides nothing; Part II adds the deciding.
New pieces in this chapter
| Piece | Usage |
|---|---|
| API | |
Command(graph=Command.PARENT) |
Keyword arg on Command: address the goto to the parent graph’s node names. Command(goto="generate", graph=Command.PARENT) |
add_messages |
Previewed in the Gotcha only; taught in Section 14.5. Reducer for chat history that de-duplicates by message id — why a shared messages key crosses the seam without double-counting |
Code in this chapter
| File | What it runs |
|---|---|
code/ch09_subgraphs.py |
A compiled RAG graph dropped into a parent as one node, with the state mapping across the boundary. |
Challenge
🥉 Bronze — see inside the node with Xray
The parent’s state never shows the child’s private steps, but the stream can. (Streaming is Chapter 18; this challenge can wait until then.)
Run main_graph.stream({"question": question}, stream_mode="updates", subgraphs=True) and print each (namespace, update) pair. The three inner steps appear tagged with the subgraph’s namespace, ('rag:…',) ['rewrite'], between the parent’s own () ['agent'] and () ['rag'].
Then draw the same nesting with main_graph.get_graph(xray=1).draw_mermaid(): the subgraph’s nodes should render inside a subgraph rag … end block within the parent’s diagram. draw_mermaid() returns Mermaid source, not an image; save it to a .mmd file or paste it into a Mermaid renderer to see the graph.

Worked solution with tests: code/answers/ch09_see_inside_node.py.
🥈 Silver — turn the adapter into a runnable file
The query/sources parent from Section 11.4 compiles fine and dies in the subgraph’s first node with KeyError: 'question' — nothing checks the two schemas against each other at compile() time. Fix it: fill in the wrapper node, wire it as rag in place of the raw subgraph, and give the parent a generate that reads sources. Make it a file you can run, with two asserts on the final state — sources arrives, and rewritten never appears.
Worked solution with tests: code/answers/ch09_schema_adapter.py.
11.7 The end of Part I
Stop and look at what we’ve built. Starting from a single node that did nothing but return a dict, the doc-bot learned to branch, to loop until it had enough, to reach for tools, to persist and resume after a failed step, to pause for a human before anything irreversible, to fan out in parallel and rejoin, and now to compose whole graphs inside other graphs. Every one is a pattern real production agents rely on, and you built all of them out of the same three pieces: State, nodes, edges.
And you did it with the model turned off. Every “decision” so far has been a keyword check or a hard-coded stub, so you could see the machine itself — the control flow, the state, the wiring — without the fog of a model’s unpredictability. You know what the graph does, because you wrote every branch it can take.
Part II turns the model on. We swap the stubs for a real language model and watch what changes — and, just as importantly, what breaks. The wiring stays put; what moves inside the nodes is now a thing with opinions, latency, and failure modes of its own.

