Module 2 · Flow control

Composable, reusable subgraphs

6 min read

A growing graph quickly becomes unreadable: fifteen nodes, dozens of edges, a state mixing everyone's concerns. The answer is the same as in classic software engineering: split into modules. In LangGraph, a module is a subgraph — a compiled graph used as a node of another graph. In Relay, all refund processing is a seven-node subgraph that the main graph sees as a single refund node.

A compiled graph is a node

def build_refund_graph():
    builder = StateGraph(
        RefundState, context_schema=Context, input_schema=RefundInput, output_schema=RefundOutput
    )
    builder.add_node("load_order", load_order)
    builder.add_node("assess_item", assess_item)
    ...
    return builder.compile(name="refund")


# In the main graph
builder.add_node("refund", build_refund_graph())
builder.add_edge("refund", "finish")

The subgraph is developed, visualized and tested independently. The main graph stays readable: triage → refund → finish. And the same subgraph can be reused elsewhere — for instance in an email-processing graph.

The subgraph is compiled without a checkpointer: it automatically inherits the parent's. Its steps are saved in the same thread, in a namespace of its own, which makes it possible to interrupt it (module 4) and resume it like any node.

Communication through shared keys

When a compiled subgraph is added directly as a node, parent and subgraph communicate through the state keys they have in common:

  • on entry, the subgraph receives the values of the common keys;
  • on exit, its final values for the common keys are sent back to the parent, which applies them with its own reducers.

Keys that exist only in the subgraph (like assessments) stay private: the parent never sees them, and they start from scratch at each new run of the subgraph.

The shared-reducer trap

This mechanism hides a trap, which we ran into while building Relay. The audit log is a shared key, with an addition reducer on both sides. Without precautions:

  1. The parent contains audit = ["triage → refund"].
  2. The subgraph receives that list, and appends its own lines.
  3. On exit, it returns its complete list: ["triage → refund", "refund: 848 € proposés", …].
  4. The parent applies operator.add: "triage → refund" appears twice.

The problem is general: any key with an addition reducer that makes the round trip through a subgraph gets duplicated. (messages escapes it, because add_messages replaces messages with the same id instead of duplicating them.)

The solution is to declare the subgraph's interface explicitly, with distinct input and output schemas:

class RefundInput(TypedDict, total=False):
    """What the subgraph RECEIVES from the parent."""
    messages: Annotated[list[AnyMessage], add_messages]
    order_id: str | None
    language: Literal["fr", "en"]


class RefundOutput(TypedDict, total=False):
    """What the subgraph RETURNS to the parent: its own contributions only."""
    messages: Annotated[list[AnyMessage], add_messages]
    status: Status
    refund: dict | None
    audit: Annotated[list[str], operator.add]

audit isn't in the input: the subgraph starts with an empty log and returns only its own lines. The test_two_level_approval test checks the final log, with no duplicates.

Input and output schemas are valuable beyond this bug: they document the subgraph's contract. You see at a glance what it needs and what it produces — its public interface.

The alternative: calling the subgraph from a node

When the parent's and subgraph's schemas really differ, you can call the subgraph inside a function that translates input and output:

refund_graph = build_refund_graph()


async def refund_node(state: SupportState) -> dict:
    inputs = {"order_id": state["order_id"], "messages": state["messages"][-1:]}
    result = await refund_graph.ainvoke(inputs)
    return {"refund": result["refund"], "status": result["status"]}
Subgraph added as a nodeSubgraph called in a function
CommunicationCommon keys (filtered by input/output schema)Explicit translation, in code
SchemasMust share keysFully independent
VisualizationThe subgraph appears in get_graph(xray=True)Black box
Interrupts and persistenceHandled automaticallyHandled too, if the call happens inside a node of the parent graph

Relay uses the first form, which is more declarative. The second is preferable when the subgraph is a third-party component whose state you don't control.

Inspecting a subgraph

During execution, a subgraph's state hasn't yet propagated to the parent. This is especially visible when the subgraph is paused, waiting for an approval: the parent doesn't yet contain a refund key. To read the inner state, explicitly ask for subgraphs:

parent = await graph.aget_state(config, subgraphs=True)
assert "refund" not in parent.values             # not propagated yet
refund = parent.tasks[0].state.values["refund"]  # the inner state of the paused subgraph

That is what Relay's server does to display pending approvals (lesson 5.2).

For visualization, graph.get_graph(xray=True).draw_mermaid() draws the main graph with the inside of its subgraphs. One limitation in LangGraph 1.2: a subgraph in which a node has an error handler (error_handler, lesson 2.2) isn't expanded by xray. That is the case of the refund subgraph; draw it directly instead: build_refund_graph().get_graph().draw_mermaid().

When to split?

Create a subgraph when a set of nodes:

  • forms a coherent business unit (refunds, document search);
  • has private data the rest of the graph doesn't need (assessments);
  • must be tested in isolation, or reused in several graphs;
  • is developed by another team.

Conversely, don't split a five-node graph "to keep things tidy": each boundary has a cost (interface schemas, more indirect inspection).

Key takeaways

  • A compiled graph is added as a node; it inherits the parent's checkpointer.
  • Parent and subgraph communicate through their common keys; other keys stay private.
  • A key with an addition reducer that makes the round trip is duplicated: declare input_schema and output_schema.
  • For incompatible schemas, call the subgraph inside a function that translates input and output.
  • aget_state(config, subgraphs=True) reads a running subgraph's state; get_graph(xray=True) draws it.

Practice

  1. Remove input_schema and output_schema from the refund subgraph, run test_two_level_approval and look at the audit log.
  2. Display build_refund_graph().get_graph().draw_mermaid(), then temporarily remove the error_handler from the execute node and compare with build_graph().get_graph(xray=True).draw_mermaid().
  3. Extract Relay's agent ⇄ tools loop into a conversation subgraph, with its own input and output schema.

Resources