跳转到内容

工具

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

了解应由哪个智能体负责相应任务并希望赋予其相关能力后,请在阅读智能体后继续阅读本页。如果您仍在不同委派模式之间进行选择,请参阅智能体编排

  1. OpenAI 托管工具——与模型一起在 OpenAI 服务器上运行。(Web 搜索、文件搜索、code interpreter、图像生成、工具搜索)
  2. 内置执行工具——由 SDK 提供、在模型外部执行的工具。(计算机操作和 apply_patch 在本地运行;shell 可在本地或托管容器中运行)
  3. 函数工具——使用 JSON Schema 封装任意本地函数,以便 LLM 调用。
  4. Agents as tools——将整个智能体公开为可调用工具。
  5. MCP 服务器——连接本地或远程 Model Context Protocol 服务器。
  6. 沙盒能力——将工作区范围的 shell、文件系统、技能、记忆或压缩工具连接到 SandboxAgent
  7. 实验性:Codex 工具——将 Codex SDK 封装为函数工具,以运行可感知工作区的任务。

本指南的其余部分将先介绍每种工具类别,然后总结跨类别的工具选择和提示指南。

使用 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?)适合 JS 使用的选项,例如 searchContextSizeuserLocationfilters.allowedDomains
fileSearchTool(ids, options?)第一个参数接受一个或多个向量存储 ID,并支持 maxNumResultsincludeSearchResultsrankingOptions 和过滤器等选项。
codeInterpreterTool(options?)未提供 container 时,默认使用自动管理的容器。
imageGenerationTool(options?)支持图像生成配置,例如 modelsizequalitybackgroundinputFidelityinputImageMaskmoderationoutputCompressionpartialImages 和输出格式。
toolSearchTool(options?)添加内置 tool_search 辅助工具。可将其与设置了 deferLoading: true 的延迟函数工具或托管 MCP 工具配合使用。默认支持托管执行,也支持使用 execution: 'client'execute 进行客户端执行。
programmaticToolCallingTool()启用程序化工具调用。可将其与 allowedCallers 包含 'programmatic' 的工具配合使用。

这些辅助函数会将适合 JavaScript/TypeScript 使用的选项名称映射到底层 OpenAI Responses API 工具负载。有关完整的工具模式以及排名选项、语义过滤器等高级选项,请参阅 OpenAI 官方的工具指南;有关当前内置工具搜索流程和模型可用性,请参阅官方工具搜索指南;有关模型支持和传输层行为,请参阅官方程序化工具调用指南


这些工具内置于 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 }),
],
});

computerTool() 接受以下任一项:

  • 一个具体的 Computer 实例。
  • 一个初始化函数,为每次运行创建一个 Computer
  • 当您需要按运行范围执行设置和清理时,使用包含 { create, dispose } 的提供程序对象。

若要使用 OpenAI 当前的计算机操作路径,请设置支持计算机操作的模型,例如 gpt-5.4。明确指定请求模型时,SDK 会发送正式版内置 computer 工具格式。如果有效模型仍来自已存储提示或其他较旧的集成,SDK 会保留旧版 computer_use_preview 传输格式以保持兼容,除非您通过 modelSettings.toolChoice: 'computer' 明确选择正式版路径。

正式版计算机调用可在单个 computer_call 中包含批量 actions[]。SDK 会按顺序执行这些操作,针对每个操作评估 needsApproval,并将最终屏幕截图作为工具输出返回。如果您基于 interruption.rawItem 构建审批界面,请在存在 actions 时读取它,否则对旧版预览项目回退到 action

当高影响计算机操作应暂停以供用户审核时,请使用 needsApproval;如果希望确认或拒绝计算机调用报告的待处理安全检查,请使用 onSafetyCheck。有关模型端指南和迁移详情,请参阅 OpenAI 官方的计算机操作指南及其迁移说明

shellTool() 有两种模式:

  • 本地模式:提供 shell,还可以选择提供 environment: { type: 'local', skills },以及用于自动处理审批的 needsApprovalonApproval
  • 托管容器模式:提供 environment,并将 type 设置为 'container_auto''container_reference'

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

在托管容器模式下,使用以下任一方式配置 shellTool({ environment })

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

托管的 container_auto 环境支持:

  • networkPolicy,包括带有 domainSecrets 的允许列表。
  • 用于挂载已上传文件的 fileIds
  • 用于设置容器规格的 memoryLimit
  • skills,可通过 skill_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() 辅助函数将任何函数转换为工具。

使用 Zod 参数的函数工具
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 展示的清晰易懂说明。
parametersZod 模式、受支持的 Standard Schema 值或原始 JSON Schema 对象。验证模式会自动启用严格模式。
stricttrue(默认值)时,如果参数未通过验证,SDK 会返回模型错误。设置为 false 可启用宽松匹配。
execute(args, context, details) => string | unknown | Promise<...>——您的业务逻辑。非字符串输出会序列化后提供给模型。context 是可选的 RunContextdetails 包含 toolCallresumeStatesignal 等元数据。
allowedCallers仅适用于 Responses 的非空列表,用于控制工具是否可直接调用、以程序化方式调用或同时支持两者。使用 'direct''programmatic' 或同时使用这两个值。
outputSchema仅适用于 Responses 的工具结果模式。Zod 模式会约束 execute 的返回类型,并验证或转换运行时结果;原始 JSON Schema 仅描述传输契约。
errorFunction自定义处理程序 (context, error, details) => result,用于将内部错误转换为模型可见的结果。设置 outputSchema 后,结果必须满足该模式。默认处理程序已禁用,因此原始错误会被重新抛出。
timeoutMs每次调用的超时时间,以毫秒为单位。必须大于 0 且小于或等于 2147483647
timeoutBehavior超时模式:error_as_result 返回模型可见的结果,raise_exception 抛出 ToolTimeoutError。未设置 outputSchema 时默认为 error_as_result,设置后默认为 raise_exception
timeoutErrorFunctionerror_as_result 的自定义处理程序 (context, timeoutError, details) => result。设置 outputSchema 后必须提供此处理程序,并且其结果必须满足该模式。
customDataExtractor回调 (context) => Record<string, unknown> | null | undefined,用于将仅供 SDK 使用的元数据附加到发出的 RunToolCallOutputItem.customData。这些数据不会发送回模型。
needsApproval执行前需要人工批准。请参阅人机协作
isEnabled根据每次运行的情况决定是否公开工具;接受布尔值或谓词。
inputGuardrails在工具执行前运行的护栏;可以拒绝操作或抛出错误。请参阅护栏
outputGuardrails在工具执行后运行的护栏;可以拒绝操作或抛出错误。请参阅护栏

对于请求范围的能力可见性、特定环境中的可用性、功能开关或实验,请使用 isEnabled。运行器会在为当前轮次准备模型可见工具集时评估该谓词。

isEnabled 无法替代依赖工具参数或被访问资源的授权,因为该谓词会在模型生成这些参数之前运行。请在 execute 内强制执行参数级和资源级授权,或在适当情况下添加工具输入护栏审批。MCP 服务器必须对自身受保护的操作进行授权。有关将同一应用程序策略应用于函数工具、本地 MCP 工具和交接的模式,请参阅上下文管理

受支持的 Standard Schema 参数会转换为供模型使用的 JSON Schema,并在 execute 运行前进行本地验证。验证输出类型(包括库转换和默认值)将成为推断出的 execute 参数类型。有关 Valibot 示例和当前限制,请参阅模式验证

当您的应用程序需要在工具结果旁附加渲染提示、内部 ID 或其他兼容 JSON 的元数据时,请使用 customDataExtractor。该回调会接收运行上下文、工具定义、模型工具调用、解析后的输入、输出以及克隆的原始输出项。返回的数据会存储在 RunToolCallOutputItem.customDataRunState 中,但不会包含在 history 和模型重放中。

使用 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 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;
},
});

工具搜索允许模型在运行时仅加载所需的工具定义,而不必预先发送所有模式。在 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,就应将 toolSearchTool() 添加到同一个 tools 数组。
  • modelSettings.toolChoice 保持为 'auto'。SDK 不允许按名称强制调用内置 tool_search 工具或延迟函数工具。
  • 默认使用托管执行。如果设置 toolSearchTool({ execution: 'client', execute }),标准 run() 循环仅支持内置的 { paths: string[] } 客户端查询格式;自定义客户端模式需要您自行实现 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,并使用该运行器在函数工具调用中执行智能体。传入 runConfig 可配置嵌套运行器,传入 runOptions 可配置嵌套运行。

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

customOutputExtractor 内,使用 result.agentToolInvocation 检查当前 Agent.asTool() 调用。在该回调中,结果始终来自 Agent.asTool(),因此 agentToolInvocation 始终有定义,并公开 toolNametoolCallIdtoolArguments。使用 result.runContext.context 获取应用程序上下文。使用默认的单 input 模式时,result.runContext.toolInput 未定义;请改用 result.agentToolInvocation.toolArguments 读取调用参数。配置自定义 parametersinputBuilder 时,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 Schema,以获得更强的模式感知行为。
  • resumeState:控制恢复嵌套序列化 RunState 时的上下文协调策略:'merge'(默认值)将实时审批/上下文状态合并到序列化状态中;'replace' 改用当前运行上下文;'preferSerialized' 使用未更改的序列化上下文恢复运行。

智能体工具可以将所有嵌套运行事件以流式方式传回您的应用程序。请选择适合工具构建方式的钩子样式:

流式智能体工具
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(...) 处理程序,作为工具的智能体将自动以流式模式运行;未提供时,则保持非流式路径。
  • 各处理程序会并行调用,因此较慢的 onStream 回调不会阻塞 on(...) 处理程序,反之亦然。
  • 通过模型工具调用来调用该工具时会提供 toolCallId;直接调用 invoke() 或提供程序的特殊行为可能导致其缺失。

您可以通过 Model Context Protocol (MCP) 服务器公开工具,并将其连接到智能体。例如,可以使用 MCPServerStdio 生成并连接 stdio MCP 服务器:

本地 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 集成中的生命周期指南。


@openai/agents-extensions/experimental/codex 提供 codexTool(),这是一个将模型工具调用路由到 Codex SDK 的函数工具,使智能体能够自主运行工作区范围的任务(shell、文件编辑、MCP 工具)。此 API 处于实验阶段,可能会发生变化。

请先安装依赖项:

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

快速开始:

实验性 Codex 工具
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 }
  • 安全性:将 sandboxModeworkingDirectory 配合使用;如果目录不是 Git 仓库,请设置 skipGitRepoCheck
  • 线程:useRunContextThreadId: true 会在 runContext.context 中读取或存储最新线程 ID,有助于在应用程序状态中跨轮次复用线程。
  • 线程 ID 优先级:工具调用的 threadId(如果模式中包含该字段)优先级最高,其次是运行上下文线程 ID,最后是 codexTool({ threadId })
  • 运行上下文键:当 name: 'codex' 时,默认为 codexThreadId;对于 name: 'engineer' 等名称,则为 codexThreadId_<suffix>(规范化后为 codex_engineer)。
  • 可变上下文要求:启用 useRunContextThreadId 后,请将可变对象或 Map 作为 run(..., { context }) 传入。
  • 命名:工具名称会规范化到 codex 命名空间中(engineer 会变为 codex_engineer),同一智能体中的重复 Codex 工具名称会被拒绝。
  • 流式传输:onStream 会同步 Codex 事件(推理、命令执行、MCP 工具调用、文件更改、Web 搜索),以便记录日志或追踪进度。
  • 输出:工具结果包含 responseusagethreadId,Codex 的 token 使用量会记录在 RunContext 中。
  • 结构:outputSchema 可以是描述符、JSON Schema 对象或 Zod 对象。对于 JSON 对象模式,additionalProperties 必须为 false

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

Codex 运行上下文线程复用
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;

程序化工具调用允许受支持的 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()],
});

设置包括两部分:

  1. programmaticToolCallingTool() 添加到智能体。
  2. 为生成的程序可以调用的每个工具设置 allowedCallers
allowedCallers行为
省略或 ['direct']模型可以直接调用该工具。
['programmatic']只有生成的程序可以调用该工具。
['direct', 'programmatic']模型或生成的程序均可调用该工具。

SDK 支持以程序化方式调用通过 tool() 创建的工具、本地或托管的 shellTool()applyPatchTool()hostedMcpTool()codeInterpreterTool()

SDK 会在发送请求前验证配置。仅支持程序化调用的工具需要 programmaticToolCallingTool()。除非请求包含工具搜索或能够提供符合条件工具的已存储提示,否则该辅助函数还要求至少存在一个符合条件的工具。

当函数工具必须返回结构化数据时,请使用 outputSchema。Zod 模式会约束 execute 返回类型,并验证和转换运行时结果。原始 JSON Schema 会描述传输契约,但不会增加 SDK 端结果验证。无效的 Zod 结果会引发 InvalidToolOutputError

Structured outputs 也会改变失败处理方式:

  • 默认 errorFunction 已禁用,因此执行错误会被重新抛出。自定义处理程序必须返回与 outputSchema 兼容的值。
  • 默认超时行为会变为 'raise_exception'
  • 若要使用 'error_as_result',请提供返回值满足 outputSchematimeoutErrorFunction
  • 输出护栏替换的值也必须满足 outputSchema

程序化工具调用仅适用于 Responses。Chat Completions、语音智能体和 AI SDK 模型适配器不支持这些选项。如果符合条件的工具被延迟加载,工具搜索必须先加载它,后续生成的程序才能调用它。

有关完整示例,请参阅 examples/tools/programmatic-tool-calling.ts


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


  • 简短明确的说明——说明工具的作用以及使用时机
  • 输入验证——尽可能使用 Zod 或受支持的 Standard Schema 值进行严格 JSON 验证。
  • 避免错误处理程序产生副作用——errorFunction 应返回有帮助的字符串,而不是抛出错误。
  • 每个工具只承担一项职责——小型、可组合的工具有助于模型更好地推理。

  • 智能体:定义配备工具的智能体并控制 toolUseBehavior
  • 智能体编排:确定何时使用 Agents as tools,何时使用交接。
  • 运行智能体:了解执行流程、流式传输和对话状态。
  • 模型:了解托管 OpenAI 模型配置和 Responses 传输方式选择。
  • 护栏:验证工具输入或输出。
  • 深入查阅 tool() 和各种托管工具类型的 TypeDoc 参考文档。