跳转到内容

人机协作

本指南介绍 SDK 基于审批的人工干预流程。当工具调用需要审批时,SDK 会暂停运行,返回 interruptions,并允许您稍后从同一个 RunState 恢复运行。

该审批机制覆盖整个运行过程,而不局限于当前的顶层智能体。无论工具属于当前智能体、通过交接到达的智能体,还是嵌套的 agent.asTool() 执行过程,都适用同样的模式。在嵌套的 agent.asTool() 场景中,中断仍会出现在外层运行中,因此您需要在外层的 result.state 上批准或拒绝该请求,然后恢复原始的根运行。

使用 agent.asTool() 时,审批可能发生在两个不同的层级:智能体工具本身可以通过 asTool({ needsApproval }) 要求审批;嵌套运行开始后,嵌套智能体内部的工具也可能发起各自的审批请求。这两种情况都通过同一套外层运行中断流程处理。

本页重点介绍通过 interruptions 进行手动审批的流程。如果您的应用可以通过代码做出决定,某些工具类型还支持程序化审批回调,让运行无需暂停即可继续。如果您正在配置 agent.asTool() 本身,请参阅工具指南;本页介绍的是该运行层级中任意工具需要审批时的处理方式。

对于 computerTool(),请使用 onSafetyCheck 接受或拒绝 Responses API 返回的安全检查。此回调仅在计算机调用包含待处理检查,且检查的 id 和 code 值均非空时运行,不使用本页介绍的暂停与恢复审批流程。详情和示例请参阅计算机安全检查。

您可以将 needsApproval 选项设置为 true 或返回布尔值的异步函数,以定义需要审批的工具。

工具审批定义
import { tool } from '@openai/agents';
import z from 'zod';
const sensitiveTool = tool({
name: 'cancelOrder',
description: 'Cancel order',
parameters: z.object({
orderId: z.number(),
}),
// always requires approval
needsApproval: true,
execute: async ({ orderId }, args) => {
// prepare order return
},
});
const sendEmail = tool({
name: 'sendEmail',
description: 'Send an email',
parameters: z.object({
to: z.string(),
subject: z.string(),
body: z.string(),
}),
needsApproval: async (_context, { subject }) => {
// check if the email is spam
return subject.includes('spam');
},
execute: async ({ to, subject, body }, args) => {
// send email
},
});
  1. 工具调用即将执行时,SDK 会评估其审批规则(needsApproval 或托管 MCP 工具中的对应规则)。
  2. 如果需要审批且尚未存储决策,工具调用不会执行。运行会改为记录一个 RunToolApprovalItem。
  3. 本轮结束时,运行会暂停,并在执行结果的 interruptions 数组中返回所有待处理的审批请求,其中也包括嵌套 agent.asTool() 运行中发起的审批请求。
  4. 使用 result.state.approve(interruption) 或 result.state.reject(interruption) 处理每个待审批项。如果希望在本次运行的剩余过程中始终批准或拒绝同一工具,请传入 { alwaysApprove: true } 或 { alwaysReject: true }。拒绝时,您还可以传入 { message: '...' },以控制针对该次工具调用返回给模型的拒绝文本。
  5. 将更新后的 result.state 传回 runner.run(agent, state) 即可恢复运行,其中 agent 是本次运行原始的顶层智能体。SDK 会从中断点继续执行,包括嵌套的智能体工具执行过程。

默认情况下,函数工具的输入护栏仅在批准后、工具执行前运行。如果您希望在显示待审批请求之前,使用同样的输入护栏验证本地函数工具调用,请向 run() 或 Runner 传入 toolExecution: { preApprovalInputGuardrails: true }。当审批前护栏拒绝调用时,SDK 会将护栏消息作为工具输出返回给模型,而不是创建审批中断。当护栏允许调用时,运行仍会暂停以等待审批;批准后,输入护栏会再次运行,以防工具调用在等待期间变得不安全。

当 needsApproval 是函数时,SDK 仅在工具参数已解析为可检查的对象后才会调用它。对于格式错误的 JSON 和非对象值,SDK 会采取默认拒绝执行的安全策略:请求审批,但不调用回调,也不执行工具。即使批准了该调用,工具仍不会执行,而是继续进入常规的参数解析错误处理流程。Realtime 函数工具遵循相同规则,并会针对无效调用发出 tool_approval_requested。

通过 { alwaysApprove: true } 或 { alwaysReject: true } 创建的持续生效决策会存储在运行状态中,因此稍后恢复同一个已暂停的运行时,这些决策会在 toString() / fromString() 序列化与反序列化后保留下来。

在正式发布(GA)的模型上,计算机工具中断可以表示一个 computer_call 中的一批操作。SDK 会在执行前逐个操作评估 needsApproval,因此一个待审批请求可能涵盖移动加点击等操作序列。如果您通过检查 interruption.rawItem 来呈现 UI,请同时处理 GA 版本的 actions 数组和旧版的单个 action 字段。

序列化的 RunState 还会同时保留当前工具名称 computer 和旧版名称 computer_use_preview 对应的计算机操作审批状态,因此在从预览版迁移到 GA 版本期间,已暂停的运行也能顺利恢复。

如果您未提供 message,SDK 会先回退到已配置的 toolErrorFormatter(如果有),然后再回退到默认拒绝文本。

您不必在同一轮处理完所有待审批请求。如果仅批准或拒绝了部分请求后就重新运行,已处理的调用可以继续执行,而未处理的请求仍会保留在 interruptions 中,并再次暂停运行。

通过 alwaysApprove: true 或 alwaysReject: true 创建的持续生效决策,会作为后续调用同一工具时的默认决策。针对某个调用 ID 的特定决策优先于该持续生效的默认决策:您可以在持续批准的情况下拒绝某次调用,也可以在持续拒绝的情况下批准某次调用,而不改变其他调用的默认决策。如果您随后替换了该特定决策,新的特定决策将应用于该调用,而持续生效的默认决策仍可用于其余调用。

如果运行暂停期间收到了新的用户输入,并且应在恢复后的下一次模型调用之前将其纳入,请使用 RunState.addInput()。请先添加输入,再处理审批请求,并将同一个状态传回 Runner.run()。暂存的输入是序列化状态的一部分,因此即使未处理的审批请求或本地工具任务延迟了该模型调用,输入也会在 toString() / fromString() 序列化与反序列化后保留下来。

您可以读取 state.pendingInput 来查看暂存条目的克隆快照,也可以在恢复前调用 state.clearPendingInput() 来移除所有暂存条目。addInput() 接受字符串或输入条目数组。当状态无法安全地进入下一次模型调用时,例如处于终止状态、没有剩余轮次,或某个中断的工具结果可能结束运行时,它会抛出 UserError。

每次暂存的输入一经纳入,就会在该运行的 newItems 中成为一个 RunInputItem,其原始输入条目则会被包含在 history 中。使用本地 session 时,SDK 会在发起模型请求之前,将已纳入的输入持久化一次。使用 conversationId 或 previousResponseId 时,输入会一直保持待处理状态,直到服务器接受响应,因此,如果已知故障发生在接受之前,就可以恢复运行而不丢失输入。如果提供方报告请求可能已被接受,SDK 会为该次输入记录检查点,并拒绝继续执行以确保安全,而不是静默重放。关于单独、显式启用不安全重放的覆盖选项,请参阅模型重试。

手动处理 interruptions 是最通用的模式,但并非唯一方式:

  • 本地 shellTool() 和 applyPatchTool() 可以使用 onApproval 在代码中立即批准或拒绝。
  • 托管 MCP 工具可以结合使用 requireApproval 和 onApproval,以同样的方式通过代码做出决策。
  • 普通函数工具使用本页介绍的手动中断流程。

当这些回调返回决策时,运行会继续,而不会暂停等待人工响应。对于 Realtime 会话 API,请参阅构建语音智能体指南中的审批流程。

同样的中断流程也适用于流式运行。流式运行暂停后,等待 stream.completed,读取并处理 stream.interruptions;如果希望恢复后的输出继续以流式方式传输,请再次调用 run() 并传入 { stream: true }。有关此模式的流式版本,请参阅流式传输中的人工干预。

如果您同时使用了 session,从 RunState 恢复时请继续传入同一个 session。这样,恢复后的轮次会追加到会话记忆中,而无需重新准备输入。有关会话生命周期的详细信息,请参阅会话指南。

下面是一个更完整的人工干预流程示例,它在终端中提示用户审批,并将状态临时存储在文件中。

人工干预
// This local CLI trusts its saved state. Browser/mobile approval UIs should keep
// snapshots on the server; see human-in-the-loop-server.ts in agent-patterns.
import { z } from 'zod';
import readline from 'node:readline/promises';
import fs from 'node:fs/promises';
import { Agent, run, tool, RunState, RunResult } from '@openai/agents';
const getWeatherTool = tool({
name: 'get_weather',
description: 'Get the weather for a given city',
parameters: z.object({
location: z.string(),
}),
needsApproval: async (_context, { location }) => {
// forces approval to look up the weather in San Francisco
return location === 'San Francisco';
},
execute: async ({ location }) => {
return `The weather in ${location} is sunny`;
},
});
const dataAgentTwo = new Agent({
name: 'Data agent',
instructions: 'You are a data agent',
handoffDescription: 'You know everything about the weather',
tools: [getWeatherTool],
});
const agent = new Agent({
name: 'Basic test agent',
instructions: 'You are a basic agent',
handoffs: [dataAgentTwo],
});
async function confirm(question: string) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const answer = await rl.question(`${question} (y/n): `);
const normalizedAnswer = answer.toLowerCase();
rl.close();
return normalizedAnswer === 'y' || normalizedAnswer === 'yes';
}
async function main() {
let result: RunResult<unknown, Agent<unknown, any>> = await run(
agent,
'What is the weather in Oakland and San Francisco?',
);
let hasInterruptions = result.interruptions?.length > 0;
while (hasInterruptions) {
// Store the current run state
await fs.writeFile(
'result.json',
JSON.stringify(result.state, null, 2),
'utf-8',
);
// At this point, another process could review the saved state
// Read the saved state later
const storedState = await fs.readFile('result.json', 'utf-8');
const state = await RunState.fromString(agent, storedState);
for (const interruption of result.interruptions) {
const confirmed = await confirm(
`Agent ${interruption.agent.name} would like to use the tool ${interruption.name} with "${interruption.arguments}". Do you approve?`,
);
if (confirmed) {
state.approve(interruption);
} else {
state.reject(interruption);
}
}
// Resume execution from the restored state
result = await run(agent, state);
hasInterruptions = result.interruptions?.length > 0;
}
console.log(result.finalOutput);
}
main().catch((error) => {
console.dir(error, { depth: null });
});

可运行的端到端版本请参阅完整示例脚本。

人工干预流程支持长时间中断,而无需让服务器一直保持运行。如果您需要结束当前请求并稍后继续,可以将状态序列化,然后在之后恢复运行。

您可以使用 result.state.toString()(或 JSON.stringify(result.state))序列化状态,之后将序列化状态传入 RunState.fromString(agent, serializedState) 来恢复运行,其中 agent 是触发整个运行的智能体实例。

当已获批准的函数工具结果可能成为运行的最终输出时,输出护栏会对恢复条件施加更严格的限制。在 SDK 能够确认归属关系的情况下,当前的 RunState 模式会记录当前响应所生成条目的确切归属,因此受支持的、包含输出的部分审批检查点可以通过状态序列化与反序列化来保存和恢复。在进一步产生模型、工具或会话副作用之前,SDK 会验证该归属关系。对于旧版快照,以及归属关系缺失、无效或不明确的检查点,SDK 仍会抛出 UserError,拒绝继续执行以确保安全。遇到这种情况时,请从安全的输入开始新的运行。请重建相同的智能体图,并保留原始的 toolUseBehavior;不要通过重放原始条目来绕过归属错误。

序列化 RunState 时,SDK 会为交接和 Agent.asTool() 构成的图记录稳定的智能体标识。这样,即使不同智能体具有相同的 name,只要恢复运行的进程重建了相同的智能体图,已暂停的运行也能恢复。

传入 RunState.fromString(agent, serializedState) 的 agent 是重建后的图的根节点。反序列化时,SDK 会遍历该智能体的交接和 Agent.asTool() 引用,然后根据重建后的图解析状态中每一个序列化的智能体引用。这包括当前智能体,以及生成条目、已处理的模型响应和排队等待执行的后续步骤中持有的嵌套引用。

如果您需要使用替换后的图恢复运行,例如智能体的模型或工具已被另一个运行时包装,请先使用原始图反序列化状态,再次将其序列化,然后使用替换后的根智能体反序列化该字符串。调用 state.setCurrentAgent(agent) 只会更改活动智能体,不会重写反序列化期间已解析的嵌套引用。

如果恢复运行的进程需要注入新的上下文对象,请改用 RunState.fromStringWithContext(agent, serializedState, context, { contextStrategy })。

  • contextStrategy: 'merge'(默认值)会保留提供的 RunContext,合并序列化的审批状态,并在新上下文尚未定义 toolInput 时恢复序列化的 toolInput。
  • contextStrategy: 'replace' 会按原样使用提供的 RunContext 重建运行。

序列化的运行状态包含您的应用上下文,以及 SDK 管理的运行时元数据,例如审批状态、用量、嵌套的 toolInput 和待恢复的嵌套智能体工具执行。如果您计划存储或传输序列化状态,请将 runContext.context 视为持久化数据,并避免在其中放入机密信息,除非您明确希望这些信息随状态一起存储或传输。

默认情况下,序列化状态会省略追踪 API 密钥,以免意外持久化机密信息。只有在明确需要随状态一起转移追踪凭据时,才应传入 result.state.toString({ includeTracingApiKey: true })。

请将序列化状态保存在应用控制的存储中,例如服务器端数据库。

序列化的 RunState 包含执行状态,包括审批决策、待处理的工具调用、工具参数和应用上下文。RunState.fromString() 会恢复该状态,但此方法不会验证快照的真实性或提交者的身份。仅应对来自可信存储的快照进行反序列化,或者在应用验证了完整快照的完整性、归属和重放防护之后进行反序列化。模式验证和工具调用指纹不会验证快照的真实性。SDK 中提到的智能体或生成条目归属关系,也不能作为应用用户的授权依据。

对于浏览器或移动端审批界面,请将完整快照保留在应用控制的服务器存储中。仅向审批者发送其有权查看的展示详情,以及待决策项的不透明标识符。运行 ID 或决策 ID 不是授权证明。请将工具名称和参数视为不可信的展示内容:过滤敏感值,并在渲染 HTML 时对内容进行转义。将完整的运行结果和错误保留在服务器上,仅向客户端返回由应用选定的输出。

收到决策时,服务器必须:

  1. 使用应用的会话或身份验证中间件验证审批者身份。切勿从审批请求正文中获取已验证的身份。
  2. 针对存储的运行和选定的待处理调用,检查审批者是否有权审批。
  3. 根据服务器上存储的待处理请求,验证决策标识符和布尔决策值。不要接受客户端提供的替代工具调用、参数、审批记录或序列化状态。
  4. 在反序列化和恢复执行之前,以原子方式检查归属并消耗待处理请求。并发提交或重放提交不得导致同一快照被恢复两次。在共享存储中,请使用事务或等效的原子条件状态转换。
  5. 加载服务器持有的快照,通过 state.getInterruptions() 获取待处理项,并仅对这些条目应用 state.approve() 或 state.reject(),然后恢复运行。

以下示例要求对一批请求中的每个待处理调用都做出决策。这是应用层策略;如上所述,SDK 也支持部分审批。该存储仅限于单个进程中的一个事件循环。归属检查、验证和消耗操作之间没有任何 await。如果反序列化或执行失败,或者执行被取消,请求仍保持已消耗状态。消耗操作可以防止重新提交此快照,但不能保证工具副作用恰好发生一次。在开始恢复或另一次运行之前,请先核实并处理已完成或状态不确定的工具副作用。

服务器持有的审批状态
import { randomUUID } from 'node:crypto';
import { Agent, Runner, RunState, type RunResult } from '@openai/agents';
import { z } from 'zod';
export type PendingApproval = {
kind: 'approval';
requestId: string;
prompts: { decisionId: string; toolName: string; arguments: string }[];
};
type StoredRun = {
ownerId: string;
snapshot: string;
decisionIds: string[];
};
// Simulation only: one event loop in one process. Production storage needs an
// atomic owner-checked consume operation and bounded retention. Consumption is
// permanent even after failure/cancellation; reconcile side effects before retry.
export class ApprovalServer {
#agent: Agent;
#runner = new Runner({ tracingDisabled: true });
#pending = new Map<string, StoredRun>();
constructor(agent: Agent) {
this.#agent = agent;
}
// An HTTP adapter must obtain this identity from trusted authentication
// middleware and apply request/CSRF protections. Never read it from the body.
async start(authenticatedUserId: string, message: string) {
const result = await this.#runner.run(this.#agent, message);
return this.#save(authenticatedUserId, result);
}
#save<TContext, TAgent extends Agent<any, any>>(
ownerId: string,
result: RunResult<TContext, TAgent>,
) {
const interruptions = result.state.getInterruptions();
if (interruptions.length === 0) {
// RunResult stays on the server; the app selects what the client may see.
return { kind: 'completed' as const, output: result.finalOutput };
}
const requestId = randomUUID();
const decisionIds = interruptions.map(() => randomUUID());
this.#pending.set(requestId, {
ownerId,
snapshot: result.state.toString(),
decisionIds,
});
const response: PendingApproval = {
kind: 'approval',
requestId,
// Detached display values only. Filter arguments for the reviewer's access
// policy; this demo uses synthetic weather data. Escape HTML in a web UI.
prompts: interruptions.map((item, index) => ({
decisionId: decisionIds[index],
toolName: item.name ?? 'unknown_tool',
arguments: item.arguments ?? '',
})),
};
return response;
}
async decide(
authenticatedUserId: string,
requestId: string,
decisions: unknown,
signal?: AbortSignal,
) {
const stored = this.#pending.get(requestId);
if (!stored || stored.ownerId !== authenticatedUserId) {
throw new Error('Approval request is unavailable.');
}
// Validate JSON request data, not client-supplied calls, state, or identity.
const parsed = z.record(z.string(), z.boolean()).safeParse(decisions);
if (
!parsed.success ||
Object.keys(parsed.data).length !== stored.decisionIds.length ||
!stored.decisionIds.every((id) =>
Object.prototype.hasOwnProperty.call(parsed.data, id),
)
) {
throw new Error(
'Provide one boolean decision for every pending tool call.',
);
}
// No await between the owner check and consume. The parsed decisions are a
// detached copy, so client mutation while deserialization awaits has no effect.
this.#pending.delete(requestId);
const state = await RunState.fromString(this.#agent, stored.snapshot);
const interruptions = state.getInterruptions();
for (const [index, interruption] of interruptions.entries()) {
if (parsed.data[stored.decisionIds[index]]) {
state.approve(interruption);
} else {
state.reject(interruption);
}
}
const result = await this.#runner.run(this.#agent, state, { signal });
return this.#save(authenticatedUserId, result);
}
}

完整代码示例请参阅 CLI 客户端/服务器模拟。这不是可部署的 HTTP 服务。生产应用必须提供可信的身份验证、对展示详情和选定调用的授权、适用的请求及 CSRF 防护、有时限的存储保留策略、共享存储中的原子消耗机制,以及恢复策略。该 CLI 使用合成的工具数据并禁用了追踪;实际应用的快照和诊断信息可能包含敏感数据。

使用带有 contextStrategy: 'replace' 的 RunState.fromStringWithContext(),或仅移除序列化的审批记录,都不能使不可信快照变得安全。其他字段仍然控制着执行。如果客户端传输完整快照,请在反序列化之前验证整个快照的完整性,将其绑定到获授权的用户和运行,并防止重放。完整性验证不会加密快照,也不会向客户端隐藏其内容。

如果审批请求耗时较长,并且您计划有意义地管理智能体定义的版本,或升级 Agents SDK 版本,我们目前建议您使用包别名并行安装两个版本的 Agents SDK,并实现自己的分支逻辑。

具体而言,就是为您自己的代码分配版本号,将其与序列化状态一起存储,并在反序列化时使用对应版本的代码。