工具
工具让智能体能够执行操作——获取数据、调用外部 API、执行代码,甚至操作计算机。JavaScript/TypeScript SDK 支持六大类别:
在阅读完智能体后再阅读本页:当您已经确定由哪个智能体负责该任务,并希望为其赋予能力时使用本页。如果您仍在选择委派模式,请参阅智能体编排。
- OpenAI 托管工具——与模型一起在 OpenAI 服务器上运行。(Web 搜索、文件搜索、代码解释器、图像生成、工具搜索)
- 内置执行工具——由 SDK 提供、在模型之外执行的工具。(计算机操作和 apply_patch 在本地运行;shell 可在本地或托管容器中运行)
- 函数工具——用 JSON schema 封装任意本地函数,供 LLM 调用。
- Agents as tools——将整个智能体暴露为可调用工具。
- MCP 服务器——挂载 Model Context Protocol 服务器(本地或远程)。
- 实验性:Codex 工具——将 Codex SDK 封装为函数工具,以执行感知工作区的任务。
本指南其余部分将先介绍各类工具,再总结跨类别的工具选择与提示词实践。
1. 托管工具(OpenAI Responses API)
Section titled “1. 托管工具(OpenAI Responses API)”使用 OpenAIResponsesModel 时,您可以添加以下内置工具:
| 工具 | 类型字符串 | 用途 |
|---|---|---|
| Web 搜索 | 'web_search' | 互联网搜索。 |
| 文件/检索搜索 | 'file_search' | 查询 OpenAI 托管的向量存储。 |
| 代码解释器 | 'code_interpreter' | 在沙箱环境中运行代码。 |
| 图像生成 | 'image_generation' | 根据文本生成图像。 |
| 工具搜索 | 'tool_search' | 在运行时加载延迟函数工具、命名空间或可搜索 MCP 工具。 |
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。 |
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 使用客户端执行。 |
这些辅助函数会将 JavaScript/TypeScript 友好的选项名映射到底层 OpenAI Responses API 工具负载。完整工具 schema 与高级选项(如 ranking options、semantic filters)请参考官方OpenAI 工具指南,当前内置工具搜索流程与模型可用性请参考官方工具搜索指南。
2. 内置执行工具
Section titled “2. 内置执行工具”这些工具内置于 SDK,但执行发生在模型响应之外:
- 计算机操作——实现
Computer接口并传给computerTool()。这始终针对您提供的本地Computer实现运行。 - Shell——可提供本地
Shell实现,或通过shellTool({ environment })配置托管容器环境。 - Apply patch——实现
Editor接口并传给applyPatchTool()。这始终针对您提供的本地Editor实现运行。
工具调用仍由模型发起,但实际工作由您的应用或配置的执行环境完成。
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 会按顺序执行、对每个 action 评估 needsApproval,并将最终截图作为工具输出返回。如果您基于 interruption.rawItem 构建审批 UI,存在 actions 时请读取它;旧版预览项则回退到 action。
当高影响计算机操作需要用户复核时使用 needsApproval;当您希望确认或拒绝计算机调用上报的待处理安全检查时使用 onSafetyCheck。模型侧指导与迁移细节见官方OpenAI 计算机操作指南及其迁移说明。
Shell 工具细节
Section titled “Shell 工具细节”shellTool() 有两种模式:
- 本地模式:提供
shell,并可选environment: { type: 'local', skills },以及needsApproval和onApproval以处理自动审批。 - 托管容器模式:提供
environment,其中type为container_auto或container_reference。
在本地模式中,environment.skills 允许通过 name、description 和文件系统 path 挂载本地 skills。
在托管容器模式中,通过 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。
Apply-patch 工具细节
Section titled “Apply-patch 工具细节”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 schema 或原始 JSON schema 对象。Zod 参数会自动启用严格模式。 |
strict | 否 | 为 true(默认)时,参数校验失败会返回模型错误。设为 false 可进行模糊匹配。 |
execute | 是 | (args, context, details) => string | unknown | Promise<...>——您的业务逻辑。非字符串输出会序列化后给模型。context 是可选 RunContext;details 包含 toolCall、resumeState、signal 等元数据。 |
errorFunction | 否 | 自定义处理器 (context, error) => string,将内部错误转换为用户可见字符串。 |
timeoutMs | 否 | 单次调用超时(毫秒)。必须大于 0 且小于等于 2147483647。 |
timeoutBehavior | 否 | 超时模式:error_as_result(默认)返回模型可见超时消息;raise_exception 抛出 ToolTimeoutError。 |
timeoutErrorFunction | 否 | 当 timeoutBehavior 为 error_as_result 时,自定义超时输出处理器 (context, timeoutError) => string。 |
needsApproval | 否 | 执行前要求人工审批。见人机协作指南。 |
isEnabled | 否 | 按运行条件暴露工具;接受布尔值或谓词。 |
inputGuardrails | 否 | 工具执行前运行的护栏;可拒绝或抛错。见护栏。 |
outputGuardrails | 否 | 工具执行后运行的护栏;可拒绝或抛错。见护栏。 |
函数工具超时
Section titled “函数工具超时”使用 timeoutMs 限制每次函数工具调用时长。
timeoutBehavior: 'error_as_result'(默认)会向模型返回Tool '<name>' timed out after <timeoutMs>ms.。timeoutBehavior: 'raise_exception'会抛出ToolTimeoutError,可作为运行智能体异常的一部分捕获。timeoutErrorFunction允许在error_as_result模式下自定义超时文案。- 超时会中止
details.signal,因此长时工具在监听取消时可及时停止。
如果您直接调用函数工具,请使用 invokeFunctionTool 以获得与常规智能体运行一致的超时行为。
非严格 JSON-schema 工具
Section titled “非严格 JSON-schema 工具”如果您需要模型对无效或不完整输入进行猜测,可在使用原始 JSON schema 时关闭严格模式:
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 “使用工具搜索进行延迟工具加载”工具搜索让模型在运行时只加载所需工具定义,而非预先发送全部 schema。在 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[] }客户端查询格式;自定义客户端 schema 需您自行实现 Responses 循环。 - 一个命名空间可同时包含即时成员与延迟成员。即时成员无需工具搜索即可调用,同一命名空间中的延迟成员按需加载。
- 延迟函数工具与
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() 以自定义 runner 行为。
您也可以通过 asTool() 选项为智能体工具设置 needsApproval 和 isEnabled,以集成人机协作流程和条件化工具可用性。
在 customOutputExtractor 内,使用 result.agentToolInvocation 查看当前 Agent.asTool() 调用。在该回调中,结果始终来自 Agent.asTool(),因此 agentToolInvocation 一定存在,并提供 toolName、toolCallId 和 toolArguments。常规应用上下文与 toolInput 请使用 result.runContext。这些元数据仅作用于当前嵌套调用,不会序列化进 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() 的高级结构化输入选项:
inputBuilder:将结构化工具参数映射为嵌套智能体输入负载。includeInputSchema:在嵌套运行中包含输入 JSON schema,以获得更强的 schema 感知行为。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(...)处理器,agent-as-tool 就会自动以流式模式运行;否则保持非流式路径。 - 处理器并行调用,因此较慢的
onStream回调不会阻塞on(...)处理器(反之亦然)。 - 当工具通过模型工具调用触发时会提供
toolCallId;直接invoke()调用或某些 provider 差异下可能缺失。
5. MCP 服务器
Section titled “5. MCP 服务器”您可以通过 Model Context Protocol(MCP) 服务器暴露工具并挂载到智能体。例如,可使用 MCPServerStdio 启动并连接 stdio MCP 服务器:
import { Agent, MCPServerStdio } from '@openai/agents';
const server = new MCPServerStdio({ fullCommand: 'npx -y @modelcontextprotocol/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。 - 输入:严格 schema——
inputs必须至少包含一个{ type: 'text', text }或{ type: 'local_image', path }。 - 安全:将
sandboxMode与workingDirectory搭配使用;若目录不是 Git 仓库,设置skipGitRepoCheck。 - 线程:
useRunContextThreadId: true会在runContext.context中读写最新 thread id,适合在应用状态中跨轮次复用。 - Thread ID 优先级:工具调用
threadId(若 schema 包含)优先,其次运行上下文 thread id,最后codexTool({ threadId })。 - 运行上下文键:
name: 'codex'时默认为codexThreadId;name: 'engineer'这类名称则为codexThreadId_<suffix>(规范化后为codex_engineer)。 - 可变上下文要求:启用
useRunContextThreadId时,请以可变对象或Map作为run(..., { context })的context。 - 命名:工具名会规范化到
codex命名空间(engineer变为codex_engineer),同一智能体中重复 Codex 工具名会被拒绝。 - 流式:
onStream会镜像 Codex 事件(reasoning、命令执行、MCP 工具调用、文件变更、Web 搜索),便于记录或追踪进度。 - 输出:工具结果包含
response、usage、threadId,且 Codex token 用量会记录在RunContext。 - 结构:
outputSchema可为描述符、JSON schema 对象或 Zod 对象。对于 JSON 对象 schema,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 “工具策略与最佳实践”工具使用行为
Section titled “工具使用行为”关于控制模型何时以及如何必须使用工具(modelSettings.toolChoice、toolUseBehavior 等),请参阅智能体。
- 简短且明确的描述——说明工具做什么,以及何时使用。
- 校验输入——尽可能使用 Zod schema 进行严格 JSON 校验。
- 避免在错误处理器中产生副作用——
errorFunction应返回有帮助的字符串,而不是抛错。 - 每个工具只做一件事——小而可组合的工具更利于模型推理。