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

Subgraph State

Sharing keys.

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

Sometimes a subgraph needs completely different state. A stock search subgraph might use a query and a list of matches, which the parent knows nothing about. Then we call it from inside a node, and translate.

Subgraph State
From the video: Subgraph State
  • Different state
  • Parent doesn't know its keys
  • Call it from a node

Translating in and out

The search subgraph has its own state, a query and matches. The parent node, find, turns the parent's title into a query, invokes the subgraph, and turns its matches back into the parent's stock key. Run it. The parent gets its answer, without ever seeing the subgraph's private keys.

subgraph_state.pypython
from typing import TypedDict
from langgraph.graph import StateGraph, START

class Search(TypedDict):
    query: str
    matches: list[str]
SHELF = ["Dune", "Dune Messiah", "Children of Dune", "Circe"]
def match(s): return {"matches": [t for t in SHELF if s["query"].lower() in t.lower()]}
search = StateGraph(Search); search.add_node(match); search.add_edge(START, "match")
search = search.compile()

class Shop(TypedDict):
    title: str
    stock: list[str]
def find(s):
    result = search.invoke({"query": s["title"]})
    return {"stock": result["matches"]}
shop = StateGraph(Shop); shop.add_node(find); shop.add_edge(START, "find")
print(shop.compile().invoke({"title": "dune"}))
Output
{'title': 'dune', 'stock': ['Dune', 'Dune Messiah', 'Children of Dune']}

Two ways to use a subgraph

There are two ways to connect a subgraph. If it shares state keys with the parent, add it directly as a node. If its state is different, call it inside a node, and translate the input and output yourself.

Add as a node

  • Shared state keysData flows throughLeast code

Call from a node

  • Different stateTranslate in and outFully separate

Summary

When a subgraph has different state, invoke it inside a node, and translate keys in and out. Next, a powerful tool for dynamic parallel work, Send.

Key takeaways
  • Own state
  • Invoke inside a node
  • Translate keys
Next up: Send — dynamic fan-out