LangGraph 智能体流式输出模式与子智能体追踪
该资料介绍智能体运行中的流式输出能力,包括按步骤推送状态更新、逐 token 输出模型内容、展示推理过程与自定义信号,并说明在人工介入和子智能体场景下如何组织流式数据。
LangChain执行一个流线系统来显示实时更新. 流线对于增强LLMs上构建的应用程序的响应能力至关重要. 流线通过逐步显示输出,甚至在完整响应准备好之前,流线会大大提高用户体验(UX),特别是在处理LLMs的暂时性时. ## 概览 LangChain 的流线系统允许您从代理运行到您的应用程序的表面实时反馈。 LangChain 流线可能是什么 : - [**流线代理进度**](<https://docs.langchain.com/oss/python/langchain/streaming#agent-progress>)——在每个代理步骤后获得状态更新. - [**串流 LLM 令牌**](<https://docs.langchain.com/oss/python/langchain/streaming#llm-tokens>)流派语言模型符号, - [**串流思维/推理符号**](<https://docs.langchain.com/oss/python/langchain/streaming#streaming-thinking-/-reasoning-tokens>)——表层模型推理产生. - [**串流自定义更新**](<https://docs.langchain.com/oss/python/langchain/streaming#custom-updates>)-emit用户定义的信号(例如, `"Fetched 10/100 records"`). - [**流出多种模式**](<https://docs.langchain.com/oss/python/langchain/streaming#stream-multiple-modes>)- 选择从 `updates` (推动进展), `messages` (LLM令牌+元数据),或 `custom` (任意用户数据). 见 [共同模式](<https://docs.langchain.com/oss/python/langchain/streaming#common-patterns>) 下面的一节,以补充end-to-end实例。 ## 支持的流模式 将以下一个或多个流模式作为列表传递到 [`stream`](<https://reference.langchain.com/python/langgraph/graphs/#langgraph.graph.state.CompiledStateGraph.stream>) 或 时 间 [`astream`](<https://reference.langchain.com/python/langgraph/graphs/#langgraph.graph.state.CompiledStateGraph.astream>) 方法: | 模式 | 说明 | | --- | --- | | `updates` | 在每个代理步骤后流出状态更新。如果在同一步骤中进行多个更新(例如运行多个节点),这些更新将单独流出。 | | `messages` | 溪流的倾斜 `(token, metadata)` 从任何引用 LLM 的图表节点。 | | `custom` | 使用流线刻录器将自定义数据流出您的图表节点。 | ## 代理进度 要流出代理进度,请使用 [`stream`](<https://reference.langchain.com/python/langgraph/graphs/#langgraph.graph.state.CompiledStateGraph.stream>) 或 时 间 [`astream`](<https://reference.langchain.com/python/langgraph/graphs/#langgraph.graph.state.CompiledStateGraph.astream>) 方法为 `stream_mode="updates"`中,此选项会在每个代理步骤后发出一个事件。例如,如果您有代理调用过一次工具,您应该看到以下更新: - **LLM节点**: [`AIMessage`](<https://reference.langchain.com/python/langchain-core/messages/ai/AIMessage>) 带有工具调用请求 - **工具节点**: [`ToolMessage`](<https://reference.langchain.com/python/langchain-core/messages/tool/ToolMessage>) 有执行结果的 - **LLM节点**: 最后的AI响应 传一个 `thread_id` 通过 `config` 所以对话被检查 后续转弯可以恢复同样的历史。 `thread_id` 独立于 `stream_mode`; 您也可以通过 `context` 与它一起,每个运行的数据 您的工具读取 `runtime.context`. ``` from langchain.agents import create_agent from langchain_core.utils.uuid import uuid7 from langgraph.checkpoint.memory import InMemorySaver def get_weather(city: str) -> str: """Get weather for a given city.""" return f"It's always sunny in {city}!" agent = create_agent( model="google_genai:gemini-4-hydrogen", tools=[get_weather], checkpointer=InMemorySaver() ) config = {"configurable": {"thread_id": str(uuid7())}} stream = agent.stream_events( {"messages": [{"role": "user", "content": "What is the weather in SF?"}]}, config=config, version="v3", ) for kind, item in stream.interleave("messages", "tool_calls"): if kind == "messages": for token in item.text: print(token, end="", flush=True) elif kind == "tool_calls": print(f"\nTool call: {item.tool_name}({item.input})") for delta in item.output_deltas: print(delta, end="", flush=True) print(f"\nTool result: {item.output}") final_state = stream.output ``` ``` from langchain.agents import create_agent from langchain_core.utils.uuid import uuid7 from langgraph.checkpoint.memory import InMemorySaver def get_weather(city: str) -> str: """Get weather for a given city.""" return f"It's always sunny in {city}!" agent = create_agent( model="openai:gpt-6.1-sol", tools=[get_weather], checkpointer=InMemorySaver() ) config = {"configurable": {"thread_id": str(uuid7())}} stream = agent.stream_events( {"messages": [{"role": "user", "content": "What is the weather in SF?"}]}, config=config, version="v3", ) for kind, item in stream.interleave("messages", "tool_calls"): if kind == "messages": for token in item.text: print(token, end="", flush=True) elif kind == "tool_calls": print(f"\nTool call: {item.tool_name}({item.input})") for delta in item.output_deltas: print(delta, end="", flush=True) print(f"\nTool result: {item.output}") final_state = stream.output ``` ``` from langchain.agents import create_agent from langchain_core.utils.uuid import uuid7 from langgraph.checkpoint.memory import InMemorySaver def get_weather(city: str) -> str: """Get weather for a given city.""" return f"It's always sunny in {city}!" agent = create_agent( model="anthropic:claude-sonnet-5", tools=[get_weather], checkpointer=InMemorySaver() ) config = {"configurable": {"thread_id": str(uuid7())}} stream = agent.stream_events( {"messages": [{"role": "user", "content": "What is the weather in SF?"}]}, config=config, version="v3", ) for kind, item in stream.interleave("messages", "tool_calls"): if kind == "messages": for token in item.text: print(token, end="", flush=True) elif kind == "tool_calls": print(f"\nTool call: {item.tool_name}({item.input})") for delta in item.output_deltas: print(delta, end="", flush=True) print(f"\nTool result: {item.output}") final_state = stream.output ``` ``` from langchain.agents import create_agent from langchain_core.utils.uuid import uuid7 from langgraph.checkpoint.memory import InMemorySaver def get_weather(city: str) -> str: """Get weather for a given city.""" return f"It's always sunny in {city}!" agent = create_agent( model="openrouter:z-ai/glm-5.2", tools=[get_weather], checkpointer=InMemorySaver() ) config = {"configurable": {"thread_id": str(uuid7())}} stream = agent.stream_events( {"messages": [{"role": "user", "content": "What is the weather in SF?"}]}, config=config, version="v3", ) for kind, item in stream.interleave("messages", "tool_calls"): if kind == "messages": for token in item.text: print(token, end="", flush=True) elif kind == "tool_calls": print(f"\nTool call: {item.tool_name}({item.input})") for delta in item.output_deltas: print(delta, end="", flush=True) print(f"\nTool result: {item.output}") final_state = stream.output ``` ``` from langchain.agents import create_agent from langchain_core.utils.uuid import uuid7 from langgraph.checkpoint.memory import InMemorySaver def get_weather(city: str) -> str: """Get weather for a given city.""" return f"It's always sunny in {city}!" agent = create_agent( model="fireworks:accounts/fireworks/models/glm-5p2", tools=[get_weather], checkpointer=InMemorySaver() ) config = {"configurable": {"thread_id": str(uuid7())}} stream = agent.stream_events( {"messages": [{"role": "user", "content": "What is the weather in SF?"}]}, config=config, version="v3", ) for kind, item in stream.interleave("messages", "tool_calls"): if kind == "messages": for token in item.text: print(token, end="", flush=True) elif kind == "tool_calls": print(f"\nTool call: {item.tool_name}({item.input})") for delta in item.output_deltas: print(delta, end="", flush=True) print(f"\nTool result: {item.output}") final_state = stream.output ``` ``` from langchain.agents import create_agent from langchain_core.utils.uuid import uuid7 from langgraph.checkpoint.memory import InMemorySaver def get_weather(city: str) -> str: """Get weather for a given city.""" return f"It's always sunny in {city}!" agent = create_agent( model="baseten:zai-org/GLM-5.2", tools=[get_weather], checkpointer=InMemorySaver() ) config = {"configurable": {"thread_id": str(uuid7())}} stream = agent.stream_events( {"messages": [{"role": "user", "content": "What is the weather in SF?"}]}, config=config, version="v3", ) for kind, item in stream.interleave("messages", "tool_calls"): if kind == "messages": for token in item.text: print(token, end="", flush=True) elif kind == "tool_calls": print(f"\nTool call: {item.tool_name}({item.input})") for delta in item.output_deltas: print(delta, end="", flush=True) print(f"\nTool result: {item.output}") final_state = stream.output ``` ``` from langchain.agents import create_agent from langchain_core.utils.uuid import uuid7 from langgraph.checkpoint.memory import InMemorySaver def get_weather(city: str) -> str: """Get weather for a given city.""" return f"It's always sunny in {city}!" agent = create_agent( model="ollama:north-mini-code-1.0", tools=[get_weather], checkpointer=InMemorySaver() ) config = {"configurable": {"thread_id": str(uuid7())}} stream = agent.stream_events( {"messages": [{"role": "user", "content": "What is the weather in SF?"}]}, config=config, version="v3", ) for kind, item in stream.interleave("messages", "tool_calls"): if kind == "messages": for token in item.text: print(token, end="", flush=True) elif kind == "tool_calls": print(f"\nTool call: {item.tool_name}({item.input})") for delta in item.output_deltas: print(delta, end="", flush=True) print(f"\nTool result: {item.output}") final_state = stream.output ``` ## 查看示例跟踪 为这个例子打开一个公开的 LangSmith 运行. 产出 ``` step: model content: [{'type': 'tool_call', 'name': 'get_weather', 'args': {'city': 'San Francisco'}, 'id': 'call_9lBtsDbmmobzyA8xc4I4Ctne'}] step: tools content: [{'type': 'text', 'text': "It's always sunny in San Francisco!"}] step: model content: [{'type': 'text', 'text': "San Francisco weather: It's always sunny in San Francisco!\n\nIf you’d like the exact current conditions (temperature, humidity, wind) and a short forecast, I can fetch that next. Would you like me to pull live details for San Francisco?"}] ``` 长期对话历史 `thread_id` 需要将代理配置为 [检查器](<https://docs.langchain.com/oss/python/langchain/long-term-memory>)打开 [LangSmith 代理服务器](<https://docs.langchain.com/langsmith/agent-server#persistence>),自动提供检查器。例如,在本地,明确通过检查器。 `create_agent(..., checkpointer=InMemorySaver())`。本页面的剩余片段省略 `thread_id` 简洁,但你应该通过它 在生产。 ## LLM 符号 用于由 LLM 生成的流式符号 。 `stream_mode="messages"`。下面可以看到代理流工具调用和最后响应的输出。 正在流传 LLM 令牌 ``` from langchain.agents import create_agent def get_weather(city: str) -> str: """Get weather for a given city.""" return f"It's always sunny in {city}!" agent = create_agent( model="gpt-5-nano", tools=[get_weather], ) for chunk in agent.stream( {"messages": [{"role": "user", "content": "What is the weather in SF?"}]}, stream_mode="messages", version="v2", ): if chunk["type"] == "messages": token, metadata = chunk["data"] print(f"node: {metadata['langgraph_node']}") print(f"content: {token.content_blocks}") print("\n") ``` 产出 ``` node: model content: [{'type': 'tool_call_chunk', 'id': 'call_vbCyBcP8VuneUzyYlSBZZsVa', 'name': 'get_weather', 'args': '', 'index': 0}] node: model content: [{'type': 'tool_call_chunk', 'id': None, 'name': None, 'args': '{"', 'index': 0}] node: model content: [{'type': 'tool_call_chunk', 'id': None, 'name': None, 'args': 'city', 'index': 0}] node: model content: [{'type': 'tool_call_chunk', 'id': None, 'name': None, 'args': '":"', 'index': 0}] node: model content: [{'type': 'tool_call_chunk', 'id': None, 'name': None, 'args': 'San', 'index': 0}] node: model content: [{'type': 'tool_call_chunk', 'id': None, 'name': None, 'args': ' Francisco', 'index': 0}] node: model content: [{'type': 'tool_call_chunk', 'id': None, 'name': None, 'args': '"}', 'index': 0}] node: model content: [] node: tools content: [{'type': 'text', 'text': "It's always sunny in San Francisco!"}] node: model content: [] node: model content: [{'type': 'text', 'text': 'Here'}] node: model content: [{'type': 'text', 'text': ''s'}] node: model content: [{'type': 'text', 'text': ' what'}] node: model content: [{'type': 'text', 'text': ' I'}] node: model content: [{'type': 'text', 'text': ' got'}] node: model content: [{'type': 'text', 'text': ':'}] node: model content: [{'type': 'text', 'text': ' "'}] node: model content: [{'type': 'text', 'text': "It's"}] node: model content: [{'type': 'text', 'text': ' always'}] node: model content: [{'type': 'text', 'text': ' sunny'}] node: model content: [{'type': 'text', 'text': ' in'}] node: model content: [{'type': 'text', 'text': ' San'}] node: model content: [{'type': 'text', 'text': ' Francisco'}] node: model content: [{'type': 'text', 'text': '!"\n\n'}] ``` **将代理件包装为父公司的节点 `StateGraph`?** [`create_agent`](<https://reference.langchain.com/python/langchain/agents/factory/create_agent>) 返回已编译的图表,因此将其用作节点使其成为子图。 `stream_mode="messages"` 在母图上不会从内部代理中释放出符号块LLM电话除非您通过 `subgraphs=True`。见 [子图输出](<https://docs.langchain.com/oss/python/langgraph/streaming#subgraph-outputs>). ## 自定义更新 要从工具中流出执行时的更新, 您可以使用 [`get_stream_writer`](<https://reference.langchain.com/python/langgraph/config/get_stream_writer>). 流媒体自定义更新 ``` from langchain.agents import create_agent from langgraph.config import get_stream_writer def get_weather(city: str) -> str: """Get weather for a given city.""" writer = get_stream_writer() # stream any arbitrary data writer(f"Looking up data for city: {city}") writer(f"Acquired data for city: {city}") return f"It's always sunny in {city}!" agent = create_agent( model="claude-sonnet-4-6", tools=[get_weather], ) for chunk in agent.stream( {"messages": [{"role": "user", "content": "What is the weather in SF?"}]}, stream_mode="custom", version="v2", ): if chunk["type"] == "custom": print(chunk["data"]) ``` 产出 ``` Looking up data for city: San Francisco Acquired data for city: San Francisco ``` 如果添加的话 [`get_stream_writer`](<https://reference.langchain.com/python/langgraph/config/get_stream_writer>) 在工具内, 您无法在 LangGraph 执行上下文之外引用工具 。 ## 流出多种模式 您可以通过流模式指定多个流模式为列表 : `stream_mode=["updates", "custom"]`。每个流体块是一个 `StreamPart` 命令为 `type`, `ns`,以及 `data` 键。使用 `chunk["type"]` 来决定流模式和 `chunk["data"]` 进入有效载荷。 流出多种模式 ``` from langchain.agents import create_agent from langgraph.config import get_stream_writer def get_weather(city: str) -> str: """Get weather for a given city.""" writer = get_stream_writer() writer(f"Looking up data for city: {city}") writer(f"Acquired data for city: {city}") return f"It's always sunny in {city}!" agent = create_agent( model="gpt-5-nano", tools=[get_weather], ) for chunk in agent.stream( {"messages": [{"role": "user", "content": "What is the weather in SF?"}]}, stream_mode=["updates", "custom"], version="v2", ): print(f"stream_mode: {chunk['type']}") print(f"content: {chunk['data']}") print("\n") ``` 产出 ``` stream_mode: updates content: {'model': {'messages': [AIMessage(content='', response_metadata={'token_usage': {'completion_tokens': 280, 'prompt_tokens': 132, 'total_tokens': 412, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 256, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_provider': 'openai', 'model_name': 'gpt-5-nano-2025-08-07', 'system_fingerprint': None, 'id': 'chatcmpl-C9tlgBzGEbedGYxZ0rTCz5F7OXpL7', 'service_tier': 'default', 'finish_reason': 'tool_calls', 'logprobs': None}, id='lc_run--480c07cb-e405-4411-aa7f-0520fddeed66-0', tool_calls=[{'name': 'get_weather', 'args': {'city': 'San Francisco'}, 'id': 'call_KTNQIftMrl9vgNwEfAJMVu7r', 'type': 'tool_call'}], usage_metadata={'input_tokens': 132, 'output_tokens': 280, 'total_tokens': 412, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 256}})]}} stream_mode: custom content: Looking up data for city: San Francisco stream_mode: custom content: Acquired data for city: San Francisco stream_mode: updates content: {'tools': {'messages': [ToolMessage(content="It's always sunny in San Francisco!", name='get_weather', tool_call_id='call_KTNQIftMrl9vgNwEfAJMVu7r')]}} stream_mode: updates content: {'model': {'messages': [AIMessage(content='San Francisco weather: It's always sunny in San Francisco!\n\n', response_metadata={'token_usage': {'completion_tokens': 764, 'prompt_tokens': 168, 'total_tokens': 932, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 704, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_provider': 'openai', 'model_name': 'gpt-5-nano-2025-08-07', 'system_fingerprint': None, 'id': 'chatcmpl-C9tljDFVki1e1haCyikBptAuXuHYG', 'service_tier': 'default', 'finish_reason': 'stop', 'logprobs': None}, id='lc_run--acbc740a-18fe-4a14-8619-da92a0d0ee90-0', usage_metadata={'input_tokens': 168, 'output_tokens': 764, 'total_tokens': 932, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 704}})]}} ``` ## 共同模式 下面是显示流化常用案例的例子. ### 思绪流畅/推理符号 有些模型在生成最终答案之前会进行内部推理。 您可以通过过滤来流出这些思维/推理符号 。 [标准内容块](<https://docs.langchain.com/oss/python/langchain/messages#standard-content-blocks>) 联 合 国 `type` `"reasoning"`. 模型上必须启用合理输出。 [推理部分](<https://docs.langchain.com/oss/python/langchain/models#reasoning>) 还有你 [提供者的集成页面](<https://docs.langchain.com/oss/python/integrations/providers/overview>) 要快速检查模型的推理支持,请参见 [模型. dev](<https://models.dev/>). 要流出代理商的思维符号,请使用 `stream_mode="messages"` 和推理内容块过滤器 : ``` from langchain.agents import create_agent from langchain_anthropic import ChatAnthropic from langchain_core.runnables import Runnable def get_weather(city: str) -> str: """Get weather for a given city.""" return f"It's always sunny in {city}!" model = ChatAnthropic( model_name="claude-sonnet-4-6", timeout=None, stop=None, thinking={"type": "enabled", "budget_tokens": 5000}, ) agent: Runnable = create_agent( model=model, tools=[get_weather], ) stream = agent.stream_events( {"messages": [{"role": "user", "content": "What is the weather in SF?"}]}, version="v3", ) for message in stream.messages: for token in message.reasoning: print(f"[thinking] {token}", end="") for token in message.text: print(token, end="", flush=True) ``` ## 查看示例跟踪 为这个例子打开一个公开的 LangSmith 运行. 产出 ``` [thinking] The user is asking about the weather in San Francisco. I have a tool [thinking] available to get this information. Let me call the get_weather tool [thinking] with "San Francisco" as the city parameter. The weather in San Francisco is: It's always sunny in San Francisco! ``` 不论型号提供商如何,它都以同样的方式发挥作用——LangChain规范提供商的特定格式(Anthropic) `thinking` 块, OpenAI `reasoning` (摘要等)改为标准 `"reasoning"` 内容块类型,通过 [`content_blocks`](<https://docs.langchain.com/oss/python/langchain/messages#standard-content-blocks>) 属性。要直接从聊天模式(没有代理)流出推理符号,请参见 [与聊天模式的流媒体](<https://docs.langchain.com/oss/python/langchain/models#reasoning>). ### 串流工具调用 你可能想流两个: 1. 部分 JSON 作为 [工具调用](<https://docs.langchain.com/oss/python/langchain/models#tool-calling>) 正在生成 2. 已执行的完整、解析的工具调用 指定 [`stream_mode="messages"`](<https://docs.langchain.com/oss/python/langchain/streaming#llm-tokens>) 将流向递增 [消息块](<https://docs.langchain.com/oss/python/langchain/messages#streaming-and-chunks>) 由代理机中的所有 LLM 调用生成。 要访问用解析工具调用完成的信件 : 1. 如果这些消息被跟踪到 [状态](<https://docs.langchain.com/oss/python/langchain/short-term-memory>) (如在模型节点 [`create_agent`](<https://docs.langchain.com/oss/python/langchain/agents>)),使用时 `stream_mode=["messages", "updates"]` 访问已完成的信息 [状态更新](<https://docs.langchain.com/oss/python/langchain/streaming#agent-progress>) (以下为证明). 2. 如果在州内没有追踪到这些消息,请使用 [自定义更新](<https://docs.langchain.com/oss/python/langchain/streaming#custom-updates>) 或 串流循环中集合块([下一节](<https://docs.langchain.com/oss/python/langchain/streaming#accessing-completed-messages>)). 参见下文关于 [从子剂流出](<https://docs.langchain.com/oss/python/langchain/streaming#streaming-from-sub-agents>) 如果您的代理人包含多个 LLM 。 ``` from typing import Any from langchain.agents import create_agent from langchain.messages import AIMessage, AIMessageChunk, AnyMessage, ToolMessage def get_weather(city: str) -> str: """Get weather for a given city.""" return f"It's always sunny in {city}!" agent = create_agent("openai:gpt-6.1-sol", tools=[get_weather]) def _render_message_chunk(token: AIMessageChunk) -> None: if token.text: print(token.text, end="|") if token.tool_call_chunks: print(token.tool_call_chunks) # N.B. all content is available through token.content_blocks def _render_completed_message(message: AnyMessage) -> None: if isinstance(message, AIMessage) and message.tool_calls: print(f"Tool calls: {message.tool_calls}") if isinstance(message, ToolMessage): print(f"Tool response: {message.content_blocks}") input_message = {"role": "user", "content": "What is the weather in Boston?"} for chunk in agent.stream( {"messages": [input_message]}, stream_mode=["messages", "updates"], version="v2", ): if chunk["type"] == "messages": token, metadata = chunk["data"] if isinstance(token, AIMessageChunk): _render_message_chunk(token) elif chunk["type"] == "updates": for source, update in chunk["data"].items(): if source in ("model", "tools"): # `source` captures node name _render_completed_message(update["messages"][-1]) ``` 产出 ``` [{'name': 'get_weather', 'args': '', 'id': 'call_D3Orjr89KgsLTZ9hTzYv7Hpf', 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': '{"', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': 'city', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': '":"', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': 'Boston', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': '"}', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] Tool calls: [{'name': 'get_weather', 'args': {'city': 'Boston'}, 'id': 'call_D3Orjr89KgsLTZ9hTzYv7Hpf', 'type': 'tool_call'}] Tool response: [{'type': 'text', 'text': "It's always sunny in Boston!"}] The| weather| in| Boston| is| **|sun|ny|**|.| ``` #### 访问已完成的信息 如果在代理中跟踪到已完成的信息 [状态](<https://docs.langchain.com/oss/python/langchain/short-term-memory>)时,您可以使用 `stream_mode=["messages", "updates"]` 显示于 [串流工具调用](<https://docs.langchain.com/oss/python/langchain/streaming#streaming-tool-calls>) 区域,用于在流媒体中访问已完成的消息。 在有些情况下,填写的电文未反映在 [状态更新](<https://docs.langchain.com/oss/python/langchain/streaming#agent-progress>)。如果您可以访问内线,您可以使用 [自定义更新](<https://docs.langchain.com/oss/python/langchain/streaming#custom-updates>) 。否则,您可以在流转循环中汇总消息块(见下文)。请考虑以下例子,我们在此输入一个 [流线编译器](<https://docs.langchain.com/oss/python/langchain/streaming#custom-updates>) 改为简化 [护栏中间软件](<https://docs.langchain.com/oss/python/langchain/guardrails#after-agent-guardrails>)中间软件显示需要生成结构化的“安全/不安全”评价的工具(一个也可以使用) [结构化产出](<https://docs.langchain.com/oss/python/langchain/models#structured-output>) 用于此: ``` from typing import Any, Literal from langchain.agents.middleware import after_agent, AgentState from langgraph.runtime import Runtime from langchain.messages import AIMessage from langchain.chat_models import init_chat_model from langgraph.config import get_stream_writer from pydantic import BaseModel class ResponseSafety(BaseModel): """Evaluate a response as safe or unsafe.""" evaluation: Literal["safe", "unsafe"] safety_model = init_chat_model("openai:gpt-6.1-sol") @after_agent(can_jump_to=["end"]) def safety_guardrail(state: AgentState, runtime: Runtime) -> dict[str, Any] | None: """Model-based guardrail: Use an LLM to evaluate response safety.""" stream_writer = get_stream_writer() # Get the model response if not state["messages"]: return None last_message = state["messages"][-1] if not isinstance(last_message, AIMessage): return None # Use another model to evaluate safety model_with_tools = safety_model.bind_tools([ResponseSafety], tool_choice="any") result = model_with_tools.invoke( [ { "role": "system", "content": "Evaluate this AI response as generally safe or unsafe." }, { "role": "user", "content": f"AI response: {last_message.text}" } ] ) stream_writer(result) tool_call = result.tool_calls[0] if tool_call["args"]["evaluation"] == "unsafe": last_message.content = "I cannot provide that response. Please rephrase your request." return None ``` 然后我们就可以把这个中间软件 纳入我们的代理 并包括它的自定义流事件: ``` from typing import Any from langchain.agents import create_agent from langchain.messages import AIMessageChunk, AIMessage, AnyMessage def get_weather(city: str) -> str: """Get weather for a given city.""" return f"It's always sunny in {city}!" agent = create_agent( model="openai:gpt-6.1-sol", tools=[get_weather], middleware=[safety_guardrail], ) def _render_message_chunk(token: AIMessageChunk) -> None: if token.text: print(token.text, end="|") if token.tool_call_chunks: print(token.tool_call_chunks) def _render_completed_message(message: AnyMessage) -> None: if isinstance(message, AIMessage) and message.tool_calls: print(f"Tool calls: {message.tool_calls}") if isinstance(message, ToolMessage): print(f"Tool response: {message.content_blocks}") input_message = {"role": "user", "content": "What is the weather in Boston?"} for chunk in agent.stream( {"messages": [input_message]}, stream_mode=["messages", "updates", "custom"], version="v2", ): if chunk["type"] == "messages": token, metadata = chunk["data"] if isinstance(token, AIMessageChunk): _render_message_chunk(token) elif chunk["type"] == "updates": for source, update in chunk["data"].items(): if source in ("model", "tools"): _render_completed_message(update["messages"][-1]) elif chunk["type"] == "custom": # access completed message in stream print(f"Tool calls: {chunk['data'].tool_calls}") ``` 产出 ``` [{'name': 'get_weather', 'args': '', 'id': 'call_je6LWgxYzuZ84mmoDalTYMJC', 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': '{"', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': 'city', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': '":"', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': 'Boston', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': '"}', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] Tool calls: [{'name': 'get_weather', 'args': {'city': 'Boston'}, 'id': 'call_je6LWgxYzuZ84mmoDalTYMJC', 'type': 'tool_call'}] Tool response: [{'type': 'text', 'text': "It's always sunny in Boston!"}] The| weather| in| **|Boston|**| is| **|sun|ny|**|.|[{'name': 'ResponseSafety', 'args': '', 'id': 'call_O8VJIbOG4Q9nQF0T8ltVi58O', 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': '{"', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': 'evaluation', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': '":"', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': 'safe', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': '"}', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] Tool calls: [{'name': 'ResponseSafety', 'args': {'evaluation': 'safe'}, 'id': 'call_O8VJIbOG4Q9nQF0T8ltVi58O', 'type': 'tool_call'}] ``` 或者, 如果您无法将自定义事件添加到流中, 您可以在流中循环中汇总消息块 : ``` input_message = {"role": "user", "content": "What is the weather in Boston?"} full_message = None for chunk in agent.stream( {"messages": [input_message]}, stream_mode=["messages", "updates"], version="v2", ): if chunk["type"] == "messages": token, metadata = chunk["data"] if isinstance(token, AIMessageChunk): _render_message_chunk(token) full_message = token if full_message is None else full_message + token if token.chunk_position == "last": if full_message.tool_calls: print(f"Tool calls: {full_message.tool_calls}") full_message = None elif chunk["type"] == "updates": for source, update in chunk["data"].items(): if source == "tools": _render_completed_message(update["messages"][-1]) ``` ### 与 human-in-the-loop 的流线 处理 human-in-the-loop [中断](<https://docs.langchain.com/oss/python/langchain/human-in-the-loop>),我们建立在 [以上实例](<https://docs.langchain.com/oss/python/langchain/streaming#streaming-tool-calls>): 1. 我们配置的代理 [human-in-the-loop 中间软件和一个检查器](<https://docs.langchain.com/oss/python/langchain/human-in-the-loop#configuring-interrupts>) 2. 我们收集中断 期间产生的中断 `"updates"` 流模式 3. 我们对这些中断的反应是: [命令](<https://docs.langchain.com/oss/python/langchain/human-in-the-loop#responding-to-interrupts>) ``` from typing import Any from langchain.agents import create_agent from langchain.agents.middleware import HumanInTheLoopMiddleware from langchain.messages import AIMessage, AIMessageChunk, AnyMessage, ToolMessage from langgraph.checkpoint.memory import InMemorySaver from langgraph.types import Command, Interrupt def get_weather(city: str) -> str: """Get weather for a given city.""" return f"It's always sunny in {city}!" checkpointer = InMemorySaver() agent = create_agent( "openai:gpt-6.1-sol", tools=[get_weather], middleware=[ HumanInTheLoopMiddleware(interrupt_on={"get_weather": True}), ], checkpointer=checkpointer, ) def _render_message_chunk(token: AIMessageChunk) -> None: if token.text: print(token.text, end="|") if token.tool_call_chunks: print(token.tool_call_chunks) def _render_completed_message(message: AnyMessage) -> None: if isinstance(message, AIMessage) and message.tool_calls: print(f"Tool calls: {message.tool_calls}") if isinstance(message, ToolMessage): print(f"Tool response: {message.content_blocks}") def _render_interrupt(interrupt: Interrupt) -> None: interrupts = interrupt.value for request in interrupts["action_requests"]: print(request["description"]) input_message = { "role": "user", "content": ( "Can you look up the weather in Boston and San Francisco?" ), } config = {"configurable": {"thread_id": "some_id"}} interrupts = [] for chunk in agent.stream( {"messages": [input_message]}, config=config, stream_mode=["messages", "updates"], version="v2", ): if chunk["type"] == "messages": token, metadata = chunk["data"] if isinstance(token, AIMessageChunk): _render_message_chunk(token) elif chunk["type"] == "updates": for source, update in chunk["data"].items(): if source in ("model", "tools"): _render_completed_message(update["messages"][-1]) if source == "__interrupt__": interrupts.extend(update) _render_interrupt(update[0]) ``` 产出 ``` [{'name': 'get_weather', 'args': '', 'id': 'call_GOwNaQHeqMixay2qy80padfE', 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': '{"ci', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': 'ty": ', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': '"Bosto', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': 'n"}', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': 'get_weather', 'args': '', 'id': 'call_Ndb4jvWm2uMA0JDQXu37wDH6', 'index': 1, 'type': 'tool_call_chunk'}] [{'name': None, 'args': '{"ci', 'id': None, 'index': 1, 'type': 'tool_call_chunk'}] [{'name': None, 'args': 'ty": ', 'id': None, 'index': 1, 'type': 'tool_call_chunk'}] [{'name': None, 'args': '"San F', 'id': None, 'index': 1, 'type': 'tool_call_chunk'}] [{'name': None, 'args': 'ranc', 'id': None, 'index': 1, 'type': 'tool_call_chunk'}] [{'name': None, 'args': 'isco"', 'id': None, 'index': 1, 'type': 'tool_call_chunk'}] [{'name': None, 'args': '}', 'id': None, 'index': 1, 'type': 'tool_call_chunk'}] Tool calls: [{'name': 'get_weather', 'args': {'city': 'Boston'}, 'id': 'call_GOwNaQHeqMixay2qy80padfE', 'type': 'tool_call'}, {'name': 'get_weather', 'args': {'city': 'San Francisco'}, 'id': 'call_Ndb4jvWm2uMA0JDQXu37wDH6', 'type': 'tool_call'}] Tool execution requires approval Tool: get_weather Args: {'city': 'Boston'} Tool execution requires approval Tool: get_weather Args: {'city': 'San Francisco'} ``` 接下来我们收集 [决定](<https://docs.langchain.com/oss/python/langchain/human-in-the-loop#interrupt-decision-types>) 重要的是,决定的顺序必须与我们收集的行动顺序一致。 ``` def _get_interrupt_decisions(interrupt: Interrupt) -> list[dict]: return [ { "type": "edit", "edited_action": { "name": "get_weather", "args": {"city": "Boston, U.K."}, }, } if "boston" in request["description"].lower() else {"type": "approve"} for request in interrupt.value["action_requests"] ] decisions = {} for interrupt in interrupts: decisions[interrupt.id] = { "decisions": _get_interrupt_decisions(interrupt) } decisions ``` 产出 ``` { 'a96c40474e429d661b5b32a8d86f0f3e': { 'decisions': [ { 'type': 'edit', 'edited_action': { 'name': 'get_weather', 'args': {'city': 'Boston, U.K.'} } }, {'type': 'approve'}, ] } } ``` 然后,我们可以继续通过一个 [命令](<https://docs.langchain.com/oss/python/langchain/human-in-the-loop#responding-to-interrupts>) 进入同一流圈 : ``` interrupts = [] for chunk in agent.stream( Command(resume=decisions), config=config, stream_mode=["messages", "updates"], version="v2", ): # Streaming loop is unchanged if chunk["type"] == "messages": token, metadata = chunk["data"] if isinstance(token, AIMessageChunk): _render_message_chunk(token) elif chunk["type"] == "updates": for source, update in chunk["data"].items(): if source in ("model", "tools"): _render_completed_message(update["messages"][-1]) if source == "__interrupt__": interrupts.extend(update) _render_interrupt(update[0]) ``` 产出 ``` Tool response: [{'type': 'text', 'text': "It's always sunny in Boston, U.K.!"}] Tool response: [{'type': 'text', 'text': "It's always sunny in San Francisco!"}] -| **|Boston|**|:| It|'s| always| sunny| in| Boston|,| U|.K|.| |-| **|San| Francisco|**|:| It|'s| always| sunny| in| San| Francisco|!| ``` ### 从子剂流出 当代理商在任何时刻都存在多个LLMs时,往往需要将生成的消息源分散开来。要做到这一点,需要通过一个 [`name`](<https://reference.langchain.com/python/langchain/agents/create_agent>) 在创建时,此名称可以通过元数据获取。 `lc_agent_name` 流入时按键 `"messages"` 模式。下面,我们更新 [串流工具调用](<https://docs.langchain.com/oss/python/langchain/streaming#streaming-tool-calls>) 示例: 1. 我们用一个工具来取代我们的工具 `call_weather_agent` 内部引用代理工具 2. 我们再加一个 `name` 给每个代理商 3. 我们指出 [`subgraphs=True`](<https://docs.langchain.com/oss/python/langgraph/use-subgraphs#stream-subgraph-outputs>) 创建流时 4. 我们的流处理与之前相同, 但我们添加逻辑来跟踪代理正在使用的是什么 `create_agent`’s `name` 参数 当你设置一个 `name` 在特工身上,该名称也附在任何 `AIMessage`由那个特工生成的 首先,我们构建这个特工: ``` from typing import Any from langchain.agents import create_agent from langchain.chat_models import init_chat_model from langchain.messages import AIMessage, AnyMessage def get_weather(city: str) -> str: """Get weather for a given city.""" return f"It's always sunny in {city}!" weather_model = init_chat_model("openai:gpt-6.1-sol") weather_agent = create_agent( model=weather_model, tools=[get_weather], name="weather_agent", ) def call_weather_agent(query: str) -> str: """Query the weather agent.""" result = weather_agent.invoke({ "messages": [{"role": "user", "content": query}] }) return result["messages"][-1].text supervisor_model = init_chat_model("openai:gpt-6.1-sol") agent = create_agent( model=supervisor_model, tools=[call_weather_agent], name="supervisor", ) ``` 接下来,我们在流线循环中添加逻辑,以报告哪个代理正在释放符号: ``` def _render_message_chunk(token: AIMessageChunk) -> None: if token.text: print(token.text, end="|") if token.tool_call_chunks: print(token.tool_call_chunks) def _render_completed_message(message: AnyMessage) -> None: if isinstance(message, AIMessage) and message.tool_calls: print(f"Tool calls: {message.tool_calls}") if isinstance(message, ToolMessage): print(f"Tool response: {message.content_blocks}") input_message = {"role": "user", "content": "What is the weather in Boston?"} current_agent = None for chunk in agent.stream( {"messages": [input_message]}, stream_mode=["messages", "updates"], subgraphs=True, version="v2", ): if chunk["type"] == "messages": token, metadata = chunk["data"] if agent_name := metadata.get("lc_agent_name"): if agent_name != current_agent: print(f"🤖 {agent_name}: ") current_agent = agent_name if isinstance(token, AIMessageChunk): _render_message_chunk(token) elif chunk["type"] == "updates": for source, update in chunk["data"].items(): if source in ("model", "tools"): _render_completed_message(update["messages"][-1]) ``` 产出 ``` 🤖 supervisor: [{'name': 'call_weather_agent', 'args': '', 'id': 'call_asorzUf0mB6sb7MiKfgojp7I', 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': '{"', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': 'query', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': '":"', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': 'Boston', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': ' weather', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': ' right', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': ' now', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': ' and', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': " today's", 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': ' forecast', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': '"}', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] Tool calls: [{'name': 'call_weather_agent', 'args': {'query': "Boston weather right now and today's forecast"}, 'id': 'call_asorzUf0mB6sb7MiKfgojp7I', 'type': 'tool_call'}] 🤖 weather_agent: [{'name': 'get_weather', 'args': '', 'id': 'call_LZ89lT8fW6w8vqck5pZeaDIx', 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': '{"', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': 'city', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': '":"', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': 'Boston', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] [{'name': None, 'args': '"}', 'id': None, 'index': 0, 'type': 'tool_call_chunk'}] Tool calls: [{'name': 'get_weather', 'args': {'city': 'Boston'}, 'id': 'call_LZ89lT8fW6w8vqck5pZeaDIx', 'type': 'tool_call'}] Tool response: [{'type': 'text', 'text': "It's always sunny in Boston!"}] Boston| weather| right| now|:| **|Sunny|**|. |Today|'s| forecast| for| Boston|:| **|Sunny| all| day|**|.|Tool response: [{'type': 'text', 'text': 'Boston weather right now: **Sunny**.\n\nToday's forecast for Boston: **Sunny all day**.'}] 🤖 supervisor: Boston| weather| right| now|:| **|Sunny|**|. |Today|'s| forecast| for| Boston|:| **|Sunny| all| day|**|.| ``` ## 禁用流线 在一些应用程序中,您可能需要为给定的模型禁用单个符号的流线。 当: - 与 [multi-agent](<https://docs.langchain.com/oss/python/langchain/multi-agent>) 控制哪些代理源源流输出的系统 - 支持流水模式和不支持流水模式的混合 - 部署到 [LangSmith](<https://docs.langchain.com/langsmith/observability>) 并想防止某些模型输出流到客户端 设定 `streaming=False` 当初始化的模型。 ``` from langchain_openai import ChatOpenAI model = ChatOpenAI( model="gpt-6.1-sol", streaming=False ) ``` 部署到 LangSmith 时, 设置 `streaming=False` 显示任何您不希望输出流到客户端的模型。在部署前,此选项会在您的图表代码中配置 。 并非所有聊天模式集成都支持 `streaming` 参数。如果您的模型不支持,请使用 `disable_streaming=True` 相反,这个参数可以通过基础类在所有聊天模式上提供。 见 [LangGraph 流线指南](<https://docs.langchain.com/oss/python/langgraph/streaming#disable-streaming-for-specific-chat-models>) 更多细节。 ## v2 流线格式 需要LangGraph 1.1或更晚. 过 `version="v2"` 改为: `stream()` 或 时 间 `astream()` 以获取一个统一的输出格式。每个块是一个 `StreamPart` 命令为 `type`, `ns`,以及 `data` 键 — 无论流模式或模式数量如何, 形状相同 : ``` # Unified format — no more tuple unpacking for chunk in agent.stream( {"messages": [{"role": "user", "content": "What is the weather in SF?"}]}, stream_mode=["updates", "custom"], version="v2", ): print(chunk["type"]) # "updates" or "custom" print(chunk["data"]) # payload ``` ``` # Must unpack (mode, data) tuples for mode, chunk in agent.stream( {"messages": [{"role": "user", "content": "What is the weather in SF?"}]}, stream_mode=["updates", "custom"], ): print(mode) # "updates" or "custom" print(chunk) # payload ``` v2格式也有所改进 `invoke()` - 它返回一个 `GraphOutput` 对象为 `.value` 财务报告和财务报告 `.interrupts` 属性,干净地区分状态和中断元数据: ``` result = agent.invoke( {"messages": [{"role": "user", "content": "Hello"}]}, version="v2", ) print(result.value) # state (dict, Pydantic model, or dataclass) print(result.interrupts) # tuple of Interrupt objects (empty if none) ``` 见 [LangGraph 流媒体文件](<https://docs.langchain.com/oss/python/langgraph/streaming#stream-output-format-v2>) 关于v2格式的更多细节,包括类型缩小、Pydantic/数据类强制和子图流。 ## 相关 - [前端流线](<https://docs.langchain.com/oss/python/langchain/frontend/overview>)– 构建反作用 UIs 与 [`useStream`](<https://reference.langchain.com/javascript/langchain-react/index/useStream>) 用于实时代理交互 - [与聊天模式的流化](<https://docs.langchain.com/oss/python/langchain/models#stream>)——不使用代理或图表直接从聊天模式中获取的 stream sords - [聊天模式的原因](<https://docs.langchain.com/oss/python/langchain/models#reasoning>)- 配置和访问聊天模式的推理输出 - [标准内容块](<https://docs.langchain.com/oss/python/langchain/messages#standard-content-blocks>)——理解用于推理,文本和其他内容类型的规范内容块格式. - [与 human-in-the-loop 的流线](<https://docs.langchain.com/oss/python/langchain/human-in-the-loop#streaming-with-human-in-the-loop>)- 硬质物剂在进行人为审查时处理中断时取得进展 - [LangGraph 流线](<https://docs.langchain.com/oss/python/langgraph/streaming>)- 先进的流式选项,包括 `values`, `debug` 模式和子图流 --- [连接这些文件](<https://docs.langchain.com/use-these-docs>) 通过 MCP 向您选择的代理提供实时答案。 [在 GitHub 上编辑此页面](<https://github.com/langchain-ai/docs/edit/main/src/oss/langchain/streaming.mdx>) 或 时 间 [提交一个问题](<https://github.com/langchain-ai/docs/issues/new/choose>). 这页有用吗?
查看原始来源