grok2api README

The project's README from github.com/chenyme/grok2api. As one markdown file: README.md.

Grok2API

A multi-account API gateway for Grok Build, Grok Web, and Grok Console

English | 简体中文

Go React Docker

chenyme%2Fgrok2api | Trendshift

[!TIP] Check out DEEIX-AI / DEEIX-Chat, a lightweight, integrated AI platform for model routing, chat, files, tools, billing, identity, and operations.

[!NOTE] This project is for technical research and learning purposes only. Please comply with Grok's official terms of use and local laws when using it; otherwise, you will be solely responsible for all consequences!

Sponsors

Want to sponsor this project?

APIMart Thanks to APIMart for sponsoring this project! APIMart is a low-cost API platform for AI image & video generation — GPT-Image-2 from $0.006/image, 160+ images per dollar. One async API covers both image and video: submit a task, get an ID, fetch results via polling or callback. Batch tens of thousands of images without timeouts, switch models without changing code. Pay-as-you-go with no monthly fee — sign up here to get started.
PackyCode PackyCode is a stable and professional API relay for Claude Code, Codex, Gemini, and leading Chinese models. With fast unified access, full-stack observability, risk controls, elastic scaling, and cost optimization, it delivers a smooth developer experience. Sign up here to bring production-ready AI into your workflows.
DEEIX AI / DEEIX Chat DEEIX-Chat is an open-source, self-hostable AI Chat platform for individuals, teams, and enterprises that need stable, long-term, unified access to multiple models. It brings models, conversations, files, tool calling, and administration together in one deployable and extensible system. Click here to start deploying.
RightCode Right Code is an enterprise-grade AI Agent distribution platform that primarily provides stable access services for Claude Code, Codex, Gemini, and other models. It supports invoicing and dedicated one-to-one assistance for enterprises and teams. Thanks to Right Code for providing token support. Click here to register and get started.
FennoAI FennoAI provides enterprise-grade OpenAI/Anthropic-compatible APIs for Codex, Claude Code, and OpenCode, processing hundreds of billions of tokens daily with global business settlement and invoicing. Through the Grok2API exclusive offer, USD 1.99 unlocks USD 50 in Coding Plan credits, plus referral commissions up to 20%.
Qiniu Cloud AI Qiniu Cloud AI, Qiniu Cloud’s (02567.HK) enterprise MaaS platform, offers protocol-compatible access to 150+ global models for text, image, audio, video, and files, serving 1.69+ million users. Grok2API registrations through the exclusive link receive 12 million free enterprise tokens or 3 million developer tokens.
Swiftproxy Swiftproxy provides 90M+ clean residential IPs across 220+ locations, supporting HTTP(S)/SOCKS5, IP rotation, Sticky Sessions, and precise location targeting. It helps API services and automation workflows access online platforms reliably from different locations, making it suitable for API requests, automation, data collection, and location-based access. Residential proxies start at $0.7/GB. Free testing is available, and code PROXY90 gives 10% off. Try Swiftproxy now.

Overview

Grok2API is a Go gateway with a built-in React admin console. It manages independent Grok Build, Grok Web, and Grok Console account pools and exposes unified OpenAI- and Anthropic-compatible APIs.

Architecture

flowchart LR
    %% Color definitions
    classDef access fill:#e1f5fe,stroke:#01579b
    classDef core fill:#fff3e0,stroke:#e65100
    classDef providers fill:#f3e5f5,stroke:#4a148c
    classDef infra fill:#e8f5e9,stroke:#1b5e20
    classDef upstream fill:#fce4ec,stroke:#880e4f

    subgraph Access["Access Domain"]
        direction LR
        Clients["API Clients"]
        Admin["React Admin"]
    end

    subgraph Core["Gateway Core Domain"]
        direction LR
        Management["Management Services<br/>Accounts · Models · Keys · Settings"]
        Sync["Account Sync<br/>Credentials · Quota · Models"]
        Gateway["Gateway Service<br/>Protocols · Routing · Selection · Retry"]
        Audit["Audit Service<br/>Usage · Client Billing"]
        Management --> Sync
        Gateway -.-> Audit
    end

    subgraph Providers["Provider Channel Domain"]
        direction LR
        Registry["Provider Registry"]
        Build["Grok Build<br/>OAuth · Dynamic Models · Billing"]
        Web["Grok Web<br/>SSO · Remote Quota · Media"]
        Console["Grok Console<br/>SSO · Local Window · Stateless"]
        Registry --> Build
        Registry --> Web
        Registry --> Console
    end

    subgraph Infra["Shared Infrastructure Domain"]
        direction LR
        Egress["Egress Manager<br/>Scopes · Proxy Pool · Fallback · Clearance"]
        Database[("SQLite / PostgreSQL")]
        Runtime[("Memory / Redis")]
    end

    Upstream["🌐 Grok Upstream"]

    %% Cross-domain calls
    Clients --> Gateway
    Admin --> Management
    Gateway --> Registry
    Sync --> Registry
    Build -->|grok_build| Egress
    Web -->|grok_web / asset| Egress
    Console -->|grok_console| Egress
    Egress --> Upstream
    Management --> Database
    Audit --> Database
    Gateway <--> Runtime

    %% Application styles
    class Clients,Admin access
    class Management,Sync,Gateway,Audit core
    class Registry,Build,Web,Console providers
    class Egress,Database,Runtime infra
    class Upstream upstream

The Gateway routes requests through the Provider Registry. Account Sync refreshes credentials, quota, and models. Each Provider keeps independent account state and uses an isolated egress scope; usage, audits, and client billing are finalized after the request.

Core capabilities

Area Capabilities
APIs Responses, Chat Completions, Anthropic Messages, Images, and asynchronous Videos
Clients Codex, Claude Code, OpenAI-compatible SDKs, and Anthropic-compatible SDKs
Accounts Bulk import/export, quota sync, credential renewal, conversion, tools, and cleanup
Routing Model discovery, Provider pinning, sticky sessions, quota/concurrency guards, and bounded failover
Sessions Stored responses, compact, prompt-cache affinity, and optional reasoning replay
Media Image generation/editing, video jobs, local archiving, and URL/Base64/SSE output
Egress HTTP/SOCKS/Resin and Trojan/VLESS/Shadowsocks/VMess tunnels, subscriptions, probes, proxy pools, allocation, fallback, and FlareSolverr
Operations Dashboard, model routes, client keys, audits, runtime settings, and media libraries

Provider boundaries

Provider Authentication Models Main capabilities
Grok Build OAuth / Device OAuth Discovered per account Responses, Chat, Messages, compact, stored responses, paid-account video
Grok Web SSO Built-in, filtered by tier Responses, Chat, Messages, stored responses, images, image editing, video
Grok Console SSO Built-in Stateless Responses, Chat, Messages, images, image editing, video, TTS, STT, Realtime

Each Provider keeps its own credentials, quota, health, cooldown, concurrency, and model capabilities. Account retries stay within one route; when one public model ID intentionally aggregates multiple routes, the gateway may select another schedulable route without mixing Provider state.

Quick start

Official images support linux/amd64 and linux/arm64.

git clone https://github.com/chenyme/grok2api.git
cd grok2api
cp config.example.yaml config.yaml

Generate secrets and place them in config.yaml:

openssl rand -hex 32
openssl rand -base64 32
secrets:
  jwtSecret: "replace-with-the-generated-hex-value"
  credentialEncryptionKey: "replace-with-the-generated-base64-key"

bootstrapAdmin:
  username: "admin"
  password: "replace-with-a-strong-password"

Start the service:

docker compose pull
docker compose up -d
docker compose logs -f grok2api

Open http://127.0.0.1:8000. The image already includes the frontend; SQLite data and local media are stored in the Compose volume.

Run from source

cp config.example.yaml config.yaml
make run

For frontend development:

cd frontend
pnpm install
pnpm dev

Set up the gateway

  1. Sign in with the bootstrap administrator.
  2. Connect a Build, Web, or Console account.
  3. Wait for its quota and model capabilities to sync.
  4. Review the public routes under Model Routes.
  5. Create a client key under Client Keys.
  6. Call a /v1/* endpoint with that key.

After first sign-in, change the administrator password and remove bootstrapAdmin from the configuration. Never rotate credentialEncryptionKey after credentials have been stored.

Account operations

Provider Connect or import Export
Build Device OAuth, JSON/JSONL Re-importable account file
Web Pasted/TXT SSO, JSON/JSONL Re-importable account file
Console Pasted/TXT SSO, JSON/JSONL Re-importable account file

Imports accept UTF-8 BOM. Bulk quota sync, Build credential renewal, Web→Build/Console conversion, account tools, and cleanup report live progress.

Build refresh tokens may rotate when renewed. Do not actively share one Build credential between grok2api, the official CLI, another gateway, or another independent client: one client can consume a token that another client still holds. Authorize each active client separately, or transfer the credential only after the previous client has stopped using it.

Web account tools can accept the terms, set a random birthday corresponding to an age of 20–40, and enable NSFW. Completed steps are recorded and skipped on later runs.

Automatic deletion of old reauthRequired accounts is available but disabled by default. Active inference leases and video jobs are protected.

[!TIP] To migrate from the Python version, export Grok Web SSO tokens as TXT and import them under Grok Web. Old pool metadata and databases are not compatible.

Models and routing

Build models are discovered from each account's actual capabilities. Web and Console use built-in catalogs. The Model Routes page shows Provider-qualified routes, endpoint capabilities, and supporting-account counts; clients should treat the currently serviceable results from GET /v1/models as authoritative.

Grok Build

Build does not use one global static model list. Account synchronization reads the upstream /models endpoint, and different accounts, subscription tiers, or staged rollouts may expose different models. Routing retains these per-account capabilities instead of replacing the global catalog with one account's response.

Model Type Availability Gateway surfaces
Conversation models returned by upstream /models (for example, grok-4.5) Conversation Returned by the selected account Chat Completions, Responses, Messages, compact, stored responses
grok-composer-2.5-fast Conversation Grok Build OAuth accounts Chat Completions, Responses, Messages; supplemented from the OAuth session contract when a sparse upstream catalog omits it
grok-imagine-video-1.5 Video Super/paid Build accounts Videos; not assigned to Free or unknown-entitlement accounts

Conversation requests are translated to the Build Responses protocol while preserving the tool, reasoning, multi-turn, and prompt-cache compatibility required by Codex and Claude Code. Build currently exposes no image generation or image editing routes.

Grok Web

Web uses a built-in catalog filtered by account tier; higher tiers inherit lower-tier models.

Model Type Minimum tier Gateway surfaces
grok-chat-fast Conversation Basic Chat Completions, Responses, Messages
grok-chat-auto Conversation Super Chat Completions, Responses, Messages
grok-chat-expert Conversation Super Chat Completions, Responses, Messages
grok-chat-heavy Conversation Heavy Chat Completions, Responses, Messages
grok-imagine-image-lite Image Basic Images Generations
grok-imagine-image Image Basic Images Generations (enable_pro=false)
grok-imagine-image-2.0 Image Basic Images Generations (enable_pro=true)
grok-imagine-image-edit Image Edit Basic Images Edits
grok-imagine-video Video Basic for 720p; Super for 480p Videos

Web Imagine generation maps aspect_ratio and n to the browser protocol. size remains an OpenAI-compatible aspect-ratio alias, while generation-only resolution and quality are ignored on Web routes because the upstream product is selected by the model name rather than by those Console-oriented controls.

Grok Console

Console uses the catalog built into the current release. Conversation forwarding is stateless, while image, video, and voice use the standard xAI resource APIs.

Model Type Gateway surfaces
grok-4.20-0309-non-reasoning Conversation Chat Completions, Responses, Messages
grok-4.20-0309-reasoning Conversation Chat Completions, Responses, Messages; the model reasons but the upstream rejects configurable reasoningEffort
grok-4.20-multi-agent-0309 Conversation Chat Completions, Responses, Messages
grok-4.5 Conversation Chat Completions, Responses, Messages
grok-4.3 Conversation Chat Completions, Responses, Messages
grok-build-0.1 Conversation Chat Completions, Responses, Messages
grok-imagine-image Image, Image

grok2api (chenyme/grok2api)

Searching Database…

Что это такое?Самостоятельно размещаемый шлюз на Go, который объединяет несколько аккаунтов Grok Build, Grok Web и Grok Console и открывает их через единые API, совместимые с OpenAI и Anthropic. Также включает встроенную панель администратора на React.
Это библиотека, которую я подключаю, или отдельный сервер, который я запускаю?Это отдельный сервер, который вы развёртываете, а не библиотека. Официальные Docker-образы есть для linux/amd64 и linux/arm64, а работа идёт через REST API и встроенную веб-панель.
Как это запустить?Сгенерируйте секреты и поместите их в config.yaml, затем запустите сервис через Docker Compose. В образ уже входит фронтенд, а данные SQLite и локальные медиафайлы хранятся в томе Compose.
Какие аккаунты нужны, чтобы всё заработало?Нужны настоящие аккаунты Grok Build (OAuth/Device OAuth), Grok Web (SSO) или Grok Console (SSO), которые подключаются к пулу аккаунтов шлюза. Отдельного официального ключа Grok API помимо этих учётных данных не требуется.
Безопасно ли использовать одни и те же учётные данные Grok Build в других клиентах?Нет. Токены обновления Build могут меняться при продлении, поэтому, если одни и те же учётные данные одновременно используются в grok2api, официальном CLI или другом шлюзе, один клиент может израсходовать токен, который другой ещё использует. Авторизуйте каждый клиент отдельно или передавайте учётные данные только после того, как предыдущий клиент перестал ими пользоваться.
Где хранятся мои учётные данные и данные?Всё остаётся на вашем сервере: данные SQLite и локальные медиафайлы лежат в томе Docker Compose, а учётные данные защищены ключом credentialEncryptionKey, который вы задаёте сами. Его нельзя менять после того, как учётные данные уже сохранены.
Какие клиенты могут подключаться к этому шлюзу?Codex, Claude Code и любой SDK, совместимый с OpenAI или Anthropic, могут напрямую обращаться к его эндпоинтам /v1.
Поддерживает ли он генерацию изображений и видео, а не только чат?Да, в зависимости от подключённого провайдера и уровня аккаунта. Grok Web и Grok Console поддерживают генерацию и редактирование изображений и асинхронные задания на видео, а Console дополнительно предлагает TTS, STT и Realtime.
Одинаково ли ведут себя имена моделей у всех провайдеров?Нет. Build получает список моделей для каждого аккаунта из актуального эндпоинта /models на стороне провайдера, Web использует встроенный каталог с фильтрацией по уровню аккаунта, а Console использует каталог, поставляемый в текущей версии. Поэтому один и тот же публичный ID модели может маршрутизироваться по-разному в зависимости от провайдера.
Нарушает ли использование этого проекта условия использования Grok?Проект прямо заявляет, что предназначен только для технических исследований и обучения. Пользователи должны соблюдать официальные условия использования Grok и местные законы на свой страх и риск.
Creator
chenyme
Size
11.9 MB
Stars
7.8K
Age
1y
Commits · 90 Days