logo
0
0
WeChat Login

Grok2API

中文 | English

NOTE

This project is for learning and research only. You must comply with Grok's Terms of Use and applicable laws. Do not use it for illegal purposes.

Grok2API rebuilt with FastAPI, fully aligned with the latest web call format. Supports streaming and non-streaming chat, image generation/editing, deep thinking, token pool concurrency, and automatic load balancing.

image

Usage

How to start

  • Local development
uv sync uv run main.py
  • Deployment
git clone https://github.com/chenyme/grok2api docker compose up -d

Admin panel

URL: http://<host>:8000/admin
Default password: grok2api (config key app.app_key, change it in production).

Environment variables

VariableDescriptionDefaultExample
LOG_LEVELLog levelINFODEBUG
SERVER_HOSTBind address0.0.0.00.0.0.0
SERVER_PORTService port80008000
SERVER_WORKERSUvicorn worker count12
SERVER_STORAGE_TYPEStorage type (local/redis/mysql/pgsql)localpgsql
SERVER_STORAGE_URLStorage URL (empty for local)""postgresql+asyncpg://user:password@host:5432/db

MySQL example: mysql+aiomysql://user:password@host:3306/db (if you set mysql://, it will be normalized to mysql+aiomysql://)

Usage limits

  • Basic account: 80 requests / 20h
  • Super account: not tested by the author

Models

ModelCostAccountChatImageVideo
grok-31Basic/SuperYesYes-
grok-3-fast1Basic/SuperYesYes-
grok-41Basic/SuperYesYes-
grok-4-mini1Basic/SuperYesYes-
grok-4-fast1Basic/SuperYesYes-
grok-4-heavy4SuperYesYes-
grok-4.11Basic/SuperYesYes-
grok-4.1-thinking4Basic/SuperYesYes-
grok-imagine-1.04Basic/Super-Yes-
grok-imagine-1.0-video-Basic/Super--Yes

API

POST /v1/chat/completions

Generic endpoint: chat, image generation, image editing, video generation, video upscaling

curl http://localhost:8000/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $GROK2API_API_KEY" \ -d '{ "model": "grok-4", "messages": [{"role":"user","content":"Hello"}] }'
Supported request parameters
FieldTypeDescriptionAllowed values
modelstringModel ID-
messagesarrayMessage listdeveloper, system, user, assistant
streambooleanEnable streamingtrue, false
thinkingstringThinking modeenabled, disabled, null
video_configobjectVideo model only-
└─ aspect_ratiostringVideo aspect ratio16:9, 9:16, 1:1, 2:3, 3:2
└─ video_lengthintegerVideo length (seconds)6, 10
└─ resolution_namestringResolution480p, 720p
└─ presetstringStyle presetfun, normal, spicy

Note: any other parameters will be discarded and ignored.


POST /v1/images/generations

Image endpoint: image generation, image editing

curl http://localhost:8000/v1/images/generations \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $GROK2API_API_KEY" \ -d '{ "model": "grok-imagine-1.0", "prompt": "A cat floating in space", "n": 1 }'
Supported request parameters
FieldTypeDescriptionAllowed values
modelstringImage model IDgrok-imagine-1.0
promptstringPrompt-
nintegerNumber of images1 - 10 (streaming: 1 or 2 only)
streambooleanEnable streamingtrue, false

Note: any other parameters will be discarded and ignored.



Configuration

Config file: data/config.toml

NOTE

In production or behind a reverse proxy, make sure app.app_url is set to the public URL. Otherwise file links may be incorrect or return 403.

ModuleFieldKeyDescriptionDefault
appapp_urlApp URLExternal access URL for Grok2API (used for file links).http://127.0.0.1:8000
app_keyAdmin passwordPassword for the Grok2API admin panel (required).grok2api
api_keyAPI keyToken for calling Grok2API (optional).""
image_formatImage formatOutput image format (url or base64).url
video_formatVideo formatOutput video format (html tag or processed url).html
groktemporaryTemporary chatEnable temporary conversation mode.true
streamStreamingEnable streaming by default.true
thinkingThinking chainEnable model thinking output.true
dynamic_statsigDynamic fingerprintEnable dynamic Statsig value generation.true
filter_tagsFilter tagsAuto-filter special tags in Grok responses.["xaiartifact", "xai:tool_usage_card", "grok:render"]
timeoutTimeoutTimeout for Grok requests (seconds).120
base_proxy_urlBase proxy URLBase service address proxying Grok official site.""
asset_proxy_urlAsset proxy URLProxy URL for Grok static assets (images/videos).""
cf_clearanceCF ClearanceCloudflare clearance cookie for verification.""
max_retryMax retriesMax retries on Grok request failure.3
retry_status_codesRetry status codesHTTP status codes that trigger retry.[401, 429, 403]
retry_backoff_baseBackoff baseBase delay for retry backoff (seconds).0.5
retry_backoff_factorBackoff factorExponential multiplier for retry backoff.2.0
retry_backoff_maxBackoff maxMax wait per retry (seconds).30.0
retry_budgetBackoff budgetMax total retry time per request (seconds).90.0
stream_idle_timeoutStream idle timeoutIdle timeout for streaming responses (seconds).45.0
video_idle_timeoutVideo idle timeoutIdle timeout for video generation (seconds).90.0
tokenauto_refreshAuto refreshEnable automatic token refresh.true
refresh_interval_hoursRefresh intervalToken refresh interval (hours).8
fail_thresholdFailure thresholdConsecutive failures before a token is disabled.5
save_delay_msSave delayDebounced save delay for token changes (ms).500
reload_interval_secConsistency refreshToken state refresh interval in multi-worker setups (sec).30
cacheenable_auto_cleanAuto cleanEnable cache auto clean; cleanup when exceeding limit.true
limit_mbCleanup thresholdCache size threshold (MB) that triggers cleanup.1024
performancensfw_max_concurrentNSFW enable concurrencyConcurrency cap for enabling NSFW in batch. Recommended 10.10
nsfw_batch_sizeNSFW enable batch sizeBatch size for enabling NSFW. Recommended 50.50
nsfw_max_tokensNSFW enable max tokensMax tokens per NSFW batch to avoid mistakes. Recommended 1000.1000
usage_max_concurrentToken usage refresh concurrencyConcurrency cap for batch usage refresh. Recommended 25.25
usage_batch_sizeToken usage refresh batch sizeBatch size for usage refresh. Recommended 50.50
usage_max_tokensToken usage refresh max tokensMax tokens per usage refresh batch. Recommended 1000.1000
assets_max_concurrentOnline assets find/delete concurrencyConcurrency cap for online asset find/delete. Recommended 25.25
assets_batch_sizeOnline assets find/delete batch sizeBatch size for online asset find/delete. Recommended 10.10
assets_max_tokensOnline assets find/delete max tokensMax tokens per online asset find/delete batch. Recommended 1000.1000
assets_delete_batch_sizeOnline assets delete batchBatch concurrency for online asset deletion. Recommended 10.10
media_max_concurrentMedia concurrencyConcurrency cap for video/media generation. Recommended 50.50

Star History

Star History Chart

About

https://github.com/chenyme/grok2api

1.07 MiB
0 forks0 stars3 branches19 TagREADMEMIT license
grok2apirepo-named
Language
Python74.5%
JavaScript15.8%
HTML5.4%
CSS4%
Others0.3%