跳转到内容

工具

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

  1. 托管工具——与模型在 OpenAI 服务器上并行运行。(Web 搜索、文件搜索、计算机操作、Code Interpreter、图像生成)
  2. 函数工具——使用 JSON schema 封装任意本地函数,以便 LLM 调用。
  3. 将智能体作为工具——将整个智能体暴露为可调用的工具。
  4. 本地 MCP 服务器——连接运行在本机上的 Model Context Protocol 服务器。

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

工具类型字符串目的
Web 搜索'web_search'互联网搜索。
文件/检索搜索'file_search'查询托管在 OpenAI 上的向量存储。
计算机操作'computer'自动化 GUI 交互。
Shell'shell'在主机上运行 shell 命令。
应用补丁'apply_patch'将 V4A diff 应用于本地文件。
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 或语义过滤器)请参考官方文档。


你可以使用 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 的清晰、可读的人类描述。
parameters可以是 Zod schema 或原始 JSON schema 对象。使用 Zod 参数会自动启用 strict 模式。
strict当为 true(默认)时,若参数校验失败,SDK 会返回模型错误。将其设为 false 可进行模糊匹配。
execute(args, context) => string | Promise<string>——你的业务逻辑。可选的第二个参数为 RunContext
errorFunction自定义处理器 (context, error) => string,用于将内部错误转换为对用户可见的字符串。

如果你需要模型在输入无效或不完整时进行“猜测”,可以在使用原始 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;
},
});

有时你希望某个智能体在不完全交接会话的情况下“协助”另一个智能体。使用 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,并在函数执行中用它来运行该智能体。若你想提供任何 runConfigrunOptions 的属性,可将它们传给 asTool() 方法以自定义 runner 的行为。


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

本地 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 集成 了解详情。


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


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

  • 了解如何强制使用工具
  • 添加护栏来验证工具输入或输出。
  • 查看 TypeDoc 参考文档中的 tool() 及各类托管工具类型。