SPB Git

Repository Public

x-search.md 8.8 KB 357 lines markdown

1<!-- source: https://docs.x.ai/developers/tools/x-search (from https://docs.x.ai/llms-full.txt, retrieved 2026-09-19T05:28:55Z) -->2#### Tools34# X Search56The X Search tool enables Grok to perform keyword search, semantic search, user search, and thread fetch on X (formerly Twitter). This powerful tool allows the model to access real-time social media content, analyze posts, and gather insights from X's vast data.78> [!WARNING]9> Pricing changes on September 21, 202610>11> Starting September 21, 2026 at 12:00 PM PT, X Search is billed at $5 per 1k posts fetched and $10 per 1k user profiles fetched, replacing the current $5 per 1k calls. Every post returned by a search or thread fetch, including parent and quoted posts, counts; every profile returned by a user search counts.1213## SDK Support1415| SDK/API | Tool Name |16|---------|-----------|17| xAI SDK | `x_search` |18| OpenAI Responses API | `x_search` |19| Vercel AI SDK | `xai.tools.xSearch()` |2021This tool is also supported in all Responses API compatible SDKs.2223## Basic Usage2425```pythonXAI26import os2728from xai_sdk import Client29from xai_sdk.chat import user30from xai_sdk.tools import x_search3132client = Client(api_key=os.getenv("XAI_API_KEY"))33chat = client.chat.create(34    model="grok-4.6",  # reasoning model35    tools=[x_search()],36    include=["verbose_streaming"],37)3839chat.append(user("What are people saying about xAI on X?"))4041is_thinking = True42for response, chunk in chat.stream():43    for tool_call in chunk.tool_calls:44        print(f"\\nCalling tool: {tool_call.function.name} with arguments: {tool_call.function.arguments}")45    if response.usage.reasoning_tokens and is_thinking:46        print(f"\\rThinking... ({response.usage.reasoning_tokens} tokens)", end="", flush=True)47    if chunk.content and is_thinking:48        print("\\n\\nFinal Response:")49        is_thinking = False50    if chunk.content and not is_thinking:51        print(chunk.content, end="", flush=True)5253print("\\n\\nCitations:")54print(response.citations)55```5657```pythonOpenAISDK58import os59from openai import OpenAI6061api_key = os.getenv("XAI_API_KEY")62client = OpenAI(63    api_key=api_key,64    base_url="https://api.x.ai/v1",65)6667response = client.responses.create(68    model="grok-4.6",69    input=[70        {71            "role": "user",72            "content": "What are people saying about xAI on X?",73        },74    ],75    tools=[76        {77            "type": "x_search",78        },79    ],80)8182print(response)83```8485```javascriptAISDK86import { xai } from '@ai-sdk/xai';87import { generateText } from 'ai';8889const { text, sources } = await generateText({90  model: xai.responses('grok-4.6'),91  prompt: 'What are people saying about xAI on X?',92  tools: {93    x_search: xai.tools.xSearch(),94  },95});9697console.log(text);98console.log('Citations:', sources);99```100101```bash102curl https://api.x.ai/v1/responses \\103  -H "Content-Type: application/json" \\104  -H "Authorization: Bearer $XAI_API_KEY" \\105  -d '{106  "model": "grok-4.6",107  "input": [108    {109      "role": "user",110      "content": "What are people saying about xAI on X?"111    }112  ],113  "tools": [114    {115      "type": "x_search"116    }117  ]118}'119```120121## X Search Parameters122123| Parameter | Description |124|-----------|-------------|125| `allowed_x_handles` | Only consider posts from specific X handles (max 20) |126| `excluded_x_handles` | Exclude posts from specific X handles (max 20) |127| `from_date` | Start date for search range (ISO8601 format) |128| `to_date` | End date for search range (ISO8601 format) |129| `enable_image_understanding` | Enable analysis of images in posts |130| `enable_video_understanding` | Enable analysis of videos in posts |131132### Only Consider Posts from Specific Handles133134Use `allowed_x_handles` to consider X posts only from a given list of X handles. The maximum number of handles you can include is 20.135136> [!NOTE]137>138> `allowed_x_handles` cannot be set together with `excluded_x_handles` in the same request.139140```pythonXAI141import os142143from xai_sdk import Client144from xai_sdk.chat import user145from xai_sdk.tools import x_search146147client = Client(api_key=os.getenv("XAI_API_KEY"))148chat = client.chat.create(149    model="grok-4.6",150    tools=[151        x_search(allowed_x_handles=["elonmusk"]),152    ],153)154155chat.append(user("What is the current status of xAI?"))156# stream or sample the response...157```158159```pythonOpenAISDK160response = client.responses.create(161    model="grok-4.6",162    input=[{"role": "user", "content": "What is the current status of xAI?"}],163    tools=[164        {165            "type": "x_search",166            "allowed_x_handles": ["elonmusk"],167        },168    ],169)170```171172```javascriptAISDK173const { text } = await generateText({174  model: xai.responses('grok-4.6'),175  prompt: 'What is the current status of xAI?',176  tools: {177    x_search: xai.tools.xSearch({178      allowedXHandles: ['elonmusk'],179    }),180  },181});182```183184### Exclude Posts from Specific Handles185186Use `excluded_x_handles` to prevent the model from including X posts from the specified handles in any X search tool invocations. The maximum number of handles you can exclude is 20.187188```pythonXAI189chat = client.chat.create(190    model="grok-4.6",191    tools=[192        x_search(excluded_x_handles=["elonmusk"]),193    ],194)195```196197```pythonOpenAISDK198response = client.responses.create(199    model="grok-4.6",200    input=[{"role": "user", "content": "What is the current status of xAI?"}],201    tools=[202        {203            "type": "x_search",204            "excluded_x_handles": ["elonmusk"],205        },206    ],207)208```209210```javascriptAISDK211const { text } = await generateText({212  model: xai.responses('grok-4.6'),213  prompt: 'What is the current status of xAI?',214  tools: {215    x_search: xai.tools.xSearch({216      excludedXHandles: ['elonmusk'],217    }),218  },219});220```221222### Date Range223224You can restrict the date range of search data used by specifying `from_date` and `to_date`. This limits the data to the period from `from_date` to `to_date`, including both dates.225226Both fields need to be in ISO8601 format, e.g., "YYYY-MM-DD". If you're using the xAI Python SDK, the `from_date` and `to_date` fields can be passed as `datetime.datetime` objects.227228```pythonXAI229import os230from datetime import datetime231232from xai_sdk import Client233from xai_sdk.chat import user234from xai_sdk.tools import x_search235236client = Client(api_key=os.getenv("XAI_API_KEY"))237chat = client.chat.create(238    model="grok-4.6",239    tools=[240        x_search(241            from_date=datetime(2025, 10, 1),242            to_date=datetime(2025, 10, 10),243        ),244    ],245)246247chat.append(user("What is the current status of xAI?"))248# stream or sample the response...249```250251```pythonOpenAISDK252response = client.responses.create(253    model="grok-4.6",254    input=[{"role": "user", "content": "What is the current status of xAI?"}],255    tools=[256        {257            "type": "x_search",258            "from_date": "2025-10-01",259            "to_date": "2025-10-10",260        },261    ],262)263```264265```javascriptAISDK266const { text } = await generateText({267  model: xai.responses('grok-4.6'),268  prompt: 'What is the current status of xAI?',269  tools: {270    x_search: xai.tools.xSearch({271      fromDate: '2025-10-01',272      toDate: '2025-10-10',273    }),274  },275});276```277278### Enable Image Understanding279280Setting `enable_image_understanding` to true allows the agent to analyze images in X posts encountered during the search process.281282```pythonXAI283chat = client.chat.create(284    model="grok-4.6",285    tools=[286        x_search(enable_image_understanding=True),287    ],288)289```290291```pythonOpenAISDK292response = client.responses.create(293    model="grok-4.6",294    input=[{"role": "user", "content": "Find X posts with images about AI"}],295    tools=[296        {297            "type": "x_search",298            "enable_image_understanding": True,299        },300    ],301)302```303304```javascriptAISDK305const { text } = await generateText({306  model: xai.responses('grok-4.6'),307  prompt: 'Find X posts with images about AI',308  tools: {309    x_search: xai.tools.xSearch({310      enableImageUnderstanding: true,311    }),312  },313});314```315316### Enable Video Understanding317318Setting `enable_video_understanding` to true allows the agent to analyze videos in X posts. This is only available for X Search (not Web Search).319320```pythonXAI321chat = client.chat.create(322    model="grok-4.6",323    tools=[324        x_search(enable_video_understanding=True),325    ],326)327```328329```pythonOpenAISDK330response = client.responses.create(331    model="grok-4.6",332    input=[{"role": "user", "content": "Find X posts with videos about AI"}],333    tools=[334        {335            "type": "x_search",336            "enable_video_understanding": True,337        },338    ],339)340```341342```javascriptAISDK343const { text } = await generateText({344  model: xai.responses('grok-4.6'),345  prompt: 'Find X posts with videos about AI',346  tools: {347    x_search: xai.tools.xSearch({348      enableVideoUnderstanding: true,349    }),350  },351});352```353354## Citations355356For details on how to retrieve and use citations from search results, see the [Citations](/developers/tools/citations) page.357
Files main
Menu

Theme