13. Subgraphs

Chapter 13 of 18 · 15 min

A subgraph is a compiled LangGraph that is embedded as a single node inside a parent graph. The parent graph sees the subgraph as a black box—it passes state in, the subgraph processes, and the parent receives updated state out. Subgraphs are the composition primitive for building agent teams hierarchically.

To embed a subgraph, compile it first, then pass the compiled app to add_node:

researcher_subgraph = researcher_builder.compile()
team_builder.add_node("research_team", researcher_subgraph)

The subgraph receives the parent state dict. If the parent and subgraph have different state schemas, LangGraph applies a state mapping using input/output converters. By default, fields present in both schemas are passed through; fields unique to one schema are ignored unless an explicit mapper is defined.

# Explicit input/output state mapping
team_builder.add_node(
    "research_team",
    researcher_subgraph,
    input=lambda s: {"query": s["task"]},       # parent field "task" → subgraph field "query"
    output=lambda s: {"findings": s["findings"]}  # subgraph field "findings" → parent field "findings"
)

This mapping lets heterogeneous teams compose without forcing all subgraphs to share a single monolithic state schema. Each subgraph can maintain its own internal state (subgraph_state) while only surfacing relevant fields to the parent.

The failure mode: if a subgraph's node raises an exception, execution inside the subgraph terminates and returns control to the parent graph. The parent graph then continues from the subgraph node. If you expect the parent to handle subgraph errors, catch them inside the subgraph or use a conditional edge following the subgraph node that inspects an error field.

Local verification checkpoint

Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.

EXERCISE

Build a subgraph with two internal nodes. Embed it in a parent graph. Use explicit input= and output= mappers. Confirm that the parent state only receives the mapped fields and not the internal subgraph state keys.