概述
LangChain 的流式传输系统让您可以从智能体运行中向应用程序提供实时反馈。 LangChain 流式传输的功能:- 流式传输智能体进度 — 在每个智能体步骤后获取状态更新。
- 流式传输 LLM 令牌 — 在生成时流式传输语言模型令牌。
- 流式传输自定义更新 — 发出用户定义的信号(例如,
"已获取 10/100 条记录")。 - 流式传输多种模式 — 从
updates(智能体进度)、messages(LLM 令牌 + 元数据)或custom(任意用户数据)中选择。
智能体进度
要流式传输智能体进度,请使用带有stream_mode="updates" 的 stream 或 astream 方法。这会在每个智能体步骤后发出一个事件。
例如,如果您有一个调用工具一次的智能体,您应该看到以下更新:
- LLM 节点:带有工具调用请求的
AIMessage - 工具节点:带有执行结果的
ToolMessage - LLM 节点:最终 AI 响应
Streaming agent progress
Output
LLM tokens
要在 LLM 生成 token 时流式传输它们,请使用stream_mode="messages"。下面您可以看到智能体流式传输工具调用和最终响应的输出。
Streaming LLM tokens
Output
Custom updates
To stream updates from tools as they are executed, you can useget_stream_writer.
Streaming custom updates
Output
If you add
get_stream_writer inside your tool, you won’t be able to invoke the tool outside of a LangGraph execution context.Stream multiple modes
You can specify multiple streaming modes by passing stream mode as a list:stream_mode=["updates", "custom"]:
Streaming multiple modes
Output