Skip to content
,

Grok API Search Tools in Python: Web Search and X Search Guide

11–16 minutes
Woman in a sunny cafe holding a tablet with a GROK API card, hook $5 per 1K Grok search calls

The Grok API no longer uses the old Live Search search_parameters block. Web and X search now run as server-side tools called web_search and x_search, and Grok decides when to call them.

That change matters for your code and your bill. X Search is now billed per post and per profile fetched, not per call, so one careless query can cost far more than the tokens.

This guide shows you how to use both tools from Python, with the xAI SDK and with the OpenAI SDK, plus filters, citations, real prices and fixes.

TLDR

  • Tool names: web_search and x_search, used through the Responses API (/v1/responses) or the xAI Python SDK.
  • Live Search is gone: old search_parameters requests were reported to return a 410 error. Move to the tools API.
  • Web Search price: $5 per 1,000 successful calls, plus tokens.
  • X Search price: $5 per 1,000 posts fetched and $10 per 1,000 user profiles fetched, plus tokens (since 21 September 2026).
  • Filters: up to 5 allowed or excluded domains, up to 20 allowed or excluded X handles, and a from_date / to_date range.
  • Cost control: use max_turns, narrow handles and dates, and read server_side_tool_usage_details.

What Are Grok Search Tools (and What Happened to Live Search)

Grok search tools are built-in, server-side tools. You list them in the tools array, and the model runs the searches on xAI’s servers, reads the results and writes an answer with citations.

You do not run any search code yourself. This is different from function calling, where the model asks you to run a function and send back the result.

The two search tools

  • web_search: searches the internet and browses pages. It can also look at images and return image results.
  • x_search: searches X posts with keyword search, semantic search, user search and thread fetch.

What happened to Live Search

The older Live Search feature used a search_parameters object on Chat Completions requests. The old Live Search guide on the xAI docs now redirects to the Web Search tool page.

Developers on the Make community forum reported that old requests now fail with a 410 error that says Live Search is deprecated and points to the Agent Tools API. If you still have search_parameters in your code, it needs to be rewritten.

Note: xAI is now branded SpaceXSI, and the docs moved to docs.grok.com. The API itself still lives at https://api.x.ai/v1, and the examples still read the key from XAI_API_KEY.

When to use which tool

You want Use Why
News, docs, product pages, prices web_search Flat $5 per 1,000 calls, any public site
What people are saying right now x_search Direct access to X posts, threads and profiles
Posts from one brand or person x_search + allowed_x_handles Limits fetched posts, so it costs less
Answers from your own docs site only web_search + allowed_domains Up to 5 trusted domains
Broad research Both tools together The model picks the best source per step

Setup: Keys, SDKs and Your First Search

You can call the search tools in two ways from Python. The xAI SDK (xai-sdk, gRPC) and the OpenAI SDK pointed at https://api.x.ai/v1 using the Responses API.

For this guide I checked xai-sdk 1.21.0 (released 23 October 2026, needs Python 3.10 or newer) and openai 3.63.0 on PyPI. The model in every example is grok-4.7, the model the official docs use.

  1. Get an API key. Create a key in the Grok Console. If you need help, follow how to get a Grok API key.
  2. Save it as an environment variable. On macOS or Linux run export XAI_API_KEY="your-key". On Windows PowerShell run $env:XAI_API_KEY="your-key".
  3. Install the SDKs. Run pip install -U xai-sdk openai inside a virtual environment.
  4. Pick an endpoint. Use the Responses API (client.responses.create) with the OpenAI SDK, or client.chat.create with the xAI SDK. Search tools are listed for these, not for the old Chat Completions search_parameters.
  5. Run the first example below. Check that the answer prints, then look at the citations list.

If you are new to the Grok API in general, start with my Grok API Python tutorial first, then come back here.

Example 1: first web search with the OpenAI SDK

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("XAI_API_KEY"),
    base_url="https://api.x.ai/v1",
)

response = client.responses.create(
    model="grok-4.7",
    input=[{"role": "user", "content": "What did xAI announce this week?"}],
    tools=[{"type": "web_search"}],
)

print(response.output_text)

The same call with curl

curl https://api.x.ai/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
    "model": "grok-4.7",
    "input": [{"role": "user", "content": "What did xAI announce this week?"}],
    "tools": [{"type": "web_search"}]
  }'

The web_search tool takes five optional settings. The names are the same in both SDKs, but the OpenAI SDK puts the domain lists inside a filters object.

xAI Web search parameters table showing allowed_domains and excluded_domains (max 5), enable_image_understanding, enable_image_search and user_location
Official Grok API Web Search docs: the five web_search parameters (checked 3 Dec 2026).
Parameter What it does Limit
allowed_domains Only search and browse these domains Max 5. Cannot be used with excluded_domains
excluded_domains Never use these domains Max 5
enable_image_understanding Gives the model a view_image tool for images it finds Image tokens are billed
enable_image_search Finds images and embeds them as Markdown in the answer Separate from image understanding
user_location Localizes results such as “weather today” Country (ISO alpha-2), city, region, IANA timezone

The SDK docstring says domains are written without the protocol or subdomain, for example example.com, not https://www.example.com.

Example 2: domain filter and location with the xAI SDK

import os
from xai_sdk import Client
from xai_sdk.chat import user
from xai_sdk.tools import web_search

client = Client(api_key=os.getenv("XAI_API_KEY"))

chat = client.chat.create(
    model="grok-4.7",
    tools=[
        web_search(
            allowed_domains=["python.org", "pypi.org"],
            user_location_country="US",
            user_location_timezone="America/Chicago",
        ),
    ],
    max_turns=3,
)

chat.append(user("What is the latest stable Python release?"))
response = chat.sample()

print(response.content)
print("Sources:", response.citations)
print("Usage:", response.server_side_tool_usage)

In the OpenAI SDK, the same domain filter is written as {"type": "web_search", "filters": {"allowed_domains": ["python.org"]}}. Location is an object: "user_location": {"type": "approximate", "country": "US", "city": "Austin"}.

Streaming and watching tool calls

With the xAI SDK you can stream and print each tool call as the model makes it. Each chunk has a tool_calls list with the function name and its arguments.

for response, chunk in chat.stream():
    for tool_call in chunk.tool_calls:
        print("Calling:", tool_call.function.name, tool_call.function.arguments)
    if chunk.content:
        print(chunk.content, end="", flush=True)

print("\nCitations:", response.citations)

Tip: Only the tool calls are shown, not the raw search results. xAI keeps the tool outputs on the server and uses them to write the final answer.

When you add x_search, the model can call four internal functions. It picks which ones to use and how often.

  • x_keyword_search: keyword search with X’s advanced operators, sorted by Top or Latest. Billed per post fetched.
  • x_semantic_search: search by meaning, not exact words. Billed per post fetched.
  • x_user_search: finds accounts by name or bio. Billed per profile fetched.
  • x_thread_fetch: gets one post with its parents and replies. Billed per post fetched.

X Search parameters

Parameter Type Notes
allowed_x_handles list of strings Only these handles, no “@”. Max 20. Not with excluded_x_handles
excluded_x_handles list of strings Skip these handles. Max 20
from_date string YYYY-MM-DD (Responses API) Starts at 00:00 UTC on that day
to_date string YYYY-MM-DD (Responses API) Excluded. For one day, set it to the next day
enable_image_understanding boolean Default false
enable_video_understanding boolean Default false. X Search only

Warning: Dates in any other format, including full date-times, are not applied. The request still runs, but with no date filter, so it may fetch far more posts than you expect.

Handle and date filters apply to every keyword and semantic search the model writes. Thread fetches ignore them.

Example 3: handles, dates and usage counts with the OpenAI SDK

import os
from openai import OpenAI

client = OpenAI(api_key=os.getenv("XAI_API_KEY"), base_url="https://api.x.ai/v1")

response = client.responses.create(
    model="grok-4.7",
    input="What did SpaceX post about Starship in November 2026?",
    tools=[{
        "type": "x_search",
        "allowed_x_handles": ["SpaceX"],
        "from_date": "2026-11-01",
        "to_date": "2026-12-01",
    }],
    extra_body={"max_turns": 2},
)

print(response.output_text)

details = response.usage.model_dump()["server_side_tool_usage_details"]
print("Posts fetched:", details["x_posts_fetched"])
print("Profiles fetched:", details["x_users_fetched"])

The max_turns setting is not part of the OpenAI SDK’s own arguments, so it goes in extra_body, exactly as the official example does.

Example 4: X Search with the xAI SDK

The xAI SDK is a little different. Its x_search() helper takes Python datetime objects for from_date and to_date, not strings (checked in the xai-sdk 1.21.0 source).

import os
from datetime import datetime
from xai_sdk import Client
from xai_sdk.chat import user
from xai_sdk.tools import x_search

client = Client(api_key=os.getenv("XAI_API_KEY"))

chat = client.chat.create(
    model="grok-4.7",
    tools=[
        x_search(
            allowed_x_handles=["xai", "grok"],
            from_date=datetime(2026, 11, 20),
            to_date=datetime(2026, 12, 3),
        ),
    ],
    include=["inline_citations"],
    max_turns=2,
)

chat.append(user("Summarize the latest Grok API updates posted on X."))
response = chat.sample()

print(response.content)
for c in response.inline_citations:
    if c.HasField("x_citation"):
        print(c.id, c.x_citation.url)

Reading Citations

Grok gives you two kinds of citation data. Knowing the difference saves confusion when a source shows up that the answer never mentions.

  • All citations: response.citations lists every URL the agent looked at. It is always returned. Some URLs may not be used in the final answer.
  • Inline citations: Markdown links like [[1]](https://x.ai/news) placed inside the answer text, plus structured position data.
Client Inline citations default How to change
Responses API (OpenAI SDK, curl) On Turn off with include=["no_inline_citations"]
xAI Python SDK Off Turn on with include=["inline_citations"] in chat.create()

Reading annotations in the Responses API

Each output_text block has an annotations list. Every item has type (“url_citation”), url, start_index, end_index and title (the citation number).

for item in response.output:
    if item.type == "message":
        for content in item.content:
            if content.type == "output_text":
                for a in content.annotations:
                    print(f"[{a.title}] {a.url} ({a.start_index}-{a.end_index})")

The index values follow Python slice rules, so text[a.start_index:a.end_index] gives you the exact [[N]](url) link. Numbers start at 1, and a source cited twice keeps its first number.

Note: Turning inline citations on does not force the model to cite every answer. It decides when a citation fits.

Pricing per Call and per Post, with a Worked Example

A search request has two costs. You pay token costs for the model, and tool invocation costs for each successful search. Failed tool calls are not billed.

Grok API pricing page tool invocation costs: web_search $5 per 1k calls, x_search $5 per 1k posts and $10 per 1k profiles
Official Grok API pricing page, tool invocation costs (checked 3 Dec 2026).
Item Price Billed on
Web Search (web_search) $5 per 1,000 calls Successful calls ($0.005 each)
X Search posts $5 per 1,000 posts x_posts_fetched ($0.005 each)
X Search profiles $10 per 1,000 profiles x_users_fetched ($0.01 each)
Image understanding / X video understanding No invocation fee Image or video tokens
grok-4.7 tokens (under 200k prompt) $2 input / $0.50 cached / $6 output per 1M All tokens
grok-4.7 tokens (200k+ prompt) $4 / $1 / $12 per 1M All tokens in that request
grok-4.3 tokens (under 200k) $1.25 / $0.20 / $2.50 per 1M All tokens

X Search post counts include parent posts, quoted posts and every post in a fetched thread. They add up across all X searches in a request and are not de-duplicated, so the same post found twice counts twice.

Worked example: one research request

Say one grok-4.7 request uses both tools. The numbers below are an illustration based on the docs’ own sample usage block, not a measured run.

Line Usage Math Cost
Web searches 3 calls 3 x $0.005 $0.015
X posts fetched 44 posts 44 x $0.005 $0.220
X profiles fetched 3 profiles 3 x $0.01 $0.030
Input tokens 30,000 (uncached) 30,000 / 1M x $2 $0.060
Output + reasoning tokens 2,000 2,000 / 1M x $6 $0.012
Total $0.337

The X posts are about 65% of the bill. At 1,000 requests a day, that is about $337 a day, and $220 of it is posts alone.

A quick web-only lookup costs much less. With 2 searches, 15,000 input tokens and 1,000 output tokens, it is $0.010 + $0.030 + $0.006 = $0.046. This example budgets reasoning tokens at the output rate.

Prompt tokens grow with every step, because each step resends the history. Most of that prompt can be served from cache at $0.50 per 1M, which lowers the token line. For plan prices and other models, see my Grok pricing guide (SuperGrok and API).

Limits and Cost Controls

Limit Value
Allowed or excluded domains 5 max, one list per request
Allowed or excluded X handles 20 max, one list per request
Date range format YYYY-MM-DD, to_date excluded, UTC
Video understanding X Search only
max_turns default A server-side global cap applies if you do not set it
grok-4.7 context 500k tokens; pricing doubles at 200k+ prompt tokens
Rate limits Per team, shown and raised in the Grok Console

How max_turns works

max_turns limits turns, not tool calls. In one turn the model can run several tools in parallel, so 2 turns can still mean 5 searches.

  • Quick lookups: 1-2 turns. Fastest, may miss detail.
  • Balanced research: 3-5 turns.
  • Deep research: 10 or more, or unset. Slowest and most expensive.

Five ways to spend less

  • Narrow X handles: allowed_x_handles cuts the posts fetched.
  • Set a tight date range: a week instead of a year.
  • Cap turns: start with max_turns=2 and raise it only if answers are thin.
  • Use web search for facts: a flat $0.005 per call is often cheaper than fetching dozens of posts.
  • Log usage: save server_side_tool_usage_details for every request and alert on spikes.

For how other providers price search, compare Claude’s web search API and Gemini grounding with Google Search.

Troubleshooting: Common Errors and Fixes

Error or symptom Likely cause Fix
410 “Live search is deprecated. Please switch to the Agent Tools API” Old search_parameters request Remove search_parameters and add web_search / x_search tools
400 Bad Request Invalid argument in the body. Setting both allowed and excluded lists, or going over a limit, is a likely trigger Use one list per request and stay under the limits
401 Unauthorized Missing or bad key Send Authorization: Bearer $XAI_API_KEY; check the env variable is set
403 Forbidden Key or team lacks permission or is blocked Ask your team admin in the Grok Console
404 Not Found Wrong model name or URL Use grok-4.7 and https://api.x.ai/v1
422 Unprocessable Entity A field has the wrong format Compare your JSON with the API reference
429 Too Many Requests Rate limit hit Back off and retry, or raise limits in the console
Date filter seems ignored Date not in YYYY-MM-DD Use plain dates (Responses API) or datetime objects (xAI SDK)
No [[1]] links in xAI SDK output Inline citations are off by default there Add include=["inline_citations"]
Bill much higher than expected Many X posts fetched and counted twice Check x_posts_fetched; add handles, dates and max_turns
tool_calls and usage counts differ Some tool calls failed (dead page, deleted post) Normal; only successful calls are billed

For general retry patterns, see my guide to LLM API rate limits and tiers. Check status.x.ai if every request fails at once.

Frequently Asked Questions

Is Grok Live Search still available in the API?

No. The old Live Search guide now redirects to the Web Search tool page, and developers report that search_parameters requests return a 410 error. Use the web_search and x_search tools instead.

How much does Grok web search cost per call?

Web Search costs $5 per 1,000 successful calls, which is $0.005 per call. You also pay normal token costs for the model.

How is X Search billed now?

Since 21 September 2026, X Search costs $5 per 1,000 posts fetched and $10 per 1,000 user profiles fetched, plus tokens. Counts are not de-duplicated.

Can I use the OpenAI Python SDK for Grok search?

Yes. Point the OpenAI client at https://api.x.ai/v1, call client.responses.create, and add {"type": "web_search"} or {"type": "x_search"} to tools.

How do I search only one website?

Add allowed_domains to the web search tool, for example ["python.org"]. You can list up to 5 domains, but you cannot also set excluded_domains.

How do I search X posts for a single day?

Set from_date to that day and to_date to the next day, because to_date is excluded. Use the YYYY-MM-DD format.

Why does response.citations include sites the answer never used?

That list holds every source the agent looked at, even ones it judged not relevant. Use inline citations or annotations to see which sources back each part of the answer.

Sources

Free weekly email

Get new AI guides every week

One short weekly email with our newest local AI, ComfyUI and AI tool guides. No spam, no pop-ups, just the good stuff.

Free. Unsubscribe anytime in one click. We only use your email to send this newsletter. See our privacy policy.

Woman in a sunny cafe holding a tablet with a GROK API card, hook $5 per 1K Grok search calls