Skip to content

使用工具

在生成模型响应或构建代理时,你可以通过内置工具、函数调用、工具搜索和远程 MCP 服务器来扩展模型能力。这些工具使模型能够搜索网页、从你的文件中检索信息、在运行时加载延迟的工具定义、调用你自己的函数,或访问第三方服务。只有 gpt-5.4 及之后的模型支持 tool_search

可用工具

以下是 OpenAI 平台中可用工具的概览:

工具说明
函数调用调用自定义代码,让模型访问额外数据与能力
网页搜索在模型响应生成中包含来自互联网的数据
MCP 连接器通过 Model Context Protocol (MCP) 服务器为模型提供新能力
Skills上传并复用版本化的技能包到托管 shell 环境中
Shell在托管容器或本地运行时中执行 shell 命令
计算机使用创建代理工作流,让模型控制计算机界面
图像生成使用 GPT Image 生成或编辑图像
文件搜索在生成响应时搜索已上传文件的内容作为上下文
工具搜索动态加载相关工具到模型上下文中,优化 token 使用

在 API 中使用

当你发起模型响应请求时,通常通过在 tools 参数中指定配置来启用工具访问。每个工具都有自己独特的配置要求,详见上方的可用工具列表。

模型会根据提供的提示词自动决定是否使用已配置的工具。例如,如果你的提示词请求的信息超出了模型训练截止日期,并且启用了网页搜索,模型通常会调用网页搜索工具来获取相关的最新信息。

某些高级工作流还可以在交互过程中加载更多工具定义。例如,工具搜索可以延迟函数定义,直到模型判断需要它们时再加载。

你可以通过在 API 请求中设置 tool_choice 参数来显式控制或引导这一行为。

工具使用示例

文件搜索

在响应中搜索你的文件:

python
from openai import OpenAI
client = OpenAI()

response = client.responses.create(
    model="gpt-5.5",
    input="What is deep research by OpenAI?",
    tools=[{
        "type": "file_search",
        "vector_store_ids": ["<vector_store_id>"]
    }]
)
print(response)
javascript
import OpenAI from "openai";
const openai = new OpenAI();

const response = await openai.responses.create({
    model: "gpt-5.5",
    input: "What is deep research by OpenAI?",
    tools: [
        {
            type: "file_search",
            vector_store_ids: ["<vector_store_id>"],
        },
    ],
});
console.log(response);
csharp
using OpenAI.Responses;

string key = Environment.GetEnvironmentVariable("XIKAPI_API_KEY")!;
OpenAIResponseClient client = new(model: "gpt-5.5", apiKey: key);

ResponseCreationOptions options = new();
options.Tools.Add(ResponseTool.CreateFileSearchTool(["<vector_store_id>"]));

OpenAIResponse response = (OpenAIResponse)client.CreateResponse([
    ResponseItem.CreateUserMessageItem([
        ResponseContentPart.CreateInputTextPart("What is deep research by OpenAI?"),
    ]),
], options);

Console.WriteLine(response.GetOutputText());

远程 MCP

调用远程 MCP 服务器:

bash
curl https://xikapi.com/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XIKAPI_API_KEY" \
  -d '{
    "model": "gpt-5.5",
    "tools": [
      {
        "type": "mcp",
        "server_label": "dmcp",
        "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",
        "server_url": "https://dmcp-server.deno.dev/sse",
        "require_approval": "never"
      }
    ],
    "input": "Roll 2d4+1"
  }'
javascript
import OpenAI from "openai";
const client = new OpenAI();

const resp = await client.responses.create({
  model: "gpt-5.5",
  tools: [
    {
      type: "mcp",
      server_label: "dmcp",
      server_description: "A Dungeons and Dragons MCP server to assist with dice rolling.",
      server_url: "https://dmcp-server.deno.dev/sse",
      require_approval: "never",
    },
  ],
  input: "Roll 2d4+1",
});

console.log(resp.output_text);
python
from openai import OpenAI

client = OpenAI()

resp = client.responses.create(
    model="gpt-5.5",
    tools=[
        {
            "type": "mcp",
            "server_label": "dmcp",
            "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",
            "server_url": "https://dmcp-server.deno.dev/sse",
            "require_approval": "never",
        },
    ],
    input="Roll 2d4+1",
)

print(resp.output_text)
csharp
using OpenAI.Responses;

string key = Environment.GetEnvironmentVariable("XIKAPI_API_KEY")!;
OpenAIResponseClient client = new(model: "gpt-5.5", apiKey: key);

ResponseCreationOptions options = new();
options.Tools.Add(ResponseTool.CreateMcpTool(
    serverLabel: "dmcp",
    serverUri: new Uri("https://dmcp-server.deno.dev/sse"),
    toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.NeverRequireApproval)
));

OpenAIResponse response = (OpenAIResponse)client.CreateResponse([
    ResponseItem.CreateUserMessageItem([
        ResponseContentPart.CreateInputTextPart("Roll 2d4+1")
    ])
], options);

Console.WriteLine(response.GetOutputText());

在 Agents SDK 中使用

在 Agents SDK 中,工具的语义保持不变,但接线方式从单个 Responses API 请求转移到了代理定义和工作流设计中。

  • 将托管工具、函数工具或托管 MCP 工具直接附加到代理上
  • 将专家代理暴露为工具,让管理者代理保持对用户回复的控制
  • 在你的运行时中保留 shell、apply patch 和 computer-use 工具

将本地逻辑包装为函数工具

typescript
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.`;
  },
});
python
from agents import function_tool


@function_tool
def get_weather(city: str) -> str:
    """Get the weather for a given city."""
    return f"The weather in {city} is sunny."

将专家代理暴露为工具

typescript
import { Agent } from "@openai/agents";

const summarizer = new Agent({
  name: "Summarizer",
  instructions: "Generate a concise summary of the supplied text.",
});

const mainAgent = new Agent({
  name: "Research assistant",
  tools: [
    summarizer.asTool({
      toolName: "summarize_text",
      toolDescription: "Generate a concise summary of the supplied text.",
    }),
  ],
});
python
from agents import Agent

summarizer = Agent(
    name="Summarizer",
    instructions="Generate a concise summary of the supplied text.",
)

main_agent = Agent(
    name="Research assistant",
    tools=[
        summarizer.as_tool(
            tool_name="summarize_text",
            tool_description="Generate a concise summary of the supplied text.",
        )
    ],
)

更多关于代理定义、编排与交接、安全护栏与人工审核、集成与可观测性的内容,请参考 Agents SDK 文档。