Lesson 9 of 11 · Advanced
Subgraphs
Compose LangGraph apps from subgraphs: add a compiled graph as a node, call one inside a node when schemas differ, keep keys private and stream with namespaces.
- 7 min read
- Advanced
- Reviewed
- Explain why large graphs are built from subgraphs
- Add a compiled graph as a node when it shares state keys with the parent
- Call a subgraph inside a node when the schemas differ, mapping keys in and out
- Keep a subgraph's private keys out of the parent's state
- Stream from subgraphs and read namespaces
Graphs inside graphs
As graphs grow, one big graph with 30 nodes becomes hard to read, test and reuse. Like functions in a program, you can break it into smaller graphs, each with one job, and combine them.
Subgraphs help you:
- Reuse a piece, such as a review step or a research step, in several applications.
- Test each piece on its own.
- Divide the work among a team, each owning a subgraph.
- Build multi-agent systems, where each agent is its own graph (next lesson).
Shared keys: add the subgraph as a node
When the subgraph and the parent use the same key names for the data they share, add the compiled subgraph as a node, just like a function:
import operator
from typing import Annotated, TypedDict
from langgraph.graph import END, START, StateGraph
# ---- The research subgraph: its own nodes and a private key (raw_results) ----
class ResearchState(TypedDict):
topic: str # shared with the parent (same name)
raw_results: list[str] # private to the subgraph
findings: Annotated[list[str], operator.add] # shared with the parent
def search(state: ResearchState) -> dict:
return {"raw_results": [f"{state['topic']}: result {i}" for i in range(1, 6)]}
def keep_best(state: ResearchState) -> dict:
return {"findings": state["raw_results"][:2]} # only the best results go back up
research_builder = StateGraph(ResearchState)
research_builder.add_node("search", search)
research_builder.add_node("keep_best", keep_best)
research_builder.add_edge(START, "search")
research_builder.add_edge("search", "keep_best")
research_builder.add_edge("keep_best", END)
research = research_builder.compile()
# ---- The parent graph uses the compiled subgraph as a node ----
class ReportState(TypedDict):
topic: str
findings: Annotated[list[str], operator.add]
report: str
def write(state: ReportState) -> dict:
return {"report": f"Report on {state['topic']} based on {len(state['findings'])} findings."}
builder = StateGraph(ReportState)
builder.add_node("research", research) # a whole graph as one node
builder.add_node("write", write)
builder.add_edge(START, "research")
builder.add_edge("research", "write")
builder.add_edge("write", END)
graph = builder.compile()
result = graph.invoke({"topic": "e-bike batteries", "findings": []})
print(result)
for namespace, update in graph.stream({"topic": "tyres", "findings": []}, stream_mode="updates", subgraphs=True):
where = namespace[0].split(":")[0] if namespace else "(parent)" # namespace: which (sub)graph
print(f"{where:<9} {list(update)}"){'topic': 'e-bike batteries', 'findings': ['e-bike batteries: result 1', 'e-bike batteries: result 2'], 'report': 'Report on e-bike batteries based on 2 findings.'}
research ['search']
research ['keep_best']
(parent) ['research']
(parent) ['write']The subgraph reads topic from the parent and returns findings. Its private key, raw_results, holding all five results, never appears in the parent's state, because the parent's schema doesn't have it. Only the two best findings travel up.
With subgraphs=True, the stream includes the subgraph's own steps, each labelled with a namespace saying which subgraph produced it, so you can show progress inside the research step too.
Different keys: call it inside a node
When a subgraph has its own schema, call it from a node and translate between the two:
from typing import TypedDict
from langgraph.graph import END, START, StateGraph
# A reusable subgraph with its OWN schema: nothing in common with the parent's keys
class TranslateState(TypedDict):
text: str
language: str
translation: str
def translate(state: TranslateState) -> dict: # a model would do this
phrasebook = {"Your order has shipped.": {"pt": "A sua encomenda foi enviada."}}
return {"translation": phrasebook.get(state["text"], {}).get(state["language"], state["text"])}
t_builder = StateGraph(TranslateState)
t_builder.add_node("translate", translate)
t_builder.add_edge(START, "translate")
t_builder.add_edge("translate", END)
translator = t_builder.compile()
class NotifyState(TypedDict):
customer_language: str
message: str
def localise(state: NotifyState) -> dict:
# Call the subgraph inside a node, mapping the parent's keys in and out
out = translator.invoke({"text": state["message"], "language": state["customer_language"]})
return {"message": out["translation"]}
builder = StateGraph(NotifyState)
builder.add_node("localise", localise)
builder.add_edge(START, "localise")
builder.add_edge("localise", END)
print(builder.compile().invoke({"customer_language": "pt", "message": "Your order has shipped."})){'customer_language': 'pt', 'message': 'A sua encomenda foi enviada.'}The localise node is an adapter: it builds the subgraph's input from the parent's keys and maps the output back. The translator subgraph knows nothing about notifications, so any graph can reuse it.
Composition in plain Python
A compiled graph is “state in, state out”, which is why it can be a node. Here's the idea with plain functions, including the adapter for a parent that uses different key names:
# Subgraphs in plain Python: a compiled graph is just "state in, state out", so it can be used
# as a node in a bigger graph. Adapters map keys when the two graphs use different names.
def make_graph(nodes):
def run(state):
for node in nodes:
state = {**state, **node(state)}
return state
return run
# A reusable "review" subgraph: works on {"text", "issues"}
def find_long_sentences(s):
return {"issues": [x for x in s["text"].split(". ") if len(x.split()) > 12]}
def verdict(s):
return {"verdict": "ok" if not s["issues"] else f"{len(s['issues'])} sentence(s) too long"}
review = make_graph([find_long_sentences, verdict])
# Parent 1 uses the same key name, "text", so the subgraph can be a node directly
blog = make_graph([lambda s: {"text": s["text"].strip()}, review])
print("blog:", blog({"text": " Short post. Done. "})["verdict"])
# Parent 2 calls its text "email_body", so an adapter maps the keys in and out
def review_email(s):
out = review({"text": s["email_body"]})
return {"email_review": out["verdict"]}
emails = make_graph([review_email])
body = "We are writing to let you know that your recent order has been dispatched from our warehouse today. Thanks."
print("email:", emails({"email_body": body})["email_review"])Common mistakes
Write the adapter node that calls a subgraph whose state uses different key names from the parent's.
def summarise_subgraph(state): # a subgraph's schema: {"document", "max_words"} -> {"summary"}
words = state["document"].split()
return {"summary": " ".join(words[:state["max_words"]]) + "..."}
def summarise_node(parent):
# Parent state has "contract_text". Call summarise_subgraph with document=contract_text and
# max_words=5, then return {"contract_summary": <the summary>} for the parent.
pass
parent = {"contract_text": "This agreement starts on 1 March 2027 and lasts two years.", "client": "Mei"}
parent = {**parent, **summarise_node(parent)}
print(parent["contract_summary"])
When can a compiled subgraph be added directly as a node with add_node?
Summary
- Subgraphs split big graphs into reusable, testable pieces.
- With shared key names, add the compiled subgraph as a node; private keys stay private.
- With different schemas, call the subgraph inside a node that maps keys in and out.
subgraphs=Truestreams subgraph steps with namespaces.- Subgraphs are checkpointed with their parent, so interrupts inside them work.
Next: multi-agent graphs.
Finished reading? Tick it off to track your progress.