Grok 4

XaiOpenAI-compatible REST (Chat Completions) and Anthropic-compatible Messages

grok-4Model ID
2025-07-09Release Date
xai

Grok 4

Last checked: 2025-08-11

Model ID
grok-4
Release2025-07-09
APIOpenAI-compatible REST (Chat Completions) and Anthropic-compatible Messages

Endpoints

base_url
https://api.x.ai/v1
chat_completions
/chat/completions
messages
/messages

Install

Node
— use fetch/axios or a community provider (e.g. @ai-sdk/xai)
Python
pip install requests  # (or use the xAI Python SDK if preferred)

Environment

api_key
XAI_API_KEY

Code examples

JavaScript
const resp = await fetch("https://api.x.ai/v1/chat/completions", {\n  method: "POST",\n  headers: {\n    "Authorization": `Bearer ${process.env.XAI_API_KEY}` ,\n    "Content-Type": "application/json"\n  },\n  body: JSON.stringify({\n    model: "grok-4",\n    messages: [{ role: "user", content: "Write a 3-line haiku about sunrise over London." }]\n  })\n});\nconst data = await resp.json();\nconsole.log(data.choices?.[0]?.message?.content);
Python
import os, requests\nheaders = {\n  "Authorization": f"Bearer {os.environ['XAI_API_KEY']}",\n  "Content-Type": "application/json"\n}\npayload = {\n  "model": "grok-4",\n  "messages": [{"role": "user", "content": "Write a 3-line haiku about sunrise over London."}]\n}\nr = requests.post("https://api.x.ai/v1/chat/completions", headers=headers, json=payload)\nprint(r.json()["choices"][0]["message"]["content"])

Notes

xAI’s REST is OpenAI-compatible for Chat Completions, and they also offer an Anthropic-compatible Messages endpoint. Use model id "grok-4".