logo
0
0
WeChat Login
Grok2API

Python FastAPI Version License 中文 DeepWiki Project%20Docs

NOTE

This project is for learning and research only. Please comply with Grok's terms of use and all applicable local laws and regulations. Do not use it for illegal purposes. If you fork the project or open a PR, please keep the original author and frontend attribution.


Grok2API is a FastAPI-based Grok gateway that exposes Grok Web capabilities through OpenAI-compatible APIs. Core features:

  • OpenAI-compatible endpoints: /v1/models, /v1/chat/completions, /v1/responses, /v1/images/generations, /v1/images/edits, /v1/videos, /v1/videos/{video_id}, /v1/videos/{video_id}/content
  • Anthropic-compatible endpoint: /v1/messages
  • Streaming and non-streaming chat, explicit reasoning output, function-tool structure passthrough, and unified token / usage accounting
  • Multi-account pools, tier-aware selection, failure feedback, quota synchronization, and automatic maintenance
  • Local image/video caching and locally proxied media URLs
  • Text-to-image, image editing, text-to-video, and image-to-video support
  • Built-in Admin dashboard, Web Chat, Masonry image generation, and ChatKit voice page

Service Architecture


Quick Start

Local Deployment

git clone https://github.com/chenyme/grok2api
cd grok2api
cp .env.example .env
uv sync
uv run granian --interface asgi --host 0.0.0.0 --port 8000 --workers 1 app.main:app

Docker Compose

git clone https://github.com/chenyme/grok2api
cd grok2api
cp .env.example .env
docker compose up -d

Vercel

Deploy with Vercel

Render

Deploy to Render

First Launch

  1. Change app.app_key
  2. Set app.api_key
  3. Set app.app_url otherwise image and video URLs may return 403 Forbidden

WebUI

Routes

PagePath
Admin login/admin/login
Account management/admin/account
Config management/admin/config
Cache management/admin/cache
WebUI login/webui/login
Web Chat/webui/chat
Masonry/webui/masonry
ChatKit/webui/chatkit

Authentication Rules

ScopeConfigRule
/v1/*app.api_keyNo extra authentication when empty
/admin/*app.app_keyDefault value: grok2api
/webui/*app.webui_enabled, app.webui_keyDisabled by default; if webui_key is empty, no extra verification is required

Configuration

Configuration Layers

LocationPurposeEffective Time
.envPre-start configurationAt service startup
${DATA_DIR}/config.tomlRuntime configurationEffective immediately after save
config.defaults.tomlDefault templateOn first initialization

Environment Variables

VariableDescriptionDefault
TZTime zoneAsia/Shanghai
LOG_LEVELLog levelINFO
LOG_FILE_ENABLEDWrite local log filestrue
ACCOUNT_SYNC_INTERVALAccount directory incremental sync interval in seconds30
ACCOUNT_SYNC_ACTIVE_INTERVALActive sync interval after account-directory changes are detected, in seconds3
SERVER_HOSTService bind address0.0.0.0
SERVER_PORTService port8000
SERVER_WORKERSGranian worker count1
HOST_PORTDocker Compose published host port8000
DATA_DIRLocal data root for accounts, locally cached media files, and cache indexes./data
LOG_DIRLocal log directory./logs
ACCOUNT_STORAGEAccount storage backendlocal
ACCOUNT_LOCAL_PATHSQLite path for local account storage${DATA_DIR}/accounts.db
ACCOUNT_REDIS_URLRedis DSN for redis mode""
ACCOUNT_MYSQL_URLSQLAlchemy DSN for mysql mode""
ACCOUNT_POSTGRESQL_URLSQLAlchemy DSN for postgresql mode""
ACCOUNT_SQL_POOL_SIZECore connection pool size for SQL backends5
ACCOUNT_SQL_MAX_OVERFLOWMaximum overflow connections above pool size10
ACCOUNT_SQL_POOL_TIMEOUTSeconds to wait for a free connection from the pool30
ACCOUNT_SQL_POOL_RECYCLEMax connection lifetime in seconds before reconnect1800
CONFIG_LOCAL_PATHRuntime config file path for local config storage${DATA_DIR}/config.toml

Runtime config can also be overridden with GROK_-prefixed environment variables. For example, GROK_APP_API_KEY overrides app.api_key, and GROK_FEATURES_STREAM overrides features.stream.

System Configuration Groups

GroupKey Items
appapp_key, app_url, api_key, webui_enabled, webui_key
loggingfile_level, max_files
featurestemporary, memory, stream, thinking, auto_chat_mode_fallback, thinking_summary, dynamic_statsig, enable_nsfw, show_search_sources, custom_instruction, image_format, imagine_public_image_proxy, video_format
proxy.egressmode, proxy_url, proxy_pool, resource_proxy_url, resource_proxy_pool, skip_ssl_verify
proxy.clearancemode, cf_cookies, user_agent, browser, flaresolverr_url, timeout_sec, refresh_interval
retryreset_session_status_codes, max_retries, on_codes
account.refreshbasic_interval_sec, super_interval_sec, heavy_interval_sec, usage_concurrency, on_demand_min_interval_sec
cache.localimage_max_mb, video_max_mb
chattimeout
imagetimeout, stream_timeout
videotimeout
voicetimeout
assetupload_timeout, download_timeout, list_timeout, delete_timeout
nsfwtimeout
batchnsfw_concurrency, refresh_concurrency, asset_upload_concurrency, asset_list_concurrency, asset_delete_concurrency

Image and Video Formats

ConfigAllowed Values
features.image_formatgrok_url, local_url, grok_md, local_md, base64
features.imagine_public_image_proxytrue, false
features.video_formatgrok_url, local_url, grok_html, local_html

Supported Models

You can use GET /v1/models to retrieve the currently supported model list.

Chat

Modelmodetier
grok-4.20-0309-non-reasoningfastbasic
grok-4.20-0309autosuper
grok-4.20-0309-reasoningexpertsuper
grok-4.20-0309-non-reasoning-superfastsuper
grok-4.20-0309-superautosuper
grok-4.20-0309-reasoning-superexpertsuper
grok-4.20-0309-non-reasoning-heavyfastheavy
grok-4.20-0309-heavyautoheavy
grok-4.20-0309-reasoning-heavyexpertheavy
grok-4.20-multi-agent-0309heavyheavy
grok-4.20-fastfastbasic, prefers higher-tier pools
grok-4.20-autoautosuper, prefers higher-tier pools
grok-4.20-expertexpertsuper, prefers higher-tier pools
grok-4.20-heavyheavyheavy
grok-4.3-betagrok-420-computer-use-sasuper

Image

Modelmodetier
grok-imagine-image-litefastbasic
grok-imagine-imageautosuper
grok-imagine-image-proautosuper

Image Edit

Modelmodetier
grok-imagine-image-editautosuper

Video

Modelmodetier
grok-imagine-videoautosuper

API Overview

EndpointAuth RequiredDescription
GET /v1/modelsYesList currently enabled models
GET /v1/models/{model_id}YesRetrieve one model
POST /v1/chat/completionsYesUnified entry point for chat, image, and video
POST /v1/responsesYesOpenAI Responses API compatible subset
POST /v1/messagesYesAnthropic Messages API compatible endpoint
POST /v1/images/generationsYesStandalone image generation endpoint
POST /v1/images/editsYesStandalone image editing endpoint
POST /v1/videosYesAsynchronous video job creation
GET /v1/videos/{video_id}YesRetrieve a video job
GET /v1/videos/{video_id}/contentYesFetch the final video file
GET /v1/files/video?id=...NoFetch a locally cached video
GET /v1/files/image?id=...NoFetch a locally cached image

API Examples

The examples below use http://localhost:8000.

GET /v1/models
curl http://localhost:8000/v1/models \
  -H "Authorization: Bearer $GROK2API_API_KEY"
Field Notes
FieldLocationDescription
AuthorizationHeaderRequired when app.api_key is non-empty. Use Bearer <api_key>


POST /v1/chat/completions

Chat:

curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $GROK2API_API_KEY" \
  -d '{
    "model": "grok-4.20-auto",
    "stream": true,
    "reasoning_effort": "high",
    "messages": [
      {"role":"user","content":"Hello"}
    ]
  }'

Image:

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

Video:

curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $GROK2API_API_KEY" \
  -d '{
    "model": "grok-imagine-video",
    "stream": true,
    "messages": [
      {"role":"user","content":"A neon rainy street at night, cinematic slow tracking shot"}
    ],
    "video_config": {
      "seconds": 10,
      "size": "1792x1024",
      "resolution_name": "720p",
      "preset": "normal"
    }
  }'
Field Notes
FieldDescription
messagesSupports text and multimodal content blocks
streamWhether to stream output; falls back to features.stream when omitted
reasoning_effortnone, minimal, low, medium, high, xhigh; none disables reasoning output
temperature / top_pSampling parameters, default 0.8 / 0.95
toolsOpenAI function tools structure
tool_choiceauto, required, or a specific function tool
image_configImage model parameters
|_ n1-4 for lite, 1-10 for other image models, 1-2 for edit
|_ size1280x720, 720x1280, 1792x1024, 1024x1792, 1024x1024
|_ response_formaturl, b64_json
video_configVideo model parameters
|_ seconds6, 10, 12, 16, 20
|_ size720x1280, 1280x720, 1024x1024, 1024x1792, 1792x1024
|_ resolution_name480p, 720p
|_ presetfun, normal, spicy, custom


POST /v1/responses
curl http://localhost:8000/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $GROK2API_API_KEY" \
  -d '{
    "model": "grok-4.20-auto",
    "input": "Explain quantum tunneling",
    "instructions": "Keep the answer concise.",
    "stream": true,
    "reasoning": {
      "effort": "high"
    }
  }'
Field Notes
FieldDescription
modelModel ID. It must be an enabled model
inputUser input; supports a string or a Responses API-style message array
instructionsOptional system instructions injected as a system message
streamWhether to stream output; falls back to features.stream when omitted
reasoningOptional reasoning configuration
|_ effortnone disables reasoning output; other values enable it
temperature / top_pSampling parameters, default 0.8 / 0.95
tools / tool_choiceFunction tools are supported; flat Responses API tool definitions are normalized automatically


POST /v1/messages
curl http://localhost:8000/v1/messages \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $GROK2API_API_KEY" \
  -d '{
    "model": "grok-4.20-auto",
    "stream": true,
    "thinking": {
      "type": "enabled",
      "budget_tokens": 1024
    },
    "messages": [
      {
        "role": "user",
        "content": "Explain quantum tunneling in three sentences"
      }
    ]
  }'
Field Notes
FieldDescription
modelModel ID. It must be an enabled model
messagesAnthropic Messages-format messages; supports text, image, document, and tool-result blocks
systemOptional system prompt; accepts a string or an array of text blocks
streamWhether to stream output; falls back to features.stream when omitted
thinkingOptional reasoning configuration
|_ typedisabled disables reasoning output; other configs enable it
max_tokensAccepted but currently ignored because Grok upstream does not expose this parameter
tools / tool_choiceAnthropic tool definitions are supported and converted to internal function tools


POST /v1/images/generations
curl http://localhost:8000/v1/images/generations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $GROK2API_API_KEY" \
  -d '{
    "model": "grok-imagine-image",
    "prompt": "A cat floating in space",
    "n": 1,
    "size": "1792x1024",
    "response_format": "url"
  }'
Field Notes
FieldDescription
modelImage model: grok-imagine-image-lite, grok-imagine-image, or grok-imagine-image-pro
promptImage generation prompt
nNumber of images; 1-4 for lite, 1-10 for other image models
sizeSupports 1280x720, 720x1280, 1792x1024, 1024x1792, 1024x1024
response_formaturl or b64_json


POST /v1/images/edits
curl http://localhost:8000/v1/images/edits \
  -H "Authorization: Bearer $GROK2API_API_KEY" \
  -F "model=grok-imagine-image-edit" \
  -F "prompt=Make this image sharper" \
  -F "image[]=@/path/to/image.png" \
  -F "n=1" \
  -F "size=1024x1024" \
  -F "response_format=url"
Field Notes
FieldDescription
modelImage-edit model, currently grok-imagine-image-edit
promptEdit instruction
image[]Reference image multipart file field; up to 5 images are used
nNumber of outputs, range 1-2
sizeCurrently only 1024x1024 is supported
response_formaturl or b64_json
maskNot supported yet; passing it returns a validation error


POST /v1/videos
curl http://localhost:8000/v1/videos \
  -H "Authorization: Bearer $GROK2API_API_KEY" \
  -F "model=grok-imagine-video" \
  -F "prompt=A neon rainy street at night, cinematic slow tracking shot" \
  -F "seconds=10" \
  -F "size=1792x1024" \
  -F "resolution_name=720p" \
  -F "preset=normal" \
  -F "input_reference[]=@/path/to/reference.png"
curl http://localhost:8000/v1/videos/<video_id> \
  -H "Authorization: Bearer $GROK2API_API_KEY"

curl -L http://localhost:8000/v1/videos/<video_id>/content \
  -H "Authorization: Bearer $GROK2API_API_KEY" \
  -o result.mp4
Field Notes
FieldDescription
modelVideo model, currently grok-imagine-video
promptVideo generation prompt
secondsVideo length: 6, 10, 12, 16, 20
sizeSupports 720x1280, 1280x720, 1024x1024, 1024x1792, 1792x1024
resolution_name480p or 720p
presetfun, normal, spicy, custom
input_reference[]Optional image-to-video reference multipart file field; at most the first 7 images are used
video_idVideo job ID returned by POST /v1/videos; used to retrieve the job or download the final video



Star History

Star History Chart

About

Grok2API 是一个基于 FastAPI 构建的 Grok 网关,支持将 Grok Web 能力以 OpenAI 兼容 API 的方式转换。

Sponsor

Language
Python66%
HTML17.5%
JavaScript11.8%
CSS4.5%
Others0.2%