工具
工具让智能体能够采取行动——获取数据、调用外部 API、执行代码,甚至进行计算机操作。JavaScript/TypeScript SDK 支持六大类别:
- OpenAI 托管工具——在 OpenAI 服务器上与模型并行运行。(Web 搜索、文件搜索、Code Interpreter、图像生成)
- 本地内置工具——在您的环境中运行。(计算机操作、shell、apply_patch)
- 函数工具——用 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 | 'code_interpreter' | 在沙箱环境中运行代码。 |
| 图像生成 | 'image_generation' | 基于文本生成图像。 |
import { Agent, webSearchTool, fileSearchTool } from '@openai/agents';
const agent = new Agent({ name: 'Travel assistant', tools: [webSearchTool(), fileSearchTool('VS_ID')],});精确的参数集合与 OpenAI Responses API 一致——高级选项(如 rankingOptions 或语义过滤器)请参阅官方文档。
2. 本地内置工具
Section titled “2. 本地内置工具”本地内置工具在您的环境中运行,需要您提供实现:
- 计算机操作——实现
Computer接口并传给computerTool()。 - Shell——实现
Shell接口并传给shellTool()。 - 应用补丁——实现
Editor接口并传给applyPatchTool()。
这些工具在本地执行,不由 OpenAI 托管。需要在运行时直接访问文件、终端或 GUI 自动化时使用。工具调用依然由 OpenAI 模型的响应发起,但您的应用应在本地执行它们。
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', tools: [ computerTool({ computer }), shellTool({ shell, needsApproval: true }), applyPatchTool({ editor, needsApproval: true }), ],});
void agent;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(默认)时,如果参数校验失败,SDK 会返回模型错误。设为 false 可进行模糊匹配。 |
execute | 是 | (args, context) => string | unknown | Promise<...>——您的业务逻辑。非字符串输出会序列化给模型。可选第二个参数为 RunContext。 |
errorFunction | 否 | 自定义处理器 (context, error) => string,将内部错误转换为用户可见的字符串。 |
needsApproval | 否 | 执行前需要人工批准。参见人机协作。 |
isEnabled | 否 | 按运行条件性暴露工具;接受布尔值或谓词。 |
inputGuardrails | 否 | 工具执行前运行的护栏;可拒绝或抛出。参见护栏。 |
outputGuardrails | 否 | 工具执行后运行的护栏;可拒绝或抛出。参见护栏。 |
非严格 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; },});4. Agents as tools
Section titled “4. Agents as tools”有时您希望一个智能体在不完全交接对话的情况下“协助”另一个智能体。使用 agent.asTool():
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,以集成人工干预流程和条件性工具可用性。
来自智能体工具的流式事件
Section titled “来自智能体工具的流式事件”智能体工具可以将所有嵌套运行事件流回到您的应用。根据您构建工具的方式选择合适的 hook 风格:
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()调用或部分提供商行为可能不提供它。
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 集成。
6. 实验:Codex 工具
Section titled “6. 实验:Codex 工具”@openai/agents-extensions/experimental/codex 提供 codexTool(),这是一种函数工具,可将模型的工具调用路由到 Codex SDK,使智能体能够自主运行具备工作区范围的任务(shell、文件编辑、MCP 工具)。该接口为实验性质,可能变更。
快速开始:
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.2-codex', networkAccessEnabled: true, webSearchEnabled: false, }, persistSession: true, }), ],});注意事项:
- 鉴权:提供
CODEX_API_KEY(优先)或OPENAI_API_KEY,或传入codexOptions.apiKey。 - 输入:严格 schema——
inputs至少包含一个{ type: 'text', text }或{ type: 'local_image', path }。 - 安全:将
sandboxMode与workingDirectory搭配使用;如果目录不是 Git 仓库,请设置skipGitRepoCheck。 - 行为:
persistSession: true会复用单个 Codex 线程并返回其threadId;您可将其用于可恢复的工作。 - 流式传输:
onStream映射 Codex 事件(推理、命令执行、MCP 工具调用、文件变更、Web 搜索),便于记录或追踪进度。 - 输出:工具结果包含
response、usage和threadId,Codex 的 token 使用量会记录在RunContext中。 - 结构:
outputSchema在需要类型化输出时,可对单轮 Codex 响应强制采用 structured outputs。
工具使用行为
Section titled “工具使用行为”关于控制模型何时及如何必须使用工具(tool_choice、toolUseBehavior 等),请参阅智能体。
- 简短且明确的描述——说明工具做什么,以及何时使用。
- 校验输入——尽可能使用 Zod schema 进行严格的 JSON 校验。
- 避免在错误处理器中产生副作用——
errorFunction应返回有用的字符串,而不是抛出异常。 - 单一职责——小而可组合的工具有助于更好的模型推理。