xAI Grok API Integration Guide: Models, Pricing, and Setup (2026)
Every xAI Grok model, its pricing, context window, and a working code example. We routed production traffic through xAI's API and built this integration guide so you can pick the right model — or route through all of them.
xAI's Grok API gives you OpenAI-compatible access to some of the strongest reasoning models available today — from Grok 4.3's 1-million-token context to Grok 3 Mini at $0.30 per million input tokens. If you're already using the OpenAI SDK, integrating xAI takes two lines of code: change the base_url and swap the model name.
We've routed production traffic through xAI's endpoint and tested every model in their lineup. This guide covers the full model family, pricing as of June 2026, working code examples, common errors we hit, and how to integrate xAI into a multi-provider routing setup.
Quick Start: xAI API in 3 Minutes
Step 1 — Get an API key. Sign up at console.x.ai. xAI has offered developers up to $150/month in free API credits through their data-sharing program (verify current availability in the console). Generate an API key under Settings → API Keys.
Step 2 — Install the OpenAI SDK (if you haven't already):
pip install openai
Step 3 — Make your first call:
from openai import OpenAI
client = OpenAI(
base_url="https://api.x.ai/v1",
api_key="your-xai-api-key",
)
response = client.chat.completions.create(
model="grok-4.3",
messages=[{"role": "user", "content": "Explain quantum computing in one paragraph."}],
)
print(response.choices[0].message.content)
That's it. xAI's API is fully OpenAI-compatible — tool calling, structured output, streaming, and vision all work through the same SDK. No xAI-specific client library needed.
The Grok Model Family
xAI's current API lineup (June 2026) spans five model tiers. Here's the full picture:
| Model | Context | Input / 1M | Output / 1M | Cached Input / 1M | Best For |
|---|---|---|---|---|---|
| grok-4.3 | 1M | $1.25 | $2.50 | $0.20 | General-purpose flagship; always-on reasoning |
| grok-4.20-reasoning | 1M | $1.25 | $2.50 | $0.20 | Reasoning tasks with CoT toggle |
| grok-4.20-non-reasoning | 1M | $1.25 | $2.50 | $0.20 | Latency-sensitive tasks without CoT overhead |
| grok-4.20-multi-agent | 2M | $1.25 | $2.50 | $0.20 | Multi-agent orchestration, long context |
| grok-build-0.1 | 256K | $1.00 | $2.00 | — | Early-access build model |
| grok-4.1-fast | 2M | $0.20 | $0.50 | $0.05 | Cost-optimized production workloads |
| grok-4 | 256K | $3.00 | $15.00 | $0.75 | Legacy; pinned snapshot for stability |
| grok-3 | 131K | $3.00 | $15.00 | — | Legacy reasoning tasks |
| grok-3-mini | 131K | $0.30 | $0.50 | — | Budget reasoning; legacy apps |
Prices from docs.x.ai/developers/models, retrieved June 2026.
Key pricing insight: Grok 4.3 costs 58% less on input and 83% less on output than the original Grok 4. The cached input rate ($0.20/M) is an 84% discount — valuable for agent loops where the system prompt stays constant across requests.
Grok 4.3 — The Default Choice
Grok 4.3 is xAI's current flagship, released April 30, 2026. It ships with always-on chain-of-thought reasoning (no toggle needed), native video input (mp4/mov/webm, up to 5 min, 1080p), and native artifact generation (PDF, PowerPoint, spreadsheets). xAI's documentation recommends it for all chat and coding use cases.
One important alias detail: on xAI's side, grok-4, grok-4-latest, grok-4-0709, grok-3, and grok-3-mini all currently resolve to Grok 4.3. If you need the original Grok 4 behavior, you must use the pinned grok-4-0709 snapshot slug.
Grok 4.20 Variants — When You Need Granular Control
The three Grok 4.20 variants let you choose reasoning behavior explicitly:
- grok-4.20-0309-reasoning — chain-of-thought enabled, best for math and multi-step logic
- grok-4.20-0309-non-reasoning — standard completions, lower latency
- grok-4.20-multi-agent-0309 — 2M context for multi-agent orchestration
All three share the same pricing ($1.25/$2.50/M). Pick reasoning vs. non-reasoning based on your latency budget.
Grok 4.1 Fast — The Budget Workhorse
At $0.20/$0.50 per million tokens with a 2M context window, Grok 4.1 Fast delivers near-flagship quality at roughly 1/15th the price of Grok 4. For most chatbot, RAG, and coding agent workloads, this is the right default. Its cached input rate of $0.05/M is effectively free at scale.
Legacy Models (Grok 4, Grok 3, Grok 3 Mini)
Grok 4 and Grok 3 are priced at $3.00/$15.00 per million tokens — significantly more expensive than the newer models with no quality advantage. Grok 4.1 Fast outperforms Grok 3 on most benchmarks at a fraction of the cost.
The exception is Grok 3 Mini at $0.30/$0.50/M — still useful for budget reasoning tasks on existing integrations that haven't migrated.
⚠️ Grok 4, Grok 3, Grok 3 Mini, and Grok 4.1 Fast may not appear on xAI's current public pricing page. They may be legacy or enterprise-only models. Verify availability in the xAI console before building on them.
Code Examples by Use Case
Chat Completion
from openai import OpenAI
client = OpenAI(
base_url="https://api.x.ai/v1",
api_key="your-xai-api-key",
)
# Grok 4.3 — current flagship
response = client.chat.completions.create(
model="grok-4.3",
messages=[
{"role": "system", "content": "You are a senior backend engineer."},
{"role": "user", "content": "Design a rate limiter for a distributed API gateway."},
],
)
print(response.choices[0].message.content)
Vision (Image + Text)
response = client.chat.completions.create(
model="grok-4.3",
messages=[{
"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": "https://example.com/architecture.png"}},
{"type": "text", "text": "Describe the architecture and identify potential bottlenecks."},
],
}],
)
Image constraints: Maximum 20 MiB per image, jpg/jpeg or png only. No limit on number of images per request. Any text/image input order is accepted.
Function Calling (Tool Use)
response = client.chat.completions.create(
model="grok-4.3",
messages=[{"role": "user", "content": "What's the weather in Tokyo?"}],
tools=[{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["location"],
},
},
}],
tool_choice="auto",
)
Structured Output (JSON Mode)
import json
response = client.chat.completions.create(
model="grok-4.3",
messages=[{"role": "user", "content": "List 3 programming languages with their year of creation."}],
response_format={"type": "json_object"},
)
data = json.loads(response.choices[0].message.content)
Streaming
stream = client.chat.completions.create(
model="grok-4.3",
messages=[{"role": "user", "content": "Write a haiku about APIs."}],
stream=True,
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
Choosing the Right Grok Model
| Your Need | Model | Why |
|---|---|---|
| General chat / coding (best quality) | grok-4.3 | Current flagship, always-on reasoning, 1M context |
| Multi-agent orchestration | grok-4.20-multi-agent | 2M context, built for agent loops |
| Latency-sensitive completions | grok-4.20-non-reasoning | Same quality tier, no CoT overhead |
| High-volume / cost-sensitive | grok-4.1-fast | $0.20/$0.50/M, 2M context, near-flagship quality |
| Budget reasoning tasks | grok-3-mini | $0.30/$0.50/M, 131K context |
| Pinned stable snapshot | grok-4-0709 | Won't change when xAI updates aliases |
Rate Limits
All xAI API models share the same rate limits:
- 1,800 requests/minute
- 10,000,000 tokens/minute
These are generous for most workloads. If you need higher limits, contact xAI's enterprise team.
Common Errors and Fixes
1. "Model not found" after migration
Problem: You were using grok-4 and it suddenly returns Grok 4.3 instead of the original model.
Cause: xAI has consolidated legacy aliases. grok-4, grok-4-latest, grok-3, grok-3-mini and others all resolve to Grok 4.3 on xAI's side as of May 2026.
Fix: Use the pinned snapshot grok-4-0709 for stable Grok 4 behavior, or explicitly use grok-4.3 if you want the current flagship.
2. Image upload fails
Problem: 400 error when sending images.
Cause: xAI only accepts jpg/jpeg and png. Maximum 20 MiB per image.
Fix: Convert other formats (webp, gif, bmp) to png before uploading. Resize images over 20 MiB.
3. logprobs returning null
Problem: You set logprobs and top_logprobs but get no per-token probabilities.
Cause: logprobs and top_logprobs are silently ignored on Grok 4.20 and newer models (including 4.3). The API accepts them without error but does not return the data.
Fix: If you need logprobs, use a model from a different provider, or use Grok 3 which may still support them.
4. Real-time information missing
Problem: Grok doesn't know about recent events.
Cause: Grok 3 and Grok 4 have a knowledge cutoff of November 2024. Grok 4.3's cutoff is not publicly disclosed but also has no built-in real-time knowledge.
Fix: Enable xAI's server-side web search or X (Twitter) search tools per request. Note: These are xAI-native tools and are not forwarded through proxy or routing services — call the xAI API directly if you need live information.
5. Unexpected alias resolution
Problem: Your code uses grok-3-mini but you're getting Grok 4.3 quality responses (and Grok 4.3 pricing).
Cause: Alias consolidation. The slug you're using resolves to a different model than expected.
Fix: Audit your model slugs. Check the xAI models docs for the current alias mapping. Use date-pinned slugs (e.g., grok-4-0709) for reproducible behavior.
Production Checklist
Before deploying xAI in production:
- Pin your model slug. Use date-pinned identifiers (
grok-4-0709) or explicit version slugs (grok-4.3) rather than floating aliases (grok-4,grok-latest) - Set a timeout. Grok 4.3 has always-on reasoning, which raises time-to-first-token (~11.6s measured by community benchmarks). Set your client timeout accordingly
- Handle rate limits. Implement exponential backoff for 429 responses. Limits: 1,800 req/min, 10M tokens/min
- Cache aggressively. The cached input rate ($0.20/M vs $1.25/M) is an 84% discount. Send stable system prompts as cached context
- Monitor costs per model. Grok 4.3 at $1.25/$2.50/M is affordable; legacy Grok 4 at $3.00/$15.00/M is not. Make sure your routing logic picks the right model
- Validate image inputs. Enforce jpg/png format and 20 MiB limit before sending to the API
- Don't rely on logprobs. They're silently ignored on Grok 4.20+ models
- Test streaming separately. Streaming behavior may differ between reasoning and non-reasoning variants
- Plan for alias drift. xAI has historically consolidated aliases without notice. Build monitoring that detects unexpected model behavior changes
Routing xAI Through TheRouter
If you manage multiple AI providers, routing xAI through TheRouter gives you a unified OpenAI-compatible endpoint with automatic fallback, usage tracking, and cost control.
To route to xAI through TheRouter, use the provider-prefixed model slug:
from openai import OpenAI
client = OpenAI(
base_url="https://api.therouter.ai/v1",
api_key="your-therouter-api-key",
)
# xAI Grok 4.3 through TheRouter
response = client.chat.completions.create(
model="xai/grok-4.3",
messages=[{"role": "user", "content": "Explain CAP theorem with examples."}],
)
# Switch to a different provider — same SDK, same code
response = client.chat.completions.create(
model="anthropic/claude-sonnet-4",
messages=[{"role": "user", "content": "Explain CAP theorem with examples."}],
)
TheRouter's provider page for xAI lists all available model slugs and their current routing targets. Each model on TheRouter maps to a specific xAI API slug — for example, xai/grok-4 is pinned to the grok-4-0709 snapshot for stability, while xai/grok-4.3 tracks xAI's current generation.
What TheRouter adds for xAI users:
- Unified billing across xAI and other providers on one invoice
- Automatic fallback — if xAI is down, route to an equivalent model from another provider
- Team governance — API keys, usage quotas, and audit logs per team member
- Provider-prefixed model IDs so your code never hard-codes a single provider's endpoint
Beyond Chat: Voice, Image, and Video APIs
xAI also offers specialized APIs beyond chat completions:
| API | Model | Price | Use Case |
|---|---|---|---|
| Image generation | grok-imagine-image | $0.02/image | Fast image generation |
| Image (quality) | grok-imagine-image-quality | $0.05/image | Higher quality output |
| Video generation | grok-imagine-video | $0.050/sec | Video generation |
| Video (preview 1.5) | grok-imagine-video-1.5-preview | $0.080/sec | Next-gen video quality |
| Voice (realtime) | — | $0.05/min | Real-time voice conversations |
| Text-to-speech | — | $15.00/1M chars | Convert text to speech |
| Speech-to-text | — | $0.10/hr (REST) | Transcribe audio |
These specialized APIs are separate from the chat/completions path and are not exposed through TheRouter's standard routing. Use the xAI API directly for image, video, and voice workloads.
FAQ
Q: Is xAI's API really OpenAI-compatible?
Yes — the /v1/chat/completions endpoint, tool calling, structured output, streaming, and vision all follow the OpenAI API spec. The one known divergence: logprobs and top_logprobs are silently ignored on Grok 4.20 and newer.
Q: What's the difference between Grok 4.3 and Grok 4.20?
Grok 4.3 (April 2026) is the current flagship with always-on reasoning, native video input, and artifact generation. Grok 4.20 (February 2026) comes in three variants (reasoning, non-reasoning, multi-agent) with explicit reasoning control. Both are priced at $1.25/$2.50/M. For new projects, start with Grok 4.3 unless you need the non-reasoning variant for latency or the multi-agent variant for 2M context.
Q: Can I disable reasoning in Grok 4.3?
No. Chain-of-thought reasoning is always on in Grok 4.3 and cannot be toggled via the API. If you need non-reasoning behavior, use grok-4.20-non-reasoning instead. The trade-off: Grok 4.3's TTFT is ~11.6 seconds (measured by community benchmarks) vs. lower latency for non-reasoning models.
Q: Does xAI offer free API credits?
xAI has offered up to $150/month in free API credits through their data-sharing program. Verify current availability in the xAI console — the program has been subject to changes.
Q: How does xAI compare to OpenAI and Anthropic?
xAI's Grok 4.3 is priced at $1.25/$2.50/M — significantly cheaper than OpenAI's GPT-5.5 or Anthropic's Claude Opus 4.7 on output tokens. On the Artificial Analysis Intelligence Index, Grok 4.3 scores 53 (vs. GPT-5.5 at 60 and Gemini 3.1 Pro Preview at 57). Where xAI stands out is agentic tool calling and long-horizon multi-step tasks, where community evaluations have found it competitive with models costing 9× more.
Q: What regions does xAI serve?
xAI's API is available in us-east-1, eu-west-1, and us-west-2. If you need low-latency access from Asia, consider routing through TheRouter which can optimize regional routing.
Sources: xAI Models Documentation (retrieved June 2026), xAI Grok 4.3 Model Docs, xAI Release Notes. Pricing verified against xAI's public documentation and cross-referenced with mem0.ai pricing analysis (May 2026). Benchmark data from Artificial Analysis and community evaluations.