Agent 流式输出
🎯 引言
多工具 Agent 执行任务时可能需要多次请求模型和业务接口。使用 invoke() 只能等待整个任务结束后获得结果,用户无法知道当前正在查询什么。本篇将学习 Agent 的流式输出,在任务运行过程中获得工具调用、工具结果、模型文本与业务进度,为后续开发具有实时反馈的 AI 应用打下基础。
🧱 Agent 流式输出与模型流的区别
之前学习的模型流式输出主要用于逐步显示文本。但 Agent 在生成回答之前还可能进行多次工具调用,工具执行期间不一定产生模型文本。
如果界面只显示文本,用户可能长时间看到空白。我们需要根据不同类型的事件更新界面:工具开始执行时显示查询状态,工具返回时展示数据,模型生成文本时逐步显示回答。
LangChain 的 stream() 提供以下三种常用模式:
| 模式 | 输出内容 | 用途 |
|---|---|---|
updates | Agent 完成一个执行步骤后的状态更新 | 观察工具调用与结果 |
messages | 模型产生的消息片段及相关元数据 | 逐步显示模型文本 |
custom | 应用或工具主动发送的数据 | 显示业务处理进度 |
这些是 LangChain 的流式输出模式,不是 HTTP SSE 传输协议。本篇先在 Node.js 终端观察事件,后续开发 AI 工作台时再将事件转发到前端。
🧱 获取执行步骤
继续使用《第一个 LangChain Agent》中创建的 agent.mjs,新建 03.streaming.mjs:
import { agent } from './agent.mjs';
const input = {
messages: [{ role: 'user', content: '机械键盘库存够不够购买 15 件?' }],
};
// 获取 Agent 每个执行步骤的状态更新
const stream = await agent.stream(input, {
streamMode: 'updates',
recursionLimit: 20,
});
for await (const update of stream) {
console.log(JSON.stringify(update, null, 4));
}
stream() 不会等待整个任务结束才返回结果。通过异步迭代可以在每次执行步骤完成后取得相应的更新。
运行:
node --env-file=.env 03.streaming.mjs
下面是两次可能的状态更新,仅保留关键字段。实际消息对象的序列化结构和节点名称以 SDK 输出为准。
{
"model": {
"messages": [
{
"tool_calls": [{ "name": "find_product", "args": { "name": "机械键盘" } }]
}
]
}
}
这是模型完成决策后发出的更新,说明它提出了商品搜索请求。此时不能认为工具已经执行成功。
{
"tools": {
"messages": [{ "content": "{\"id\":\"P100\",\"name\":\"机械键盘\"}" }]
}
}
这是工具执行完成后的更新。随后可能再次出现模型更新和库存工具更新,最后出现模型的回答消息。
只打印需要的执行信息
完整状态对象可能很长。将 for await 循环替换为以下代码,按消息内容判断发生了什么:
for await (const update of stream) {
// 获取各执行节点本次新增的消息
for (const state of Object.values(update)) {
const messages = state?.messages ?? [];
for (const message of messages) {
console.log('消息类型:', message.type);
console.log('消息内容:', message.content);
if (message.tool_calls?.length) {
console.log('工具调用:', message.tool_calls);
}
}
}
}
updates 以执行节点名称为键返回状态更新。这里通过 Object.values() 获取各节点的更新,不需要提前知道节点名称。
再次运行,可能看到以下输出(工具调用 ID 为示例):
消息类型: ai
消息内容:
工具调用: [
{
name: 'find_product',
args: { name: '机械键盘' },
id: 'call_1',
type: 'tool_call'
}
]
消息类型: tool
消息内容: {"id":"P100","name":"机械键盘"}
消息类型: ai
消息内容:
工具调用: [
{
name: 'get_stock',
args: { id: 'P100' },
id: 'call_2',
type: 'tool_call'
}
]
消息类型: tool
消息内容: {"id":"P100","stock":12}
消息类型: ai
消息内容: 目前有 12 件库存,还差 3 件。
与 invoke() 不同,这些日志会随着各执行步骤完成陆续打印,而不是等整个任务结束后一次性输出。
🧱 流式获取模型文本
在 03.streaming.mjs 中,保留导入和 input,将创建流及消费流的代码替换为:
const stream = await agent.stream(input, {
streamMode: 'messages',
recursionLimit: 20,
});
// 每次收到模型消息片段,这里只取元组中的第一项
for await (const [chunk] of stream) {
// 只输出文本,忽略工具调用等其他内容块
for (const block of chunk.contentBlocks ?? []) {
if (block.type === 'text') {
process.stdout.write(block.text);
}
}
}
process.stdout.write('\n');
messages 模式每次返回 [chunk, metadata],分别是消息片段和元数据。元数据可用于判断消息来自哪个执行节点,本例暂不使用。
再次运行,可能看到以下文字逐步输出:
目前有 12 件库存,还差 3 件。
由于 Agent 可能多次调用模型,这些文本不一定都属于最终回答,实际应用应区分不同的模型消息。
🧱 发送自定义进度
假设库存查询需要访问外部接口,应用希望在请求开始时就展示“正在查询库存”,而不是等工具执行结束才更新界面。我们可以在工具内部使用 writer 主动发送进度事件。
在 agent.mjs 中,将原来的 stockTool 定义替换为:
export const stockTool = tool(
({ id }, config) => {
// 工具开始执行时发送进度
const writer = config?.writer;
writer?.({ status: 'loading', id, message: '正在查询库存' });
const result = getStock(id);
// 根据查询结果发送结束状态
if (result.error) {
writer?.({ status: 'error', id, message: result.error });
} else {
writer?.({ status: 'done', id, message: '库存查询结束' });
}
return JSON.stringify(result);
},
{
name: 'get_stock',
description: '根据已知商品编号查询库存,不接受商品名称',
schema: z.object({
id: z.string().describe('商品编号,例如 P100'),
}),
}
);
config.writer 由运行环境提供,用于向流中发送自定义数据。这里使用可选调用,避免未提供 writer 时发生错误。进度事件是给应用看的,工具仍需通过 return 将业务结果返回给模型。
接收自定义进度
在 03.streaming.mjs 中,保留导入和 input,替换创建流及后面的代码:
const stream = await agent.stream(input, {
streamMode: 'custom',
recursionLimit: 20,
});
for await (const data of stream) {
console.log('业务进度:', data);
}
运行:
node --env-file=.env 03.streaming.mjs
如果模型调用库存工具,可能看到:
业务进度: { status: 'loading', id: 'P100', message: '正在查询库存' }
业务进度: { status: 'done', id: 'P100', message: '库存查询结束' }
本例使用内存数据,两个事件可能紧接着出现。实际查询数据库或接口时,这段等待时间更能体现进度反馈的价值。custom 模式只输出主动发送的数据,不输出模型文本。
🧱 同时获取多种事件
在 03.streaming.mjs 中,保留导入和 input,替换创建流及后面的代码:
const stream = await agent.stream(input, {
streamMode: ['updates', 'messages', 'custom'],
recursionLimit: 20,
});
for await (const [mode, data] of stream) {
// 显示业务进度
if (mode === 'custom') {
console.log('\n业务进度:', data);
continue;
}
// 显示执行步骤
if (mode === 'updates') {
console.log('\n执行步骤:', Object.keys(data));
continue;
}
// 逐步输出模型文本
if (mode === 'messages') {
const [chunk] = data;
for (const block of chunk.contentBlocks ?? []) {
if (block.type === 'text') {
process.stdout.write(block.text);
}
}
}
}
process.stdout.write('\n');
多个模式同时启用时,每次迭代返回 [mode, data]。根据 mode 选择对应的处理方式,就可以同时接收三种数据。
再次运行 node --env-file=.env 03.streaming.mjs,可能看到以下输出(省略空行,将连续文本片段合并展示):
执行步骤: ['model']
执行步骤: ['tools']
执行步骤: ['model']
业务进度: { status: 'loading', id: 'P100', message: '正在查询库存' }
业务进度: { status: 'done', id: 'P100', message: '库存查询结束' }
执行步骤: ['tools']
目前有 12 件库存,还差 3 件。
执行步骤: ['model']
done 只表示库存查询结束,不代表整个任务完成。不要根据固定的节点数量或事件顺序判断任务是否结束;应等待流正常结束,并结合业务结果判断;若流抛出异常,应显示失败状态。❓ 知识问答
Q1:使用 stream() 会减少模型实际执行的次数吗?
不一定。流式输出改变的是应用接收数据的时机与方式,并没有改变 Agent 的决策逻辑。工具调用次数和模型请求次数仍然取决于任务及执行控制配置。
🧪 小练习
在 findProductTool 的执行函数中加入搜索开始与结束的进度事件,使用多模式流查询机械键盘库存。检查商品搜索与库存查询的进度是否出现,最终回答是否为库存 12 件、还差 3 件。保留原有工具返回值。
🎉 恭喜你!你已经能够实时观察 Agent 的执行过程。
