Thanks to visit codestin.com
Credit goes to openai.github.io

跳转到内容

工具

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

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

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

工具类型字符串目的
Web search'web_search'互联网搜索。
File / retrieval search'file_search'查询托管在 OpenAI 上的向量存储。
Computer use'computer'自动化 GUI 交互。
Shell'shell'在主机上运行 shell 命令。
Apply patch'apply_patch'将 V4A diffs 应用于本地文件。
Code Interpreter'code_interpreter'在沙盒环境中运行代码。
Image generation'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当为 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 会使用默认设置创建一个运行器,并在函数执行内用它来运行该智能体。如果你想提供任何 runConfigrunOptions 的属性,可以将它们传给 asTool() 方法来自定义运行器行为。


你可以通过 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() 以及多种托管工具类型的参考文档。