跳转到内容

执行结果

当您运行智能体时,您会收到以下两者之一:

两种结果类型都暴露相同的核心结果字段,例如 finalOutputnewItemsinterruptionsstateStreamedRunResult 额外提供流式控制能力,如 completedtoStream()toTextStream()currentAgent

大多数应用只需要少数字段:

如果您需要……使用
向用户展示最终答案finalOutput
可重放的下一轮输入(包含完整本地转录)history
仅包含本次运行中新生成的模型形态条目output
带有智能体/工具/交接元数据的丰富运行条目newItems
通常应处理下一轮用户输入的智能体lastAgentactiveAgent
OpenAI Responses API 的链式调用(使用 previousResponseIdlastResponseId
待审批项和可恢复快照interruptionsstate
应用上下文、审批、用量及嵌套智能体工具输入runContext
当前嵌套 Agent.asTool() 调用的元数据(例如在 customOutputExtractor 内)agentToolInvocation
原始模型调用或护栏诊断rawResponses 和护栏结果数组

finalOutput 属性包含最后一个运行智能体的最终输出。该结果可能是:

  • string —— 对于未定义 outputType 的任意智能体,默认如此
  • unknown —— 如果智能体将 JSON schema 定义为输出类型。在这种情况下 JSON 已解析,但您仍需手动验证其类型。
  • z.infer<outputType> —— 如果智能体将 Zod schema 定义为输出类型。输出会按该 schema 自动解析。
  • undefined —— 如果智能体未产生输出(例如在产生输出前就停止)

在流式运行尚未完成时,或运行在到达最终输出前因审批中断而暂停时,finalOutput 也会是 undefined

如果您在不同输出类型之间使用交接,应该使用 Agent.create() 方法而不是 new Agent() 构造函数来创建智能体。

这样 SDK 就能推断所有可能交接路径上的输出类型,并为 finalOutput 属性提供联合类型。

例如:

Handoff final output types
import { Agent, run } from '@openai/agents';
import { z } from 'zod';
const refundAgent = new Agent({
name: 'Refund Agent',
instructions:
'You are a refund agent. You are responsible for refunding customers.',
outputType: z.object({
refundApproved: z.boolean(),
}),
});
const orderAgent = new Agent({
name: 'Order Agent',
instructions:
'You are an order agent. You are responsible for processing orders.',
outputType: z.object({
orderId: z.string(),
}),
});
const triageAgent = Agent.create({
name: 'Triage Agent',
instructions:
'You are a triage agent. You are responsible for triaging customer issues.',
handoffs: [refundAgent, orderAgent],
});
const result = await run(triageAgent, 'I need to a refund for my order');
const output = result.finalOutput;
// ^? { refundApproved: boolean } | { orderId: string } | string | undefined

这些属性回答的是不同问题:

属性包含内容最适用场景
input本次运行的基础输入。若交接输入过滤器重写了历史,这里反映的是运行继续时使用的过滤后输入。审计本次运行实际使用了什么输入
output仅包含本次运行中生成的模型形态条目,不含智能体元数据。只存储或重放新的模型增量
newItems带智能体/工具/交接元数据的丰富 RunItem 包装对象。日志、UI、审计和调试
historyinput + newItems 构建的、可重放的下一轮输入。手动聊天循环和客户端管理会话状态

在实践中:

  • 当您在应用中手动维护完整会话时,使用 history
  • 当您已在其他地方存储历史,只想拿到本次运行的新生成条目时,使用 output
  • 当您需要智能体关联、工具输出、交接边界或审批条目时,使用 newItems
  • 如果您使用 conversationIdpreviousResponseId,通常不需要把 history 回传给 run()。而是只传新的用户输入并复用服务器管理的 ID。完整对比请参见运行智能体

在类似聊天的场景中,history 是维护完整历史的便捷方式:

History loop
import { Agent, user, run } from '@openai/agents';
import type { AgentInputItem } from '@openai/agents';
const agent = new Agent({
name: 'Assistant',
instructions:
'You are a helpful assistant knowledgeable about recent AGI research.',
});
let history: AgentInputItem[] = [
// initial message
user('Are we there yet?'),
];
for (let i = 0; i < 10; i++) {
// run 10 times
const result = await run(agent, history);
// update the history to the new output
history = result.history;
history.push(user('How about now?'));
}

newItems 为您提供运行期间发生情况的最丰富视图。常见条目类型有:

当您需要知道某条目由哪个智能体生成,或它是否标记了工具、工具搜索、交接或审批边界时,应优先使用 newItems 而不是 output。当您使用 toolSearchTool() 时,这些工具搜索条目也是检查在正常工具调用发生前加载了哪些延迟工具或命名空间的最简方式。

lastAgent 属性包含最后运行的智能体。在交接之后,这通常是下一轮用户输入最适合复用的智能体。activeAgent 是同一值的别名。

在流式模式下,当运行仍在进行时,currentAgent 会告诉您当前处于活动状态的智能体。

如果某个工具需要审批,运行会暂停,interruptions 会包含待处理的 RunToolApprovalItem。这可能包括直接工具触发的审批、交接后触达工具触发的审批,或嵌套 agent.asTool() 运行触发的审批。

通过 result.state.approve(...) / result.state.reject(...) 处理审批,然后把同一个 state 传回 run() 以恢复运行。您无需一次性处理所有中断。如果只处理了部分条目就重新运行,已解决的调用可以继续,而未解决的会保持待处理并再次让运行暂停。

state 属性是结果背后的可序列化快照。可用于人机协作、重试流程,或任何需要稍后恢复暂停运行的场景。

当您使用 OpenAI Responses API 链式调用时,lastResponseId 是下一轮作为 previousResponseId 传入的值。

如果您已通过 historysessionconversationId 延续会话,通常不需要 lastResponseId。若您需要多步运行中的每个原始模型响应,请改为查看 rawResponses

agentToolInvocation 用于嵌套 Agent.asTool() 结果,特别是在 customOutputExtractor 内需要当前工具调用元数据时。它不是通用的“整次运行已完成”汇总字段。

在该嵌套上下文中,agentToolInvocation 暴露:

  • toolName
  • toolCallId
  • toolArguments

如果您还需要传入该嵌套智能体工具运行的结构化输入,可配合 result.runContext.toolInput 一起使用。

在普通顶层 run() 结果中,这通常是 undefined。这些元数据仅存在于运行时,不会序列化到 RunState。相关模式请参见Agents as tools

StreamedRunResult 继承了上述相同的结果字段,但增加了流式专用控制能力:

  • toTextStream():仅输出助手文本。
  • toStream()for await ... of stream:获取完整事件流。
  • completed:等待直到运行及所有后处理回调完成。
  • errorcancelled:检查流式终态。
  • currentAgent:在运行中途跟踪活动智能体。

如果您需要流式运行的稳定最终状态,请在读取 finalOutputhistoryinterruptions 或其他汇总属性前等待 completed。如需逐事件处理,请参见流式传输指南

runContext 属性是在结果上可支持的公开运行上下文视图。result.runContext.context 是您的应用上下文,同一对象还携带 SDK 管理的运行时元数据,如审批、用量和嵌套 toolInput。完整结构请参见上下文管理

rawResponses 包含运行期间收集到的原始模型响应。多步运行可能产生多个响应,例如跨交接或重复工具/模型循环时。

inputGuardrailResultsoutputGuardrailResults 属性包含智能体级别的护栏结果。工具级护栏结果通过 toolInputGuardrailResultstoolOutputGuardrailResults 单独暴露。

当您需要记录护栏决策、检查护栏函数返回的额外元数据,或调试运行为何被阻止时,请使用这些数组。

Token 用量聚合在 result.state.usage 中,它跟踪该次运行的请求次数和 token 总量。同一个用量对象也可通过 result.runContext.usage 获取。对于流式运行,这些数据会随着响应到达而更新。

Read usage from RunState
import { Agent, run } from '@openai/agents';
const agent = new Agent({
name: 'Usage Tracker',
instructions: 'Summarize the latest project update in one sentence.',
});
const result = await run(
agent,
'Summarize this: key customer feedback themes and the next product iteration.',
);
const usage = result.state.usage;
console.log({
requests: usage.requests,
inputTokens: usage.inputTokens,
outputTokens: usage.outputTokens,
totalTokens: usage.totalTokens,
});
if (usage.requestUsageEntries) {
for (const entry of usage.requestUsageEntries) {
console.log('request', {
endpoint: entry.endpoint,
inputTokens: entry.inputTokens,
outputTokens: entry.outputTokens,
totalTokens: entry.totalTokens,
});
}
}