xAI Grok Free code examples in Python and JavaScript
Grok models over an OpenAI-compatible API.
WHAT THIS PAGE COVERS
Pointing an existing OpenAI client at a different base URL.
grok-4.7
openai
Model ids change. If a sample returns a 404 on the model, that is the first thing to check against the official docs.
No xAI package to install — this is the OpenAI SDK pointed somewhere else. If you already call OpenAI, you already have it.
pip install openai
export XAI_API_KEY="xai-..." # macOS / Linux
setx XAI_API_KEY "xai-..." # Windows, then open a new shell
base_url and the key. Everything below this line is the OpenAI Chat Completions API you already know, so the OpenAI page in this guide covers streaming, tool calling and error handling unchanged.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["XAI_API_KEY"],
base_url="https://api.x.ai/v1",
)
response = client.chat.completions.create(
model="grok-4.7",
messages=[
{"role": "system", "content": "You are a concise technical assistant."},
{"role": "user", "content": "Explain a database index in two sentences."},
],
)
print(response.choices[0].message.content)
Identical to OpenAI, because it is the same client. Worth showing only so you can confirm the base URL swap did not change anything else.
stream = client.chat.completions.create(
model="grok-4.7",
messages=[{"role": "user", "content": "Write a haiku about indexes."}],
stream=True,
)
for chunk in stream:
if not chunk.choices:
continue
delta = chunk.choices[0].delta.content
if delta:
print(delta, end="", flush=True)
print()
Compatible does not mean identical. These are the four that bite, and none of them raise a helpful error.
# 1. MODEL IDS ARE xAI'S. "gpt-5.4-mini" here returns a 404, not a fallback.
# Keep the id in config, not scattered through the code.
MODEL = os.environ.get("XAI_MODEL", "grok-4.7")
# 2. ONE CLIENT PER PROVIDER. A base_url is per-client, so you cannot
# swap providers per call — build the client where you choose.
def client_for(provider: str) -> OpenAI:
if provider == "xai":
return OpenAI(api_key=os.environ["XAI_API_KEY"],
base_url="https://api.x.ai/v1")
return OpenAI() # plain OpenAI
# 3. NEWER OPENAI-ONLY PARAMETERS MAY BE REJECTED. The Responses API
# (client.responses.create) is OpenAI's, not a shared standard —
# stay on chat.completions for portable code.
# 4. RATE LIMITS AND ERROR BODIES ARE xAI'S. The typed exceptions still
# work because they key off the HTTP status, not the vendor.
The OpenAI SDK, pointed elsewhere. Server-side only — a key in browser JavaScript is a published key.
npm install openai
export XAI_API_KEY="xai-..."
baseURL and apiKey. Everything else is the OpenAI Chat Completions API unchanged.
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.XAI_API_KEY,
baseURL: "https://api.x.ai/v1",
});
const response = await client.chat.completions.create({
model: "grok-4.7",
messages: [
{ role: "system", content: "You are a concise technical assistant." },
{ role: "user", content: "Explain a database index in two sentences." },
],
});
console.log(response.choices[0].message.content);
Identical to OpenAI — same client, same events.
const stream = await client.chat.completions.create({
model: "grok-4.7",
messages: [{ role: "user", content: "Write a haiku about indexes." }],
stream: true,
});
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta?.content;
if (delta) process.stdout.write(delta);
}
Compatible is not identical. None of these fail with a message that tells you what happened.
// 1. MODEL IDS ARE xAI'S. "gpt-5.4-mini" here is a 404, not a fallback.
const MODEL = process.env.XAI_MODEL ?? "grok-4.7";
// 2. ONE CLIENT PER PROVIDER — baseURL is set on the client, not the call.
function clientFor(provider) {
return provider === "xai"
? new OpenAI({ apiKey: process.env.XAI_API_KEY,
baseURL: "https://api.x.ai/v1" })
: new OpenAI();
}
// 3. THE RESPONSES API IS OPENAI-ONLY. client.responses.create is not a
// shared standard — stay on chat.completions for portable code.
// 4. ERROR BODIES AND RATE LIMITS ARE xAI'S, but the typed error classes
// still work: they branch on HTTP status, not on the vendor.
QUESTIONS
Which languages are the xAI Grok examples in?
Python and JavaScript. Every sample runs as pasted and reads its credentials from an environment variable — no key is ever written into the code.
Which package do I install for xAI Grok?
The samples use openai. The install step on each language tab gives the exact command.
Which xAI Grok model do these examples use?
grok-4.7, checked against the official documentation on 25 September 2026. Model ids change often; if a call returns a model-not-found error, check the current list in the official docs.
Where is the official xAI Grok documentation?
https://docs.x.ai/ — it is linked at the bottom of this page, and it is the authority whenever it disagrees with a sample here.
ALSO IN LANGUAGE MODELS
The authority
Official xAI Grok documentation
Model names, pricing and rate limits change faster than any page here can. When this page and the official docs disagree, the official docs are right.
https://docs.x.ai/