xAI Integration Guide

Technology: xai · Category: ai · Last reviewed: 2026-10-18

Source: https://tech-stack.codeamanilabs.org/guide/xai

Insight:

xAI is the real-time grounding tier: Grok's server-side web_search and x_search tools give a frontier reasoning model live web + X data with citations, no scraping pipeline needed. Flagship grok-4.7 runs a 500K-token context; grok-4.3 is the cheap 1M-token option. Two things changed in 2026: xAI now recommends its Responses API (Chat Completions is marked deprecated), and "Live Search" became a pair of priced tools ($5 per 1k web searches). The AI SDK's xai() already targets Responses, so new TypeScript code is on the right path by default.

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

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.

flowchart LR
  A["Your app code"] --> B{"Which client?"}
  B -->|"TypeScript"| C["@ai-sdk/xai<br/>Responses API by default"]
  B -->|"Python"| D["xai-sdk<br/>official gRPC client"]
  B -->|"Any language"| E["OpenAI SDK<br/>baseURL · api.x.ai/v1"]
  C --> F["grok-4.7<br/>500K-token context"]
  D --> F
  E --> F
  F --> G["Server-side tools<br/>web_search · x_search<br/>code · MCP · images"]

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)
Status Recommended Deprecated
State Optional server-side state: previous_response_id, store (default true, kept 30 days) Stateless, so resend history
Tools Function calling and server-side tools (search, code, MCP) Function calling only
Reasoning Encrypted reasoning content returned (include: ["reasoning.encrypted_content"]) Not returned
Request shape input, max_output_tokens messages, 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

Resource URL
Quickstart https://docs.x.ai/developers/quickstart
Models & pricing https://docs.x.ai/developers/models
Grok 4.7 https://docs.x.ai/developers/grok-4-7
Responses vs Chat Completions https://docs.x.ai/developers/model-capabilities/text/comparison
Web Search / X Search tools https://docs.x.ai/developers/tools/web-search · https://docs.x.ai/developers/tools/x-search
Function calling https://docs.x.ai/developers/tools/function-calling
Tool invocation pricing https://docs.x.ai/developers/pricing
Prompt caching (multi-turn) https://docs.x.ai/developers/advanced-api-usage/prompt-caching/multi-turn
Rate limits https://docs.x.ai/developers/rate-limits
May 15 2026 model retirements https://docs.x.ai/developers/migration/may-15-retirement
Image generation https://docs.x.ai/developers/model-capabilities/images/generation
Batch API https://docs.x.ai/developers/advanced-api-usage/batch-api
Console (keys, billing, limits) https://console.x.ai
Python SDK https://github.com/xai-org/xai-sdk-python
AI SDK xAI provider https://ai-sdk.dev/providers/ai-sdk-providers/xai

SDK Setup

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

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.

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):

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

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

TypeScript — OpenAI SDK (drop-in compatibility)

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

pip install xai-sdk   # 1.20.0, Python >= 3.10
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 ID Context Input / cached / output (<200K) Notes
grok-4.7 500K $2.00 / $0.50 / $6.00 Flagship. Coding, agentic tasks, knowledge work
grok-4.6 500K $2.00 / $0.50 / $6.00 Previous flagship, same price. Supports reasoningEffort: 'xhigh'
grok-4.5 500K $2.00 / $0.30 / $6.00 Older generation; can't disable reasoning
grok-4.3 1M $1.25 / $0.20 / $2.50 Cheap long-context option; reasoning effort none–high
grok-4.20-0309-reasoning / -non-reasoning 1M $1.25 / $0.20 / $2.50 Fixed reasoning variants (no effort option)
grok-4.20-multi-agent-0309 1M $1.25 / $0.20 / $2.50 Effort controls the number of agents
grok-build-0.1 256K $1.00 / $0.20 / $2.00 Coding model (replaced grok-code-fast-1)
grok-imagine-image-2.0 — $0.04 / image Latest image model (also grok-imagine-image $0.02)
grok-imagine-video-1.5 / -lite — $0.08 / $0.02 per second Video generation
grok-voice-3.0 — $0.08 / min Speech-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:

Model Accepts Default
grok-4.3 none, low, medium, high —
grok-4.5 low, medium, high (can't disable) high
grok-4.6 low, medium, high, xhigh high
grok-4.20 reasoning / non-reasoning not accepted —
grok-4.7 not 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)

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.

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);
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.

Tool Price (on top of tokens)
web_search $5 per 1k calls
x_search $5 per 1k posts returned, $10 per 1k profiles
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"}]
  }'
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
});
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:

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)

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:

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_).

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


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:

flowchart TD
  A["Incoming task"] --> B{"Needs real-time<br/>web or X data?"}
  B -->|"yes"| C["xAI grok-4.7<br/>web_search + x_search"]
  B -->|"no"| D{"Complex reasoning<br/>or code gen?"}
  D -->|"yes"| E["Anthropic Claude"]
  D -->|"no"| F["Route by cost tier<br/>(grok-4.3 effort none / DeepSeek / Haiku)"]
Task Recommended
Real-time news / market / social sentiment grok-4.7 + web_search
"What's happening on X about …" grok-4.7 + x_search
Ground a >500K-token corpus in live data grok-4.3 (1M context) + search tools
Cheap classification / summarisation grok-4.3 with reasoningEffort: 'none'
Complex reasoning, agents, code gen Anthropic Claude

Environment Variables

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

codeAmani notes


Troubleshooting

Issue Fix
401 Unauthorized Verify XAI_API_KEY (starts with xai-) and that it's set server-side
Request times out Reasoning 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 changed Retired slug silently redirected to grok-4.3. Pin grok-4.7 / grok-4.3
allowedDomains rejected Max 5 domains; can't combine with excludedDomains in one request
No citations in response Citations require a search tool (web_search / x_search) in tools
Search bill higher than expected Each web search is $0.005 on top of tokens. Cap with maxTurns and meter server_side_tool_usage
cached_tokens always 0 Append-only history, a stable x-grok-conv-id, and send reasoning content back. In AI SDK v7 read inputTokenDetails.cacheReadTokens
429 Too Many Requests RPS (RPM ÷ 48) or TPM tier limit. Back off; tiers rise with spend
experimental_generateImage is not exported Use generateImage from ai (stable in v7)
Model not found Check current IDs at docs.x.ai/developers/models. The lineup rotates quickly

Official docs: