工具
工具让智能体采取行动——获取数据、调用外部 API、执行代码,甚至进行计算机操作。JavaScript/TypeScript SDK 支持四个类别:
- 托管工具——与模型一同在 OpenAI 服务器上运行。(Web 搜索、文件搜索、计算机操作、Code Interpreter、图像生成)
- 函数工具——使用 JSON schema 封装任意本地函数,便于 LLM 调用。
- 智能体作为工具——将整个智能体暴露为可调用的工具。
- 本地 MCP 服务器——挂载运行在你机器上的 Model Context Protocol 服务器。
1. 托管工具
Section titled “1. 托管工具”当你使用 OpenAIResponsesModel
时,可以添加以下内置工具:
工具 | 类型字符串 | 目的 |
---|---|---|
Web search | 'web_search' | 互联网搜索。 |
File / retrieval search | 'file_search' | 查询 OpenAI 托管的向量存储。 |
Computer use | 'computer' | 自动化 GUI 交互。 |
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
或语义过滤等高级选项。
2. 函数工具
Section titled “2. 函数工具”你可以用 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 | Promise<string> ——你的业务逻辑。可选的第二个参数为 RunContext 。 |
errorFunction | 否 | 自定义处理器 (context, error) => string ,用于将内部错误转换为对用户可见的字符串。 |
非严格 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; },});
3. 智能体作为工具
Section titled “3. 智能体作为工具”有时你希望一个智能体在不完全交接对话的情况下“协助”另一个智能体。使用 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 会使用默认设置创建一个运行器,并在函数执行中用它运行该智能体。如果你想提供任何 runConfig
或 runOptions
的属性,可以将它们传递给 asTool()
方法以自定义运行器行为。
4. MCP 服务器
Section titled “4. 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 集成 获取详情。
工具使用行为
Section titled “工具使用行为”参见智能体,了解如何控制模型何时以及如何必须使用工具(tool_choice
、toolUseBehavior
等)。
- 简短且明确的描述——说明工具做什么,以及何时使用。
- 验证输入——尽可能使用 Zod schema 进行严格的 JSON 验证。
- 避免在错误处理器中产生副作用——
errorFunction
应返回有用的字符串,而不是抛出异常。 - 单一职责——小而可组合的工具有助于更好的模型推理。