xAI Grok Search
Search the web and X (Twitter) using xAI's Grok API with real-time internet access, citations, and optional image/video understanding.
Setup
export XAI_API_KEY="your-key-here"
Get API key from: https://console.x.ai/
When to Use
Web Search:
- Current info from websites, news, documentation
- Real-time data (stock prices, weather, events)
- Research with up-to-date sources
- Finding info from specific domains
X/Twitter Search:
- What people are saying about a topic on X
- Trending discussions and sentiment
- Real-time reactions to events
- Posts from specific handles within date ranges
Usage via curl/Python
Web Search
import os, json, requests
def grok_web_search(query, allowed_domains=None, excluded_domains=None):
tool = {"type": "web_search"}
if allowed_domains: tool["allowed_domains"] = allowed_domains
if excluded_domains: tool["excluded_domains"] = excluded_domains
resp = requests.post("https://api.x.ai/v1/responses",
headers={"Authorization": f"Bearer {os.environ['XAI_API_KEY']}", "Content-Type": "application/json"},
json={"model": "grok-4-1-fast-reasoning", "input": [{"role": "user", "content": query}], "tools": [tool]}
)
return resp.json()
X/Twitter Search
def grok_x_search(query, handles=None, from_date=None, to_date=None):
tool = {"type": "web_search"} # X search uses same endpoint, query-routed
if handles: tool["allowed_x_handles"] = handles
body = {"model": "grok-4-1-fast-reasoning", "input": [{"role": "user", "content": query}], "tools": [tool]}
resp = requests.post("https://api.x.ai/v1/responses",
headers={"Authorization": f"Bearer {os.environ['XAI_API_KEY']}", "Content-Type": "application/json"},
json=body
)
return resp.json()
curl example
curl -s https://api.x.ai/v1/responses \
-H "Authorization: Bearer ***" \
-H "Content-Type: application/json" \
-d '{"model":"grok-4-1-fast-reasoning","input":[{"role":"user","content":"latest AI news"}],"tools":[{"type":"web_search"}]}'
Notes
- Default model:
grok-4-1-fast-reasoning(can take 30-60s for complex queries) - Max 5 allowed/excluded domains
- Max 10 allowed/excluded X handles
- Date format for X search: ISO8601 (YYYY-MM-DD)
- Supports image and video understanding when enabled
Pitfalls
- ⚠️ Requires
XAI_API_KEY— NOT currently set in environment - Grok reasoning models are slower than simple search — expect 30-60s
- X search and web search use the same endpoint, Grok routes automatically
Verification
# Confirm API key is set
echo $XAI_API_KEY
# Quick web search via curl (expect JSON with output field)
curl -s https://api.x.ai/v1/responses \
-H "Authorization: Bearer $XAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"grok-3-fast","input":[{"role":"user","content":"hello"}],"tools":[{"type":"web_search"}]}' | python3 -m json.tool | head -20