SPB Git

Repository Public

tools-web-search.md 46.3 KB 1,402 lines markdown

1# Web search23> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.45Web search allows models to access up-to-date information from the internet and provide answers with sourced citations. To enable this, use the web search tool in the Responses API or, in some cases, Chat Completions.67There are three main types of web search available with OpenAI models:891. Non‑reasoning web search: The non-reasoning model sends the user’s query to the web search tool, which returns the response based on top results. There’s no internal planning and the model simply passes along the search tool’s responses. This method is fast and ideal for quick lookups.102. Agentic search with reasoning models is an approach where the model actively manages the search process. It can perform web searches as part of its chain of thought, analyze results, and decide whether to keep searching. This flexibility makes agentic search well suited to complex workflows, but it also means searches take longer than quick lookups. For example, you can adjust reasoning levels on models like `gpt-5.5` to change both the depth and latency of the search.113. Deep research is a specialized, agent-driven method for in-depth, extended investigations by reasoning models. The model conducts web searches as part of its chain of thought, often tapping into hundreds of sources. Deep research can run for several minutes and is best used with background mode. Use `gpt-5.5` with reasoning set to `high` or `xhigh`.1213## Choose an integration1415| Use case                                      | Recommended path                              | Notes                                                                                                       |16| --------------------------------------------- | --------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |17| New web search integration                    | Responses API with `web_search` and `gpt-5.5` | Supports hosted web search controls such as filters, sources, live-access control, and longer research runs |18| Existing Chat Completions search integration  | Chat Completions with `gpt-5-search-api`      | Use this only when you need to preserve a Chat Completions integration                                      |19| Multi-step research or long-running reporting | `gpt-5.5` with `high` or `xhigh` reasoning    | Use background mode for reports that can take several minutes                                               |2021Using the [Responses API](https://developers.openai.com/api/reference/resources/responses), you can enable web search by configuring it in the `tools` array in an API request to generate content. Like any other tool, the model can choose to search the web or not based on the content of the input prompt.2223For new Responses API integrations, use `{ "type": "web_search" }`. The earlier `web_search_preview` tool remains available for legacy integrations, but it does not support newer controls such as `filters`, `external_web_access`, and `return_token_budget`.2425Web search tool example2627```javascript28import OpenAI from "openai";29const client = new OpenAI();3031const response = await client.responses.create({32  model: "gpt-6-astra",33  tools: [{ type: "web_search" }],34  input: "What was a positive news story from today?",35});3637console.log(response.output_text);38```3940```python41from openai import OpenAI4243client = OpenAI()4445response = client.responses.create(46    model="gpt-6-astra",47    tools=[{"type": "web_search"}],48    input="What was a positive news story from today?",49)5051print(response.output_text)52```5354```go55package main5657import (58	"context"59	"fmt"6061	"github.com/openai/openai-go/v3"62	"github.com/openai/openai-go/v3/responses"63)6465func main() {66	client := openai.NewClient()67	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{68		Model: "gpt-6-astra",69		Tools: []responses.ToolUnionParam{70			responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch),71		},72		Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What was a positive news story from today?")},73	})74	if err != nil {75		panic(err)76	}77	fmt.Println(response.OutputText())78}79```8081```java82import com.openai.client.OpenAIClient;83import com.openai.client.okhttp.OpenAIOkHttpClient;84import com.openai.models.responses.ResponseCreateParams;85import com.openai.models.responses.WebSearchTool;8687ResponseCreateParams params =88    ResponseCreateParams.builder()89        .model("gpt-6-astra")90        .input("What was a positive news story from today?")91        .addTool(WebSearchTool.builder().type(WebSearchTool.Type.WEB_SEARCH).build())92        .build();9394client.responses().create(params).output().stream()95    .flatMap(item -> item.message().stream())96    .flatMap(message -> message.content().stream())97    .flatMap(content -> content.outputText().stream())98    .forEach(text -> System.out.println(text.text()));99```100101```csharp102using OpenAI.Responses;103#pragma warning disable OPENAI001104105string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;106ResponsesClient client = new(key);107108CreateResponseOptions options = new() { Model = "gpt-6-astra" };109options.Tools.Add(ResponseTool.CreateWebSearchTool());110options.InputItems.Add(111    ResponseItem.CreateUserMessageItem("What was a positive news story from today?")112);113114ResponseResult response = await client.CreateResponseAsync(options);115116Console.WriteLine(response.GetOutputText());117```118119```ruby120require "openai"121122openai = OpenAI::Client.new123124response = openai.responses.create(125  model: "gpt-6-astra",126  tools: [{ type: "web_search" }],127  input: "What was a positive news story from today?"128)129130puts(response.output_text)131```132133```bash134curl "https://api.openai.com/v1/responses" \135    -H "Content-Type: application/json" \136    -H "Authorization: Bearer $OPENAI_API_KEY" \137    -d '{138        "model": "gpt-6-astra",139        "tools": [{"type": "web_search"}],140        "input": "what was a positive news story from today?"141}'142```143144```bash145openai responses create \146  --model gpt-6-astra \147  --raw-output \148  --transform 'output.#(type=="message").content.0.text' <<'YAML'149tools:150  - type: web_search151input: What was a positive news story from today?152YAML153```154155156## Output and citations157158Model responses that use the web search tool will include two parts:159160- A `web_search_call` output item with the ID of the search call, along with the action taken in `web_search_call.action`. The action is one of:161  - `search`, which represents a web search. It will usually (but not always) includes the search `queries` which were searched. Search actions incur a tool call cost (see [pricing](https://developers.openai.com/api/docs/pricing#built-in-tools)).162  - `open_page`, which represents a page being opened. Supported in reasoning models.163  - `find_in_page`, which represents searching within a page. Supported in reasoning models.164- A `message` output item containing:165  - The text result in `message.content[0].text`166  - Annotations `message.content[0].annotations` for the cited URLs167168By default, the model's response will include inline citations for URLs found in the web search results. In addition to this, the `url_citation` annotation object will contain the URL, title and location of the cited source.169170When displaying web results or information contained in web results to end171  users, inline citations must be made clearly visible and clickable in your172  user interface.173174```json175[176  {177    "type": "web_search_call",178    "id": "ws_67c9fa0502748190b7dd390736892e100be649c1a5ff9609",179    "status": "completed",180    "action": {181      "type": "search",182      "query": "latest news about AI"183    }184  },185  {186    "id": "msg_67c9fa077e288190af08fdffda2e34f20be649c1a5ff9609",187    "type": "message",188    "status": "completed",189    "role": "assistant",190    "content": [191      {192        "type": "output_text",193        "text": "On March 6, 2025, several news...",194        "annotations": [195          {196            "type": "url_citation",197            "start_index": 2606,198            "end_index": 2758,199            "url": "https://...",200            "title": "Title..."201          }202        ]203      }204    ]205  }206]207```208209210211212213## Migrating from legacy web search214215| If you use                                              | Recommended path                                                                                        | Notes                                                                                                    |216| ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |217| `web_search_preview` in Responses                       | Migrate to `web_search`                                                                                 | `web_search` supports newer controls such as `filters`, `external_web_access`, and `return_token_budget` |218| `gpt-4o-search-preview` or `gpt-4o-mini-search-preview` | Migrate to Responses `web_search`, or use `gpt-5-search-api` if you must stay on Chat Completions       | The preview search models are deprecated and shut down on 2026-07-23                                     |219| Chat Completions search integrations                    | Use `gpt-5-search-api`, or migrate to Responses `web_search` for more tool controls and optional search | Chat Completions search models always search before responding; Responses search is a tool               |220221## Search context size222223`search_context_size` controls how much context from web search results is made available to the model before it generates a response. Use `low` for simple lookups, `medium` for a balanced default, and `high` when the answer may require more detail from search results. This setting does not set an exact token count or guarantee a specific number of sources or citations.224225226227Set search context size228229```javascript230import OpenAI from "openai";231const openai = new OpenAI();232233const response = await openai.responses.create({234  model: "gpt-6-astra",235  tools: [236    {237      type: "web_search",238      search_context_size: "low",239    },240  ],241  input: "What movie won best picture in 2025?",242});243console.log(response.output_text);244```245246```python247from openai import OpenAI248249client = OpenAI()250251response = client.responses.create(252    model="gpt-6-astra",253    tools=[254        {255            "type": "web_search",256            "search_context_size": "low",257        }258    ],259    input="What movie won best picture in 2025?",260)261262print(response.output_text)263```264265```go266package main267268import (269	"context"270	"fmt"271272	"github.com/openai/openai-go/v3"273	"github.com/openai/openai-go/v3/responses"274)275276func main() {277	client := openai.NewClient()278	tool := responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch)279	tool.OfWebSearch.SearchContextSize = responses.WebSearchToolSearchContextSizeLow280	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{281		Model: "gpt-6-astra",282		Tools: []responses.ToolUnionParam{tool},283		Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What movie won best picture in 2025?")},284	})285	if err != nil {286		panic(err)287	}288	fmt.Println(response.OutputText())289}290```291292```java293import com.openai.client.OpenAIClient;294import com.openai.client.okhttp.OpenAIOkHttpClient;295import com.openai.models.responses.ResponseCreateParams;296import com.openai.models.responses.WebSearchTool;297298ResponseCreateParams params =299    ResponseCreateParams.builder()300        .model("gpt-6-astra")301        .input("What movie won best picture in 2025?")302        .addTool(303            WebSearchTool.builder()304                .type(WebSearchTool.Type.WEB_SEARCH)305                .searchContextSize(WebSearchTool.SearchContextSize.LOW)306                .build())307        .build();308309client.responses().create(params).output().stream()310    .flatMap(item -> item.message().stream())311    .flatMap(message -> message.content().stream())312    .flatMap(content -> content.outputText().stream())313    .forEach(text -> System.out.println(text.text()));314```315316```csharp317using OpenAI.Responses;318#pragma warning disable OPENAI001319320string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;321ResponsesClient client = new(key);322323CreateResponseOptions options = new() { Model = "gpt-6-astra" };324options.Tools.Add(325    ResponseTool.CreateWebSearchTool(326        searchContextSize: WebSearchToolContextSize.Low327    )328);329options.InputItems.Add(330    ResponseItem.CreateUserMessageItem("What movie won best picture in 2025?")331);332333ResponseResult response = await client.CreateResponseAsync(options);334335Console.WriteLine(response.GetOutputText());336```337338```ruby339require "openai"340341client = OpenAI::Client.new342343response = client.responses.create(344  model: "gpt-6-astra",345  input: "What movie won best picture in 2025?",346  tools: [347    {348      type: :web_search,349      search_context_size: :low350    }351  ]352)353354puts(response.output_text)355```356357```bash358curl "https://api.openai.com/v1/responses" \359    -H "Content-Type: application/json" \360    -H "Authorization: Bearer $OPENAI_API_KEY" \361    -d '{362        "model": "gpt-6-astra",363        "tools": [{364            "type": "web_search",365            "search_context_size": "low"366        }],367        "input": "What movie won best picture in 2025?"368    }'369```370371372373374## Run longer web research375376`return_token_budget` controls how much web search result content the tool can return during a Responses API search run with GPT-5+ reasoning models. Keep the default for most requests. Set it to `unlimited` only for high-effort research or evaluation runs that need to inspect many pages and might otherwise stop at the standard returned-token cap.377378Use `unlimited` selectively because it can increase latency and cost. For long-running multi-search tasks, use background mode (`background: true`) so the request can keep running asynchronously and you can retrieve the final response later.379380| Value       | Behavior                                                                                                                     |381| ----------- | ---------------------------------------------------------------------------------------------------------------------------- |382| `default`   | Uses the standard returned-token budget for web search results. This is the same behavior as omitting `return_token_budget`. |383| `unlimited` | Removes the default returned-token budget for the web search run.                                                            |384385This parameter applies only to the hosted Responses API `web_search` tool with GPT-5+ reasoning web search. It does not change the search context window, and it does not apply to non-reasoning web search, legacy Search API paths, container web search, Chat Completions search models, or `web_search_preview`. Only `default` and `unlimited` are supported values; `null`, numbers, and other strings are rejected.386387388389Run longer web searches390391```javascript392import OpenAI from "openai";393const client = new OpenAI();394395const response = await client.responses.create({396  model: "gpt-6-astra",397  reasoning: { effort: "xhigh" },398  tools: [399    {400      type: "web_search",401      return_token_budget: "unlimited",402    },403  ],404  input: [405    "Research the economic impact of semaglutide on global healthcare systems.",406    "",407    "Do:",408    "- Include specific figures, trends, statistics, and measurable outcomes.",409    "- Prioritize reliable, up-to-date sources: peer-reviewed research, health organizations (e.g., WHO, CDC), regulatory agencies, or pharmaceutical earnings reports.",410    "- Include inline citations and return all source metadata.",411    "",412    "Be analytical, avoid generalities, and ensure that each section supports data-backed reasoning that could inform healthcare policy or financial modeling.",413  ].join("\n"),414});415416console.log(response.output_text);417```418419```python420from openai import OpenAI421422client = OpenAI()423424response = client.responses.create(425    model="gpt-6-astra",426    reasoning={"effort": "xhigh"},427    tools=[428        {429            "type": "web_search",430            "return_token_budget": "unlimited",431        }432    ],433    input="""Research the economic impact of semaglutide on global healthcare systems.434435Do:436- Include specific figures, trends, statistics, and measurable outcomes.437- Prioritize reliable, up-to-date sources: peer-reviewed research, health organizations (e.g., WHO, CDC), regulatory agencies, or pharmaceutical earnings reports.438- Include inline citations and return all source metadata.439440Be analytical, avoid generalities, and ensure that each section supports data-backed reasoning that could inform healthcare policy or financial modeling.""",441)442443print(response.output_text)444```445446```go447package main448449import (450	"context"451	"fmt"452	"strings"453454	"github.com/openai/openai-go/v3"455	"github.com/openai/openai-go/v3/responses"456	"github.com/openai/openai-go/v3/shared"457)458459func main() {460	client := openai.NewClient()461	tool := responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch)462	tool.OfWebSearch.SetExtraFields(map[string]any{"return_token_budget": "unlimited"})463	input := strings.Join([]string{464		"Research the economic impact of semaglutide on global healthcare systems.",465		"",466		"Do:",467		"- Include specific figures, trends, statistics, and measurable outcomes.",468		"- Prioritize reliable, up-to-date sources: peer-reviewed research, health organizations, regulatory agencies, or pharmaceutical earnings reports.",469		"- Include inline citations and return all source metadata.",470		"",471		"Be analytical, avoid generalities, and ensure that each section supports data-backed reasoning that could inform healthcare policy or financial modeling.",472	}, "\n")473	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{474		Model:     "gpt-6-astra",475		Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortXhigh},476		Tools:     []responses.ToolUnionParam{tool},477		Input:     responses.ResponseNewParamsInputUnion{OfString: openai.String(input)},478	})479	if err != nil {480		panic(err)481	}482	fmt.Println(response.OutputText())483}484```485486```java487import com.openai.client.OpenAIClient;488import com.openai.client.okhttp.OpenAIOkHttpClient;489import com.openai.core.JsonValue;490import com.openai.models.Reasoning;491import com.openai.models.ReasoningEffort;492import com.openai.models.responses.ResponseCreateParams;493import com.openai.models.responses.WebSearchTool;494495ResponseCreateParams params =496    ResponseCreateParams.builder()497        .model("gpt-6-astra")498        .input(499            "Research the economic impact of semaglutide on global healthcare systems. Include current figures and citations.")500        .reasoning(Reasoning.builder().effort(ReasoningEffort.XHIGH).build())501        .addTool(502            WebSearchTool.builder()503                .type(WebSearchTool.Type.WEB_SEARCH)504                .putAdditionalProperty("return_token_budget", JsonValue.from("unlimited"))505                .build())506        .build();507508client.responses().create(params).output().stream()509    .flatMap(item -> item.message().stream())510    .flatMap(message -> message.content().stream())511    .flatMap(content -> content.outputText().stream())512    .forEach(text -> System.out.println(text.text()));513```514515```ruby516require "openai"517518client = OpenAI::Client.new519response = client.responses.create(520  model: "gpt-6-astra",521  input: "Research the economic impact of semaglutide on global healthcare systems. Include current figures and citations.",522  reasoning: { effort: :xhigh },523  tools: [524    {525      type: :web_search,526      return_token_budget: :unlimited527    }528  ]529)530531puts(response.output_text)532```533534```bash535curl "https://api.openai.com/v1/responses" \536  -H "Content-Type: application/json" \537  -H "Authorization: Bearer $OPENAI_API_KEY" \538  -d '{539    "model": "gpt-6-astra",540    "reasoning": { "effort": "xhigh" },541    "tools": [542      {543        "type": "web_search",544        "return_token_budget": "unlimited"545      }546    ],547    "input": "Research the economic impact of semaglutide on global healthcare systems.\n\nDo:\n- Include specific figures, trends, statistics, and measurable outcomes.\n- Prioritize reliable, up-to-date sources: peer-reviewed research, health organizations (e.g., WHO, CDC), regulatory agencies, or pharmaceutical earnings reports.\n- Include inline citations and return all source metadata.\n\nBe analytical, avoid generalities, and ensure that each section supports data-backed reasoning that could inform healthcare policy or financial modeling."548  }'549```550551552553554## Domain filtering555556Domain filtering in web search lets you limit results to a specific set of domains. With the `filters` parameter you can configure up to 100 `allowed_domains` or up to 100 `blocked_domains`. When formatting domains, omit the HTTP or HTTPS prefix. For example, use `openai.com` instead of `https://openai.com/`. This approach also includes subdomains in the search. Note that domain filtering is only available in the Responses API with the `web_search` tool.557558559560## Sources561562To view all URLs retrieved during a web search, use the `sources` field. Unlike inline citations, which show only the most relevant references, sources returns the complete list of URLs the model consulted when forming its response.563The number of sources is often greater than the number of citations. Real-time third-party feeds are also surfaced here and are labeled as `oai-sports`, `oai-weather`, or `oai-finance`. The sources field is available with both the `web_search` and `web_search_preview` tools.564565List sources566567```javascript568import OpenAI from "openai";569const client = new OpenAI();570571const response = await client.responses.create({572  model: "gpt-6-astra",573  reasoning: { effort: "low" },574  tools: [575    {576      type: "web_search",577      filters: {578        allowed_domains: [579          "pubmed.ncbi.nlm.nih.gov",580          "clinicaltrials.gov",581          "www.who.int",582          "www.cdc.gov",583          "www.fda.gov",584        ],585        blocked_domains: ["reddit.com", "quora.com", "wikipedia.org"],586      },587    },588  ],589  tool_choice: "auto",590  include: ["web_search_call.action.sources"],591  input:592    "Please perform a web search on how semaglutide is used in the treatment of diabetes.",593});594595console.log(response.output_text);596```597598```python599from openai import OpenAI600601client = OpenAI()602603response = client.responses.create(604    model="gpt-6-astra",605    reasoning={"effort": "low"},606    tools=[607        {608            "type": "web_search",609            "filters": {610                "allowed_domains": [611                    "pubmed.ncbi.nlm.nih.gov",612                    "clinicaltrials.gov",613                    "www.who.int",614                    "www.cdc.gov",615                    "www.fda.gov",616                ],617                "blocked_domains": [618                    "reddit.com",619                    "quora.com",620                    "wikipedia.org",621                ],622            },623        }624    ],625    tool_choice="auto",626    include=["web_search_call.action.sources"],627    input="Please perform a web search on how semaglutide is used in the treatment of diabetes.",628)629630print(response.output_text)631```632633```go634package main635636import (637	"context"638	"fmt"639640	"github.com/openai/openai-go/v3"641	"github.com/openai/openai-go/v3/responses"642	"github.com/openai/openai-go/v3/shared"643)644645func main() {646	client := openai.NewClient()647	tool := responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch)648	tool.OfWebSearch.Filters = responses.WebSearchToolFiltersParam{649		AllowedDomains: []string{"pubmed.ncbi.nlm.nih.gov", "clinicaltrials.gov", "www.who.int", "www.cdc.gov", "www.fda.gov"},650	}651	tool.OfWebSearch.Filters.SetExtraFields(map[string]any{"blocked_domains": []string{"reddit.com", "quora.com", "wikipedia.org"}})652	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{653		Model:     "gpt-6-astra",654		Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortLow},655		Tools:     []responses.ToolUnionParam{tool},656		Include:   []responses.ResponseIncludable{responses.ResponseIncludableWebSearchCallActionSources},657		Input:     responses.ResponseNewParamsInputUnion{OfString: openai.String("Please perform a web search on how semaglutide is used in the treatment of diabetes.")},658	})659	if err != nil {660		panic(err)661	}662	fmt.Println(response.OutputText())663}664```665666```java667import com.openai.client.OpenAIClient;668import com.openai.client.okhttp.OpenAIOkHttpClient;669import com.openai.core.JsonValue;670import com.openai.models.Reasoning;671import com.openai.models.ReasoningEffort;672import com.openai.models.responses.ResponseCreateParams;673import com.openai.models.responses.ResponseIncludable;674import com.openai.models.responses.WebSearchTool;675import java.util.List;676677ResponseCreateParams params =678    ResponseCreateParams.builder()679        .model("gpt-6-astra")680        .input("Search for how semaglutide is used in the treatment of diabetes.")681        .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())682        .addInclude(ResponseIncludable.of("web_search_call.action.sources"))683        .addTool(684            WebSearchTool.builder()685                .type(WebSearchTool.Type.WEB_SEARCH)686                .filters(687                    WebSearchTool.Filters.builder()688                        .allowedDomains(689                            List.of(690                                "pubmed.ncbi.nlm.nih.gov",691                                "clinicaltrials.gov",692                                "www.who.int",693                                "www.cdc.gov",694                                "www.fda.gov"))695                        .putAdditionalProperty(696                            "blocked_domains",697                            JsonValue.from(List.of("reddit.com", "quora.com", "wikipedia.org")))698                        .build())699                .build())700        .build();701702var response = client.responses().create(params);703response.output().stream()704    .flatMap(item -> item.message().stream())705    .flatMap(message -> message.content().stream())706    .flatMap(content -> content.outputText().stream())707    .forEach(text -> System.out.println(text.text()));708response.output().stream()709    .flatMap(item -> item.webSearchCall().stream())710    .flatMap(call -> call.action().search().stream())711    .flatMap(action -> action.sources().stream())712    .flatMap(List::stream)713    .forEach(source -> System.out.println(source.url()));714```715716```ruby717require "openai"718719client = OpenAI::Client.new720721response = client.responses.create(722  model: "gpt-6-astra",723  reasoning: { effort: :low },724  input: "Search for how semaglutide is used in the treatment of diabetes.",725  include: ["web_search_call.action.sources"],726  tools: [727    {728      type: :web_search,729      filters: {730        allowed_domains: [731          "pubmed.ncbi.nlm.nih.gov",732          "clinicaltrials.gov",733          "www.who.int",734          "www.cdc.gov",735          "www.fda.gov"736        ],737        blocked_domains: ["reddit.com", "quora.com", "wikipedia.org"]738      }739    }740  ]741)742743puts(response.output_text)744response.output745        .grep(OpenAI::Models::Responses::ResponseFunctionWebSearch)746        .each do |search_call|747          action = search_call.action748          next unless action.is_a?(749            OpenAI::Models::Responses::ResponseFunctionWebSearch::Action::Search750          )751752          Array(action.sources).each { |source| puts(source.url) }753        end754```755756```bash757curl "https://api.openai.com/v1/responses" \758  -H "Content-Type: application/json" \759  -H "Authorization: Bearer $OPENAI_API_KEY" \760  -d '{761    "model": "gpt-6-astra",762    "reasoning": { "effort": "low" },763    "tools": [764      {765        "type": "web_search",766        "filters": {767          "allowed_domains": [768            "pubmed.ncbi.nlm.nih.gov",769            "clinicaltrials.gov",770            "www.who.int",771            "www.cdc.gov",772            "www.fda.gov"773          ],774          "blocked_domains": [775            "reddit.com",776            "quora.com",777            "wikipedia.org"778          ]779        }780      }781    ],782    "tool_choice": "auto",783    "include": ["web_search_call.action.sources"],784    "input": "Please perform a web search on how semaglutide is used in the treatment of diabetes."785  }'786```787788789790791792793## Image search results794795Web search can return image results alongside regular text results. Use image search when your application needs current or web-grounded visuals, such as product photos, landmarks, places, events, or visual references.796797To use image search, set `search_content_types` to include `image`. Add `text` when you also want supporting text results that help the model summarize, rank, or explain the retrieved images.798799Use `image_settings` to control image-specific behavior:800801- `max_results`: Request a positive number of image results.802- `caption`: Ask for short image descriptions when available.803804To inspect raw image results, include `web_search_call.results` in the request and read `web_search_call.results[]` from the response. Image results are returned separately from the assistant message, so parse the `web_search_call` item directly when your application needs the URLs or metadata.805806Search for images807808```javascript809import OpenAI from "openai";810const client = new OpenAI();811812const response = await client.responses.create({813  model: "gpt-6-astra",814  reasoning: { effort: "low" },815  tools: [816    {817      type: "web_search",818      search_content_types: ["image", "text"],819      image_settings: {820        max_results: 3,821        caption: true,822      },823    },824  ],825  include: ["web_search_call.results"],826  input:827    "Search for recent images and supporting text sources about the Golden Gate Bridge at sunset.",828});829830console.log(response.output);831```832833```python834from openai import OpenAI835836client = OpenAI()837838response = client.responses.create(839    model="gpt-6-astra",840    reasoning={"effort": "low"},841    tools=[842        {843            "type": "web_search",844            "search_content_types": ["image", "text"],845            "image_settings": {846                "max_results": 3,847                "caption": True,848            },849        }850    ],851    include=["web_search_call.results"],852    input="Search for recent images and supporting text sources about the Golden Gate Bridge at sunset.",853)854855print(response.output)856```857858```go859package main860861import (862	"context"863	"fmt"864865	"github.com/openai/openai-go/v3"866	"github.com/openai/openai-go/v3/responses"867	"github.com/openai/openai-go/v3/shared"868)869870func main() {871	client := openai.NewClient()872	tool := responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch)873	tool.OfWebSearch.SetExtraFields(map[string]any{874		"search_content_types": []string{"image", "text"},875		"image_settings":       map[string]any{"max_results": 3, "caption": true},876	})877	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{878		Model:     "gpt-6-astra",879		Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortLow},880		Tools:     []responses.ToolUnionParam{tool},881		Include:   []responses.ResponseIncludable{responses.ResponseIncludableWebSearchCallResults},882		Input:     responses.ResponseNewParamsInputUnion{OfString: openai.String("Search for recent images and supporting text sources about the Golden Gate Bridge at sunset.")},883	})884	if err != nil {885		panic(err)886	}887	fmt.Println(response.Output)888}889```890891```java892import com.openai.client.OpenAIClient;893import com.openai.client.okhttp.OpenAIOkHttpClient;894import com.openai.core.JsonValue;895import com.openai.models.Reasoning;896import com.openai.models.ReasoningEffort;897import com.openai.models.responses.ResponseCreateParams;898import com.openai.models.responses.ResponseIncludable;899import com.openai.models.responses.WebSearchTool;900import java.util.List;901import java.util.Map;902903ResponseCreateParams params =904    ResponseCreateParams.builder()905        .model("gpt-6-astra")906        .input(907            "Search for recent images and supporting text sources about the Golden Gate Bridge at sunset.")908        .reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())909        .addInclude(ResponseIncludable.of("web_search_call.results"))910        .addTool(911            WebSearchTool.builder()912                .type(WebSearchTool.Type.WEB_SEARCH)913                .putAdditionalProperty(914                    "search_content_types", JsonValue.from(List.of("image", "text")))915                .putAdditionalProperty(916                    "image_settings", JsonValue.from(Map.of("max_results", 3, "caption", true)))917                .build())918        .build();919920client.responses().create(params).output().stream()921    .flatMap(item -> item.webSearchCall().stream())922    .map(call -> call._additionalProperties().get("results"))923    .filter(java.util.Objects::nonNull)924    .forEach(System.out::println);925```926927```ruby928require "openai"929930client = OpenAI::Client.new931932response = client.responses.create(933  model: "gpt-6-astra",934  reasoning: { effort: :low },935  input: "Search for recent images and supporting text sources about the Golden Gate Bridge at sunset.",936  include: ["web_search_call.results"],937  tools: [938    {939      type: :web_search,940      search_content_types: ["image", "text"],941      image_settings: {942        max_results: 3,943        caption: true944      }945    }946  ]947)948949puts(response.output)950```951952```bash953curl "https://api.openai.com/v1/responses" \954  -H "Content-Type: application/json" \955  -H "Authorization: Bearer $OPENAI_API_KEY" \956  -d '{957    "model": "gpt-6-astra",958    "reasoning": { "effort": "low" },959    "tools": [960      {961        "type": "web_search",962        "search_content_types": ["image", "text"],963        "image_settings": {964          "max_results": 3,965          "caption": true966        }967      }968    ],969    "include": ["web_search_call.results"],970    "input": "Search for recent images and supporting text sources about the Golden Gate Bridge at sunset."971  }'972```973974975Each `image_result` includes:976977- `image_url`: The canonical image URL for the result.978- `source_website_url`: The page where the image was found.979- `thumbnail_url`: A thumbnail URL when available.980- `caption`: A short caption or description when available.981982```json983{984  "output": [985    {986      "type": "web_search_call",987      "status": "completed",988      "results": [989        {990          "type": "image_result",991          "image_url": "https://cdn.example/golden-gate-sunset.jpg",992          "thumbnail_url": "https://cdn.example/golden-gate-sunset-thumb.jpg",993          "source_website_url": "https://example.com/source-page",994          "caption": "Golden Gate Bridge at sunset"995        }996      ]997    }998  ]999}1000```1001100210031004## User location10051006To refine search results based on geography, you can specify an approximate user location using country, city, region, and/or timezone.10071008- The `city` and `region` fields are free text strings, like `Minneapolis` and `Minnesota` respectively.1009- The `country` field is a two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1), like `US`.1010- The `timezone` field is an [IANA timezone](https://timeapi.io/documentation/iana-timezones) like `America/Chicago`.10111012Note that user location is not supported for deep research models using web1013  search.1014101510161017Customizing user location10181019```javascript1020import OpenAI from "openai";1021const openai = new OpenAI();10221023const response = await openai.responses.create({1024  model: "gpt-6-astra",1025  tools: [1026    {1027      type: "web_search",1028      user_location: {1029        type: "approximate",1030        country: "GB",1031        city: "London",1032        region: "London",1033      },1034    },1035  ],1036  input: "What are the best restaurants near me?",1037});1038console.log(response.output_text);1039```10401041```python1042from openai import OpenAI10431044client = OpenAI()10451046response = client.responses.create(1047    model="gpt-6-astra",1048    tools=[1049        {1050            "type": "web_search",1051            "user_location": {1052                "type": "approximate",1053                "country": "GB",1054                "city": "London",1055                "region": "London",1056            },1057        }1058    ],1059    input="What are the best restaurants near me?",1060)10611062print(response.output_text)1063```10641065```go1066package main10671068import (1069	"context"1070	"fmt"10711072	"github.com/openai/openai-go/v3"1073	"github.com/openai/openai-go/v3/responses"1074)10751076func main() {1077	client := openai.NewClient()1078	tool := responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch)1079	tool.OfWebSearch.UserLocation = responses.WebSearchToolUserLocationParam{1080		Type:    "approximate",1081		Country: openai.String("GB"),1082		City:    openai.String("London"),1083		Region:  openai.String("London"),1084	}1085	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1086		Model: "gpt-6-astra",1087		Tools: []responses.ToolUnionParam{tool},1088		Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What are the best restaurants near me?")},1089	})1090	if err != nil {1091		panic(err)1092	}1093	fmt.Println(response.OutputText())1094}1095```10961097```java1098import com.openai.client.OpenAIClient;1099import com.openai.client.okhttp.OpenAIOkHttpClient;1100import com.openai.models.responses.ResponseCreateParams;1101import com.openai.models.responses.WebSearchTool;11021103ResponseCreateParams params =1104    ResponseCreateParams.builder()1105        .model("gpt-6-astra")1106        .input("What are the best restaurants near me?")1107        .addTool(1108            WebSearchTool.builder()1109                .type(WebSearchTool.Type.WEB_SEARCH)1110                .userLocation(1111                    WebSearchTool.UserLocation.builder()1112                        .type(WebSearchTool.UserLocation.Type.APPROXIMATE)1113                        .city("London")1114                        .country("GB")1115                        .region("London")1116                        .build())1117                .build())1118        .build();11191120client.responses().create(params).output().stream()1121    .flatMap(item -> item.message().stream())1122    .flatMap(message -> message.content().stream())1123    .flatMap(content -> content.outputText().stream())1124    .forEach(text -> System.out.println(text.text()));1125```11261127```csharp1128using OpenAI.Responses;1129#pragma warning disable OPENAI00111301131string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;1132ResponsesClient client = new(key);11331134CreateResponseOptions options = new() { Model = "gpt-6-astra" };1135options.Tools.Add(1136    ResponseTool.CreateWebSearchTool(1137        userLocation: WebSearchToolLocation.CreateApproximateLocation(1138            country: "GB",1139            city: "London",1140            region: "London"1141        )1142    )1143);1144options.InputItems.Add(1145    ResponseItem.CreateUserMessageItem("What are the best restaurants near me?")1146);11471148ResponseResult response = await client.CreateResponseAsync(options);11491150Console.WriteLine(response.GetOutputText());1151```11521153```ruby1154require "openai"11551156client = OpenAI::Client.new11571158response = client.responses.create(1159  model: "gpt-6-astra",1160  input: "What are the best restaurants near me?",1161  tools: [1162    {1163      type: :web_search,1164      user_location: {1165        type: :approximate,1166        country: "GB",1167        city: "London",1168        region: "London"1169      }1170    }1171  ]1172)11731174puts(response.output_text)1175```11761177```bash1178curl "https://api.openai.com/v1/responses" \1179    -H "Content-Type: application/json" \1180    -H "Authorization: Bearer $OPENAI_API_KEY" \1181    -d '{1182        "model": "gpt-6-astra",1183        "tools": [{1184            "type": "web_search",1185            "user_location": {1186                "type": "approximate",1187                "country": "GB",1188                "city": "London",1189                "region": "London"1190            }1191        }],1192        "input": "What are the best restaurants near me?"1193    }'1194```1195119611971198119912001201## Live internet access12021203Control whether the web search tool fetches live content or uses only cached/indexed results in the Responses API.12041205- Set `external_web_access: false` on the `web_search` tool to run in offline/cache‑only mode.1206- Default is `true` (live access) if you do not set it.1207- Preview variants (`web_search_preview`) ignore this parameter and behave as if `external_web_access` is `true`.1208120912101211Control live internet access12121213```bash1214curl "https://api.openai.com/v1/responses" \1215  -H "Content-Type: application/json" \1216  -H "Authorization: Bearer $OPENAI_API_KEY" \1217  -d '{1218    "model": "gpt-6-astra",1219    "tools": [1220      { "type": "web_search", "external_web_access": false }1221    ],1222    "tool_choice": "auto",1223    "input": "Find when the Eiffel Tower opened to the public and cite the source."1224  }'1225```12261227```javascript1228import OpenAI from "openai";1229const client = new OpenAI();12301231const response = await client.responses.create({1232  model: "gpt-6-astra",1233  tools: [{ type: "web_search", external_web_access: false }],1234  tool_choice: "auto",1235  input: "Find when the Eiffel Tower opened to the public and cite the source.",1236});12371238console.log(response.output_text);1239```12401241```python1242from openai import OpenAI12431244client = OpenAI()12451246resp = client.responses.create(1247    model="gpt-6-astra",1248    tools=[{"type": "web_search", "external_web_access": False}],1249    tool_choice="auto",1250    input="Find when the Eiffel Tower opened to the public and cite the source.",1251)1252print(resp.output_text)1253```12541255```go1256package main12571258import (1259	"context"1260	"fmt"12611262	"github.com/openai/openai-go/v3"1263	"github.com/openai/openai-go/v3/responses"1264)12651266func main() {1267	client := openai.NewClient()1268	tool := responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch)1269	tool.OfWebSearch.SetExtraFields(map[string]any{"external_web_access": false})1270	response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1271		Model: "gpt-6-astra",1272		Tools: []responses.ToolUnionParam{tool},1273		Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Find when the Eiffel Tower opened to the public and cite the source.")},1274	})1275	if err != nil {1276		panic(err)1277	}1278	fmt.Println(response.OutputText())1279}1280```12811282```java1283import com.openai.client.OpenAIClient;1284import com.openai.client.okhttp.OpenAIOkHttpClient;1285import com.openai.core.JsonValue;1286import com.openai.models.responses.ResponseCreateParams;1287import com.openai.models.responses.WebSearchTool;12881289ResponseCreateParams params =1290    ResponseCreateParams.builder()1291        .model("gpt-6-astra")1292        .input("Find when the Eiffel Tower opened to the public and cite the source.")1293        .addTool(1294            WebSearchTool.builder()1295                .type(WebSearchTool.Type.WEB_SEARCH)1296                .putAdditionalProperty("external_web_access", JsonValue.from(false))1297                .build())1298        .build();12991300client.responses().create(params).output().stream()1301    .flatMap(item -> item.message().stream())1302    .flatMap(message -> message.content().stream())1303    .flatMap(content -> content.outputText().stream())1304    .forEach(text -> System.out.println(text.text()));1305```13061307```ruby1308require "openai"13091310client = OpenAI::Client.new13111312response = client.responses.create(1313  model: "gpt-6-astra",1314  input: "Find when the Eiffel Tower opened to the public and cite the source.",1315  tools: [1316    {1317      type: :web_search,1318      external_web_access: false1319    }1320  ]1321)13221323puts(response.output_text)1324```13251326132713281329## Limitations13301331#### Chat Completions API13321333The Chat Completions API supports only specialized search models for web search. These models do not support Responses API `web_search` features such as domain filters, complete source lists, live-access control, and returned-token budget control.13341335| Model                        | Context window | Limitation                                                                                                                                   |1336| ---------------------------- | -------------: | -------------------------------------------------------------------------------------------------------------------------------------------- |1337| `gpt-5-search-api`           |           200k | Uses the Chat Completions search model path                                                                                                  |1338| `gpt-4o-search-preview`      |           128k | Uses the Chat Completions search model path; [deprecated, shutdown 2026-07-23](https://developers.openai.com/api/docs/deprecations#2026-04-22-legacy-gpt-model-snapshots) |1339| `gpt-4o-mini-search-preview` |           128k | Uses the Chat Completions search model path; [deprecated, shutdown 2026-07-23](https://developers.openai.com/api/docs/deprecations#2026-04-22-legacy-gpt-model-snapshots) |13401341#### Responses API13421343Use the hosted `web_search` tool. The Responses API still accepts `web_search_preview` for legacy integrations, but use `web_search` for new integrations.13441345For a larger model context window, use `gpt-5.5`. The web search context window remains 128k.13461347| Model          | Model context window | Limitation                                                                                                                         |1348| -------------- | -------------------: | ---------------------------------------------------------------------------------------------------------------------------------- |1349| `gpt-4.1`      |                   1M | Search context is limited to 128k                                                                                                  |1350| `gpt-4.1-mini` |                   1M | Search context is limited to 128k                                                                                                  |1351| `o4-mini`      |                 200k | Search context is limited to 128k; [deprecated, shutdown 2026-10-23](https://developers.openai.com/api/docs/deprecations#2026-04-22-legacy-gpt-model-snapshots) |13521353For Responses API web search, the search context window is limited to 128k, even when the model context window is larger.13541355- Web search does not support [`gpt-5`](https://developers.openai.com/api/docs/models/gpt-5) with `minimal` reasoning.1356- [`gpt-5.4`](https://developers.openai.com/api/docs/models/gpt-5.4) with reasoning effort set to `none` may produce lower-quality results.1357- Responses API web search uses the underlying model's tiered rate limits.1358- `web_search_preview` does not support `filters` or `return_token_budget`, and ignores `external_web_access`.1359- With `tool_choice: "auto"`, search is optional. Use `tool_choice: "required"` or a specific web search tool choice when search must run.13601361## Usage notes13621363<table>1364<tbody>13651366<tr>1367  <th>API Availability</th>1368  <th>Rate limits</th>1369  <th>Notes</th>1370</tr>13711372<tr>1373  <td>1374    13751376      [Responses](https://developers.openai.com/api/reference/resources/responses)1377    13781379    13801381      [Chat Completions](https://developers.openai.com/api/reference/resources/chat)1382    13831384    13851386      [Assistants](https://developers.openai.com/api/reference/resources/beta/subresources/assistants)1387    13881389  </td>1390  <td style={{ maxWidth: "150px" }}>1391    Same as tiered rate limits for underlying [model](https://developers.openai.com/api/docs/models) used1392    with the tool.1393  </td>1394  <td style={{ maxWidth: "150px" }}>1395    [Pricing](https://developers.openai.com/api/docs/pricing#built-in-tools) 13961397    [ZDR and data residency](https://developers.openai.com/api/docs/guides/your-data)1398  </td>1399</tr>14001401</tbody>1402</table>
Files main
Menu

Theme