SPB Git

Repository Public

web-search.md 8.6 KB 347 lines markdown

1<!-- source: https://docs.x.ai/developers/tools/web-search (from https://docs.x.ai/llms-full.txt, retrieved 2026-09-19T05:28:55Z) -->2#### Tools34# Web Search56The Web Search tool enables Grok to search the web in real-time and browse web pages to find information. This powerful tool allows the model to search the internet, access web pages, and extract relevant information to answer queries with up-to-date content.78## SDK Support910| SDK/API | Tool Name |11|---------|-----------|12| xAI SDK | `web_search` |13| OpenAI Responses API | `web_search` |14| Vercel AI SDK | `xai.tools.webSearch()` |1516This tool is also supported in all Responses API compatible SDKs.1718## Basic Usage1920```pythonXAI21import os2223from xai_sdk import Client24from xai_sdk.chat import user25from xai_sdk.tools import web_search2627client = Client(api_key=os.getenv("XAI_API_KEY"))28chat = client.chat.create(29    model="grok-4.6",  # reasoning model30    tools=[web_search()],31    include=["verbose_streaming"],32)3334chat.append(user("What is xAI?"))3536is_thinking = True37for response, chunk in chat.stream():38    for tool_call in chunk.tool_calls:39        print(f"\\nCalling tool: {tool_call.function.name} with arguments: {tool_call.function.arguments}")40    if response.usage.reasoning_tokens and is_thinking:41        print(f"\\rThinking... ({response.usage.reasoning_tokens} tokens)", end="", flush=True)42    if chunk.content and is_thinking:43        print("\\n\\nFinal Response:")44        is_thinking = False45    if chunk.content and not is_thinking:46        print(chunk.content, end="", flush=True)4748print("\\n\\nCitations:")49print(response.citations)50```5152```pythonOpenAISDK53import os54from openai import OpenAI5556api_key = os.getenv("XAI_API_KEY")57client = OpenAI(58    api_key=api_key,59    base_url="https://api.x.ai/v1",60)6162response = client.responses.create(63    model="grok-4.6",64    input=[65        {66            "role": "user",67            "content": "What is xAI?",68        },69    ],70    tools=[71        {72            "type": "web_search",73        },74    ],75)7677print(response)78```7980```javascriptAISDK81import { xai } from '@ai-sdk/xai';82import { generateText } from 'ai';8384const { text, sources } = await generateText({85  model: xai.responses('grok-4.6'),86  prompt: 'What is xAI?',87  tools: {88    web_search: xai.tools.webSearch(),89  },90});9192console.log(text);93console.log('Citations:', sources);94```9596```bash97curl https://api.x.ai/v1/responses \\98  -H "Content-Type: application/json" \\99  -H "Authorization: Bearer $XAI_API_KEY" \\100  -d '{101  "model": "grok-4.6",102  "input": [103    {104      "role": "user",105      "content": "What is xAI?"106    }107  ],108  "tools": [109    {110      "type": "web_search"111    }112  ]113}'114```115116## Web Search Parameters117118| Parameter | Description |119|-----------|-------------|120| `allowed_domains` | Only search within specific domains (max 5) |121| `excluded_domains` | Exclude specific domains from search (max 5) |122| `enable_image_understanding` | Enable analysis of images found during browsing |123| `enable_image_search` | Enable image search results that can be embedded in responses |124125### Only Search in Specific Domains126127Use `allowed_domains` to make the web search **only** perform the search and web browsing on web pages that fall within the specified domains.128129> [!NOTE]130>131> `allowed_domains` cannot be set together with `excluded_domains` in the same request.132133```pythonXAI134import os135136from xai_sdk import Client137from xai_sdk.chat import user138from xai_sdk.tools import web_search139140client = Client(api_key=os.getenv("XAI_API_KEY"))141chat = client.chat.create(142    model="grok-4.6",143    tools=[144        web_search(allowed_domains=["grokipedia.com"]),145    ],146)147148chat.append(user("What is xAI?"))149# stream or sample the response...150```151152```pythonOpenAISDK153response = client.responses.create(154    model="grok-4.6",155    input=[{"role": "user", "content": "What is xAI?"}],156    tools=[157        {158            "type": "web_search",159            "filters": {"allowed_domains": ["grokipedia.com"]},160        },161    ],162)163```164165```javascriptAISDK166const { text } = await generateText({167  model: xai.responses('grok-4.6'),168  prompt: 'What is xAI?',169  tools: {170    web_search: xai.tools.webSearch({171      allowedDomains: ['grokipedia.com'],172    }),173  },174});175```176177### Exclude Specific Domains178179Use `excluded_domains` to prevent the model from including the specified domains in any web search tool invocations.180181```pythonXAI182chat = client.chat.create(183    model="grok-4.6",184    tools=[185        web_search(excluded_domains=["grokipedia.com"]),186    ],187)188```189190```pythonOpenAISDK191response = client.responses.create(192    model="grok-4.6",193    input=[{"role": "user", "content": "What is xAI?"}],194    tools=[195        {196            "type": "web_search",197            "filters": {"excluded_domains": ["grokipedia.com"]},198        },199    ],200)201```202203### Enable Image Understanding204205Setting `enable_image_understanding` to true equips the agent with access to the `view_image` tool, allowing it to analyze images encountered during the search process.206207When enabled, you will see `SERVER_SIDE_TOOL_VIEW_IMAGE` in `response.server_side_tool_usage` along with the number of times it was called.208209> [!NOTE]210>211> Enabling this parameter for Web Search will also enable the image understanding for X Search tool if it's also included in the request.212213```pythonXAI214import os215216from xai_sdk import Client217from xai_sdk.chat import user218from xai_sdk.tools import web_search219220client = Client(api_key=os.getenv("XAI_API_KEY"))221chat = client.chat.create(222    model="grok-4.6",223    tools=[224        web_search(enable_image_understanding=True),225    ],226)227228chat.append(user("What is included in the image in xAI's official website?"))229# stream or sample the response...230```231232```pythonOpenAISDK233response = client.responses.create(234    model="grok-4.6",235    input=[236        {237            "role": "user",238            "content": "What is included in the image in xAI's official website?",239        },240    ],241    tools=[242        {243            "type": "web_search",244            "enable_image_understanding": True,245        },246    ],247)248```249250```javascriptAISDK251const { text } = await generateText({252  model: xai.responses('grok-4.6'),253  prompt: "What is included in the image in xAI's official website?",254  tools: {255    web_search: xai.tools.webSearch({256      enableImageUnderstanding: true,257    }),258  },259});260```261262### Enable Image Search263264Setting `enable_image_search` to true lets Grok search for relevant images and include them in the response as Markdown image embeds such as `![alt](url)`.265266> [!NOTE]267>268> After Grok searches for images, the returned images are included in the model context used to write the response. This is separate from `enable_image_understanding`, which lets Grok inspect images it finds while browsing regular web pages.269270The Vercel AI SDK does not yet expose `enableImageSearch`; the examples below use the Responses API and xAI Python SDK.271272```bash customLanguage="bash"273curl https://api.x.ai/v1/responses \274  -H "Content-Type: application/json" \275  -H "Authorization: Bearer $XAI_API_KEY" \276  -d '{277  "model": "grok-4.6",278  "input": [279    {280      "role": "user",281      "content": "Show me images of Starship on the launch pad."282    }283  ],284  "tools": [285    {286      "type": "web_search",287      "enable_image_search": true288    }289  ]290}'291```292293```python customLanguage="pythonXAI"294import os295296from xai_sdk import Client297from xai_sdk.chat import user298from xai_sdk.tools import web_search299300client = Client(api_key=os.getenv("XAI_API_KEY"))301chat = client.chat.create(302    model="grok-4.6",303    tools=[304        web_search(enable_image_search=True),305    ],306)307308chat.append(user("Show me images of Starship on the launch pad."))309response = chat.sample()310print(response.content)311print(response.server_side_tool_usage)312```313314```python customLanguage="pythonOpenAISDK"315response = client.responses.create(316    model="grok-4.6",317    input=[318        {319            "role": "user",320            "content": "Show me images of Starship on the launch pad.",321        },322    ],323    tools=[324        {325            "type": "web_search",326            "enable_image_search": True,327        },328    ],329)330331print(response)332```333334A response can include Markdown image embeds directly in the output text:335336```output337![Why the SpaceX Starship launch pad matters](https://www.astronomy.com/wp-content/uploads/2024/09/starship-test-flight-mission-scaled.jpg)338339Here are several high-quality images of SpaceX's Starship on the launch pad at Starbase in Boca Chica, Texas.340```341342In the xAI SDK, successful image search executions appear in `response.server_side_tool_usage` as `SERVER_SIDE_TOOL_IMAGE_SEARCH`.343344## Citations345346For details on how to retrieve and use citations from search results, see the [Citations](/developers/tools/citations) page.347
Files main
Menu

Theme