跳转到内容

工具

工具让智能体能够执行操作——获取数据、调用外部 API、执行代码,甚至操作计算机。JavaScript/TypeScript SDK 支持六大类别:

在阅读完智能体后再阅读本页:当您已经确定由哪个智能体负责该任务,并希望为其赋予能力时使用本页。如果您仍在选择委派模式,请参阅智能体编排

  1. OpenAI 托管工具——与模型一起在 OpenAI 服务器上运行。(Web 搜索、文件搜索、代码解释器、图像生成、工具搜索)
  2. 内置执行工具——由 SDK 提供、在模型之外执行的工具。(计算机操作和 apply_patch 在本地运行;shell 可在本地或托管容器中运行)
  3. 函数工具——用 JSON schema 封装任意本地函数,供 LLM 调用。
  4. Agents as tools——将整个智能体暴露为可调用工具。
  5. MCP 服务器——挂载 Model Context Protocol 服务器(本地或远程)。
  6. 实验性:Codex 工具——将 Codex SDK 封装为函数工具,以执行感知工作区的任务。

本指南其余部分将先介绍各类工具,再总结跨类别的工具选择与提示词实践。

使用 OpenAIResponsesModel 时,您可以添加以下内置工具:

工具类型字符串用途
Web 搜索'web_search'互联网搜索。
文件/检索搜索'file_search'查询 OpenAI 托管的向量存储。
代码解释器'code_interpreter'在沙箱环境中运行代码。
图像生成'image_generation'根据文本生成图像。
工具搜索'tool_search'在运行时加载延迟函数工具、命名空间或可搜索 MCP 工具。
Hosted tools
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 友好的选项,如 searchContextSizeuserLocationfilters.allowedDomains
fileSearchTool(ids, options?)第一个参数接收一个或多个向量存储 ID,另可传入 maxNumResultsincludeSearchResultsrankingOptions 和过滤器等选项。
codeInterpreterTool(options?)未提供 container 时默认使用自动管理的容器。
imageGenerationTool(options?)支持图像生成配置,如 modelsizequalitybackgroundinputFidelityinputImageMaskmoderationoutputCompressionpartialImages 和输出格式。
toolSearchTool(options?)添加内置 tool_search 辅助工具。可与设置了 deferLoading: true 的延迟函数工具或托管 MCP 工具配合。默认支持托管执行,也可通过 execution: 'client'execute 使用客户端执行。

这些辅助函数会将 JavaScript/TypeScript 友好的选项名映射到底层 OpenAI Responses API 工具负载。完整工具 schema 与高级选项(如 ranking options、semantic filters)请参考官方OpenAI 工具指南,当前内置工具搜索流程与模型可用性请参考官方工具搜索指南


这些工具内置于 SDK,但执行发生在模型响应之外:

  • 计算机操作——实现 Computer 接口并传给 computerTool()。这始终针对您提供的本地 Computer 实现运行。
  • Shell——可提供本地 Shell 实现,或通过 shellTool({ environment }) 配置托管容器环境。
  • Apply patch——实现 Editor 接口并传给 applyPatchTool()。这始终针对您提供的本地 Editor 实现运行。

工具调用仍由模型发起,但实际工作由您的应用或配置的执行环境完成。

Built-in execution tools
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 }),
],
});

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 计算机操作指南及其迁移说明

shellTool() 有两种模式:

  • 本地模式:提供 shell,并可选 environment: { type: 'local', skills },以及 needsApprovalonApproval 以处理自动审批。
  • 托管容器模式:提供 environment,其中 typecontainer_autocontainer_reference

在本地模式中,environment.skills 允许通过 namedescription 和文件系统 path 挂载本地 skills。

在托管容器模式中,通过 shellTool({ environment }) 配置:

  • type: 'container_auto':为本次运行创建托管容器。
  • type: 'container_reference':通过 containerId 复用现有容器。

托管 container_auto 环境支持:

  • networkPolicy,包括带 domainSecrets 的允许列表。
  • 用于挂载上传文件的 fileIds
  • 用于容器规格的 memoryLimit
  • skillsskill_reference 或内联 zip 包)。

托管 shell 环境不接受 shellneedsApprovalonApproval,因为执行发生在托管容器环境而非本地进程中。

端到端用法参见 examples/tools/local-shell.tsexamples/tools/container-shell-skill-ref.tsexamples/tools/container-shell-inline-skill.ts

applyPatchTool()shellTool() 的本地审批流程一致:使用 needsApproval 在文件编辑前暂停,使用 onApproval 通过应用层回调自动批准或拒绝。


您可以用 tool() 辅助函数将任意函数变成工具。

Function tool with Zod parameters
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 参数会自动启用严格模式。
stricttrue(默认)时,参数校验失败会返回模型错误。设为 false 可进行模糊匹配。
execute(args, context, details) => string | unknown | Promise<...>——您的业务逻辑。非字符串输出会序列化后给模型。context 是可选 RunContextdetails 包含 toolCallresumeStatesignal 等元数据。
errorFunction自定义处理器 (context, error) => string,将内部错误转换为用户可见字符串。
timeoutMs单次调用超时(毫秒)。必须大于 0 且小于等于 2147483647
timeoutBehavior超时模式:error_as_result(默认)返回模型可见超时消息;raise_exception 抛出 ToolTimeoutError
timeoutErrorFunctiontimeoutBehaviorerror_as_result 时,自定义超时输出处理器 (context, timeoutError) => string
needsApproval执行前要求人工审批。见人机协作指南
isEnabled按运行条件暴露工具;接受布尔值或谓词。
inputGuardrails工具执行前运行的护栏;可拒绝或抛错。见护栏
outputGuardrails工具执行后运行的护栏;可拒绝或抛错。见护栏

使用 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 时关闭严格模式:

Non-strict JSON schema tools
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 中使用工具搜索。

Deferred tool loading with tool search
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 工具加载流程。

有时您希望一个智能体协助另一个智能体,而不是完全交接对话。可使用 agent.asTool()

如果您仍在 agent.asTool()handoff() 之间选择,请对比智能体智能体编排中的模式。

Agents as tools
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,并在函数执行中运行该智能体。若要提供 runConfigrunOptions 的任意属性,可将它们传入 asTool() 以自定义 runner 行为。

您也可以通过 asTool() 选项为智能体工具设置 needsApprovalisEnabled,以集成人机协作流程和条件化工具可用性。

customOutputExtractor 内,使用 result.agentToolInvocation 查看当前 Agent.asTool() 调用。在该回调中,结果始终来自 Agent.asTool(),因此 agentToolInvocation 一定存在,并提供 toolNametoolCallIdtoolArguments。常规应用上下文与 toolInput 请使用 result.runContext。这些元数据仅作用于当前嵌套调用,不会序列化进 RunState

Read agent tool invocation metadata
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' 则按序列化上下文原样恢复。

智能体工具可将所有嵌套运行事件流式回传到您的应用。请根据工具构建方式选择适合的钩子风格:

Streaming agent tools
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_eventrun_item_stream_eventagent_updated_stream_event
  • onStream 是最简单的“全量捕获”,适合内联声明工具(tools: [agent.asTool({ onStream })])。若不需要按事件路由,优先使用它。
  • on(eventName, handler) 允许选择性订阅(或用 '*'),适合需要更细粒度处理或希望创建后再挂监听器的场景。
  • 只要提供了 onStream 或任一 on(...) 处理器,agent-as-tool 就会自动以流式模式运行;否则保持非流式路径。
  • 处理器并行调用,因此较慢的 onStream 回调不会阻塞 on(...) 处理器(反之亦然)。
  • 当工具通过模型工具调用触发时会提供 toolCallId;直接 invoke() 调用或某些 provider 差异下可能缺失。

您可以通过 Model Context Protocol(MCP) 服务器暴露工具并挂载到智能体。例如,可使用 MCPServerStdio 启动并连接 stdio MCP 服务器:

Local MCP server
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 集成中的生命周期指导。


@openai/agents-extensions/experimental/codex 提供 codexTool():这是一个函数工具,可将模型工具调用路由到 Codex SDK,使智能体能够自主执行工作区范围任务(shell、文件编辑、MCP 工具)。该能力为实验性,后续可能变化。

请先安装依赖:

Terminal window
npm install @openai/agents-extensions @openai/codex-sdk

快速开始:

Experimental Codex tool
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 }
  • 安全:将 sandboxModeworkingDirectory 搭配使用;若目录不是 Git 仓库,设置 skipGitRepoCheck
  • 线程:useRunContextThreadId: true 会在 runContext.context 中读写最新 thread id,适合在应用状态中跨轮次复用。
  • Thread ID 优先级:工具调用 threadId(若 schema 包含)优先,其次运行上下文 thread id,最后 codexTool({ threadId })
  • 运行上下文键:name: 'codex' 时默认为 codexThreadIdname: 'engineer' 这类名称则为 codexThreadId_<suffix>(规范化后为 codex_engineer)。
  • 可变上下文要求:启用 useRunContextThreadId 时,请以可变对象或 Map 作为 run(..., { context })context
  • 命名:工具名会规范化到 codex 命名空间(engineer 变为 codex_engineer),同一智能体中重复 Codex 工具名会被拒绝。
  • 流式:onStream 会镜像 Codex 事件(reasoning、命令执行、MCP 工具调用、文件变更、Web 搜索),便于记录或追踪进度。
  • 输出:工具结果包含 responseusagethreadId,且 Codex token 用量会记录在 RunContext
  • 结构:outputSchema 可为描述符、JSON schema 对象或 Zod 对象。对于 JSON 对象 schema,additionalProperties 必须为 false

运行上下文线程复用示例:

Codex run-context thread reuse
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;

关于控制模型何时以及如何必须使用工具(modelSettings.toolChoicetoolUseBehavior 等),请参阅智能体


  • 简短且明确的描述——说明工具做什么,以及何时使用
  • 校验输入——尽可能使用 Zod schema 进行严格 JSON 校验。
  • 避免在错误处理器中产生副作用——errorFunction 应返回有帮助的字符串,而不是抛错。
  • 每个工具只做一件事——小而可组合的工具更利于模型推理。

  • 智能体:定义可携带工具的智能体,并控制 toolUseBehavior
  • 智能体编排:判断何时使用 agents as tools,何时使用交接。
  • 运行智能体:执行流程、流式传输与对话状态。
  • 模型:OpenAI 托管模型配置与 Responses 传输选择。
  • 护栏:校验工具输入或输出。
  • 深入查看 tool() 及各类托管工具类型的 TypeDoc 参考。