API Reference

August 5, 2026 · View on GitHub

grok2api exposes an OpenAI-compatible and Anthropic-compatible REST API. Default listen address: http://0.0.0.0:8000.

Authentication

MethodHeader / Parameter
Bearer tokenAuthorization: Bearer <api_key>
x-api-keyx-api-key: <api_key>

When app.api_key is empty in config, authentication is disabled (open mode).

Admin endpoints use app.app_key instead, and additionally accept ?app_key=<key> as a query parameter.


Chat Completions (OpenAI-compatible)

POST /v1/chat/completions

The main endpoint. Dispatches internally by model capability: grok.com chat, console.x.ai chat, image generation, image editing, or video generation — all through the same request shape.

Request Body

{
  "model": "grok-4.20-0309-non-reasoning",
  "messages": [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Hello!"}
  ],
  "stream": true,
  "temperature": 0.8,
  "top_p": 0.95,
  "reasoning_effort": "medium"
}
FieldTypeDefaultDescription
modelstringrequiredModel name (see Models below)
messagesarrayrequiredOpenAI message format. Supports system, user, assistant, tool roles. Content can be a string or an array of content parts (text, image_url)
streambooltrue (config)Enable SSE streaming
temperaturefloat0.8Sampling temperature
top_pfloat0.95Nucleus sampling
reasoning_effortstring(config)"none" disables thinking tokens; "low", "medium", "high", "xhigh" for console models; omit to use features.thinking default
max_tokensintMax output tokens
toolsarrayTool definitions (function calling)
tool_choiceanyTool selection strategy
image_configobjectImage generation options (n, size, response_format) when using an image model
video_configobjectVideo generation options (seconds, size) when using a video model

Messages with Images

{
  "model": "grok-4.20-0309-non-reasoning",
  "messages": [
    {
      "role": "user",
      "content": [
        {"type": "text", "text": "What's in this image?"},
        {"type": "image_url", "image_url": {"url": "https://example.com/photo.jpg"}}
      ]
    }
  ]
}

image_url also accepts data:image/jpeg;base64,... data URIs.

Streaming Response (SSE)

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1719500000,"model":"grok-4.20-0309-non-reasoning","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1719500000,"model":"grok-4.20-0309-non-reasoning","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1719500000,"model":"grok-4.20-0309-non-reasoning","choices":[{"index":0,"delta":{"content":"!"},"finish_reason":null}]}

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1719500000,"model":"grok-4.20-0309-non-reasoning","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: [DONE]

When reasoning_effort is enabled, thinking tokens appear as:

{"delta": {"reasoning_content": "Let me think about this..."}}

Non-Streaming Response

{
  "id": "chatcmpl-xxx",
  "object": "chat.completion",
  "created": 1719500000,
  "model": "grok-4.20-0309-non-reasoning",
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "Hello! How can I help you?",
      "reasoning_content": "The user said hello..."
    },
    "finish_reason": "stop"
  }],
  "usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
}

Retry Behavior

On upstream failure (429, 401, 503), the gateway automatically retries with a different account. Max retries: retry.max_retries (default 1) for quota strategy, 5 for random strategy.


Responses API (OpenAI-compatible)

POST /v1/responses

OpenAI Responses API format. Console models route to console.x.ai; others go through grok.com.

{
  "model": "grok-4.3-console",
  "input": "Explain quantum computing",
  "instructions": "You are a physics teacher.",
  "stream": false,
  "reasoning": {"effort": "high"}
}
FieldTypeDescription
modelstringrequired
inputstring or arrayUser input (string, or array of message/function_call/function_call_output items)
instructionsstringSystem prompt
streamboolEnable SSE streaming
reasoningobject`{"effort": "low"
temperaturefloatSampling temperature
top_pfloatNucleus sampling
toolsarrayTool definitions
tool_choiceanyTool selection

Anthropic-compatible

POST /v1/messages

Accepts Anthropic message format and converts internally.

{
  "model": "grok-4.20-0309-non-reasoning",
  "max_tokens": 4096,
  "system": "You are helpful.",
  "messages": [
    {"role": "user", "content": "Hello!"}
  ],
  "thinking": {"type": "enabled"},
  "stream": true
}
FieldTypeDescription
modelstringrequired
messagesarrayAnthropic message format (supports text, image, tool_use, tool_result content blocks)
systemstring or arraySystem prompt (string or array of {type: "text", text: "..."})
max_tokensintMax output tokens
streamboolEnable SSE streaming
thinkingobject{"type": "enabled"} to emit thinking tokens
temperaturefloatSampling temperature
top_pfloatNucleus sampling
toolsarrayTool definitions
tool_choiceanyTool selection

Non-Streaming Response

{
  "id": "msg_xxx",
  "type": "message",
  "role": "assistant",
  "model": "grok-4.20-0309-non-reasoning",
  "content": [{"type": "text", "text": "Hello!"}],
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {"input_tokens": 0, "output_tokens": 0}
}

Streaming Events

event: message_start
data: {"type":"message_start","message":{...}}

event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}

event: content_block_stop
data: {"type":"content_block_stop","index":0}

event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":0}}

event: message_stop
data: {"type":"message_stop"}

Image Generation

POST /v1/images/generations

OpenAI-compatible image generation endpoint. Use this for grok-imagine-image-lite (HTTP-based).

Note: grok-imagine-image and grok-imagine-image-pro use WebSocket-based real-time generation. They can also be called through POST /v1/chat/completions — the gateway auto-detects the model and routes accordingly, returning generated images as ![image](url) in the response content.

{
  "model": "grok-imagine-image",
  "prompt": "A sunset over mountains",
  "n": 1,
  "size": "1024x1024",
  "response_format": "url"
}
FieldTypeDefaultDescription
modelstringrequiredWeb: grok-imagine-image-lite, grok-imagine-image, grok-imagine-image-pro; Console DPoP: grok-imagine-image-console, grok-imagine-image-quality-console
promptstringrequiredImage description
nint1Number of images (max 4 for lite, 10 for others)
sizestringImage dimensions; Console maps common sizes to aspect ratios
aspect_ratiostringConsole: 1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3, 2:1, or 1:2
resolutionstringConsole: 1k or 2k
response_formatstring"url""url" or "b64_json"

Response

{
  "created": 1719500000,
  "data": [
    {"url": "https://xxx.grok.com/image.jpg"}
  ]
}

POST /v1/images/edits

Multipart image editing.

curl -X POST http://localhost:8000/v1/images/edits \
  -H "Authorization: Bearer YOUR_KEY" \
  -F "model=grok-imagine-image-edit" \
  -F "prompt=Add a rainbow in the sky" \
  -F "image[]=@photo.jpg" \
  -F "response_format=url"
FieldTypeDescription
modelstringrequired — Web: grok-imagine-image-edit; Console DPoP: grok-imagine-image-console or grok-imagine-image-quality-console
promptstringrequired — editing instruction
image[]filerequired — one or more source images; Console supports 1 to 3
aspect_ratiostring
resolutionstring
response_formatstring"url" (default) or "b64_json"

Video Generation

POST /v1/videos

Async video creation. Returns a job immediately; poll for completion.

curl -X POST http://localhost:8000/v1/videos \
  -H "Authorization: Bearer YOUR_KEY" \
  -F "model=grok-imagine-video" \
  -F "prompt=A cat playing piano" \
  -F "seconds=6" \
  -F "size=720x1280"
FieldTypeDefaultDescription
modelstringrequiredWeb: grok-imagine-video; Console DPoP: grok-imagine-video-console
promptstringrequiredVideo description
secondsint6Duration: 6, 10, 12, 16, or 20; current Console route is intended for values accepted by upstream (normally up to 15 seconds)
sizestring"720x1280"Video dimensions; Console maps to 480p/720p and 16:9/9:16

Response

{
  "id": "video_xxx",
  "object": "video",
  "created_at": 1719500000,
  "status": "queued",
  "model": "grok-imagine-video",
  "progress": 0,
  "prompt": "A cat playing piano",
  "seconds": "6",
  "size": "720x1280",
  "quality": "standard"
}

GET /v1/videos/{id}

Poll video job status. When status is "completed", video_url is populated.

GET /v1/videos/{id}/content

Download the completed video file (MP4).


Models

GET /v1/models

Returns available models based on active account pools.

GET /v1/models/{id}

Get a single model by ID.

Available Models

grok.com Chat Models

ModelModeTierNotes
grok-4.20-0309-non-reasoningautosuperDefault balanced
grok-4.20-0309-non-reasoning-reasoningexpertsuperDeep reasoning
grok-4.20-0309-non-reasoning-non-reasoningfastbasicFast, no reasoning
grok-4.20-0309-non-reasoning-superautosuperSuper tier
grok-4.20-0309-non-reasoning-reasoning-superexpertsuperSuper reasoning
grok-4.20-0309-non-reasoning-non-reasoning-superfastsuperSuper fast
grok-4.20-0309-non-reasoning-heavyautoheavyHeavy tier
grok-4.20-0309-non-reasoning-reasoning-heavyexpertheavyHeavy reasoning
grok-4.20-0309-non-reasoning-non-reasoning-heavyfastheavyHeavy fast
grok-4.20-multi-agent-0309heavyheavyMulti-agent
grok-4.20-fastfastbasicPreferBest
grok-4.3-fastfastbasicPreferBest
grok-4.20-autoautosuperPreferBest
grok-4.20-expertexpertsuperPreferBest
grok-4.20-heavyheavyheavyPreferBest
grok-4.3-betagrok43superBeta

Console Models (console.x.ai, DPoP)

ModelThinking Level
grok-4.3-consoledefault
grok-4.3-lowlow
grok-4.3-mediummedium
grok-4.3-highhigh
grok-4.20-0309-non-reasoning-reasoning-consoledefault
grok-4.20-0309-non-reasoning-consoledefault
grok-4.20-0309-non-reasoning-consoledefault
grok-4.20-multi-agent-consoledefault
grok-4.20-multi-agent-lowlow
grok-4.20-multi-agent-mediummedium
grok-4.20-multi-agent-highhigh
grok-4.20-multi-agent-xhighxhigh
grok-build-consoledefault

Media Models

ModelCapabilityTransport
grok-imagine-image-liteImage generation (basic)HTTP (grok.com chat)
grok-imagine-imageImage generationWebSocket (real-time streaming)
grok-imagine-image-consoleImage generation and editingConsole standard Images API + DPoP
grok-imagine-image-quality-consoleQuality image generation and editingConsole standard Images API + DPoP
grok-imagine-video-consoleAsync video generationConsole standard Videos API + DPoP
grok-imagine-image-proImage generation (pro)WebSocket (real-time streaming)
grok-imagine-image-editImage editingHTTP (grok.com chat)
grok-imagine-videoVideo generationHTTP (grok.com chat)

Utility Endpoints

GET /health

{"status": "ok"}

GET /meta

{"version": "1.0.0"}

GET /v1/files/image?id=<file_id>

Serve a cached image by file ID. Returns JPEG or PNG.

GET /v1/files/video?id=<file_id>

Serve a cached video by file ID. Returns MP4.


Admin API

All admin endpoints require app.app_key authentication via Authorization: Bearer <app_key> or ?app_key=<key>.

Config

MethodPathDescription
GET/admin/api/configGet current config
POST/admin/api/configUpdate config (persisted to user config file)

Token Management

MethodPathDescription
GET/admin/api/tokensList all tokens (paginated)
POST/admin/api/tokens/addAdd tokens
POST/admin/api/tokensReplace all tokens in a pool
DELETE/admin/api/tokensDelete tokens
DELETE/admin/api/tokens/invalidDelete invalid/expired tokens
PUT/admin/api/tokens/editEdit token properties
POST/admin/api/tokens/disabledToggle disabled state
POST/admin/api/tokens/disabled/batchBatch toggle disabled

Pool & Batch Operations

MethodPathDescription
PUT/admin/api/poolReplace entire pool
POST/admin/api/batch/nsfwBatch NSFW toggle
POST/admin/api/batch/refreshTrigger quota refresh
POST/admin/api/batch/cache-clearClear all caches

Status & Sync

MethodPathDescription
GET/admin/api/verifyVerify admin auth
GET/admin/api/statusGet system status
GET/admin/api/storageGet storage info
POST/admin/api/syncForce directory sync

Assets

MethodPathDescription
GET/admin/api/assetsList assets
POST/admin/api/assets/delete-itemDelete a specific asset
POST/admin/api/assets/clear-tokenClear all assets for a token

Media Cache

MethodPathDescription
GET/admin/api/cacheCache statistics
GET/admin/api/cache/listList cached items
POST/admin/api/cache/clearClear all cache
POST/admin/api/cache/item/deleteDelete a cache item
POST/admin/api/cache/items/deleteDelete multiple items

Quick Start Examples

curl — Basic Chat

curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "model": "grok-4.20-0309-non-reasoning",
    "messages": [{"role": "user", "content": "Hello!"}]
  }'

curl — Streaming Chat

curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "model": "grok-4.20-0309-non-reasoning",
    "messages": [{"role": "user", "content": "Write a poem"}],
    "stream": true
  }'

curl — Console Model with Thinking

curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "model": "grok-4.3-high",
    "messages": [{"role": "user", "content": "Prove the Riemann hypothesis"}],
    "reasoning_effort": "high"
  }'

curl — Image Generation

curl http://localhost:8000/v1/images/generations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "model": "grok-imagine-image",
    "prompt": "A futuristic city at night",
    "n": 2
  }'

curl — Image Generation via Chat (WebSocket)

curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "model": "grok-imagine-image",
    "messages": [{"role": "user", "content": "A cat in space"}],
    "image_config": {"n": 2, "size": "1024x1024"}
  }'

WebSocket models (grok-imagine-image, grok-imagine-image-pro) generate images in real-time with progress updates. Results are returned as ![image](url) in the response content.

curl — Anthropic Format

curl http://localhost:8000/v1/messages \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "model": "grok-4.20-0309-non-reasoning",
    "max_tokens": 4096,
    "messages": [{"role": "user", "content": "Hello!"}]
  }'

Python (openai SDK)

from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="YOUR_API_KEY",
)

# Non-streaming
response = client.chat.completions.create(
    model="grok-4.20-0309-non-reasoning",
    messages=[{"role": "user", "content": "Hello!"}],
)
print(response.choices[0].message.content)

# Streaming
stream = client.chat.completions.create(
    model="grok-4.20-0309-non-reasoning",
    messages=[{"role": "user", "content": "Write a haiku"}],
    stream=True,
)
for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")

Python (anthropic SDK)

import anthropic

client = anthropic.Anthropic(
    base_url="http://localhost:8000",
    api_key="YOUR_API_KEY",
)

message = client.messages.create(
    model="grok-4.20-0309-non-reasoning",
    max_tokens=4096,
    messages=[{"role": "user", "content": "Hello!"}],
)
print(message.content[0].text)

Error Responses

All errors follow this format:

{
  "error": {
    "message": "Description of what went wrong",
    "type": "validation_error",
    "code": "model_not_found",
    "param": "model",
    "status": 400
  }
}
Error TypeHTTP StatusCommon Causes
validation_error400Invalid model, missing required fields, bad JSON
authentication_error401Missing or invalid API key
rate_limit_error429No available accounts, all quotas exhausted
upstream_error502Grok upstream returned an error
server_error500Internal server error