工具
工具让智能体可以采取行动——获取数据、调用外部 API、执行代码,甚至进行计算机操作。JavaScript/TypeScript SDK 支持四种类别:
- 托管工具——与模型一起在 OpenAI 服务器上运行。(Web 搜索、文件搜索、计算机操作、Code Interpreter、图像生成)
- 函数工具——用 JSON schema 封装任意本地函数,使 LLM 能调用。
- 将智能体作为工具——将整个智能体暴露为可调用的工具。
- 本地 MCP 服务器——挂载在你机器上运行的 Model Context Protocol 服务器。
1. 托管工具
Section titled “1. 托管工具”使用 OpenAIResponsesModel 时,你可以添加以下内置工具:
| 工具 | 类型字符串 | 目的 |
|---|---|---|
| Web 搜索 | 'web_search' | 互联网搜索。 |
| 文件/检索搜索 | 'file_search' | 查询托管在 OpenAI 的向量存储。 |
| 计算机操作 | 'computer' | 自动化 GUI 交互。 |
| Shell | 'shell' | 在主机上运行 shell 命令。 |
| Apply patch | '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 或语义过滤请参见官方文档。
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 模式。 |
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() 方法以自定义运行器行为。
从智能体工具进行流式传输事件
Section titled “从智能体工具进行流式传输事件”智能体工具可以将所有嵌套运行事件流式返回到你的应用。根据你构建工具的方式选择合适的钩子风格:
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()调用或某些提供方的特殊行为可能不会提供它。
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应返回有用的字符串,而不是抛出异常。 - 单一职责的工具——小而可组合的工具能带来更好的模型推理效果。