Skip to content

如何从子图进行流式输出

前提条件

本指南假设你熟悉以下内容:

如果你使用子图创建了一个图,你可能希望从这些子图流式输出内容。要实现这一点,你可以在父图的 .stream() 方法中指定 subgraphs=True

for chunk in parent_graph.stream(
    {"foo": "foo"},
    subgraphs=True
):
    print(chunk)

配置

首先,让我们安装所需的包

%%capture --no-stderr
%pip install -U langgraph

为 LangGraph 开发设置 LangSmith

注册 LangSmith,以便快速发现问题并提升你的 LangGraph 项目的性能。LangSmith 允许你使用跟踪数据来调试、测试和监控使用 LangGraph 构建的大语言模型应用程序 — 点击 此处 了解更多关于如何开始使用的信息。

示例

让我们定义一个简单的示例:

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


# Define 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):
    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()


# Define parent graph
class ParentState(TypedDict):
    foo: str


def node_1(state: ParentState):
    return {"foo": "hi! " + state["foo"]}


builder = StateGraph(ParentState)
builder.add_node("node_1", node_1)
builder.add_node("node_2", subgraph)
builder.add_edge(START, "node_1")
builder.add_edge("node_1", "node_2")
graph = builder.compile()

现在让我们流式传输图的输出:

for chunk in graph.stream({"foo": "foo"}, stream_mode="updates"):
    print(chunk)
{'node_1': {'foo': 'hi! foo'}}
{'node_2': {'foo': 'hi! foobar'}}
你可以看到,我们仅发出了父图节点(node_1node_2)的更新。若要发出 子图 节点的更新,你可以指定 subgraphs=True

for chunk in graph.stream(
    {"foo": "foo"},
    stream_mode="updates",
    subgraphs=True,
):
    print(chunk)
((), {'node_1': {'foo': 'hi! foo'}})
(('node_2:b692b345-cfb3-b709-628c-f0ba9608f72e',), {'subgraph_node_1': {'bar': 'bar'}})
(('node_2:b692b345-cfb3-b709-628c-f0ba9608f72e',), {'subgraph_node_2': {'foo': 'hi! foobar'}})
((), {'node_2': {'foo': 'hi! foobar'}})
瞧!现在流式输出包含了来自父图和子图的更新。注意,我们接收到的不仅是节点更新,还有命名空间,这些命名空间会告知我们正在从哪个图(或子图)进行流式传输。

Comments