mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-09-27 12:04:58 +02:00
11 KiB
11 KiB
In [1]:
%%capture --no-stderr
%pip install -U langgraphIn [2]:
from langgraph.graph import START, StateGraph
from langgraph.checkpoint.memory import MemorySaver
from typing import TypedDict
# subgraph
class SubgraphState(TypedDict):
foo: str # note that this key is shared with the parent graph state
bar: str
def subgraph_node_1(state: SubgraphState):
return {"bar": "bar"}
def subgraph_node_2(state: SubgraphState):
# note that this node is using a state key ('bar') that is only available in the subgraph
# and is sending update on the shared state key ('foo')
return {"foo": state["foo"] + state["bar"]}
subgraph_builder = StateGraph(SubgraphState)
subgraph_builder.add_node(subgraph_node_1)
subgraph_builder.add_node(subgraph_node_2)
subgraph_builder.add_edge(START, "subgraph_node_1")
subgraph_builder.add_edge("subgraph_node_1", "subgraph_node_2")
subgraph = subgraph_builder.compile()
# parent graph
class State(TypedDict):
foo: str
def node_1(state: State):
return {"foo": "hi! " + state["foo"]}
builder = StateGraph(State)
builder.add_node("node_1", node_1)
# note that we're adding the compiled subgraph as a node to the parent graph
builder.add_node("node_2", subgraph)
builder.add_edge(START, "node_1")
builder.add_edge("node_1", "node_2")Out [2]:
<langgraph.graph.state.StateGraph at 0x106d2fa10>
In [3]:
checkpointer = MemorySaver()
# You must only pass checkpointer when compiling the parent graph.
# LangGraph will automatically propagate the checkpointer to the child subgraphs.
graph = builder.compile(checkpointer=checkpointer)In [4]:
config = {"configurable": {"thread_id": "1"}}In [5]:
for _, chunk in graph.stream({"foo": "foo"}, config, subgraphs=True):
print(chunk){'node_1': {'foo': 'hi! foo'}}
{'subgraph_node_1': {'bar': 'bar'}}
{'subgraph_node_2': {'foo': 'hi! foobar'}}
{'node_2': {'foo': 'hi! foobar'}}
In [6]:
graph.get_state(config).valuesOut [6]:
{'foo': 'hi! foobar'}In [7]:
state_with_subgraph = [
s for s in graph.get_state_history(config) if s.next == ("node_2",)
][0]In [8]:
subgraph_config = state_with_subgraph.tasks[0].state
subgraph_configOut [8]:
{'configurable': {'thread_id': '1',
'checkpoint_ns': 'node_2:6ef111a6-f290-7376-0dfc-a4152307bc5b'}}In [9]:
graph.get_state(subgraph_config).valuesOut [9]:
{'foo': 'hi! foobar', 'bar': 'bar'}