codecamp

OpenAI 工具搜索

工具搜索让模型按需动态查找并加载工具,无需一开始把全部定义放入上下文,可能降低总词元用量和成本。它按保留模型缓存的方式设计:新发现的工具插入上下文末尾,以改善成本和延迟。

Responses API只有 gpt-5.4 及后续模型支持 tool_search。以下配置和示例针对Responses;基于会话的函数加载与MCP自动发现参见Agents API。

启用需要两步:在 tools 数组加入 tool_search;对要延迟的函数设置 defer_loading: true,或在MCP服务器工具定义上设置该属性。

尽可能使用命名空间

工具搜索支持延迟函数、命名空间和MCP服务器,推荐后两者:模型主要针对这些形式训练,通常也能节省更多词元。命名空间中的 defer_loading 应设在内部函数上,而非命名空间对象自身。

请求开始时模型仍看到可搜索对象的名称与描述。对命名空间或MCP服务器,初始只有整体名称与描述,内部函数细节到搜索加载后才出现。单个延迟函数仍暴露名称和描述,因此主要延迟的是参数模式。

应把延迟函数按明确、高层用途分组,帮助模型只加载相关功能。最佳实践是每个命名空间尽量少于10个函数,以改善词元效率和表现。

来源示例1(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

程序中的自然语言译释24:

用于查找客户与管理订单的CRM工具。

程序中的自然语言译释27:

按客户ID列出尚未关闭的订单。

{
    "tools": [
      {
// highlight-start:subtle
        "type": "namespace",
// highlight-end
        "name": "crm",
        "description": "CRM tools for customer lookup and order management.",
        "tools": [
          {
            "type": "function",
            "name": "list_open_orders",
            "description": "List open orders for a customer ID.",
// highlight-start:subtle
            "defer_loading": true,
// highlight-end
            "parameters": {
              "type": "object",
              "properties": {
                "customer_id": { "type": "string" }
              },
              "required": ["customer_id"],
              "additionalProperties": false
            }
          }
        ]
      },
      {
        "type": "tool_search"
      }
    ]
  }

同一命名空间可以混合立即可用与延迟工具。未设置 defer_loading: true 的工具立即可调用,其余通过搜索加载。

工具搜索的类型

  • 托管搜索:OpenAI在请求已声明的延迟工具中搜索,同一响应返回加载的子集。
  • 客户端执行搜索:模型返回 tool_search_call,应用检索,再返回匹配的 tool_search_output。

请求时已知全部候选工具,先选托管搜索。工具发现依赖项目、租户或应用控制的其他系统状态时,选客户端搜索。

托管工具搜索

已知全部函数、命名空间或MCP服务器清单时,这是最简单的方式。预先声明它们,加入 {"type": "tool_search"},由API决定加载哪些。

来源示例2(javascript)

程序中的自然语言译释25:

列出客户CUST-12345尚未关闭的订单。

程序中的自然语言译释26:

按客户ID获取客户资料。

本段复用的中文释义:译释24、译释27。

// [中文] 声明CRM命名空间内的延迟函数,加入托管tool_search。
import OpenAI from "openai";

const client = new OpenAI();

const crmNamespace = {
  type: "namespace",
  name: "crm",
  description: "CRM tools for customer lookup and order management.",
  tools: [
    {
      type: "function",
      name: "get_customer_profile",
      description: "Fetch a customer profile by customer ID.",
      parameters: {
        type: "object",
        properties: {
          customer_id: { type: "string" },
        },
        required: ["customer_id"],
        additionalProperties: false,
      },
    },
    {
      type: "function",
      name: "list_open_orders",
      description: "List open orders for a customer ID.",
      // [中文] 来源展示标记:高亮开始。
      // highlight-start:subtle
      defer_loading: true,
      // [中文] 来源展示标记:高亮结束。
      // highlight-end
      parameters: {
        type: "object",
        properties: {
          customer_id: { type: "string" },
        },
        required: ["customer_id"],
        additionalProperties: false,
      },
    },
  ],
};

const response = await client.responses.create({
  model: "gpt-6-astra",
  input: "List open orders for customer CUST-12345.",
  // [中文] 来源展示标记:高亮开始。
  // highlight-start:subtle
  tools: [crmNamespace, { type: "tool_search" }],
  // [中文] 来源展示标记:高亮结束。
  // highlight-end
  parallel_tool_calls: false,
});

console.log(response.output);

来源示例3(python)

本段复用的中文释义:译释24、译释25、译释26、译释27。

## [中文] 声明CRM命名空间内的延迟函数,加入托管tool_search。
from openai import OpenAI

client = OpenAI()

crm_namespace = {
    "type": "namespace",
    "name": "crm",
    "description": "CRM tools for customer lookup and order management.",
    "tools": [
        {
            "type": "function",
            "name": "get_customer_profile",
            "description": "Fetch a customer profile by customer ID.",
            "parameters": {
                "type": "object",
                "properties": {
                    "customer_id": {"type": "string"},
                },
                "required": ["customer_id"],
                "additionalProperties": False,
            },
        },
        {
            "type": "function",
            "name": "list_open_orders",
            "description": "List open orders for a customer ID.",
            # [中文] 来源展示标记:高亮开始。
            # highlight-start:subtle
            "defer_loading": True,
            # [中文] 来源展示标记:高亮结束。
            # highlight-end
            "parameters": {
                "type": "object",
                "properties": {
                    "customer_id": {"type": "string"},
                },
                "required": ["customer_id"],
                "additionalProperties": False,
            },
        },
    ],
}

response = client.responses.create(
    model="gpt-6-astra",
    input="List open orders for customer CUST-12345.",
    tools=[
        crm_namespace,
        # [中文] 来源展示标记:高亮开始。
        # highlight-start:subtle
        {"type": "tool_search"},
        # [中文] 来源展示标记:高亮结束。
        # highlight-end
    ],
    parallel_tool_calls=False,
)

print(response.output)

来源示例4(go)

本段复用的中文释义:译释24、译释25、译释26、译释27。

// [中文] 声明CRM命名空间内的延迟函数,加入托管tool_search。
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/responses"
)

func main() {
    client := openai.NewClient()
    parameters := map[string]any{
        "type":                 "object",
        "properties":           map[string]any{"customer_id": map[string]any{"type": "string"}},
        "required":             []string{"customer_id"},
        "additionalProperties": false,
    }
    namespace := responses.ToolParamOfNamespace(
        "CRM tools for customer lookup and order management.",
        "crm",
        []responses.NamespaceToolToolUnionParam{
            {OfFunction: &responses.NamespaceToolToolFunctionParam{
                Name: "get_customer_profile", Description: openai.String("Fetch a customer profile by customer ID."), Parameters: parameters,
            }},
            {OfFunction: &responses.NamespaceToolToolFunctionParam{
                Name: "list_open_orders", Description: openai.String("List open orders for a customer ID."), DeferLoading: openai.Bool(true), Parameters: parameters,
            }},
        },
    )
    response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model:             "gpt-6-astra",
        Input:             responses.ResponseNewParamsInputUnion{OfString: openai.String("List open orders for customer CUST-12345.")},
        Tools:             []responses.ToolUnionParam{namespace, {OfToolSearch: &responses.ToolSearchToolParam{}}},
        ParallelToolCalls: openai.Bool(false),
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(response.Output)
}

来源示例5(java)

本段复用的中文释义:译释24、译释25、译释26、译释27。

// [中文] 声明CRM命名空间内的延迟函数,加入托管tool_search。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.NamespaceTool;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ToolSearchTool;
import java.util.List;
import java.util.Map;

ResponseCreateParams params =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .input("List open orders for customer CUST-12345.")
        .parallelToolCalls(false)
        .addTool(
            NamespaceTool.builder()
                .name("crm")
                .description("CRM tools for customer lookup and order management.")
                .addTool(
                    NamespaceTool.Tool.Function.builder()
                        .name("get_customer_profile")
                        .description("Fetch a customer profile by customer ID.")
                        .strict(true)
                        .parameters(
                            JsonValue.from(
                                Map.of(
                                    "type",
                                    "object",
                                    "properties",
                                    Map.of("customer_id", Map.of("type", "string")),
                                    "required",
                                    List.of("customer_id"),
                                    "additionalProperties",
                                    false)))
                        .build())
                .addTool(
                    NamespaceTool.Tool.Function.builder()
                        .name("list_open_orders")
                        .description("List open orders for a customer ID.")
                        .deferLoading(true)
                        .strict(true)
                        .parameters(
                            JsonValue.from(
                                Map.of(
                                    "type",
                                    "object",
                                    "properties",
                                    Map.of("customer_id", Map.of("type", "string")),
                                    "required",
                                    List.of("customer_id"),
                                    "additionalProperties",
                                    false)))
                        .build())
                .build())
        .addTool(ToolSearchTool.builder().execution(ToolSearchTool.Execution.SERVER).build())
        .build();

client.responses().create(params).output().forEach(System.out::println);

来源示例6(ruby)

本段复用的中文释义:译释24、译释25、译释26、译释27。

## [中文] 声明CRM命名空间内的延迟函数,加入托管tool_search。
require "openai"

client = OpenAI::Client.new
parameters = {
  type: :object,
  properties: { customer_id: { type: :string } },
  required: ["customer_id"],
  additionalProperties: false
}
response = client.responses.create(
  model: "gpt-6-astra",
  input: "List open orders for customer CUST-12345.",
  parallel_tool_calls: false,
  tools: [
    {
      type: :namespace,
      name: "crm",
      description: "CRM tools for customer lookup and order management.",
      tools: [
        {
          type: :function,
          name: "get_customer_profile",
          description: "Fetch a customer profile by customer ID.",
          parameters: parameters
        },
        {
          type: :function,
          name: "list_open_orders",
          description: "List open orders for a customer ID.",
          defer_loading: true,
          parameters: parameters
        }
      ]
    },
    { type: :tool_search }
  ]
)

puts(response.output)

模型判断需要延迟工具时,实际函数调用之前会出现两个额外输出项:记录搜索步骤的 tool_search_call,以及包含已加载、随后可调用工具子集的 tool_search_output。

来源示例7(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

本段复用的中文释义:译释24、译释27。

[
  {
    // highlight-start:subtle
    "type": "tool_search_call",
    // highlight-end
    "execution": "server",
    "call_id": null,
    "status": "completed",
    "arguments": {
      "paths": ["crm"]
    }
  },
  {
    // highlight-start:subtle
    "type": "tool_search_output",
    // highlight-end
    "execution": "server",
    "call_id": null,
    "status": "completed",
    "tools": [
      {
        "type": "namespace",
        "name": "crm",
        "description": "CRM tools for customer lookup and order management.",
        "tools": [
          {
            "type": "function",
            "name": "list_open_orders",
            "description": "List open orders for a customer ID.",
            "defer_loading": true,
            "parameters": {
              "type": "object",
              "properties": {
                "customer_id": { "type": "string" }
              },
              "required": ["customer_id"],
              "additionalProperties": false
            }
          }
        ]
      }
    ]
  },
  {
    "type": "function_call",
    "name": "list_open_orders",
    "namespace": "crm",
    "call_id": "call_abc123",
    "arguments": "{\"customer_id\":\"CUST-12345\"}"
  }
]

托管模式中 execution: server、call_id: null。复杂任务也可在同一个 tool_search_call 中一起加载多个命名空间或MCP服务器,再调用各自函数。

客户端执行工具搜索

应用完全控制发现过程,适合不便在初始 tools 清单中声明全部工具的情况。将 execution 设为 client,并定义应用期望的搜索参数模式。

来源示例8(javascript)

程序中的自然语言译释92:

先找到查询预计送达时间的工具,再查询order_42。

程序中的自然语言译释93:

查询订单预计送达时间详情。

程序中的自然语言译释94:

查找继续当前任务所需的项目专用工具。

// [中文] 配置execution为client的搜索工具,应用需检索并返回工具定义。
import OpenAI from "openai";
import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems";

const client = new OpenAI();

const firstResponse = await client.responses.create({
  model: "gpt-6-astra",
  input: "Find the shipping ETA tool first, then use it for order_42.",
  tools: [
    {
      type: "tool_search",
      // [中文] 来源展示标记:高亮开始。
      // highlight-start:subtle
      execution: "client",
      // [中文] 来源展示标记:高亮结束。
      // highlight-end
      description:
        "Find the project-specific tools needed to continue the task.",
      parameters: {
        type: "object",
        properties: {
          goal: { type: "string" },
        },
        required: ["goal"],
        additionalProperties: false,
      },
    },
  ],
  parallel_tool_calls: false,
});

const searchCall = firstResponse.output.find(
  (item) => item.type === "tool_search_call"
);

if (!searchCall) {
  throw new Error("The response did not include a tool search call.");
}

const loadedTools = [
  {
    type: "function",
    name: "get_shipping_eta",
    description: "Look up shipping ETA details for an order.",
    defer_loading: true,
    parameters: {
      type: "object",
      properties: {
        order_id: { type: "string" },
      },
      required: ["order_id"],
      additionalProperties: false,
    },
    strict: true,
  },
];

const searchOutput = {
  type: "tool_search_output",
  execution: "client",
  call_id: searchCall.call_id,
  status: "completed",
  tools: loadedTools,
};

const secondResponse = await client.responses.create({
  model: "gpt-6-astra",
  input: [
    ...toResponseInputItems(firstResponse.output),
    // [中文] 来源展示标记:高亮开始。
    // highlight-start:subtle
    searchOutput,
    // [中文] 来源展示标记:高亮结束。
    // highlight-end
  ],
});

console.log(secondResponse.output);

来源示例9(python)

本段复用的中文释义:译释92、译释93、译释94。

## [中文] 配置execution为client的搜索工具,应用需检索并返回工具定义。
from openai import OpenAI

client = OpenAI()

first_response = client.responses.create(
    model="gpt-6-astra",
    input="Find the shipping ETA tool first, then use it for order_42.",
    tools=[
        {
            "type": "tool_search",
            # [中文] 来源展示标记:高亮开始。
            # highlight-start:subtle
            "execution": "client",
            # [中文] 来源展示标记:高亮结束。
            # highlight-end
            "description": "Find the project-specific tools needed to continue the task.",
            "parameters": {
                "type": "object",
                "properties": {
                    "goal": {"type": "string"},
                },
                "required": ["goal"],
                "additionalProperties": False,
            },
        }
    ],
    parallel_tool_calls=False,
)

search_call = next(
    item for item in first_response.output if item.type == "tool_search_call"
)

loaded_tools = [
    {
        "type": "function",
        "name": "get_shipping_eta",
        "description": "Look up shipping ETA details for an order.",
        "defer_loading": True,
        "parameters": {
            "type": "object",
            "properties": {
                "order_id": {"type": "string"},
            },
            "required": ["order_id"],
            "additionalProperties": False,
        },
    }
]

second_response = client.responses.create(
    model="gpt-6-astra",
    input=[
        *first_response.output,
        {
            # [中文] 来源展示标记:高亮开始。
            # highlight-start:subtle
            "type": "tool_search_output",
            # [中文] 来源展示标记:高亮结束。
            # highlight-end
            "execution": "client",
            "call_id": search_call.call_id,
            "status": "completed",
            # [中文] 来源展示标记:高亮开始。
            # highlight-start:subtle
            "tools": loaded_tools,
            # [中文] 来源展示标记:高亮结束。
            # highlight-end
        },
    ],
)

print(second_response.output)

来源示例10(go)

本段复用的中文释义:译释92、译释93、译释94。

// [中文] 配置execution为client的搜索工具,应用需检索并返回工具定义。
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/responses"
)

func main() {
    client := openai.NewClient()
    searchTool := responses.ToolUnionParam{OfToolSearch: &responses.ToolSearchToolParam{
        Execution:   responses.ToolSearchToolExecutionClient,
        Description: openai.String("Find the project-specific tools needed to continue the task."),
        Parameters: map[string]any{
            "type":                 "object",
            "properties":           map[string]any{"goal": map[string]any{"type": "string"}},
            "required":             []string{"goal"},
            "additionalProperties": false,
        },
    }}
    first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model:             "gpt-6-astra",
        Input:             responses.ResponseNewParamsInputUnion{OfString: openai.String("Find the shipping ETA tool first, then use it for order_42.")},
        Tools:             []responses.ToolUnionParam{searchTool},
        ParallelToolCalls: openai.Bool(false),
    })
    if err != nil {
        panic(err)
    }

    callID := ""
    for _, item := range first.Output {
        if item.Type == "tool_search_call" {
            callID = item.CallID
            break
        }
    }
    if callID == "" {
        panic("the response did not include a tool search call")
    }
    loadedTool := responses.ToolParamOfFunction("get_shipping_eta", map[string]any{
        "type":                 "object",
        "properties":           map[string]any{"order_id": map[string]any{"type": "string"}},
        "required":             []string{"order_id"},
        "additionalProperties": false,
    }, true)
    loadedTool.OfFunction.Description = openai.String("Look up shipping ETA details for an order.")
    loadedTool.OfFunction.DeferLoading = openai.Bool(true)
    searchOutput := responses.ResponseInputItemParamOfToolSearchOutput([]responses.ResponseToolSearchOutputItemParamToolUnion{{OfFunction: loadedTool.OfFunction}})
    searchOutput.OfToolSearchOutput.CallID = openai.String(callID)
    searchOutput.OfToolSearchOutput.Execution = responses.ResponseToolSearchOutputItemParamExecutionClient
    searchOutput.OfToolSearchOutput.Status = responses.ResponseToolSearchOutputItemParamStatusCompleted

    second, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model:              "gpt-6-astra",
        PreviousResponseID: openai.String(first.ID),
        Input:              responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{searchOutput}},
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(second.Output)
}

来源示例11(java)

程序中的自然语言译释139:

先找到预计送达时间工具,再查询order_42。

程序中的自然语言译释140:

查找继续当前任务所需的项目工具。

程序中的自然语言译释141:

查询订单配送详情。

// [中文] 配置execution为client的搜索工具,应用需检索并返回工具定义。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.FunctionTool;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputItem;
import com.openai.models.responses.ResponseToolSearchOutputItemParam;
import com.openai.models.responses.ToolSearchTool;
import java.util.List;
import java.util.Map;

ResponseCreateParams searchRequest =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .input("Find the shipping ETA tool, then use it for order_42.")
        .parallelToolCalls(false)
        .addTool(
            ToolSearchTool.builder()
                .execution(ToolSearchTool.Execution.CLIENT)
                .description("Find the project tools needed to continue the task.")
                .parameters(
                    JsonValue.from(
                        Map.of(
                            "type",
                            "object",
                            "properties",
                            Map.of("goal", Map.of("type", "string")),
                            "required",
                            List.of("goal"),
                            "additionalProperties",
                            false)))
                .build())
        .build();

var search = client.responses().create(searchRequest);
var searchCall =
    search.output().stream()
        .flatMap(item -> item.toolSearchCall().stream())
        .findFirst()
        .orElseThrow(() -> new IllegalStateException("No tool search call returned"));

FunctionTool shippingTool =
    FunctionTool.builder()
        .name("get_shipping_eta")
        .description("Look up shipping details for an order.")
        .deferLoading(true)
        .strict(true)
        .parameters(
            FunctionTool.Parameters.builder()
                .putAdditionalProperty("type", JsonValue.from("object"))
                .putAdditionalProperty(
                    "properties", JsonValue.from(Map.of("order_id", Map.of("type", "string"))))
                .putAdditionalProperty("required", JsonValue.from(List.of("order_id")))
                .putAdditionalProperty("additionalProperties", JsonValue.from(false))
                .build())
        .build();

var searchOutput =
    ResponseToolSearchOutputItemParam.builder()
        .callId(searchCall.callId().orElseThrow())
        .execution(ResponseToolSearchOutputItemParam.Execution.CLIENT)
        .status(ResponseToolSearchOutputItemParam.Status.COMPLETED)
        .addTool(shippingTool)
        .build();

var response =
    client
        .responses()
        .create(
            ResponseCreateParams.builder()
                .model("gpt-6-astra")
                .previousResponseId(search.id())
                .inputOfResponse(List.of(ResponseInputItem.ofToolSearchOutput(searchOutput)))
                .build());

var loadedCalls =
    response.output().stream().flatMap(item -> item.functionCall().stream()).toList();
if (loadedCalls.isEmpty()) {
  throw new IllegalStateException("No loaded function call returned");
}
loadedCalls.forEach(call -> System.out.println(call.name() + "(" + call.arguments() + ")"));

来源示例12(ruby)

本段复用的中文释义:译释139、译释140、译释141。

## [中文] 配置execution为client的搜索工具,应用需检索并返回工具定义。
require "openai"

client = OpenAI::Client.new
search = client.responses.create(
  model: "gpt-6-astra",
  input: "Find the shipping ETA tool, then use it for order_42.",
  parallel_tool_calls: false,
  tools: [
    {
      type: :tool_search,
      execution: :client,
      description: "Find the project tools needed to continue the task.",
      parameters: {
        type: :object,
        properties: { goal: { type: :string } },
        required: ["goal"],
        additionalProperties: false
      }
    }
  ]
)
call = search.output.find do |item|
  item.is_a?(OpenAI::Models::Responses::ResponseToolSearchCall)
end
unless call.is_a?(OpenAI::Models::Responses::ResponseToolSearchCall)
  raise "No tool search call returned"
end

response = client.responses.create(
  model: "gpt-6-astra",
  previous_response_id: search.id,
  input: [
    {
      type: :tool_search_output,
      call_id: call.call_id,
      execution: :client,
      status: :completed,
      tools: [
        {
          type: :function,
          name: "get_shipping_eta",
          description: "Look up shipping details for an order.",
          defer_loading: true,
          strict: true,
          parameters: {
            type: :object,
            properties: { order_id: { type: :string } },
            required: ["order_id"],
            additionalProperties: false
          }
        }
      ]
    }
  ]
)

function_calls = response.output.grep(
  OpenAI::Models::Responses::ResponseFunctionToolCall
)
raise "No loaded function call returned" if function_calls.empty?

function_calls.each do |function_call|
  puts("#{function_call.name}(#{function_call.arguments})")
end

第一轮模型返回 tool_search_call 后停止:

来源示例13(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

[
  {
    "type": "tool_search_call",
    "execution": "client",
    "call_id": "call_abc123",
    "status": "completed",
    "arguments": {
      "goal": "Find the shipping ETA tool for order_42."
    }
  }
]

应用执行搜索,以 tool_search_output 返回希望加载的工具:

来源示例14(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

本段复用的中文释义:译释93。

[
  {
    "type": "tool_search_output",
    "execution": "client",
    "call_id": "call_abc123",
    "status": "completed",
    "tools": [
      {
        "type": "function",
        "name": "get_shipping_eta",
        "description": "Look up shipping ETA details for an order.",
        "defer_loading": true,
        "parameters": {
          "type": "object",
          "properties": {
            "order_id": { "type": "string" }
          },
          "required": ["order_id"],
          "additionalProperties": false
        }
      }
    ]
  }
]

下一轮加载后的工具即可像普通函数一样调用:

来源示例15(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

[
  {
    "type": "function_call",
    "name": "get_shipping_eta",
    "namespace": "get_shipping_eta",
    "call_id": "call_xyz456",
    "arguments": "{\"order_id\":\"order_42\"}"
  }
]

客户端模式中 execution: client 且有明确 call_id。输出必须回传搜索调用原来的 call_id。

高级用法

保持命名空间描述清晰

描述应明确说明用例,因为模型据此决定加载哪个子集。避免过长的整体描述,将细节放进按需加载的函数描述。

理解实际加载的内容

tool_search_output.tools 列出动态加载的工具。模型后续轮次可继续使用,客户端无需每轮重新加载。不在数组中的工具不可调用。要禁用已加载工具,可从定义加载集合的 tool_search_output 移除,但改变集合会从该位置起破坏缓存。

高级注入方式

通常在请求 tools 中声明工具;客户端搜索也允许返回初始请求未声明的工具。应将它视为高级流程,仔细验证返回的模式,仅暴露可信定义。

工具搜索与缓存

无论托管还是客户端搜索,新工具均在上下文末尾加载,以保留请求间缓存,降低成本并提高速度。

在输入的指定位置加入工具

高级工作流可用 additional_tools 输入项,在会话某个位置启用工具。适合应用在标准搜索流程外加载工具,或需保留上轮工具加入顺序的情况。将 role 设为 developer,在 tools 中列出工具。

来源示例16(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

{
    "type": "additional_tools",
    "role": "developer",
    "tools": [
      {
        "type": "function",
        "name": "get_customer",
        "description": "Look up a customer by ID.",
        "parameters": {
          "type": "object",
          "properties": {
            "customer_id": { "type": "string" }
          },
          "required": ["customer_id"],
          "additionalProperties": false
        }
      }
    ]
  }

工具仅在该输入项出现后可用。手动往返传递会话项时,应保留它的位置,使模型在相同位置看到同一组工具。

Agents API

Agents API默认立即加载函数定义。要延迟选定函数,既要在 agent.tools 加入 { "type": "tool_search" },也要对各函数设置 defer_loading: true。仅添加搜索工具不会延迟所有函数。

会话请求仍应提供完整定义,包括名称、描述和参数模式。搜索改变的是定义何时到达模型;发现之后,应用照常处理函数调用并返回结果,参见Functions。运行示例前设置 OPENAI_API_KEY。

来源示例17(javascript)

程序中的自然语言译释95:

通过账号查找账户。

程序中的自然语言译释142:

查询42号账户。

// [中文] 在Agents API中启用tool_search,并分别为需要延迟的函数设置defer_loading。
import OpenAI from "openai";
const client = new OpenAI();

const result = await client.beta.agents.sessions.create({
  agent: {
    model: "gpt-6-astra",
    tools: [
      {
        type: "tool_search",
      },
      {
        type: "function",
        name: "lookup_account",
        description: "Find an account by its account number.",
        parameters: {
          type: "object",
          properties: {
            account_id: {
              type: "string",
            },
          },
          required: ["account_id"],
          additionalProperties: false,
        },
        defer_loading: true,
      },
    ],
  },
  environment: {
    type: "none",
  },
  input: [
    {
      role: "user",
      content: [
        {
          type: "input_text",
          text: "Look up account 42.",
        },
      ],
    },
  ],
});
console.log(result.id);

来源示例18(python)

本段复用的中文释义:译释95、译释142。

## [中文] 在Agents API中启用tool_search,并分别为需要延迟的函数设置defer_loading。
from openai import OpenAI

client = OpenAI()

result = client.beta.agents.sessions.create(
    agent={
        "model": "gpt-6-astra",
        "tools": [
            {"type": "tool_search"},
            {
                "type": "function",
                "name": "lookup_account",
                "description": "Find an account by its account number.",
                "parameters": {
                    "type": "object",
                    "properties": {"account_id": {"type": "string"}},
                    "required": ["account_id"],
                    "additionalProperties": False,
                },
                "defer_loading": True,
            },
        ],
    },
    environment={"type": "none"},
    input=[
        {
            "role": "user",
            "content": [{"type": "input_text", "text": "Look up account 42."}],
        }
    ],
)
print(result.id)

来源示例19(go)

本段复用的中文释义:译释95、译释142。

// [中文] 在Agents API中启用tool_search,并分别为需要延迟的函数设置defer_loading。
import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
)

ctx := context.Background()
client := openai.NewClient()
result, err := client.Beta.Agents.Sessions.New(ctx,
    openai.BetaAgentSessionNewParams{
        Agent: openai.BetaAgentSessionNewParamsAgent{
            Model: openai.String("gpt-6-astra"),
            Tools: []openai.AgentToolParamUnion{
                {OfParamToolSearch: &openai.AgentToolParamToolSearch{}},
                {
                    OfParamFunction: &openai.AgentToolParamFunction{
                        Name:        "lookup_account",
                        Description: "Find an account by its account number.",
                        Parameters: map[string]any{
                            "type":                 "object",
                            "properties":           map[string]any{"account_id": map[string]any{"type": "string"}},
                            "required":             []any{"account_id"},
                            "additionalProperties": false,
                        },
                        DeferLoading: openai.Bool(true),
                    },
                },
            },
        },
        Environment: openai.EnvironmentParamUnion{OfParamNone: &openai.EnvironmentParamNone{}},
        Input: openai.BetaAgentSessionNewParamsInputUnion{
            OfArrayOfInputMessages: []openai.AgentSessionInputMessageParam{
                {
                    Content: []openai.InputContentParamUnion{
                        {OfParamInputText: &openai.InputContentParamInputText{Text: "Look up account 42."}},
                    },
                },
            },
        },
    })
if err != nil {
    panic(err)
}
fmt.Println(result.ID)

来源示例20(java)

本段复用的中文释义:译释95、译释142。

// [中文] 在Agents API中启用tool_search,并分别为需要延迟的函数设置defer_loading。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.beta.agents.AgentToolParam;
import com.openai.models.beta.agents.sessions.SessionCreateParams;
import java.util.List;
import java.util.Map;

OpenAIClient client = OpenAIOkHttpClient.fromEnv();
var result =
    client
        .beta()
        .agents()
        .sessions()
        .create(
            SessionCreateParams.builder()
                .agent(
                    SessionCreateParams.Agent.builder()
                        .model("gpt-6-astra")
                        .addToolToolSearch()
                        .addTool(
                            AgentToolParam.Function.builder()
                                .name("lookup_account")
                                .description("Find an account by its account number.")
                                .parameters(
                                    AgentToolParam.Function.Parameters.builder()
                                        .putAdditionalProperty("type", JsonValue.from("object"))
                                        .putAdditionalProperty(
                                            "properties",
                                            JsonValue.from(
                                                Map.of("account_id", Map.of("type", "string"))))
                                        .putAdditionalProperty(
                                            "required", JsonValue.from(List.of("account_id")))
                                        .putAdditionalProperty(
                                            "additionalProperties", JsonValue.from(false))
                                        .build())
                                .deferLoading(true)
                                .build())
                        .build())
                .environmentNone()
                .input("Look up account 42.")
                .build());
System.out.println(result.id());

来源示例21(ruby)

本段复用的中文释义:译释95、译释142。

## [中文] 在Agents API中启用tool_search,并分别为需要延迟的函数设置defer_loading。
require "openai"

client = OpenAI::Client.new
result = client.beta.agents.sessions.create(
  agent: {
    model: "gpt-6-astra",
    tools: [
      { type: "tool_search" },
      {
        type: "function",
        name: "lookup_account",
        description: "Find an account by its account number.",
        parameters: {
          type: "object",
          properties: { account_id: { type: "string" } },
          required: ["account_id"],
          additionalProperties: false
        },
        defer_loading: true
      }
    ]
  },
  environment: { type: "none" },
  input: [
    {
      role: "user",
      content: [
        {
          type: "input_text",
          text: "Look up account 42."
        }
      ]
    }
  ]
)
puts result.id

选择函数加载策略

策略 配置 适用情况 取舍
立即加载 省略 defer_loading 或设为 false 函数较少,或大多数任务都会使用 未使用定义占用上下文,修改定义可能使缓存前缀失效
延迟加载 defer_loading: true 并加入 tool_search 工具目录很大,每个任务只需少数函数 发现多一个步骤,也依赖能否找到相关工具

会话支持混合加载,但一般不推荐。给延迟函数清晰名称和描述,在代表性请求上比较任务完成、输入词元和延迟后再选默认方式。

MCP与插件工具

当模型和提供方支持工具搜索时,Agents API中的MCP使用自动发现。运行时会延迟MCP工具,并在存在可搜索的延迟工具时加入工具搜索。远程MCP、executor MCP和插件提供的MCP工具均适用。

不必仅为MCP添加 tool_search,也不必在MCP服务器上设置函数级 defer_loading。按MCP连接配置。前文Responses配置不适用于Agents API的MCP服务器。

相关指南

函数调用定义函数及自定义工具;使用工具介绍Responses的整体工具能力。

OpenAI 技能
OpenAI 网页搜索
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

其他能力与进阶指南

Embeddings 接口参考

审计日志接口参考

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }