← Back to dashboard

xAI Integration Guide

What is xAI?

The real model

POST /v1/responses with tools: [{type: 'web_search'}, {type: 'x_search'}] — grounding as a request flag, priced per call.

TypeScript goes through @ai-sdk/xai 5.x, whose xai() already targets the Responses API; Python gets the official gRPC xai-sdk, where client.chat.create(tools=[web_search()]) returns response.citations and server_side_tool_usage. Search is billed on top of tokens ($5 per 1k web searches), so meter it and cap xAI's internal loop with maxTurns. Two cost traps: every token bills at roughly 2× once a prompt reaches 200K, and retired slugs like grok-4-1-fast silently redirect to grok-4.3. Responses stores requests for 30 days unless you send store: false. For codeAmani, xAI is the real-time grounding tier next to Claude: point allowedDomains at CBK or Kenyan news outlets for cited East African answers without a scraper.

Five xAI primitives

One API with server-side tools; real-time search is the reason to reach for it.

Text
██╗  ██╗ █████╗ ██╗
╚██╗██╔╝██╔══██╗██║
 ╚███╔╝ ███████║██║
 ██╔██╗ ██╔══██║██║
██╔╝ ██╗██║  ██║██║
╚═╝  ╚═╝╚═╝  ╚═╝╚═╝

xAI Integration Guide

Focus: Grok models via the xAI API: the Responses API, server-side search tools (web + X), reasoning effort, structured outputs, prompt caching, and image generation, through @ai-sdk/xai (TypeScript) or the official xai-sdk (Python). Neighbours: grok-chatbot/ builds a customer-facing bot on this API; grok-bot/ is xAI's no-code Grok Bot product (no API); ai-agents/ compares Grok with other agent stacks.

Overview

xAI serves the Grok family at https://api.x.ai/v1. The flagship grok-4.7 is a frontier reasoning model with a 500,000-token context window and text + image input. xAI's signature capability is its server-side tools: web_search and x_search (plus code execution, collections search, image generation, and remote MCP). The model plans, searches, and cites inside one request, with no tool loop on your side.

Responses API vs Chat Completions

xAI's comparison page calls the Responses API "the recommended way" and marks Chat Completions Deprecated ("legacy endpoint, limited updates"). No shutdown date is published, and some docs pages (e.g. streaming) still show Chat Completions examples. Write new code against Responses.

Responses (/v1/responses)Chat Completions (/v1/chat/completions)
StatusRecommendedDeprecated
StateOptional server-side state: previous_response_id, store (default true, kept 30 days)Stateless, so resend history
ToolsFunction calling and server-side tools (search, code, MCP)Function calling only
ReasoningEncrypted reasoning content returned (include: ["reasoning.encrypted_content"])Not returned
Request shapeinput, max_output_tokensmessages, max_tokens

store defaults to true. If your prompts carry personal data and you rebuild history yourself, send store: false (AI SDK: providerOptions.xai.store).

Official Documentation


SDK Setup

xAI's docs use the AI SDK provider and the OpenAI SDK for JavaScript. There is no first-party xAI JS SDK.

Bash
npm i @ai-sdk/xai ai zod

As of 2026-10-18: @ai-sdk/xai 5.0.24 with ai 7.0.143 (both on @ai-sdk/provider 4.0.29; upgrade them together). Since AI SDK 7, xai(modelId) calls the Responses API; xai.responses(modelId) is the explicit form.

TypeScript
import { xai } from "@ai-sdk/xai"; // reads XAI_API_KEY from env
import { generateText } from "ai";

const { text } = await generateText({
  model: xai("grok-4.7"),
  prompt: "Summarize today's US small-business payments news.",
});

Custom configuration (baseURL, headers, fetch are also accepted):

TypeScript
import { createXai } from "@ai-sdk/xai";

const xai = createXai({ apiKey: process.env.XAI_API_KEY });

TypeScript — OpenAI SDK (drop-in compatibility)

TypeScript
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.XAI_API_KEY,
  baseURL: "https://api.x.ai/v1",
  timeout: 360_000, // ms. Reasoning models can think for a while
});

const response = await client.responses.create({ model: "grok-4.7", input: "What is prompt caching?" });
console.log(response.output_text);

Python — official xai-sdk

Bash
pip install xai-sdk   # 1.20.0, Python >= 3.10
Python
from xai_sdk import Client
from xai_sdk.chat import user

client = Client()  # reads XAI_API_KEY from environment
chat = client.chat.create(model="grok-4.7")
chat.append(user("Hello, how are you?"))
response = chat.sample()
print(response.content)

Models

Prices are per 1M tokens. When a request's prompt reaches 200K tokens, every token in that request bills at the higher tier (roughly 2×).

Model IDContextInput / cached / output (<200K)Notes
grok-4.7500K$2.00 / $0.50 / $6.00Flagship. Coding, agentic tasks, knowledge work
grok-4.6500K$2.00 / $0.50 / $6.00Previous flagship, same price. Supports reasoningEffort: 'xhigh'
grok-4.5500K$2.00 / $0.30 / $6.00Older generation; can't disable reasoning
grok-4.31M$1.25 / $0.20 / $2.50Cheap long-context option; reasoning effort none–high
grok-4.20-0309-reasoning / -non-reasoning1M$1.25 / $0.20 / $2.50Fixed reasoning variants (no effort option)
grok-4.20-multi-agent-03091M$1.25 / $0.20 / $2.50Effort controls the number of agents
grok-build-0.1256K$1.00 / $0.20 / $2.00Coding model (replaced grok-code-fast-1)
grok-imagine-image-2.0—$0.04 / imageLatest image model (also grok-imagine-image $0.02)
grok-imagine-video-1.5 / -lite—$0.08 / $0.02 per secondVideo generation
grok-voice-3.0—$0.08 / minSpeech-to-speech (grok-voice-2.0 is deprecated)

Aliases: <model> tracks the latest stable version, <model>-latest the latest of any kind, and <model>-<date> never moves. Pin explicit IDs in production.

Retired on 2026-05-15 (slugs still resolve, billed at grok-4.3 rates): grok-4-1-fast-reasoning / -non-reasoning, grok-4-fast-reasoning / -non-reasoning, grok-4-0709, grok-3 (→ grok-4.3), and grok-code-fast-1 (→ grok-build-0.1). If old code "still works", it is silently running and billing as grok-4.3. grok-imagine-image-quality retires 2026-11-02 → move to grok-imagine-image-2.0.

Reasoning effort

Set it with providerOptions.xai.reasoningEffort (AI SDK) or reasoning_effort (REST). Support is per model:

ModelAcceptsDefault
grok-4.3none, low, medium, high—
grok-4.5low, medium, high (can't disable)high
grok-4.6low, medium, high, xhighhigh
grok-4.20 reasoning / non-reasoningnot accepted—
grok-4.7not yet listed in the AI SDK provider docs; leave unset until it is—

grok-4.3 with reasoningEffort: 'none' is the fast, cheap choice for classification and summarisation.


Core Patterns

A request (Responses API)

Bash
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": "system", "content": "You are a concise assistant."},
      {"role": "user", "content": "What is prompt caching?"}
    ],
    "store": false
  }'

Streaming

Set a long timeout: reasoning models can run for minutes before the first token. xAI's examples use up to 3600 s.

TypeScript
import { xai } from "@ai-sdk/xai";
import { streamText } from "ai";

const result = streamText({ model: xai("grok-4.7"), prompt });
for await (const delta of result.textStream) process.stdout.write(delta);
Python
for response, chunk in chat.stream():          # xai-sdk
    print(chunk.content, end="", flush=True)

Search tools: web + X with citations

Formerly "Live Search". These are now server-side tools. Declare them in tools, and the model plans, searches, browses, and cites inside the request, with no tool-execution loop on your side.

ToolPrice (on top of tokens)
web_search$5 per 1k calls
x_search$5 per 1k posts returned, $10 per 1k profiles
Bash
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 is the latest update from xAI?"}],
    "tools": [{"type": "web_search"}, {"type": "x_search"}]
  }'
TypeScript
import { xai } from "@ai-sdk/xai";
import { generateText } from "ai";

const { text, sources } = await generateText({
  model: xai("grok-4.7"),
  prompt: "What changed in Kenya's central bank rate this month?",
  tools: {
    web_search: xai.tools.webSearch({ allowedDomains: ["centralbank.go.ke"] }),
    x_search: xai.tools.xSearch({ allowedXHandles: ["CBKKenya"] }),
  },
  providerOptions: { xai: { maxTurns: 3 } }, // caps xAI's internal search loop
});
Python
from xai_sdk import Client
from xai_sdk.chat import user
from xai_sdk.tools import web_search, x_search

client = Client()
chat = client.chat.create(
    model="grok-4.7",
    tools=[web_search(allowed_domains=["centralbank.go.ke"]), x_search()],
)
chat.append(user("What is the latest update from xAI?"))
response = chat.sample()
print(response.content)
print(response.citations)               # source URLs
print(response.server_side_tool_usage)  # per-tool call counts, to meter cost

Filters:

  • Web: allowedDomains / excludedDomains (max 5 each, mutually exclusive), enableImageSearch, enableImageUnderstanding.
  • X: allowedXHandles / excludedXHandles (max 20 each, mutually exclusive), fromDate, toDate, enableImageUnderstanding, enableVideoUnderstanding.

The Python SDK uses the snake_case equivalents.

Mixing with your own function tools: xAI's docs say server-side and client-side tools can be combined in one request; the @ai-sdk/xai 5.0.24 docs say they can't. Test on your versions, or wrap search in a function tool that makes its own call (pattern in grok-chatbot/).

Structured Outputs (AI SDK + Zod)

TypeScript
import { xai } from "@ai-sdk/xai";
import { generateText, Output } from "ai";
import { z } from "zod";

const InvoiceSchema = z.object({
  vendor_name: z.string().describe("Name of the vendor"),
  invoice_number: z.string().describe("Unique invoice identifier"),
  total_amount: z.number().min(0).describe("Total amount due"),
});

const { output } = await generateText({
  model: xai("grok-4.7"),
  output: Output.object({ schema: InvoiceSchema }),
  prompt: "Extract the invoice fields from this email: ...",
});

Prompt Caching

Cached input bills at a quarter of the input price on grok-4.7 ($0.50 vs $2.00). xAI's multi-turn caching rules:

  • Append, never edit. Changing, removing, or reordering earlier messages breaks the cached prefix.
  • Route a conversation to one cache with a stable x-grok-conv-id header (xAI's documented mechanism). The AI SDK also exposes promptCacheKey (→ prompt_cache_key).
  • For reasoning models, send back reasoning_content / encrypted reasoning, or use previous_response_id. Omitting it is "the top cause of cache misses".
TypeScript
import { xai } from "@ai-sdk/xai";
import { generateText } from "ai";

const result = await generateText({
  model: xai("grok-4.7"),
  messages,
  headers: { "x-grok-conv-id": conversationId },
  providerOptions: { xai: { promptCacheKey: conversationId } },
});
console.log(result.usage.inputTokenDetails.cacheReadTokens); // AI SDK v7 field

On the raw API the cached count is usage.prompt_tokens_details.cached_tokens.

Image Generation

generateImage is a stable AI SDK export (no longer experimental_).

TypeScript
import { xai } from "@ai-sdk/xai";
import { generateImage } from "ai";

const { image } = await generateImage({
  model: xai.image("grok-imagine-image-2.0"),
  prompt: "A product photo of a ceramic coffee mug on a walnut desk",
});

Rate limits

  • Two limits per model. Requests per second = your per-minute request budget ÷ 48 (minimum 2). Tokens per minute counts prompt, completion, reasoning, and cached tokens.
  • Tiers rise with cumulative spend since 2026-01-01: $50 / $250 / $1,000 / $5,000 (Tier 1 to 4). Tiers upgrade automatically and never downgrade.
  • Over limit → HTTP 429. Back off exponentially (xAI's example: up to 5 tries, 2^n seconds) and don't retry non-429 errors.
  • No rate-limit headers are documented, so read your limits in the Console.
  • Priority processing (serviceTier: 'priority') lowers latency at 2× token rates, billed only when the response confirms the tier.

AI Routing: When to Use xAI

In codeAmani's routing policy, Anthropic Claude stays primary for complex reasoning and code gen. xAI earns its slot when the answer needs live web or X data:

TaskRecommended
Real-time news / market / social sentimentgrok-4.7 + web_search
"What's happening on X about …"grok-4.7 + x_search
Ground a >500K-token corpus in live datagrok-4.3 (1M context) + search tools
Cheap classification / summarisationgrok-4.3 with reasoningEffort: 'none'
Complex reasoning, agents, code genAnthropic Claude

Environment Variables

Bash
# Required — create at https://console.x.ai
XAI_API_KEY=xai-...

codeAmani notes

  • Secrets server-side only. XAI_API_KEY lives in .env.local / Vercel env vars / Hazina, never in client bundles. Call xAI from API routes or server actions.
  • Routing: xAI does not replace Anthropic as the primary provider. It is the real-time grounding tier: reach for it when search citations beat a stale training cutoff (news digests, price checks, social listening).
  • Meter search, not just tokens. Search tools bill per call ($5 per 1k web searches) on top of the tokens their results add. Log server_side_tool_usage (Python) or count tool calls, and cap xAI's internal loop with maxTurns.
  • Data retention. The Responses API stores requests for 30 days by default. Send store: false for anything carrying customer PII.
  • AI Gateway: on Vercel, xAI models also work through the Vercel AI Gateway ("xai/<model-id>" strings) for unified observability and fallbacks across providers.
  • Kenya-targeted projects: search tools with allowedDomains scoped to local sources (e.g. CBK, Kenyan news outlets) ground Swahili/English answers in East African context without building a scraper. For a WhatsApp/Telegram bot on Grok, see grok-chatbot/.
  • Reasoning latency: budget for multi-minute worst-case responses (SDK timeouts of 360s+, xAI's own examples go to 3600s) and always stream in user-facing flows.

Troubleshooting

IssueFix
401 UnauthorizedVerify XAI_API_KEY (starts with xai-) and that it's set server-side
Request times outReasoning models think before answering. Raise the SDK timeout (xAI's examples use up to 3600s) and stream
Old model ID "still works" but costs/quality changedRetired slug silently redirected to grok-4.3. Pin grok-4.7 / grok-4.3
allowedDomains rejectedMax 5 domains; can't combine with excludedDomains in one request
No citations in responseCitations require a search tool (web_search / x_search) in tools
Search bill higher than expectedEach web search is $0.005 on top of tokens. Cap with maxTurns and meter server_side_tool_usage
cached_tokens always 0Append-only history, a stable x-grok-conv-id, and send reasoning content back. In AI SDK v7 read inputTokenDetails.cacheReadTokens
429 Too Many RequestsRPS (RPM ÷ 48) or TPM tier limit. Back off; tiers rise with spend
experimental_generateImage is not exportedUse generateImage from ai (stable in v7)
Model not foundCheck current IDs at docs.x.ai/developers/models. The lineup rotates quickly