工具
工具让智能体能够执行操作——获取数据、调用外部 API、执行代码,甚至操作计算机。JavaScript/TypeScript SDK 支持七个类别:
在阅读智能体、确定哪个智能体应负责该任务,并希望为其赋予能力后,请阅读本页。如果您仍在权衡不同的委派模式,请参阅智能体编排。
- OpenAI 托管工具——与模型一同在 OpenAI 服务器上运行。(Web 搜索、文件搜索、Code Interpreter、图像生成、工具搜索)
- 内置执行工具——由 SDK 提供、在模型外部执行的工具。(计算机操作和 apply_patch 在本地运行;shell 可在本地或托管容器中运行)
- 函数工具——使用 JSON 模式封装任意本地函数,以供 LLM 调用。
- Agents as tools——将整个智能体公开为可调用的工具。
- MCP 服务器——连接 Model Context Protocol 服务器(本地或远程)。
- 沙盒能力——为
SandboxAgent附加作用于工作区的 shell、文件系统、技能、记忆或压缩工具。 - 实验性:Codex 工具——将 Codex SDK 封装为函数工具,以运行感知工作区的任务。
本指南接下来先介绍各个工具类别,然后汇总适用于各类工具的选择策略和提示编写建议。
1. 托管工具(OpenAI Responses API)
Section titled “1. 托管工具(OpenAI Responses API)”使用 OpenAIResponsesModel 时,您可以添加以下内置工具:
| 工具 | 类型字符串 | 用途 |
|---|---|---|
| Web 搜索 | 'web_search' | 互联网搜索。 |
| 文件 / 检索搜索 | 'file_search' | 查询托管在 OpenAI 上的向量存储。 |
| Code Interpreter | 'code_interpreter' | 在沙盒环境中运行代码。 |
| 图像生成 | 'image_generation' | 根据文本生成图像。 |
| 工具搜索 | 'tool_search' | 在运行时加载延迟加载的函数工具、命名空间或可搜索的 MCP 工具。 |
| 程序化工具调用 | 'programmatic_tool_calling' | 运行模型生成的 JavaScript,以协调符合条件的工具。 |
import { Agent, codeInterpreterTool, fileSearchTool, imageGenerationTool, webSearchTool,} from '@openai/agents';
const agent = new Agent({ name: 'Travel assistant', tools: [ webSearchTool({ searchContextSize: 'medium' }), fileSearchTool('VS_ID', { maxNumResults: 3 }), codeInterpreterTool(), imageGenerationTool({ size: '1024x1024' }), ],});SDK 提供了返回托管工具定义的辅助函数:
| 辅助函数 | 说明 |
|---|---|
webSearchTool(options?) | 适合 JavaScript 使用的选项,如 searchContextSize、userLocation、filters.allowedDomains、searchContentTypes 和 imageSettings。 |
fileSearchTool(ids, options?) | 第一个参数接受一个或多个向量存储 ID,另外还可传入 maxNumResults、includeSearchResults、rankingOptions 和过滤器等选项。 |
codeInterpreterTool(options?) | 未提供 container 时,默认使用自动管理的容器。 |
imageGenerationTool(options?) | 支持图像生成配置,如 model、size、quality、background、inputFidelity、inputImageMask、moderation、outputCompression、partialImages 和输出格式。 |
toolSearchTool(options?) | 添加内置的 tool_search 辅助工具。与设置了 deferLoading: true 的延迟加载函数工具或远程 MCP 服务器工具搭配使用。默认支持托管执行,也可通过 execution: 'client' 和 execute 在客户端执行。 |
programmaticToolCallingTool() | 启用程序化工具调用。与 allowedCallers 包含 'programmatic' 的工具搭配使用。 |
这些辅助函数会将适合 JavaScript/TypeScript 使用的选项名称映射到底层 OpenAI Responses API 的工具请求数据。要请求图像搜索结果,请在 webSearchTool({ searchContentTypes }) 中包含 'image'。使用 imageSettings.maxResults 请求正数数量的图像,并使用 imageSettings.caption 请求在可用时提供图像说明。只要 searchContentTypes 包含 'image',SDK 就会请求原始 Web 搜索结果,并在 Web 搜索调用项的 providerData.results 中公开返回的图像 URL 和元数据。
有关完整的工具模式以及排名选项、语义过滤器等高级选项,请参阅官方 OpenAI 工具指南;有关图像结果字段,请参阅官方 Web 搜索指南;有关当前的内置工具搜索流程和模型可用性,请参阅官方工具搜索指南;有关模型支持和通信协议层面的行为,请参阅官方程序化工具调用指南。
2. 内置执行工具
Section titled “2. 内置执行工具”这些工具内置于 SDK 中,但实际执行发生在模型响应本身之外:
- 计算机操作——实现
Computer接口,并将其传递给computerTool()。此工具始终使用您提供的本地Computer实现来运行。 - Shell——提供本地
Shell实现,或使用shellTool({ environment })配置托管容器环境。 - 补丁应用——实现
Editor接口,并将其传递给applyPatchTool()。此工具始终使用您提供的本地Editor实现来运行。 - 沙盒 shell 和文件系统工具——如果这些操作应在沙盒工作区内运行,请在
SandboxAgent上使用shell()、filesystem()、skills()、memory()或compaction()。
工具调用仍由模型发起,但由您的应用或配置的执行环境完成实际工作。
沙盒能力工具不同于进程级内置工具:它们绑定到当前 SandboxAgent 运行所使用的活动沙盒会话。如果工具应操作智能体的隔离工作区,而非您的应用进程,请使用快速入门中介绍的沙盒智能体。
import { Agent, applyPatchTool, computerTool, shellTool, Computer, Editor, Shell,} from '@openai/agents';
const computer: Computer = { environment: 'browser', dimensions: [1024, 768], screenshot: async () => '', click: async () => {}, doubleClick: async () => {}, scroll: async () => {}, type: async () => {}, wait: async () => {}, move: async () => {}, keypress: async () => {}, drag: async () => {},};
const shell: Shell = { run: async () => ({ output: [ { stdout: '', stderr: '', outcome: { type: 'exit', exitCode: 0 }, }, ], }),};
const editor: Editor = { createFile: async () => ({ status: 'completed' }), updateFile: async () => ({ status: 'completed' }), deleteFile: async () => ({ status: 'completed' }),};
const agent = new Agent({ name: 'Local tools agent', model: 'gpt-5.4', tools: [ computerTool({ computer }), shellTool({ shell, needsApproval: true }), applyPatchTool({ editor, needsApproval: true }), ],});计算机工具详解
Section titled “计算机工具详解”computerTool() 接受以下任一种形式:
- 具体的
Computer实例。 - 为每次运行创建一个
Computer的初始化函数。 - 带有
{ create, dispose }的提供者对象,适用于需要按运行设置和清理资源的情况。
要使用 OpenAI 当前的计算机操作路径,请设置支持计算机操作的模型,例如 gpt-5.4。显式指定请求模型时,SDK 会发送正式发布(GA)的内置 computer 工具格式。如果实际使用的模型仍来自已存储的提示或其他较旧的集成,SDK 会保留旧版 computer_use_preview 通信格式以保持兼容性,除非您通过 modelSettings.toolChoice: 'computer' 显式选择 GA 路径。
GA 计算机调用可以在单个 computer_call 中包含一批 actions[]。SDK 会按顺序执行这些操作,针对每个操作评估 needsApproval,并将最终截图作为工具输出返回。如果您基于 interruption.rawItem 构建审批界面,请在存在 actions 时读取该字段,并对旧版预览项回退到 action。
当影响较大的计算机操作需要暂停以供用户审查时,请使用 needsApproval;当您希望确认或拒绝计算机调用所报告的待处理安全检查时,请使用 onSafetyCheck。有关模型端指导和迁移详情,请参阅官方 OpenAI 计算机操作指南及其迁移说明。
待处理的计算机安全检查
Section titled “待处理的计算机安全检查”Responses API 可以在 computer_call 中包含 pending_safety_checks,标记需要您的应用审查的问题。每项检查都有一个 id,以及可选的 code 和 message 字段,用于描述问题类型并提供详细信息。这些检查来自 API。有关 pending_safety_checks 和 acknowledged_safety_checks,请参阅 Responses API 参考;有关应用层面的预防措施,请参阅计算机操作安全指南。
配置 computerTool({ onSafetyCheck }),以决定是否继续执行被标记的计算机调用。JavaScript SDK 会将 id 和 code 值均非空的检查传递给此回调,并忽略缺少其中任一值的检查。只有至少一项检查满足这些要求时,SDK 才会在执行该调用的操作前调用此回调。
回调接收 { runContext, pendingSafetyChecks, toolCall },并处理通过 pendingSafetyChecks 传入的检查:
- 返回
true,确认传递给回调的所有检查并允许执行。 - 返回
false,在执行操作或截图前拒绝该调用。SDK 会返回拒绝结果,并让智能体继续运行。 - 返回包含
acknowledgedSafetyChecks(或acknowledged_safety_checks)的对象,确认所提供的检查并允许执行。仅包含部分检查或为空的列表不会拒绝该调用。 - 返回
undefined或不返回任何值,允许执行但不确认检查。
如果省略 onSafetyCheck,SDK 会继续执行,并将检查保留为未确认状态。SDK 不会自动提示人工处理。如果您的应用需要审查 SDK 转发的检查,请显式配置此回调。例如,以下保守策略会拒绝传递给回调的每个调用:
import { computerTool, type Computer, type ComputerTool } from '@openai/agents';
export function computerToolWithSafetyChecks(computer: Computer): ComputerTool { return computerTool({ computer, // Reject every flagged call until the application implements a review flow. onSafetyCheck: async () => false, });}要允许已审查的调用,请将示例回调替换为这样的回调:向应用的审查人员展示 pendingSafetyChecks 和拟执行的 toolCall,等待决定,并返回该决定。未知的检查代码也应视为需要审查。
没有待处理检查的计算机调用不会触发此回调。要获取人工决定,回调必须安排相应的交互并返回决定;onSafetyCheck 不使用人机协作中描述的暂停与恢复流程。如果您的应用要求计算机操作使用该审批流程,请使用 needsApproval,包括不会触发 onSafetyCheck 的调用。
Shell 工具详解
Section titled “Shell 工具详解”shellTool() 有两种模式:
- 本地模式:提供
shell,还可选择提供environment: { type: 'local', skills },以及用于自动处理审批的needsApproval和onApproval。 - 托管容器模式:提供
environment,并将其type设为'container_auto'或'container_reference'。
在本地模式下,environment.skills 允许您通过 name、description 和文件系统 path 挂载本地技能。
在托管容器模式下,使用以下任一配置设置 shellTool({ environment }):
type: 'container_auto',为此次运行创建托管容器。type: 'container_reference',通过containerId复用现有容器。
托管的 container_auto 环境支持:
networkPolicy,包括带有domainSecrets的允许列表。fileIds,用于挂载已上传的文件。memoryLimit,用于设置容器内存大小。skills,可通过skill_reference或内联 zip 包提供。
托管 shell 环境不接受 shell、needsApproval 或 onApproval,因为执行发生在托管容器环境中,而非您的本地进程中。
有关端到端用法,请参阅 examples/tools/local-shell.ts、examples/tools/container-shell-skill-ref.ts 和 examples/tools/container-shell-inline-skill.ts。
补丁应用工具详解
Section titled “补丁应用工具详解”applyPatchTool() 采用与 shellTool() 相同的本地审批流程:使用 needsApproval 在编辑文件前暂停;如果希望通过应用级回调自动批准或拒绝,请使用 onApproval。
3. 函数工具
Section titled “3. 函数工具”您可以使用 tool() 辅助函数将任意函数转换为工具。
import { tool } from '@openai/agents';import { z } from 'zod';
const getWeatherTool = tool({ name: 'get_weather', description: 'Get the weather for a given city', parameters: z.object({ city: z.string() }), async execute({ city }) { return `The weather in ${city} is sunny.`; },});| 字段 | 是否必需 | 说明 |
|---|---|---|
name | 否 | 默认为函数名(例如 get_weather)。 |
description | 是 | 向 LLM 展示的清晰、易于理解的描述。 |
parameters | 是 | Zod 模式、受支持的 Standard Schema 值,或原始 JSON Schema 对象。验证模式会自动启用严格模式。 |
strict | 否 | 为 true(默认值)时,如果参数未通过验证,SDK 会返回模型错误。设为 false 可进行模糊匹配。 |
execute | 是 | (args, context, details) => string | unknown | Promise<...>——您的业务逻辑。非字符串输出会序列化后提供给模型。context 是可选的 RunContext;details 包含 toolCall、resumeState 和 signal 等元数据。 |
allowedCallers | 否 | 仅适用于 Responses 的非空列表,控制工具可被直接调用、以程序方式调用,或两者皆可。使用 'direct'、'programmatic' 或同时使用这两个值。 |
outputSchema | 否 | 仅适用于 Responses 的工具结果模式。Zod 模式会约束 execute 的返回类型,并验证/转换运行时结果;原始 JSON 模式仅描述通信协议约定。 |
errorFunction | 否 | 自定义处理函数 (context, error, details) => result,用于将内部错误转换为模型可见的结果。设置 outputSchema 时,结果必须满足该模式。默认处理函数会被禁用,因此会重新抛出原始错误。 |
timeoutMs | 否 | 每次调用的超时时间,以毫秒为单位。必须大于 0,且小于或等于 2147483647。 |
timeoutBehavior | 否 | 超时模式:error_as_result 返回模型可见的结果,raise_exception 抛出 ToolTimeoutError。未设置 outputSchema 时默认为 error_as_result,设置后默认为 raise_exception。 |
timeoutErrorFunction | 否 | 用于 error_as_result 的自定义处理函数 (context, timeoutError, details) => result。设置 outputSchema 时,此处理函数为必需,且其结果必须满足该模式。 |
customDataExtractor | 否 | 回调 (context) => Record<string, unknown> | null | undefined,用于向生成的 RunToolCallOutputItem.customData 附加仅供 SDK 使用的元数据。这些数据不会发回模型。 |
needsApproval | 否 | 执行前要求人工批准。请参阅人机协作。 |
isEnabled | 否 | 按条件为每次运行公开工具;接受布尔值或谓词函数。 |
inputGuardrails | 否 | 在工具执行前运行的护栏;可拒绝执行或抛出异常。请参阅护栏。 |
outputGuardrails | 否 | 在工具执行后运行的护栏;可拒绝结果或抛出异常。请参阅护栏。 |
条件式工具可用性
Section titled “条件式工具可用性”使用 isEnabled 实现请求级能力可见性、特定环境下的可用性、功能开关或实验。运行器在为当前轮次准备模型可见的工具集时,会评估该谓词函数。
isEnabled 不能替代依赖工具参数或所访问资源的授权,因为谓词函数会在模型生成这些参数之前运行。请在 execute 内部实施参数级和资源级授权,或在适当时添加工具输入护栏和人机协作中的审批机制。MCP 服务器必须自行对其受保护操作进行授权。有关将同一应用策略应用于函数工具、本地 MCP 工具和交接的模式,请参阅上下文管理。
受支持的 Standard Schema 参数会转换为供模型使用的 JSON Schema,并在 execute 运行前进行本地验证。验证输出类型(包括库的转换和默认值)会成为推断出的 execute 参数类型。有关 Valibot 示例和当前限制,请参阅模式验证。
仅供 SDK 使用的自定义数据
Section titled “仅供 SDK 使用的自定义数据”当应用需要在工具结果旁附带渲染提示、内部 ID 或其他兼容 JSON 的元数据时,请使用 customDataExtractor。回调会接收运行上下文、工具定义、模型工具调用、解析后的输入、输出,以及原始输出项的克隆副本。返回的数据存储在 RunToolCallOutputItem.customData 和 RunState 中,但不会包含在 history 或模型重放中。
函数工具超时
Section titled “函数工具超时”使用 timeoutMs 为每次函数工具调用设置时间上限。
timeoutBehavior: 'error_as_result'会向模型返回Tool '<name>' timed out after <timeoutMs>ms.。未设置outputSchema时,这是默认行为。timeoutBehavior: 'raise_exception'会抛出ToolTimeoutError,您可以按运行智能体中介绍的异常处理方式捕获它。timeoutErrorFunction允许您在error_as_result模式下自定义超时文本。- 设置
outputSchema时,默认行为变为raise_exception。使用error_as_result时,必须提供返回值符合该模式的timeoutErrorFunction。 - 超时会中止
details.signal,因此长时间运行的工具可以通过监听取消信号及时停止。
如果您直接调用函数工具,请使用 invokeFunctionTool,以实施与正常智能体运行相同的超时行为。
非严格 JSON 模式工具
Section titled “非严格 JSON 模式工具”如果您需要模型对无效或不完整的输入进行猜测,可以在使用原始 JSON 模式时禁用严格模式:
import { tool } from '@openai/agents';
interface LooseToolInput { text: string;}
const looseTool = tool({ description: 'Echo input; be forgiving about typos', strict: false, parameters: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'], additionalProperties: true, }, execute: async (input) => { // because strict is false we need to do our own verification if (typeof input !== 'object' || input === null || !('text' in input)) { return 'Invalid input. Please try again'; } return (input as LooseToolInput).text; },});使用工具搜索进行延迟工具加载
Section titled “使用工具搜索进行延迟工具加载”工具搜索让模型能够在运行时仅加载所需的工具定义,而不必预先发送所有模式。在 SDK 中,您可以通过此方式使用延迟加载的顶层函数工具、toolNamespace() 分组,以及配置了 deferLoading: true 的远程 MCP 服务器工具。
请仅对 GPT-5.4 及更新版本中在 Responses API 内支持工具搜索的模型使用此功能。
import { Agent, tool, toolNamespace, toolSearchTool } from '@openai/agents';import { z } from 'zod';
const customerIdParams = z.object({ customerId: z.string().describe('The customer identifier to look up.'),});
// Keep a standalone deferred tool at the top level when it represents a// single searchable capability that does not need a shared namespace.const shippingLookup = tool({ name: 'get_shipping_eta', description: 'Look up a shipment ETA by customer identifier.', parameters: customerIdParams, deferLoading: true, async execute({ customerId }) { return { customerId, eta: '2026-03-07', carrier: 'Priority Express', }; },});
// Group related tools into a namespace when one domain description should// cover several deferred tools and let tool search load them together.const crmTools = toolNamespace({ name: 'crm', description: 'CRM tools for customer profile lookups.', tools: [ tool({ name: 'get_customer_profile', description: 'Fetch a basic customer profile.', parameters: customerIdParams, deferLoading: true, async execute({ customerId }) { return { customerId, tier: 'enterprise', }; }, }), ],});
const agent = new Agent({ name: 'Operations assistant', model: 'gpt-5.4', // Mixing namespaced and top-level deferred tools in one request is supported. tools: [shippingLookup, ...crmTools, toolSearchTool()],});该示例有意混合使用了两种风格:
shippingLookup保持在顶层,因为它是一项独立的可搜索能力。crmTools使用toolNamespace(),因为相关的 CRM 工具共享一个高层级标签和描述。- 支持在同一请求中混合使用命名空间内和顶层的延迟加载工具;工具搜索既可以加载
crm这样的命名空间路径,也可以加载get_shipping_eta这样的顶层路径。
使用工具搜索时:
- 为每个延迟加载的函数工具设置
deferLoading: true。 - 当多个相关工具应共享一个领域描述并作为一组加载时,使用
toolNamespace({ name, description, tools })。 - 当工具是一项独立能力,且工具名本身就是合适的搜索目标时,将其保留在顶层。
- 只要任何延迟加载的函数工具或远程 MCP 服务器工具使用了
deferLoading: true,就要在同一个tools数组中添加toolSearchTool()。 - 将
modelSettings.toolChoice保持为'auto'。SDK 不允许按名称强制使用内置tool_search工具或延迟加载的函数工具。 - 默认为托管执行。如果设置
toolSearchTool({ execution: 'client', execute }),标准run()循环仅支持内置的{ paths: string[] }客户端查询格式;自定义客户端模式需要您自行实现 Responses 循环。 - 一个命名空间可以混合包含立即可用和延迟加载的成员。立即可用的成员无需工具搜索即可调用,而同一命名空间中的延迟加载成员则按需加载。
- 工具发现结果归执行搜索的智能体所有,不会通过交接转移。当该智能体的名称在运行图中唯一时,SDK 会在历史记录或 Session 重放期间为同一逻辑智能体保留发现结果。如果归属缺失或存在歧义,就需要重新搜索,因此,当持久化的发现结果必须在重建后保留时,请为智能体使用唯一名称。
- 延迟加载的函数工具和
toolNamespace()仅适用于 Responses。Chat Completions 会拒绝它们,AI SDK 适配器也不支持 Responses 的延迟工具加载流程。
4. Agents as tools
Section titled “4. Agents as tools”有时,您希望一个智能体协助另一个智能体,而不是完全交接对话。请使用 agent.asTool():
如果您仍在 agent.asTool() 和 handoff() 之间进行选择,请比较智能体和智能体编排中介绍的模式。
import { Agent } from '@openai/agents';
const summarizer = new Agent({ name: 'Summarizer', instructions: 'Generate a concise summary of the supplied text.',});
const summarizerTool = summarizer.asTool({ toolName: 'summarize_text', toolDescription: 'Generate a concise summary of the supplied text.',});
const mainAgent = new Agent({ name: 'Research assistant', tools: [summarizerTool],});SDK 在内部会:
- 创建一个仅有
input参数的函数工具。 - 在工具被调用时,使用该输入运行子智能体。
- 返回最后一条消息,或由
customOutputExtractor提取的输出。
当智能体作为工具运行时,Agents SDK 会创建一个 Runner,并使用该运行器在函数工具调用内执行智能体。传入 runConfig 可配置嵌套运行器,传入 runOptions 可配置嵌套运行。
您还可以通过 asTool() 选项在智能体工具上设置 needsApproval 和 isEnabled,以集成人机协作流程和条件式工具可用性。
在 customOutputExtractor 内,使用 result.agentToolInvocation 检查当前的 Agent.asTool() 调用。在该回调中,结果始终来自 Agent.asTool(),因此 agentToolInvocation 始终有定义,并公开 toolName、toolCallId 和 toolArguments。使用 result.runContext.context 获取应用上下文。使用默认的单一 input 模式时,result.runContext.toolInput 为 undefined;请改用 result.agentToolInvocation.toolArguments 读取调用参数。配置自定义 parameters 或 inputBuilder 时,result.runContext.toolInput 会包含捕获的结构化参数。agentToolInvocation 元数据的作用域仅限于当前嵌套调用,不会序列化到 RunState 中。
import { Agent } from '@openai/agents';
const billingAgent = new Agent({ name: 'Billing Agent', instructions: 'Handle billing questions and subscription changes.',});
const billingTool = billingAgent.asTool({ toolName: 'billing_agent', toolDescription: 'Handles customer billing questions.', customOutputExtractor(result) { console.log('tool', result.agentToolInvocation.toolName); // Direct invoke() calls may not have a model-generated tool call id. console.log('call', result.agentToolInvocation.toolCallId); console.log('args', result.agentToolInvocation.toolArguments);
return String(result.finalOutput ?? ''); },});
const orchestrator = new Agent({ name: 'Support Orchestrator', instructions: 'Delegate billing questions to the billing agent tool.', tools: [billingTool],});agent.asTool() 的高级结构化输入选项:
parameters:使用 Zod 模式、受支持的 Standard Schema 值或原始 JSON Schema,替换默认的{ input: string }格式。inputBuilder:将结构化工具参数映射为嵌套智能体的输入数据。includeInputSchema:在嵌套运行中包含输入 JSON 模式,以增强对模式的感知能力。resumeState:控制恢复嵌套的序列化RunState时所用的上下文协调策略:'merge'(默认)将当前的审批/上下文状态合并到序列化状态中;'replace'改用当前运行上下文;'preferSerialized'使用未更改的序列化上下文恢复运行。
来自智能体工具的流式事件
Section titled “来自智能体工具的流式事件”智能体工具可以将所有嵌套运行事件以流式方式传回应用。请选择适合您构建工具方式的钩子风格:
import { Agent } from '@openai/agents';
const billingAgent = new Agent({ name: 'Billing Agent', instructions: 'Answer billing questions and compute simple charges.',});
const billingTool = billingAgent.asTool({ toolName: 'billing_agent', toolDescription: 'Handles customer billing questions.', // onStream: simplest catch-all when you define the tool inline. onStream: (event) => { console.log(`[onStream] ${event.event.type}`, event); },});
// on(eventName) lets you subscribe selectively (or use '*' for all).billingTool.on('run_item_stream_event', (event) => { console.log('[on run_item_stream_event]', event);});billingTool.on('raw_model_stream_event', (event) => { console.log('[on raw_model_stream_event]', event);});
const orchestrator = new Agent({ name: 'Support Orchestrator', instructions: 'Delegate billing questions to the billing agent tool.', tools: [billingTool],});- 事件类型与
RunStreamEvent['type']一致:raw_model_stream_event、run_item_stream_event、agent_updated_stream_event。 onStream是最简单的”全事件”处理方式,适合内联声明工具时使用(tools: [agent.asTool({ onStream })])。如果不需要按事件分发,请使用它。on(eventName, handler)允许您选择性订阅事件(或使用'*'),最适合需要更细粒度处理或希望在创建后附加监听器的情况。- 如果提供了
onStream或任意on(...)处理函数,作为工具的智能体会自动以流式模式运行;否则仍使用非流式路径。 - 处理函数会并行调用,因此较慢的
onStream回调不会阻塞on(...)处理函数,反之亦然。 - 通过模型工具调用来调用工具时会提供
toolCallId;直接调用invoke()或提供者的特殊行为可能导致其缺失。
5. MCP 服务器
Section titled “5. MCP 服务器”您可以通过 Model Context Protocol(MCP) 服务器公开工具,并将其连接到智能体。例如,您可以使用 MCPServerStdio 启动并连接到 stdio MCP 服务器:
import { Agent, MCPServerStdio } from '@openai/agents';
const server = new MCPServerStdio({ fullCommand: 'pnpm exec mcp-server-filesystem ./sample_files',});
await server.connect();
const agent = new Agent({ name: 'Assistant', mcpServers: [server],});完整示例请参阅 filesystem-example.ts。如果您需要 MCP 服务器工具集成的完整指南,也请参阅 MCP 集成。管理多个服务器(或部分连接失败)时,请使用 connectMcpServers,并参考 MCP 集成中的生命周期指导。
6. 实验性:Codex 工具
Section titled “6. 实验性:Codex 工具”@openai/agents-extensions/experimental/codex 提供了 codexTool(),这是一个将模型工具调用路由到 Codex SDK 的函数工具,使智能体能够自主运行工作区范围内的任务(shell、文件编辑、MCP 工具)。此接口处于实验阶段,可能会发生变化。
首先安装依赖:
npm install @openai/agents-extensions @openai/codex-sdk快速上手:
import { Agent } from '@openai/agents';import { codexTool } from '@openai/agents-extensions/experimental/codex';
export const codexAgent = new Agent({ name: 'Codex Agent', instructions: 'Use the codex tool to inspect the workspace and answer the question. When skill names, which usually start with `$`, are mentioned, you must rely on the codex tool to use the skill and answer the question.', tools: [ codexTool({ sandboxMode: 'workspace-write', workingDirectory: '/path/to/repo', defaultThreadOptions: { model: 'gpt-5.4', networkAccessEnabled: true, webSearchEnabled: false, }, }), ],});注意事项:
- 身份验证:提供
CODEX_API_KEY(首选)或OPENAI_API_KEY,或传入codexOptions.apiKey。 - 输入:采用严格模式——
inputs必须至少包含一个{ type: 'text', text }或{ type: 'local_image', path }。 - 安全:将
sandboxMode与workingDirectory搭配使用;如果目录不是 Git 仓库,请设置skipGitRepoCheck。 - 线程:
useRunContextThreadId: true会在runContext.context中读取/存储最新的线程 ID,便于在应用状态中跨轮次复用。 - 线程 ID 优先级:工具调用的
threadId(如果模式中包含)优先,其次是运行上下文中的线程 ID,最后是codexTool({ threadId })。 - 运行上下文键:当
name: 'codex'时,默认为codexThreadId;当名称为name: 'engineer'这类值(规范化后为codex_engineer)时,默认为codexThreadId_<suffix>。 - 可变上下文要求:启用
useRunContextThreadId时,通过run(..., { context })传入可变对象或Map。 - 命名:工具名称会规范化到
codex命名空间中(engineer变为codex_engineer),同一智能体中不允许存在重复的 Codex 工具名称。 - 流式传输:
onStream会同步传递 Codex 事件(推理、命令执行、MCP 工具调用、文件更改、Web 搜索),以便您记录日志或追踪进度。 - 输出:工具结果包含
response、usage和threadId,Codex 的 token 用量会记录在RunContext中。 - 结构:
outputSchema可以是描述符、JSON 模式对象或 Zod 对象。对于 JSON 对象模式,additionalProperties必须为false。
运行上下文线程复用示例:
import { Agent, run } from '@openai/agents';import { codexTool } from '@openai/agents-extensions/experimental/codex';
// Derived from codexTool({ name: 'engineer' }) when runContextThreadIdKey is omitted.type ExampleContext = { codexThreadId_engineer?: string;};
const agent = new Agent<ExampleContext>({ name: 'Codex assistant', instructions: 'Use the codex tool for workspace tasks.', tools: [ codexTool({ // `name` is optional for a single Codex tool. // We set it so the run-context key is tool-specific and to avoid collisions when adding more Codex tools. name: 'engineer', // Reuse the same Codex thread across runs that share this context object. useRunContextThreadId: true, sandboxMode: 'workspace-write', workingDirectory: '/path/to/repo', defaultThreadOptions: { model: 'gpt-5.4', approvalPolicy: 'never', }, }), ],});
// The default key for useRunContextThreadId with name=engineer is codexThreadId_engineer.const context: ExampleContext = {};
// First turn creates (or resumes) a Codex thread and stores the thread ID in context.await run(agent, 'Inspect src/tool.ts and summarize it.', { context });// Second turn reuses the same thread because it shares the same context object.await run(agent, 'Now list refactoring opportunities.', { context });
const threadId = context.codexThreadId_engineer;程序化工具调用
Section titled “程序化工具调用”程序化工具调用让受支持的 Responses 模型能够生成 JavaScript,在托管执行环境中协调多个工具调用。您的应用仍负责执行客户端所有的工具,因此现有的验证、权限、审批、护栏和副作用仍然适用。
import { Agent, programmaticToolCallingTool, tool } from '@openai/agents';import { z } from 'zod';
const getInventory = tool({ name: 'get_inventory', description: 'Return inventory for a SKU.', parameters: z.object({ sku: z.string() }), allowedCallers: ['programmatic'], outputSchema: z.object({ sku: z.string(), availableUnits: z.number(), }), async execute({ sku }) { return { sku, availableUnits: 42 }; },});
const getDemand = tool({ name: 'get_demand', description: 'Return requested units for a SKU.', parameters: z.object({ sku: z.string() }), allowedCallers: ['programmatic'], outputSchema: z.object({ sku: z.string(), requestedUnits: z.number(), }), async execute({ sku }) { return { sku, requestedUnits: 31 }; },});
const agent = new Agent({ name: 'Inventory planner', model: 'gpt-5.6', instructions: `Use Programmatic Tool Calling to fetch inventory and demand concurrently.Return the source values and the calculated shortage in the final answer. `.trim(), tools: [getInventory, getDemand, programmaticToolCallingTool()],});配置分为两部分:
- 将
programmaticToolCallingTool()添加到智能体。 - 为生成的程序可能调用的每个工具设置
allowedCallers。
allowedCallers | 行为 |
|---|---|
省略或 ['direct'] | 模型可以直接调用该工具。 |
['programmatic'] | 只有生成的程序可以调用该工具。 |
['direct', 'programmatic'] | 模型或生成的程序均可调用该工具。 |
SDK 支持通过程序调用以下工具:使用 tool() 创建的工具、本地或托管的 shellTool()、applyPatchTool()、hostedMcpTool() 和 codeInterpreterTool()。
SDK 会在发送请求前验证配置。仅允许程序调用的工具需要 programmaticToolCallingTool()。该辅助函数还要求至少存在一个符合条件的工具,除非请求包含工具搜索或能够提供此类工具的已存储提示。
当函数工具必须返回结构化数据时,请使用 outputSchema。Zod 模式会约束 execute 的返回类型,并验证和转换运行时结果。原始 JSON 模式描述通信协议约定,但不会添加 SDK 端的结果验证。无效的 Zod 结果会引发 InvalidToolOutputError。
Structured outputs 还会改变失败处理方式:
- 默认的
errorFunction会被禁用,因此执行错误会被重新抛出。自定义处理函数必须返回与outputSchema兼容的值。 - 默认超时行为变为
'raise_exception'。 - 要使用
'error_as_result',请提供返回值满足outputSchema的timeoutErrorFunction。 - 输出护栏替换后的值也必须满足
outputSchema。
程序化工具调用仅适用于 Responses。Chat Completions、语音智能体和 AI SDK 模型适配器会拒绝这些选项。如果符合条件的工具采用延迟加载,工具搜索必须先加载它,之后生成的程序才能调用它。
完整示例请参阅 examples/tools/programmatic-tool-calling.ts。
工具策略与最佳实践
Section titled “工具策略与最佳实践”工具使用行为
Section titled “工具使用行为”有关控制模型何时以及如何必须使用工具(modelSettings.toolChoice、toolUseBehavior 等),请参阅智能体。
- 简短、明确的描述——描述工具做什么,以及何时使用。
- 验证输入——尽可能使用 Zod 或受支持的 Standard Schema 值进行严格的 JSON 验证。
- 避免错误处理函数产生副作用——
errorFunction应返回有帮助的字符串,而不是抛出异常。 - 每个工具只承担一项职责——小巧、可组合的工具有助于模型更好地推理。