
Live X Search Agent: Real-Time Trend Tracking With Grok
Summary
Use Grok 4.5's server-side X Search on the xAI API to build a cited, real-time trend agent.
Live X Search Agent: Real-Time Trend Tracking With Grok
On July 8, 2026, xAI put Grok 4.5 on the API. It is priced at $2 per million input tokens and $6 per million output tokens, with a configurable reasoning_effort of low, medium, or high (high is the default). Most of the launch coverage focused on coding and agentic benchmarks. The feature that is actually hard to copy sits somewhere else: Grok can run a server-side X Search tool that reads live posts from X and hands you back an answer with citations, in a single API call.
That matters because "what is the internet saying right now" is a genuinely painful problem to build yourself. You would normally need X API access, a scraper, rate-limit handling, an embedding pipeline, and a ranking step. With Grok 4.5 you send one request, Grok decides when to search, runs the search on xAI's servers, and returns a grounded summary plus the source URLs. You never touch the X API directly.
This guide builds a small but real trend-tracking agent: give it a topic and it returns a structured briefing of what people on X are saying in the last 24 hours, with links you can click. Every line of code here was written against the official xAI docs. By the end you will know how to call the Responses API, attach X Search, scope it by handle and date, pull citations out of the response, and avoid the mistakes that quietly break these agents in production.
Prerequisites
- Python 3.9+ and a terminal.
- An xAI API key from console.x.ai (create one under your team's API keys page).
- The official SDK:
pip install xai-sdk. Version 1.x exposes the built-in tools used below. - A rough sense of tokens and cost. X Search adds token usage for the posts it reads plus a per-invocation tool fee, so it is not free — budget for it.
Set your key once in the shell so it never lands in your code: export XAI_API_KEY="xai-...". On Windows PowerShell use $env:XAI_API_KEY="xai-...".
Step 1 - A first call to the Responses API
Before adding search, confirm your key and the model work. The xAI SDK mirrors a chat interface: create a chat, append a user turn, then sample or stream. Here is the smallest possible Grok 4.5 call.
import os
from xai_sdk import Client
from xai_sdk.chat import user
client = Client(api_key=os.getenv("XAI_API_KEY"))
chat = client.chat.create(model="grok-4.5")
chat.append(user("In one sentence, what is Grok 4.5 good at?"))
response = chat.sample()
print(response.content)
Example output:
Grok 4.5 is xAI's model tuned for coding, agentic tool use, and
knowledge work, with adjustable reasoning effort to trade speed
against depth.
If that prints, your key and model string are correct. The model id is exactly grok-4.5. If you get a 404 on the model, your account may not have Grok 4.5 enabled yet, or you are in a region where it has not rolled out.
Step 2 - Attach the X Search tool
X Search is a built-in (server-side) tool. You do not implement it, you just declare it. Import x_search from xai_sdk.tools and pass it in the tools list. Grok now decides on its own whether a question needs live X data.
import os
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.5",
tools=[x_search()],
)
chat.append(user("What are people on X saying about Grok 4.5 today?"))
response = chat.sample()
print(response.content)
print("\n--- Citations ---")
for url in response.citations:
print(url)
Abbreviated example output:
Reaction to Grok 4.5 on X is mostly positive among developers.
The recurring themes: the $2/$6 pricing undercuts comparable
frontier models, the reasoning_effort switch is popular for
cost control, and several people highlight X Search as the
standout capability. A minority complain about EU availability
lagging.
--- Citations ---
https://x.com/some_dev/status/1942...
https://x.com/ai_reporter/status/1942...
https://x.com/another_user/status/1942...
Two things to notice. First, response.citations gives you the exact posts Grok used, so your app can link back to primary sources instead of asking users to trust a summary. Second, you did not tell Grok to search — it inferred that a question about "today" needs live data. That autonomy is convenient but also a cost risk, which we handle later.
Step 3 - Scope the search so it stays accurate and cheap
An unscoped X Search reads a wide net of posts. For a focused trend agent you usually want to constrain it. X Search accepts these parameters:
allowed_x_handles- only consider posts from these handles (max 20).excluded_x_handles- ignore posts from these handles (max 20). Cannot be combined withallowed_x_handlesin the same request.from_dateandto_date- ISO8601 dates (YYYY-MM-DD) that bound the search window, inclusive.enable_image_understanding- let Grok read images inside posts.enable_video_understanding- let Grok read videos inside posts (X Search only, not Web Search).
Here we bound the window to the last day and let Grok read images, which is useful when launches are announced as screenshots rather than plain text.
import os
from datetime import datetime, timedelta, timezone
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"))
today = datetime.now(timezone.utc).date()
yesterday = today - timedelta(days=1)
chat = client.chat.create(
model="grok-4.5",
tools=[
x_search(
from_date=datetime(yesterday.year, yesterday.month, yesterday.day),
to_date=datetime(today.year, today.month, today.day),
enable_image_understanding=True,
)
],
)
chat.append(user("Summarize the new AI model launches people are discussing on X."))
response = chat.sample()
print(response.content)
The xAI SDK accepts datetime objects for the date fields. If you call the raw Responses API over HTTP instead, pass the same values as ISO strings like "2026-07-10".
Step 4 - Turn free text into a structured briefing
A trend agent is only useful if downstream code can read its output. Rather than parse prose, ask Grok to return JSON and validate it in Python. The pattern below keeps the model grounded (X Search still runs) while forcing a machine-readable shape, and it fails loudly if the model drifts.
import os, json, re
from datetime import datetime, timedelta, timezone
from xai_sdk import Client
from xai_sdk.chat import user, system
from xai_sdk.tools import x_search
client = Client(api_key=os.getenv("XAI_API_KEY"))
today = datetime.now(timezone.utc).date()
yesterday = today - timedelta(days=1)
SCHEMA_HINT = (
"Return ONLY a JSON object with this shape and no prose:\n"
"{\"topic\": str, \"window\": str, \"themes\": "
"[{\"headline\": str, \"summary\": str, \"sentiment\": "
"\"positive|negative|mixed\"}], \"notable_posts\": [str]}"
)
def trend_briefing(topic: str) -> dict:
chat = client.chat.create(
model="grok-4.5",
tools=[x_search(
from_date=datetime(yesterday.year, yesterday.month, yesterday.day),
to_date=datetime(today.year, today.month, today.day),
)],
)
chat.append(system(SCHEMA_HINT))
chat.append(user(f"What are people on X saying about: {topic}?"))
response = chat.sample()
text = response.content.strip()
# Strip accidental markdown fences before parsing.
text = re.sub(r"^```(?:json)?|```$", "", text, flags=re.MULTILINE).strip()
data = json.loads(text)
data["citations"] = list(response.citations)
return data
if __name__ == "__main__":
briefing = trend_briefing("Grok 4.5 API launch")
print(json.dumps(briefing, indent=2)[:900])
Trimmed example output:
{
"topic": "Grok 4.5 API launch",
"window": "2026-07-09 to 2026-07-10",
"themes": [
{
"headline": "Pricing seen as aggressive",
"summary": "Developers call $2/$6 per million tokens cheaper than peers for this capability tier.",
"sentiment": "positive"
},
{
"headline": "X Search is the differentiator",
"summary": "Multiple posts show live-search demos that competitors can't easily match.",
"sentiment": "positive"
},
{
"headline": "EU rollout lag",
"summary": "Users in the EU report the model is not yet available in the console.",
"sentiment": "negative"
}
],
"notable_posts": ["https://x.com/.../status/1942...", "..."],
"citations": ["https://x.com/.../status/1942...", "..."]
}
For stronger guarantees you can use the xAI structured outputs feature (a JSON schema the server enforces) instead of a prompt hint. The prompt-plus-validate approach shown here works today with zero extra dependencies and degrades gracefully, which is why it is a good default for a first version.
Worked example: an AI launch radar
Let's assemble the pieces into something you would actually run each morning: a radar that scans a fixed set of credible AI accounts for launch chatter, then prints a ranked digest. We use allowed_x_handles to keep signal high, and we set reasoning_effort to low because summarizing a scoped feed does not need deep reasoning and low effort is cheaper and faster.
import os, json, re
from datetime import datetime, timedelta, timezone
from xai_sdk import Client
from xai_sdk.chat import user, system
from xai_sdk.tools import x_search
client = Client(api_key=os.getenv("XAI_API_KEY"))
today = datetime.now(timezone.utc).date()
yesterday = today - timedelta(days=1)
WATCHLIST = ["xai", "OpenAI", "GoogleDeepMind", "AnthropicAI"]
def launch_radar():
chat = client.chat.create(
model="grok-4.5",
tools=[x_search(
allowed_x_handles=WATCHLIST,
from_date=datetime(yesterday.year, yesterday.month, yesterday.day),
to_date=datetime(today.year, today.month, today.day),
)],
# Low effort: this is summarization, not hard reasoning.
reasoning_effort="low",
)
chat.append(system(
"You are an AI launch radar. Report only concrete product or "
"model launches, updates, or pricing changes. Return a JSON list "
"of {\"who\": str, \"what\": str, \"why_it_matters\": str}. "
"If nothing launched, return []."
))
chat.append(user("Any AI launches in the last 24 hours?"))
response = chat.sample()
text = re.sub(r"^```(?:json)?|```$", "", response.content.strip(),
flags=re.MULTILINE).strip()
items = json.loads(text)
print(f"AI LAUNCH RADAR - {today.isoformat()} ({len(items)} items)\n")
for i, it in enumerate(items, 1):
print(f"{i}. [{it['who']}] {it['what']}")
print(f" Why it matters: {it['why_it_matters']}\n")
print("Sources:")
for url in response.citations:
print(" -", url)
if __name__ == "__main__":
launch_radar()
Example run:
AI LAUNCH RADAR - 2026-07-10 (1 items)
1. [xai] Grok 4.5 is live on the xAI API at $2/$6 per 1M tokens
Why it matters: First xAI model tuned for coding and agents
with server-side X Search and adjustable reasoning effort.
Sources:
- https://x.com/xai/status/1942...
- https://x.com/xai/status/1942...
Because allowed_x_handles caps the search to accounts you trust, the radar rarely hallucinates a launch from a random rumor. That single parameter is the difference between a demo and something you would put in a Slack channel.
What one run actually costs
People underestimate agent cost because they only think about their prompt. With X Search the real driver is the posts Grok pulls into context. Suppose a scoped run reads roughly 8,000 tokens of posts plus your 500-token prompt (8,500 input) and writes a 700-token JSON briefing. At $2 per million input and $6 per million output, the token cost is about 8,500 x $0.000002 + 700 x $0.000006, which is roughly $0.017 + $0.0042, so about two cents in tokens, before the per-invocation tool fee. That is cheap for one call and expensive at ten thousand calls a day.
The practical lesson: read response.usage after each call and log it. Once you can see input tokens, output tokens, and reasoning tokens per run, you can decide whether a tighter handle list, a shorter window, or lower reasoning effort is worth it. Guessing at cost is how a fun prototype turns into a surprising invoice.
response = chat.sample()
u = response.usage
print("input:", u.prompt_tokens,
"output:", u.completion_tokens,
"reasoning:", getattr(u, "reasoning_tokens", 0))
Common pitfalls and how to avoid them
1. Runaway cost from silent searches. Grok decides when to search, and every invocation adds token usage for the posts it reads plus a per-tool fee. A chatty agent can quietly rack up spend. Mitigate it by scoping with handles and dates, keeping reasoning_effort low for summarization, and reading the usage block on each response to track tokens. Set a hard monthly cap in the console.
2. Combining allowed and excluded handles. You cannot set allowed_x_handles and excluded_x_handles in the same request — the API rejects it. Pick one strategy: an allowlist for high-signal monitoring, or a denylist to filter out known noise.
3. Trusting the summary over the sources. X is full of rumor and satire. Grok grounds its answer in real posts, but a real post can still be wrong. Always surface response.citations to the user so a human can check the primary source, especially for anything financial or safety-related.
4. Parsing prose as JSON. Models sometimes wrap JSON in a markdown code fence or add a friendly sentence. The regex fence-strip plus json.loads in the examples handles the common case, but wrap it in try/except and re-ask on failure rather than crashing the whole run.
5. Assuming date filters mean freshness. from_date and to_date bound which posts are eligible, but a narrow window can return little or nothing on a quiet day. Handle the empty case (return []) instead of forcing the model to invent content.
6. Region and model availability. Grok 4.5 rolled out on July 8, 2026, with some regions (the EU in particular) trailing. If grok-4.5 404s, confirm availability for your account before assuming your code is broken.
Quick reference
| Item | Value / usage |
|---|---|
| Model id | grok-4.5 |
| Endpoint (OpenAI-compatible) | https://api.x.ai/v1 (Responses + Chat Completions) |
| Pricing | $2 / 1M input tokens, $6 / 1M output tokens |
| reasoning_effort | low | medium | high (default high) |
| X Search tool | x_search() from xai_sdk.tools; type "x_search" over HTTP |
| Scope by account | allowed_x_handles / excluded_x_handles (max 20, not both) |
| Scope by time | from_date / to_date (ISO8601, inclusive) |
| Media | enable_image_understanding, enable_video_understanding |
| Sources | response.citations (list of post URLs) |
Next steps
- Combine
x_search()withweb_search()andcode_execution()in one tools list so Grok can cross-check X chatter against articles and compute on the results. - Swap the prompt-hint JSON for xAI structured outputs to get server-enforced schemas.
- Stream the response with
chat.stream()to show tool calls and a live token counter in a CLI or web UI. - Schedule
launch_radar()as a cron job and post the digest to Slack or email. - Log
response.usageper run to build a real cost dashboard before you scale it up.
That is a complete, grounded, real-time trend agent in well under 60 lines. The unlock is that X Search runs on xAI's side, so you get live social signal with citations and none of the scraping plumbing. Point the watchlist at your own domain — competitors, a ticker, a product name — and you have a monitoring tool that would have taken a week to build a year ago.
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,617 newsletter subscribers.