SPB Git

Repository Public

tools.md 32.5 KB 1,162 lines markdown

1# Using tools23> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.45When generating model responses or building agents, you can extend capabilities using built‑in tools, function calling, Programmatic Tool Calling, tool search, and remote MCP servers. These enable the model to search the web, retrieve from your files, load deferred tool definitions at runtime, call your own functions, compose tool calls in JavaScript, or access third‑party services. Only `gpt-5.4` and later models support `tool_search`.67Choose the integration for your runtime: configure tools on [Responses API requests](#usage-in-the-api), on [Agents API agents](#agents-api), or in [Agents SDK definitions](#usage-in-the-agents-sdk). Tool availability, configuration, and call handling depend on the integration. The examples below use the Responses API.891011Web search1213    Include web search results for the model response1415```javascript16import OpenAI from "openai";17const client = new OpenAI();1819const response = await client.responses.create({20  model: "gpt-6-astra",21  tools: [{ type: "web_search" }],22  input: "What was a positive news story from today?",23});2425console.log(response.output_text);26```2728```python29from openai import OpenAI3031client = OpenAI()3233response = client.responses.create(34    model="gpt-6-astra",35    tools=[{"type": "web_search"}],36    input="What was a positive news story from today?",37)3839print(response.output_text)40```4142```go43package main4445import (46	"context"47	"fmt"4849	"github.com/openai/openai-go/v3"50	"github.com/openai/openai-go/v3/responses"51)5253func main() {54	client := openai.NewClient()55	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{56		Model: "gpt-6-astra",57		Tools: []responses.ToolUnionParam{58			responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch),59		},60		Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What was a positive news story from today?")},61	})62	if err != nil {63		panic(err)64	}65	fmt.Println(response.OutputText())66}67```6869```java70import com.openai.client.OpenAIClient;71import com.openai.client.okhttp.OpenAIOkHttpClient;72import com.openai.models.responses.ResponseCreateParams;73import com.openai.models.responses.WebSearchTool;7475ResponseCreateParams params =76    ResponseCreateParams.builder()77        .model("gpt-6-astra")78        .input("What was a positive news story from today?")79        .addTool(WebSearchTool.builder().type(WebSearchTool.Type.WEB_SEARCH).build())80        .build();8182client.responses().create(params).output().stream()83    .flatMap(item -> item.message().stream())84    .flatMap(message -> message.content().stream())85    .flatMap(content -> content.outputText().stream())86    .forEach(text -> System.out.println(text.text()));87```8889```csharp90using OpenAI.Responses;91#pragma warning disable OPENAI0019293string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;94ResponsesClient client = new(key);9596CreateResponseOptions options = new() { Model = "gpt-6-astra" };97options.Tools.Add(ResponseTool.CreateWebSearchTool());98options.InputItems.Add(99    ResponseItem.CreateUserMessageItem("What was a positive news story from today?")100);101102ResponseResult response = await client.CreateResponseAsync(options);103104Console.WriteLine(response.GetOutputText());105```106107```ruby108require "openai"109110openai = OpenAI::Client.new111112response = openai.responses.create(113  model: "gpt-6-astra",114  tools: [{ type: "web_search" }],115  input: "What was a positive news story from today?"116)117118puts(response.output_text)119```120121```bash122curl "https://api.openai.com/v1/responses" \123    -H "Content-Type: application/json" \124    -H "Authorization: Bearer $OPENAI_API_KEY" \125    -d '{126        "model": "gpt-6-astra",127        "tools": [{"type": "web_search"}],128        "input": "what was a positive news story from today?"129}'130```131132```bash133openai responses create \134  --model gpt-6-astra \135  --raw-output \136  --transform 'output.#(type=="message").content.0.text' <<'YAML'137tools:138  - type: web_search139input: What was a positive news story from today?140YAML141```142143  144145  146147    148File search149150    Search your files in a response151152```javascript153import OpenAI from "openai";154const openai = new OpenAI();155156const response = await openai.responses.create({157  model: "gpt-6-astra",158  input: "What is deep research by OpenAI?",159  tools: [160    {161      type: "file_search",162      vector_store_ids: ["<vector_store_id>"],163    },164  ],165});166console.log(response);167```168169```python170from openai import OpenAI171172client = OpenAI()173174response = client.responses.create(175    model="gpt-6-astra",176    input="What is deep research by OpenAI?",177    tools=[{"type": "file_search", "vector_store_ids": ["<vector_store_id>"]}],178)179print(response)180```181182```go183package main184185import (186	"context"187	"fmt"188189	"github.com/openai/openai-go/v3"190	"github.com/openai/openai-go/v3/responses"191)192193func main() {194	client := openai.NewClient()195	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{196		Model: "gpt-6-astra",197		Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What is deep research by OpenAI?")},198		Tools: []responses.ToolUnionParam{responses.ToolParamOfFileSearch([]string{"<vector_store_id>"})},199	})200	if err != nil {201		panic(err)202	}203	fmt.Println(response)204}205```206207```java208import com.openai.client.OpenAIClient;209import com.openai.client.okhttp.OpenAIOkHttpClient;210import com.openai.models.responses.ResponseCreateParams;211import java.util.List;212213String vectorStoreId = "<vector_store_id>";214215ResponseCreateParams params =216    ResponseCreateParams.builder()217        .model("gpt-6-astra")218        .input("What is deep research by OpenAI?")219        .addFileSearchTool(List.of(vectorStoreId))220        .build();221222client.responses().create(params).output().stream()223    .flatMap(item -> item.message().stream())224    .flatMap(message -> message.content().stream())225    .flatMap(content -> content.outputText().stream())226    .forEach(text -> System.out.println(text.text()));227```228229```csharp230using OpenAI.Responses;231#pragma warning disable OPENAI001232233string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;234string vectorStoreId = "<vector_store_id>";235ResponsesClient client = new(key);236237CreateResponseOptions options = new() { Model = "gpt-6-astra" };238options.Tools.Add(239    ResponseTool.CreateFileSearchTool([vectorStoreId])240);241options.InputItems.Add(242    ResponseItem.CreateUserMessageItem("What is deep research by OpenAI?")243);244245ResponseResult response = await client.CreateResponseAsync(options);246247Console.WriteLine(response.GetOutputText());248```249250```ruby251require "openai"252253openai = OpenAI::Client.new254255response = openai.responses.create(256  model: "gpt-6-astra",257  input: "What is deep research by OpenAI?",258  tools: [259    {260      type: "file_search",261      vector_store_ids: ["<vector_store_id>"]262    }263  ]264)265266puts(response)267```268269  270271  272273    274Tool search275276    Load deferred tools at runtime277278```javascript279import OpenAI from "openai";280281const client = new OpenAI();282283const crmNamespace = {284  type: "namespace",285  name: "crm",286  description: "CRM tools for customer lookup and order management.",287  tools: [288    {289      type: "function",290      name: "get_customer_profile",291      description: "Fetch a customer profile by customer ID.",292      parameters: {293        type: "object",294        properties: {295          customer_id: { type: "string" },296        },297        required: ["customer_id"],298        additionalProperties: false,299      },300    },301    {302      type: "function",303      name: "list_open_orders",304      description: "List open orders for a customer ID.",305      // highlight-start:subtle306      defer_loading: true,307      // highlight-end308      parameters: {309        type: "object",310        properties: {311          customer_id: { type: "string" },312        },313        required: ["customer_id"],314        additionalProperties: false,315      },316    },317  ],318};319320const response = await client.responses.create({321  model: "gpt-6-astra",322  input: "List open orders for customer CUST-12345.",323  // highlight-start:subtle324  tools: [crmNamespace, { type: "tool_search" }],325  // highlight-end326  parallel_tool_calls: false,327});328329console.log(response.output);330```331332```python333from openai import OpenAI334335client = OpenAI()336337crm_namespace = {338    "type": "namespace",339    "name": "crm",340    "description": "CRM tools for customer lookup and order management.",341    "tools": [342        {343            "type": "function",344            "name": "get_customer_profile",345            "description": "Fetch a customer profile by customer ID.",346            "parameters": {347                "type": "object",348                "properties": {349                    "customer_id": {"type": "string"},350                },351                "required": ["customer_id"],352                "additionalProperties": False,353            },354        },355        {356            "type": "function",357            "name": "list_open_orders",358            "description": "List open orders for a customer ID.",359            # highlight-start:subtle360            "defer_loading": True,361            # highlight-end362            "parameters": {363                "type": "object",364                "properties": {365                    "customer_id": {"type": "string"},366                },367                "required": ["customer_id"],368                "additionalProperties": False,369            },370        },371    ],372}373374response = client.responses.create(375    model="gpt-6-astra",376    input="List open orders for customer CUST-12345.",377    tools=[378        crm_namespace,379        # highlight-start:subtle380        {"type": "tool_search"},381        # highlight-end382    ],383    parallel_tool_calls=False,384)385386print(response.output)387```388389```go390package main391392import (393	"context"394	"fmt"395396	"github.com/openai/openai-go/v3"397	"github.com/openai/openai-go/v3/responses"398)399400func main() {401	client := openai.NewClient()402	parameters := map[string]any{403		"type":                 "object",404		"properties":           map[string]any{"customer_id": map[string]any{"type": "string"}},405		"required":             []string{"customer_id"},406		"additionalProperties": false,407	}408	namespace := responses.ToolParamOfNamespace(409		"CRM tools for customer lookup and order management.",410		"crm",411		[]responses.NamespaceToolToolUnionParam{412			{OfFunction: &responses.NamespaceToolToolFunctionParam{413				Name: "get_customer_profile", Description: openai.String("Fetch a customer profile by customer ID."), Parameters: parameters,414			}},415			{OfFunction: &responses.NamespaceToolToolFunctionParam{416				Name: "list_open_orders", Description: openai.String("List open orders for a customer ID."), DeferLoading: openai.Bool(true), Parameters: parameters,417			}},418		},419	)420	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{421		Model:             "gpt-6-astra",422		Input:             responses.ResponseNewParamsInputUnion{OfString: openai.String("List open orders for customer CUST-12345.")},423		Tools:             []responses.ToolUnionParam{namespace, {OfToolSearch: &responses.ToolSearchToolParam{}}},424		ParallelToolCalls: openai.Bool(false),425	})426	if err != nil {427		panic(err)428	}429	fmt.Println(response.Output)430}431```432433```java434import com.openai.client.OpenAIClient;435import com.openai.client.okhttp.OpenAIOkHttpClient;436import com.openai.core.JsonValue;437import com.openai.models.responses.NamespaceTool;438import com.openai.models.responses.ResponseCreateParams;439import com.openai.models.responses.ToolSearchTool;440import java.util.List;441import java.util.Map;442443ResponseCreateParams params =444    ResponseCreateParams.builder()445        .model("gpt-6-astra")446        .input("List open orders for customer CUST-12345.")447        .parallelToolCalls(false)448        .addTool(449            NamespaceTool.builder()450                .name("crm")451                .description("CRM tools for customer lookup and order management.")452                .addTool(453                    NamespaceTool.Tool.Function.builder()454                        .name("get_customer_profile")455                        .description("Fetch a customer profile by customer ID.")456                        .strict(true)457                        .parameters(458                            JsonValue.from(459                                Map.of(460                                    "type",461                                    "object",462                                    "properties",463                                    Map.of("customer_id", Map.of("type", "string")),464                                    "required",465                                    List.of("customer_id"),466                                    "additionalProperties",467                                    false)))468                        .build())469                .addTool(470                    NamespaceTool.Tool.Function.builder()471                        .name("list_open_orders")472                        .description("List open orders for a customer ID.")473                        .deferLoading(true)474                        .strict(true)475                        .parameters(476                            JsonValue.from(477                                Map.of(478                                    "type",479                                    "object",480                                    "properties",481                                    Map.of("customer_id", Map.of("type", "string")),482                                    "required",483                                    List.of("customer_id"),484                                    "additionalProperties",485                                    false)))486                        .build())487                .build())488        .addTool(ToolSearchTool.builder().execution(ToolSearchTool.Execution.SERVER).build())489        .build();490491client.responses().create(params).output().forEach(System.out::println);492```493494```ruby495require "openai"496497client = OpenAI::Client.new498parameters = {499  type: :object,500  properties: { customer_id: { type: :string } },501  required: ["customer_id"],502  additionalProperties: false503}504response = client.responses.create(505  model: "gpt-6-astra",506  input: "List open orders for customer CUST-12345.",507  parallel_tool_calls: false,508  tools: [509    {510      type: :namespace,511      name: "crm",512      description: "CRM tools for customer lookup and order management.",513      tools: [514        {515          type: :function,516          name: "get_customer_profile",517          description: "Fetch a customer profile by customer ID.",518          parameters: parameters519        },520        {521          type: :function,522          name: "list_open_orders",523          description: "List open orders for a customer ID.",524          defer_loading: true,525          parameters: parameters526        }527      ]528    },529    { type: :tool_search }530  ]531)532533puts(response.output)534```535536  537538  539540    541Function calling542543    Call your own function544545```javascript546import OpenAI from "openai";547const client = new OpenAI();548549const tools = [550  {551    type: "function",552    name: "get_weather",553    description: "Get current temperature for a given location.",554    parameters: {555      type: "object",556      properties: {557        location: {558          type: "string",559          description: "City and country e.g. Bogotá, Colombia",560        },561      },562      required: ["location"],563      additionalProperties: false,564    },565    strict: true,566  },567];568569const response = await client.responses.create({570  model: "gpt-6-astra",571  input: [572    { role: "user", content: "What is the weather like in Paris today?" },573  ],574  tools,575});576577console.log(response.output[0]);578```579580```python581from openai import OpenAI582583client = OpenAI()584585tools = [586    {587        "type": "function",588        "name": "get_weather",589        "description": "Get current temperature for a given location.",590        "parameters": {591            "type": "object",592            "properties": {593                "location": {594                    "type": "string",595                    "description": "City and country e.g. Bogotá, Colombia",596                }597            },598            "required": ["location"],599            "additionalProperties": False,600        },601        "strict": True,602    },603]604605response = client.responses.create(606    model="gpt-6-astra",607    input=[608        {"role": "user", "content": "What is the weather like in Paris today?"},609    ],610    tools=tools,611)612613print(response.output[0].to_json())614```615616```go617package main618619import (620	"context"621	"fmt"622623	"github.com/openai/openai-go/v3"624	"github.com/openai/openai-go/v3/responses"625)626627func main() {628	client := openai.NewClient()629	parameters := map[string]any{630		"type": "object",631		"properties": map[string]any{632			"location": map[string]any{633				"type":        "string",634				"description": "City and country e.g. Bogotá, Colombia",635			},636		},637		"required":             []string{"location"},638		"additionalProperties": false,639	}640	tool := responses.ToolParamOfFunction("get_weather", parameters, true)641	tool.OfFunction.Description = openai.String("Get current temperature for a given location.")642643	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{644		Model: "gpt-6-astra",645		Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{646			responses.ResponseInputItemParamOfMessage("What is the weather like in Paris today?", responses.EasyInputMessageRoleUser),647		}},648		Tools: []responses.ToolUnionParam{tool},649	})650	if err != nil {651		panic(err)652	}653	fmt.Println(response.Output)654}655```656657```java658import com.openai.client.OpenAIClient;659import com.openai.client.okhttp.OpenAIOkHttpClient;660import com.openai.core.JsonValue;661import com.openai.models.responses.FunctionTool;662import com.openai.models.responses.ResponseCreateParams;663import java.util.List;664import java.util.Map;665666ResponseCreateParams params =667    ResponseCreateParams.builder()668        .model("gpt-6-astra")669        .input("What is the weather like in Paris today?")670        .addTool(671            FunctionTool.builder()672                .name("get_weather")673                .description("Get current temperature for a given location.")674                .parameters(675                    FunctionTool.Parameters.builder()676                        .putAdditionalProperty("type", JsonValue.from("object"))677                        .putAdditionalProperty(678                            "properties",679                            JsonValue.from(680                                Map.of(681                                    "location",682                                    Map.of(683                                        "type", "string",684                                        "description",685                                            "City and country e.g. Bogotá, Colombia"))))686                        .putAdditionalProperty("required", JsonValue.from(List.of("location")))687                        .putAdditionalProperty("additionalProperties", JsonValue.from(false))688                        .build())689                .strict(true)690                .build())691        .build();692693client.responses().create(params).output().forEach(System.out::println);694```695696```csharp697using OpenAI.Responses;698#pragma warning disable OPENAI001699700string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;701ResponsesClient client = new(key);702703CreateResponseOptions options = new() { Model = "gpt-6-astra" };704options.Tools.Add(705    ResponseTool.CreateFunctionTool(706        functionName: "get_weather",707        functionDescription: "Get current temperature for a given location.",708        functionParameters: BinaryData.FromString(709            """710            {711                "type": "object",712                "properties": {713                    "location": {714                        "type": "string",715                        "description": "City and country e.g. Bogotá, Colombia"716                    }717                },718                "required": ["location"],719                "additionalProperties": false720            }721            """722        ),723        strictModeEnabled: true724    )725);726options.InputItems.Add(727    ResponseItem.CreateUserMessageItem("What is the weather like in Paris today?")728);729730ResponseResult response = await client.CreateResponseAsync(options);731foreach (ResponseItem outputItem in response.OutputItems)732{733    if (outputItem is FunctionCallResponseItem functionCall)734    {735        Console.WriteLine(736            $"{functionCall.FunctionName}({functionCall.FunctionArguments})"737        );738    }739    else if (outputItem is MessageResponseItem message)740    {741        foreach (ResponseContentPart content in message.Content)742        {743            if (content.Kind == ResponseContentPartKind.OutputText)744            {745                Console.WriteLine(content.Text);746            }747            else if (content.Kind == ResponseContentPartKind.Refusal)748            {749                Console.WriteLine(content.Refusal);750            }751        }752    }753}754```755756```ruby757require "openai"758759openai = OpenAI::Client.new760761tools = [762  {763    type: "function",764    name: "get_weather",765    description: "Get current temperature for a given location.",766    parameters: {767      type: "object",768      properties: {769        location: {770          type: "string",771          description: "City and country e.g. Bogotá, Colombia"772        }773      },774      required: ["location"],775      additionalProperties: false776    },777    strict: true778  }779]780781response = openai.responses.create(782  model: "gpt-6-astra",783  input: [784    {785      role: "user",786      content: "What is the weather like in Paris today?"787    }788  ],789  tools: tools790)791792puts(response.output.fetch(0).to_json)793```794795```bash796curl -X POST https://api.openai.com/v1/responses \797  -H "Authorization: Bearer $OPENAI_API_KEY" \798  -H "Content-Type: application/json" \799  -d '{800    "model": "gpt-6-astra",801    "input": [802      {"role": "user", "content": "What is the weather like in Paris today?"}803    ],804    "tools": [805      {806        "type": "function",807        "name": "get_weather",808        "description": "Get current temperature for a given location.",809        "parameters": {810          "type": "object",811          "properties": {812            "location": {813              "type": "string",814              "description": "City and country e.g. Bogotá, Colombia"815            }816          },817          "required": ["location"],818          "additionalProperties": false819        },820        "strict": true821      }822    ]823  }'824```825826  827828  829830    831Remote MCP832833    Call a remote MCP server834835```bash836curl https://api.openai.com/v1/responses \ 837-H "Content-Type: application/json" \ 838-H "Authorization: Bearer $OPENAI_API_KEY" \ 839-d '{840  "model": "gpt-6-astra",841    "tools": [842      {843        "type": "mcp",844        "server_label": "dmcp",845        "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",846        "server_url": "https://dmcp-server.deno.dev/mcp",847        "require_approval": "never"848      }849    ],850    "input": "Roll 2d4+1"851  }'852```853854```javascript855import OpenAI from "openai";856const client = new OpenAI();857858const resp = await client.responses.create({859  model: "gpt-6-astra",860  tools: [861    {862      type: "mcp",863      server_label: "dmcp",864      server_description:865        "A Dungeons and Dragons MCP server to assist with dice rolling.",866      server_url: "https://dmcp-server.deno.dev/mcp",867      require_approval: "never",868    },869  ],870  input: "Roll 2d4+1",871});872873console.log(resp.output_text);874```875876```python877from openai import OpenAI878879client = OpenAI()880881resp = client.responses.create(882    model="gpt-6-astra",883    tools=[884        {885            "type": "mcp",886            "server_label": "dmcp",887            "server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",888            "server_url": "https://dmcp-server.deno.dev/mcp",889            "require_approval": "never",890        },891    ],892    input="Roll 2d4+1",893)894895print(resp.output_text)896```897898```go899package main900901import (902	"context"903	"fmt"904905	"github.com/openai/openai-go/v3"906	"github.com/openai/openai-go/v3/responses"907)908909func main() {910	client := openai.NewClient()911	tool := responses.ToolParamOfMcp("dmcp")912	tool.OfMcp.ServerDescription = openai.String("A Dungeons and Dragons MCP server to assist with dice rolling.")913	tool.OfMcp.ServerURL = openai.String("https://dmcp-server.deno.dev/mcp")914	tool.OfMcp.RequireApproval = responses.ToolMcpRequireApprovalUnionParam{OfMcpToolApprovalSetting: openai.String("never")}915916	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{917		Model: "gpt-6-astra",918		Tools: []responses.ToolUnionParam{tool},919		Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Roll 2d4+1")},920	})921	if err != nil {922		panic(err)923	}924	fmt.Println(response.OutputText())925}926```927928```java929import com.openai.client.OpenAIClient;930import com.openai.client.okhttp.OpenAIOkHttpClient;931import com.openai.models.responses.ResponseCreateParams;932import com.openai.models.responses.Tool;933934ResponseCreateParams params =935    ResponseCreateParams.builder()936        .model("gpt-6-astra")937        .input("Roll 2d4+1")938        .addTool(939            Tool.Mcp.builder()940                .serverLabel("dmcp")941                .serverDescription(942                    "A Dungeons and Dragons MCP server to assist with dice rolling.")943                .serverUrl("https://dmcp-server.deno.dev/mcp")944                .requireApproval(Tool.Mcp.RequireApproval.McpToolApprovalSetting.NEVER)945                .build())946        .build();947948client.responses().create(params).output().stream()949    .flatMap(item -> item.message().stream())950    .flatMap(message -> message.content().stream())951    .flatMap(content -> content.outputText().stream())952    .forEach(text -> System.out.println(text.text()));953```954955```csharp956using OpenAI.Responses;957#pragma warning disable OPENAI001958959string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;960ResponsesClient client = new(key);961962CreateResponseOptions options = new() { Model = "gpt-6-astra" };963options.Tools.Add(964    ResponseTool.CreateMcpTool(965        serverLabel: "dmcp",966        serverUri: new Uri("https://dmcp-server.deno.dev/mcp"),967        toolCallApprovalPolicy: DefaultMcpToolCallApprovalPolicy.NeverRequireApproval968    )969);970options.InputItems.Add(ResponseItem.CreateUserMessageItem("Roll 2d4+1"));971972ResponseResult response = await client.CreateResponseAsync(options);973974Console.WriteLine(response.GetOutputText());975```976977```ruby978require "openai"979980openai = OpenAI::Client.new981982response = openai.responses.create(983  model: "gpt-6-astra",984  tools: [985    {986      type: "mcp",987      server_label: "dmcp",988      server_description: "A Dungeons and Dragons MCP server to assist with dice rolling.",989      server_url: "https://dmcp-server.deno.dev/mcp",990      require_approval: "never"991    }992  ],993  input: "Roll 2d4+1"994)995996puts(response.output_text)997```99899910001001## Available tools10021003Here's an overview of the tools available in the OpenAI platform—select one of them for further guidance on usage.10041005[Function calling1006100710081009      Call custom code to give the model access to additional data and1010    capabilities.](https://developers.openai.com/api/docs/guides/function-calling)10111012[Web search1013101410151016      Include data from the Internet in model response generation.](https://developers.openai.com/api/docs/guides/tools-web-search)10171018[Remote MCP servers1019102010211022      Give the model access to new capabilities via Model Context Protocol (MCP)1023    servers.](https://developers.openai.com/api/docs/guides/tools-connectors-mcp)10241025[Skills1026102710281029      Upload and reuse versioned skill bundles in hosted shell environments.](https://developers.openai.com/api/docs/guides/tools-skills)10301031[Shell1032103310341035      Run shell commands in hosted containers or in your own local runtime.](https://developers.openai.com/api/docs/guides/tools-shell)10361037[Computer use1038103910401041      Create agentic workflows that enable a model to control a computer1042    interface.](https://developers.openai.com/api/docs/guides/tools-computer-use)10431044[Image generation1045104610471048      Generate or edit images using GPT Image.](https://developers.openai.com/api/docs/guides/tools-image-generation)10491050[File search1051105210531054      Search the contents of uploaded files for context when generating a1055    response.](https://developers.openai.com/api/docs/guides/tools-file-search)10561057[Tool search1058105910601061      Dynamically load relevant tools into the model’s context to optimize token1062    usage.](https://developers.openai.com/api/docs/guides/tools-tool-search)10631064[Programmatic Tool Calling1065106610671068      Let models compose and run JavaScript that orchestrates tool calls.](https://developers.openai.com/api/docs/guides/tools-programmatic-tool-calling)10691070## Usage in the API10711072When making a request to generate a [model response](https://developers.openai.com/api/reference/resources/responses/methods/create), you usually enable tool access by specifying configurations in the `tools` parameter. Each tool has its own unique configuration requirements—see the [Available tools](#available-tools) section for detailed instructions.10731074Based on the provided [prompt](https://developers.openai.com/api/docs/guides/text), the model automatically decides whether to use a configured tool. For instance, if your prompt requests information beyond the model's training cutoff date and web search is enabled, the model will typically invoke the web search tool to retrieve relevant, up-to-date information.10751076Some advanced workflows can also load more tool definitions during the interaction. For example, [tool search](https://developers.openai.com/api/docs/guides/tools-tool-search) can defer function definitions until the model decides they're needed.10771078You can explicitly control or guide this behavior by setting the `tool_choice` parameter [in the API request](https://developers.openai.com/api/reference/resources/responses/methods/create).10791080## Agents API10811082The [Agents API](https://developers.openai.com/api/docs/guides/agents-api/overview) runs the agent loop for you. Configure tools in `agent.tools`, handle function calls in your application, and connect a sandbox when the tools need an execution environment.10831084See [Functions](https://developers.openai.com/api/docs/guides/agents-api/tools/functions) to call application code, [MCP connections](https://developers.openai.com/api/docs/guides/agents-api/tools/mcp) to connect tool servers, and [sandbox configuration](https://developers.openai.com/api/docs/guides/agents-api/configuration#environment-settings) for tools that need an execution environment. [Programmatic Tool Calling](https://developers.openai.com/api/docs/guides/tools-programmatic-tool-calling#agents-api) is enabled by default. [Skills](https://developers.openai.com/api/docs/guides/tools-skills#agents-api) are discovered through the sandbox's capability directories.10851086## Usage in the Agents SDK10871088In the Agents SDK, the tool semantics stay the same, but the wiring moves into the agent definition and workflow design rather than a single Responses API request.10891090- Attach hosted tools, function tools, or hosted MCP tools directly on the agent when one specialist should call them itself.1091- Expose a specialist as a tool when a manager should stay in control of the user-facing reply.1092- Keep shell, apply patch, and computer-use harnesses in your runtime even when the SDK models the tool decision.10931094Wrap local logic as a function tool10951096```javascript1097import { tool } from "@openai/agents";1098import { z } from "zod";10991100const getWeatherTool = tool({1101  name: "get_weather",1102  description: "Get the weather for a given city.",1103  parameters: z.object({ city: z.string() }),1104  async execute({ city }) {1105    return `The weather in ${city} is sunny.`;1106  },1107});1108```11091110```python1111from agents import function_tool111211131114@function_tool1115def get_weather(city: str) -> str:1116    """Get the weather for a given city."""1117    return f"The weather in {city} is sunny."1118```111911201121Expose a specialist as a tool11221123```javascript1124import { Agent } from "@openai/agents";11251126const summarizer = new Agent({1127  name: "Summarizer",1128  instructions: "Generate a concise summary of the supplied text.",1129});11301131const mainAgent = new Agent({1132  name: "Research assistant",1133  tools: [1134    summarizer.asTool({1135      toolName: "summarize_text",1136      toolDescription: "Generate a concise summary of the supplied text.",1137    }),1138  ],1139});1140```11411142```python1143from agents import Agent11441145summarizer = Agent(1146    name="Summarizer",1147    instructions="Generate a concise summary of the supplied text.",1148)11491150main_agent = Agent(1151    name="Research assistant",1152    tools=[1153        summarizer.as_tool(1154            tool_name="summarize_text",1155            tool_description="Generate a concise summary of the supplied text.",1156        )1157    ],1158)1159```116011611162Use [Agent definitions](https://developers.openai.com/api/docs/guides/agents/define-agents) when you are shaping a single specialist, [Orchestration and handoffs](https://developers.openai.com/api/docs/guides/agents/orchestration) when tools affect ownership, [Guardrails and human review](https://developers.openai.com/api/docs/guides/agents/guardrails-approvals) when tools affect approvals, and [Integrations and observability](https://developers.openai.com/api/docs/guides/agents/integrations-observability#mcp) when the capability comes from MCP.
Files main
Menu

Theme