跳转到内容

工具

工具让智能体能够执行操作——获取数据、调用外部 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 交互。
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。
parametersZod 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 应返回有用的字符串,而不是抛出异常。
  • 单一职责——小而可组合的工具有助于更好的模型推理。