Skip to content

Chapter 8 · Subgraphs and explicit boundaries ​

Encapsulate reusable text cleanup in a subgraph. The parent should depend on its input and result, not internal temporary fields.

Mechanics and design choices ​

A compiled subgraph can be added directly when schemas share the relevant keys. Otherwise use a wrapper to transform input and output. Here the wrapper keeps temporary word lists out of parent state. Reusing execution logic does not establish user authorization boundaries. Configure checkpoint inheritance, cross-call memory, and streaming according to the use case.

Example ​

python
from typing import TypedDict
from langgraph.graph import StateGraph, START, END

class ChildState(TypedDict):
    raw: str
    cleaned: str

def clean(state: ChildState):
    return {"cleaned": " ".join(state["raw"].split())}

child_builder = StateGraph(ChildState)
child_builder.add_node("clean", clean)
child_builder.add_edge(START, "clean")
child_builder.add_edge("clean", END)
child = child_builder.compile()

class ParentState(TypedDict):
    text: str
    summary: str

def prepare(state: ParentState):
    result = child.invoke({"raw": state["text"], "cleaned": ""})
    return {"summary": result["cleaned"][:60]}

parent_builder = StateGraph(ParentState)
parent_builder.add_node("prepare", prepare)
parent_builder.add_edge(START, "prepare")
parent_builder.add_edge("prepare", END)
graph = parent_builder.compile()
result = graph.invoke({"text": "  reusable   graph  ", "summary": ""})
assert result["summary"] == "reusable graph"
assert "raw" not in result
print(result)

Run and verify ​

No model is required. Only parent fields should be visible. Invoke the child independently to verify reuse. Persistence is deliberately omitted to keep schema mapping separate from lifecycle configuration.

Pitfalls ​

Do not couple the parent to every internal child key. A small child refactor would break callers. Minimize delegated context while retaining explicit acceptance criteria.

🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. What if schemas use different keys?

2. Is a subgraph an authorization boundary?

3. What should the parent depend on?

4. Can a child graph be tested independently?

Hands-on exercises ​

  1. Add a private counter and assert the parent does not expose it.
  2. Reuse the child in two parent workflows and compare contracts.
  3. Test child failure and decide whether the parent propagates or translates it.

Official references ​

Verified on: 2026-09-17.