LangGraph 入门实战(11)--输出模式

13 阅读3分钟

LangGraph 流式输出:values、updates、messages 和 debug

LangGraph 的 graph.stream() 可以边执行节点边返回数据。通过 stream_mode,我们可以选择查看完整状态、节点增量、模型消息流或详细调试信息。

1. 安装与配置

pip install -U langgraph langchain-deepseek
export DEEPSEEK_API_KEY="你的 API Key"
python index.py

2. 构建工作流

下面创建一个简单流程:先把“小狗”加入主题,再让 DeepSeek 根据新主题生成笑话。

import os
from typing import Any, TypedDict, cast

from langchain_core.messages import BaseMessage
from langchain_deepseek import ChatDeepSeek
from langgraph.graph import START, StateGraph
from pydantic import SecretStr


deepseek = ChatDeepSeek(
    model="deepseek-v4-flash",
    temperature=0,
    base_url="https://api.deepseek.com",
    api_key=SecretStr(os.environ["DEEPSEEK_API_KEY"]),
)


class State(TypedDict):
    topic: str
    joke: str


def refine_topic(state: State):
    return {"topic": state["topic"] + "和小狗"}


def generate_joke(state: State):
    response = deepseek.invoke(
        [{"role": "user", "content": f"请生成一个关于{state['topic']}的笑话"}]
    )
    return {"joke": response.content}


graph = (
    StateGraph(State)
    .add_node(refine_topic)
    .add_node(generate_joke)
    .add_edge(START, "refine_topic")
    .add_edge("refine_topic", "generate_joke")
    .compile()
)

initial_state: State = {"topic": "小猫", "joke": ""}

执行顺序如下:

START -> refine_topic -> generate_joke -> END

3. 四种输出模式

模式返回内容适用场景
values每一步合并后的完整状态观察状态变化
updates当前节点更新的字段监听节点结果
messages模型消息片段和元数据实现打字机效果
debug节点输入、结果、时间和任务 ID排查工作流问题

values:完整状态

for event in graph.stream(initial_state, stream_mode="values"):
    print(event)

输出:

{'topic': '小猫', 'joke': ''}
{'topic': '小猫和小狗', 'joke': ''}
{'topic': '小猫和小狗', 'joke': '小猫和小狗去讲笑话,结果它们都笑了。'}

updates:节点增量

for event in graph.stream(initial_state, stream_mode="updates"):
    print(event)

输出:

{'refine_topic': {'topic': '小猫和小狗'}}
{'generate_joke': {'joke': '小猫和小狗去讲笑话,结果它们都笑了。'}}

messages:模型消息流

messages 返回 (message, metadata)。下面用 标记每个消息片段的边界:

for event in graph.stream(initial_state, stream_mode="messages"):
    message, metadata = cast(tuple[BaseMessage, dict[str, Any]], event)
    if message.content:
        print(message.content, end="|", flush=True)
print()

输出:

小猫|和小狗|去讲笑话|,结果它们都笑了。|

LangGraph 当前的类型声明无法根据 messages 自动推断事件结构,所以这里用 cast 告诉 Pylance 返回值是“消息与元数据”元组。消息片段的实际切分位置由模型决定,metadata["langgraph_node"] 可以用来判断消息来自哪个节点。

debug:调试信息

for event in graph.stream(initial_state, stream_mode="debug"):
    print(event)

精简输出如下,实际结果还包含时间、任务 ID 和触发来源:

{'step': 1, 'type': 'task',
 'payload': {'name': 'refine_topic', 'input': {'topic': '小猫', 'joke': ''}}}

{'step': 1, 'type': 'task_result',
 'payload': {'name': 'refine_topic', 'result': {'topic': '小猫和小狗'}}}

小结

日常展示状态用 values,只关心节点变更用 updates,向页面实时输出模型内容用 messages,排查节点执行问题时使用 debug

示例中的四次 graph.stream() 会完整执行四遍工作流,因此也会调用模型四次。实际项目只需选择需要的模式;如果希望一次获得多种结果,也可以传入 stream_mode=["updates", "messages"]。模型生成内容存在随机性,实际笑话可能与示例不同。