AI Hints
Home›LangGraph Tutorial›Subgraphs
LangGraph · Lesson 62 of 120

Subgraphs

Graphs inside graphs.

⏱ 2 min read▶ Video at 1:05:54🎓 Free
Watch this lesson in the LangGraph courseWatch on YouTube ↗Full LangGraph course

As graphs grow, it helps to build them from smaller pieces. A compiled graph can be added as a node, inside another graph. That inner graph is called a subgraph.

Subgraphs
From the video: Subgraphs
  • Graphs grow
  • Build from pieces
  • A graph as a node

A pricing subgraph

The pricing subgraph has two steps, discount, then delivery. We compile it, and add it to the main graph as a single node, called pricing. Both graphs share the same state keys, so data flows straight through. Run it. The main graph runs the subgraph's two steps, and returns the final price.

subgraph.pypython
from typing import TypedDict
from langgraph.graph import StateGraph, START, END

class State(TypedDict):
    total: float
    delivery: float
    message: str

def discount(s): return {"total": round(s["total"] * 0.9, 2)}
def delivery(s): return {"delivery": 0 if s["total"] >= 25 else 2.99}
inner = StateGraph(State); inner.add_sequence([discount, delivery]); inner.add_edge(START, "discount")
pricing = inner.compile()

def summary(s): return {"message": f"Total £{s['total']} + delivery £{s['delivery']}"}
outer = StateGraph(State)
outer.add_node("pricing", pricing); outer.add_node(summary)
outer.add_edge(START, "pricing"); outer.add_edge("pricing", "summary")
print(outer.compile().invoke({"total": 30.0})["message"])
Output
Total £27.0 + delivery £0

Why subgraphs

Subgraphs keep big graphs tidy. Each piece can be built, and tested, on its own. Different teams can own different subgraphs. And a multi agent system is often just several agent subgraphs, inside one parent.

keyvalue
Tidysmall pieces
Testeach piece alone
Reusein many graphs
Multi-agentagents as subgraphs

Summary

A compiled graph can be a node in another graph. With shared state keys, data flows straight through. Next, subgraphs with their own private state.

Key takeaways
  • Compile the inner graph
  • add_node(name, graph)
  • Shared keys
Next up: Subgraph State — sharing keys