跳转到内容

流式传输

Agents SDK 可以按增量方式交付来自模型及其他执行步骤的输出。流式传输可让您的 UI 保持响应,并避免在更新用户前等待完整最终结果。

Runner.run() 传入 { stream: true } 选项,即可获得流式对象而非完整结果:

Enabling streaming
import { Agent, run } from '@openai/agents';
const agent = new Agent({
name: 'Storyteller',
instructions:
'You are a storyteller. You will be given a topic and you will tell a story about it.',
});
const result = await run(agent, 'Tell me a story about a cat.', {
stream: true,
});

启用流式传输后,返回的 stream 实现了 AsyncIterable 接口。每个产出的事件都是一个对象,用于描述本次运行中发生的内容。该流会产出三类事件,分别对应智能体执行的不同部分。不过大多数应用只关心模型文本,因此该流也提供了辅助方法。

调用 stream.toTextStream() 可获得已发出文本的流。当 compatibleWithNodeStreamstrue 时,返回值是标准的 Node.js Readable。我们可以将其直接管道到 process.stdout 或其他目标。

Logging out the text as it arrives
import { Agent, run } from '@openai/agents';
const agent = new Agent({
name: 'Storyteller',
instructions:
'You are a storyteller. You will be given a topic and you will tell a story about it.',
});
const result = await run(agent, 'Tell me a story about a cat.', {
stream: true,
});
result
.toTextStream({
compatibleWithNodeStreams: true,
})
.pipe(process.stdout);

当运行及所有待处理回调都完成后,stream.completed 这个 Promise 会 resolve。如果您想确保不再有输出,请始终等待它。这里也包括在最后一个文本 token 到达后才完成的后处理工作,例如会话持久化或历史压缩钩子。

toTextStream() 只会发出助手文本。函数调用、交接、审批及其他运行时事件可从完整事件流中获取。

您可以使用 for await 循环在每个事件到达时进行检查。有用的信息包括底层模型事件、任何智能体切换以及 SDK 特有的运行信息:

Listening to all events
import { Agent, run } from '@openai/agents';
const agent = new Agent({
name: 'Storyteller',
instructions:
'You are a storyteller. You will be given a topic and you will tell a story about it.',
});
const result = await run(agent, 'Tell me a story about a cat.', {
stream: true,
});
for await (const event of result) {
// these are the raw events from the model
if (event.type === 'raw_model_stream_event') {
console.log(`${event.type} %o`, event.data);
}
// agent updated events
if (event.type === 'agent_updated_stream_event') {
console.log(`${event.type} %s`, event.agent.name);
}
// Agent SDK specific events
if (event.type === 'run_item_stream_event') {
console.log(`${event.type} %o`, event.item);
}
}

请参阅流式示例,其中包含一个完整脚本,会同时打印纯文本流和原始事件流。

本页的流式传输 API 也支持 OpenAI Responses WebSocket 传输。

可通过 setOpenAIResponsesTransport('websocket') 全局启用,或使用您自己的 OpenAIProvider 并设置 useResponsesWebSocket: true

如果只是通过 WebSocket 进行流式传输,不需要 withResponsesWebSocketSession(...) 或自定义 OpenAIProvider。如果可接受运行之间重连,那么启用该传输后,run() / Runner.run(..., { stream: true }) 仍可正常工作。

当您希望复用连接并更明确地控制 provider 生命周期时,请使用 withResponsesWebSocketSession(...) 或自定义 OpenAIProvider / Runner

使用 previousResponseId 的续接语义与 HTTP 传输相同。区别仅在于传输方式和连接生命周期。

如果您自行构建 provider,请记得在关闭时调用 await provider.close()。默认情况下,基于 Websocket 的模型包装器会缓存复用,关闭 provider 会释放这些连接。withResponsesWebSocketSession(...) 也提供同样的复用能力,但会自动将清理范围限定在单个回调内。

完整示例(包含流式传输、函数调用、审批和 previousResponseId)请参阅 examples/basic/stream-ws.ts

该流会产出三种不同事件类型:

RunRawModelStreamEvent
import {
isOpenAIChatCompletionsRawModelStreamEvent,
isOpenAIResponsesRawModelStreamEvent,
type RunStreamEvent,
} from '@openai/agents';
export function logOpenAIRawModelEvent(event: RunStreamEvent) {
if (isOpenAIResponsesRawModelStreamEvent(event)) {
console.log(event.source);
console.log(event.data.event.type);
return;
}
if (isOpenAIChatCompletionsRawModelStreamEvent(event)) {
console.log(event.source);
console.log(event.data.event.object);
}
}

示例:

{
"type": "raw_model_stream_event",
"data": {
"type": "output_text_delta",
"delta": "Hello"
}
}

如果您使用 OpenAI provider,@openai/agents-openai@openai/agents 都会导出辅助方法,可在不改变 agents-core 中通用 RunRawModelStreamEvent 契约的前提下缩小 OpenAI 原始载荷类型。

Narrow OpenAI raw model events
import type { RunStreamEvent } from '@openai/agents';
import { isOpenAIResponsesRawModelStreamEvent } from '@openai/agents';
export function isOpenAIResponsesTextDelta(event: RunStreamEvent): boolean {
return (
isOpenAIResponsesRawModelStreamEvent(event) &&
event.data.event.type === 'response.output_text.delta'
);
}

当您只需要与传输无关的流式传输代码时,检查 event.type === 'raw_model_stream_event' 仍然足够。

如果您使用 OpenAI 模型,并希望在不手动类型断言的情况下检查 provider 特定载荷,SDK 还导出了类型收窄辅助方法:

  • isOpenAIResponsesRawModelStreamEvent(event):用于 Responses 原始事件。
  • isOpenAIChatCompletionsRawModelStreamEvent(event):用于 Chat Completions 分块事件。

对于这些 OpenAI 模型事件,RunRawModelStreamEvent.source 也会被填充为 'openai-responses''openai-chat-completions'

当您希望检查仅 Responses 才有的事件(如 response.reasoning_summary_text.deltaresponse.output_item.done 或 MCP 参数增量),同时让 TypeScript 感知底层事件形状时,这尤其有用。

更完整的 OpenAI 特定流式传输模式,请参阅 examples/basic/stream-ws.tsexamples/tools/code-interpreter.tsexamples/connectors/index.ts

RunItemStreamEvent
import type { RunItemStreamEvent, RunStreamEvent } from '@openai/agents';
export function isRunItemStreamEvent(
event: RunStreamEvent,
): event is RunItemStreamEvent {
return event.type === 'run_item_stream_event';
}

name 用于标识产出的条目类型:

name含义
message_output_created已创建消息输出条目。
handoff_requested模型请求了交接。
handoff_occurred运行时已完成向另一智能体的交接。
tool_search_called已发出 tool_search_call 条目。
tool_search_output_created已发出包含已加载工具定义的 tool_search_output 条目。
tool_called已发出工具调用条目。
tool_output已发出工具结果条目。
reasoning_item_created已发出推理条目。
tool_approval_requested工具调用已暂停,等待人工审批。

tool_search_* 事件仅出现在使用 toolSearchTool()、并在运行期间加载延迟工具的 Responses 运行中。

交接载荷示例:

{
"type": "run_item_stream_event",
"name": "handoff_occurred",
"item": {
"type": "handoff_call",
"id": "h1",
"status": "completed",
"name": "transfer_to_refund_agent"
}
}
RunAgentUpdatedStreamEvent
import type {
RunAgentUpdatedStreamEvent,
RunStreamEvent,
} from '@openai/agents';
export function isRunAgentUpdatedStreamEvent(
event: RunStreamEvent,
): event is RunAgentUpdatedStreamEvent {
return event.type === 'agent_updated_stream_event';
}

示例:

{
"type": "agent_updated_stream_event",
"agent": {
"name": "Refund Agent"
}
}

流式传输与会暂停执行的交接兼容(例如工具需要审批时)。流对象上的 interruptions 字段会暴露待审批项,您可对每一项调用 state.approve()state.reject() 以继续执行。流暂停后,stream.completed 会 resolve,且 stream.interruptions 包含待处理审批。再次以 { stream: true } 执行即可恢复流式输出。

Handling human approval while streaming
import { Agent, run } from '@openai/agents';
const agent = new Agent({
name: 'Storyteller',
instructions:
'You are a storyteller. You will be given a topic and you will tell a story about it.',
});
let stream = await run(
agent,
'What is the weather in San Francisco and Oakland?',
{ stream: true },
);
stream.toTextStream({ compatibleWithNodeStreams: true }).pipe(process.stdout);
await stream.completed;
while (stream.interruptions?.length) {
console.log(
'Human-in-the-loop: approval required for the following tool calls:',
);
const state = stream.state;
for (const interruption of stream.interruptions) {
const approved = confirm(
`Agent ${interruption.agent.name} would like to use the tool ${interruption.name} with "${interruption.arguments}". Do you approve?`,
);
if (approved) {
state.approve(interruption);
} else {
state.reject(interruption);
}
}
// Resume execution with streaming output
stream = await run(agent, state, { stream: true });
const textStream = stream.toTextStream({ compatibleWithNodeStreams: true });
textStream.pipe(process.stdout);
await stream.completed;
}

一个会与用户交互的更完整示例见 human-in-the-loop-stream.ts

  • 退出前请记得等待 stream.completed,以确保所有输出都已刷出。
  • 初始 { stream: true } 选项仅对提供它的那次调用生效。如果您使用 RunState 重新运行,必须再次指定该选项。
  • 如果您的应用只关心文本结果,优先使用 toTextStream(),可避免处理单个事件对象。

借助流式传输和事件系统,您可以将智能体集成到聊天界面、终端应用或任何能从增量更新中受益的场景中。