MCPcopy
hub / github.com/chenyme/grok2api

github.com/chenyme/grok2api @v2.0.3 sqlite

repository ↗ · DeepWiki ↗ · release v2.0.3 ↗
1,204 symbols 4,925 edges 149 files 342 documented · 28%
README

图片20260409204656

Python FastAPI Version License English 项目文档

[!NOTE] 本项目仅供学习与研究交流。请务必遵循 Grok 的使用条款及当地法律法规,不得用于非法用途!二开与 PR 请保留原作者与前端标识。

Grok2API 是一个基于 FastAPI 构建的 Grok 网关,支持将 Grok Web 能力以 OpenAI 兼容 API 的方式转换。核心特性: - OpenAI 兼容接口:/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 兼容接口:/v1/messages - 支持流式与非流式对话、显式思考输出、函数工具结构透传,以及统一的 token / usage 统计 - 支持多账号池、层级选号、失败反馈、额度同步与自动维护 - 支持本地缓存图片、视频与本地代理链接返回 - 支持文生图、图像编辑、文生视频、图生视频 - 内置 Admin 后台管理、Web Chat、Masonry 生图、ChatKit 语音页面

服务架构

flowchart LR
    Client["Clients\nOpenAI SDK / curl / Browser"] --> API["FastAPI App"]

    subgraph Products["Products"]
        direction TB
        OpenAI["OpenAI APIs\n/v1/*"]
        Anthropic["Anthropic APIs\n/v1/messages"]
        Web["Web Products\n/admin /webui/*"]
    end

    subgraph Control["Control"]
        direction TB
        Models["Model Registry"]
        Accounts["Account Services"]
        Proxies["Proxy Services"]
    end

    subgraph Dataplane["Dataplane"]
        direction TB
        Reverse["Reverse Protocol + Transport"]
        AccountDP["AccountDirectory"]
        ProxyDP["Proxy Runtime"]
    end

    subgraph Platform["Platform"]
        direction TB
        Tokens["Token Estimation"]
        Storage["Storage"]
        Config["Config Snapshot"]
        Auth["Auth"]
        Log["Logging"]
    end

    API --> OpenAI
    API --> Anthropic
    API --> Web

    OpenAI --> Models
    OpenAI --> AccountDP
    OpenAI --> ProxyDP
    OpenAI --> Reverse
    OpenAI --> Tokens
    OpenAI --> Storage

    Anthropic --> Models
    Anthropic --> AccountDP
    Anthropic --> ProxyDP
    Anthropic --> Reverse
    Anthropic --> Tokens

    Web --> Accounts
    Web --> Config
    Web --> Auth

    Accounts --> AccountDP
    Proxies --> ProxyDP
    Models --> Reverse

快速开始

本地部署

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

首次启动

  1. 修改 app.app_key
  2. 设置 app.api_key
  3. 设置 app.app_url(否则图片、视频的链接会 403 无权访问)

WebUI

页面入口

页面 路径
Admin 登录页 /admin/login
账号管理 /admin/account
配置管理 /admin/config
缓存管理 /admin/cache
WebUI 登录页 /webui/login
Web Chat /webui/chat
Masonry /webui/masonry
ChatKit /webui/chatkit

鉴权规则

范围 配置项 规则
/v1/* app.api_key 为空则不额外鉴权
/admin/* app.app_key 默认值 grok2api
/webui/* app.webui_enabled, app.webui_key 默认关闭;webui_key 为空则不额外校验

配置体系

配置分层

位置 用途 生效时机
.env 启动前配置 服务启动时
${DATA_DIR}/config.toml 运行时配置 保存后即时生效
config.defaults.toml 默认模板 首次初始化时

环境变量

变量名 说明 默认值
TZ 时区 Asia/Shanghai
LOG_LEVEL 日志级别 INFO
LOG_FILE_ENABLED 写入本地文件日志 true
ACCOUNT_SYNC_INTERVAL 账号目录增量同步间隔(秒) 30
SERVER_HOST 服务监听地址 0.0.0.0
SERVER_PORT 服务监听端口 8000
SERVER_WORKERS Granian worker 数量 1
HOST_PORT Docker Compose 宿主机映射端口 8000
DATA_DIR 本地数据目录 ./data
LOG_DIR 本地日志目录 ./logs
ACCOUNT_STORAGE 账号存储后端 local
ACCOUNT_REDIS_URL redis 模式 Redis DSN ""
ACCOUNT_MYSQL_URL mysql 模式 SQLAlchemy DSN ""
ACCOUNT_POSTGRESQL_URL postgresql 模式 SQLAlchemy DSN ""

系统配置项

分组 关键项
app app_key, app_url, api_key, webui_enabled, webui_key
features temporary, memory, stream, thinking, dynamic_statsig, enable_nsfw, custom_instruction, image_format, video_format
proxy.egress mode, proxy_url, proxy_pool, resource_proxy_url, resource_proxy_pool, skip_ssl_verify
proxy.clearance mode, cf_cookies, user_agent, browser, flaresolverr_url, timeout_sec, refresh_interval
retry reset_session_status_codes, max_retries, on_codes
account.refresh basic_interval_sec, super_interval_sec, heavy_interval_sec, usage_concurrency, on_demand_min_interval_sec
chat timeout
image timeout, stream_timeout
video timeout
voice timeout
asset upload_timeout, download_timeout, list_timeout, delete_timeout
nsfw timeout
batch nsfw_concurrency, refresh_concurrency, asset_upload_concurrency, asset_list_concurrency, asset_delete_concurrency

图片、视频格式

配置项 可选值
features.image_format grok_url, local_url, grok_md, local_md, base64
features.video_format grok_url, local_url, grok_html, local_html

模型支持

可通过 GET /v1/models 获取当前支持模型列表。

Chat

模型名 mode tier
grok-4.20-0309-non-reasoning fast basic
grok-4.20-0309 auto basic
grok-4.20-0309-reasoning expert basic
grok-4.20-0309-non-reasoning-super fast super
grok-4.20-0309-super auto super
grok-4.20-0309-reasoning-super expert super
grok-4.20-0309-non-reasoning-heavy fast heavy
grok-4.20-0309-heavy auto heavy
grok-4.20-0309-reasoning-heavy expert heavy
grok-4.20-multi-agent-0309 heavy heavy

Image

模型名 mode tier
grok-imagine-image-lite fast basic
grok-imagine-image auto super
grok-imagine-image-pro auto super

Image Edit

模型名 mode tier
grok-imagine-image-edit auto super

Video

模型名 mode tier
grok-imagine-video auto super

API 一览

接口 是否鉴权 说明
GET /v1/models 列出当前启用模型
GET /v1/models/{model_id} 获取单个模型信息
POST /v1/chat/completions 对话 / 图像 / 视频统一入口
POST /v1/responses OpenAI Responses API 兼容子集
POST /v1/messages Anthropic Messages API 兼容接口
POST /v1/images/generations 独立图像生成接口
POST /v1/images/edits 独立图像编辑接口
POST /v1/videos 异步视频任务创建
GET /v1/videos/{video_id} 查询视频任务
GET /v1/videos/{video_id}/content 获取最终视频文件
GET /v1/files/image?id=... 获取本地缓存图片
GET /v1/files/video?id=... 获取本地缓存视频

接口示例

以下示例默认使用 http://localhost:8000 地址。

GET /v1/models

curl http://localhost:8000/v1/models \
  -H "Authorization: Bearer $GROK2API_API_KEY"

POST /v1/chat/completions

对话:

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

图像:

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":"一只在太空漂浮的猫"}
    ],
    "image_config": {
      "n": 2,
      "size": "1024x1024",
      "response_format": "url"
    }
  }'

视频:

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":"霓虹雨夜街头,电影感慢镜头追拍"}
    ],
    "video_config": {
      "seconds": 10,
      "size": "1792x1024",
      "resolution_name": "720p",
      "preset": "normal"
    }
  }'

关键字段:

字段 说明
messages 支持文本与多模态内容块
thinking 是否显式输出思考过程
reasoning_effort none, minimal, low, medium, high, xhigh
tools OpenAI function tools 结构
image_config.n lite1-4,其他图像模型为 1-10,编辑模型为 1-2
image_config.size 1280x720, 720x1280, 1792x1024, 1024x1792, 1024x1024
video_config.seconds 6, 10, 12, 16, 20
video_config.size 720x1280, 1280x720, 1024x1024, 1024x1792, 1792x1024
video_config.resolution_name 480p, 720p
video_config.preset fun, 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-0309",
    "input": "解释一下量子隧穿",
    "stream": true
  }'

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-0309",
    "stream": true,
    "messages": [
      {
        "role": "user",
        "content": "用三句话解释量子隧穿"
      }
    ]
  }'

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": "一只在太空漂浮的猫",
    "n": 1,
    "size": "1024x1024",
    "response_format": "url"
  }'

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=把这张图变清晰一些" \
  -F "image[]=@/path/to/image.png" \
  -F "n=1" \
  -F "size=1024x1024" \
  -F "response_format=url"

POST /v1/videos

curl http://localhost:8000/v1/videos \
  -H "Authorization: Bearer $GROK2API_API_KEY" \
  -F "model=grok-imagine-video" \
  -F "prompt=霓虹雨夜街头,电影感慢镜头追拍" \
  -F "seconds=10" \
  -F "size=1792x1024" \
  -F "resolution_name=720p" \
  -F "preset=normal"
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

Star History

Star History Chart

Core symbols most depended-on inside this repo

get
called by 215
app/platform/config/snapshot.py
get
called by 196
app/control/account/models.py
get
called by 127
app/dataplane/proxy/adapters/session.py
text
called by 58
app/statics/js/webui/chat.js
get_config
called by 53
app/platform/config/snapshot.py
feedback
called by 35
app/dataplane/proxy/__init__.py
text
called by 31
app/statics/js/webui/masonry.js
to_dict
called by 30
app/control/account/models.py

Shape

Function 734
Method 296
Class 116
Route 58

Languages

Python84%
TypeScript16%

Modules by API surface

app/statics/js/webui/chat.js76 symbols
app/products/openai/video.py47 symbols
app/products/openai/images.py38 symbols
app/dataplane/reverse/protocol/xai_chat_reasoning.py36 symbols
app/statics/js/webui/masonry.js32 symbols
app/statics/js/webui/chatkit.js31 symbols
app/products/openai/router.py31 symbols
app/products/web/admin/batch.py28 symbols
app/control/account/models.py27 symbols
app/products/web/admin/tokens.py26 symbols
app/products/web/router.py24 symbols
app/statics/js/admin-header.js23 symbols

Dependencies from manifests, versioned

aiohttp3.13.4 · 1×
aiohttp-socks0.11.0 · 1×
aiomysql0.2.0 · 1×
asyncpg0.31.0 · 1×
certifi2025.10.5 · 1×
cryptography46.0.7 · 1×
curl-cffi0.15.0 · 1×
fastapi0.119.0 · 1×
granian2.7.2 · 1×
greenlet3.3.1 · 1×
loguru0.7.3 · 1×
orjson3.11.4 · 1×

For agents

$ claude mcp add grok2api \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact