English | 中文 Turn a Codex account pool into an observable, schedulable, operations-ready OpenAI / Anthropic compatible gateway. Codex2API is not a thin forwarding proxy. It is a long-running Codex access hub: it exposes /v1/chat/completions, /v1/responses, /v1/messages, Images, Videos (Grok Imagine), and Models endpoints while managing Refresh Token / Access Token accounts, health scoring, dynamic concurrency,…
Turn a Codex account pool into an observable, schedulable, operations-ready OpenAI / Anthropic compatible gateway. Codex2API is not a thin forwarding proxy. It is a long-running Codex access hub: it exposes /v1/chat/completions, /v1/responses, /v1/messages, Images, Videos (Grok Imagine), and Models endpoints while managing Refresh Token / Access Token accounts, health scoring, dynamic concurrency, rate-limit recovery, usage tracking, and admin operations behind the scenes.
Run it as a full PostgreSQL + Redis production stack or as a single-container SQLite + in-memory cache deployment. Point Codex CLI, Claude Code, the OpenAI SDK, or any compatible client at one Base URL, then manage accounts, proxies, API keys, prompt filtering, image workflows, and runtime settings from the built-in dashboard.
One compatible gateway
OpenAI-style Chat Completions / Responses / Images, Anthropic Messages, prefixless compatibility routes, and native Codex Responses forwarding are all exposed through one service.
Account-pool scheduler
Selection is driven by account status, health tier, scheduler score, dynamic concurrency, cooldown recovery, and recent usage so unhealthy accounts are avoided automatically. Supports round_robin and remaining_quota modes, with per-account credit billing flags.
Visual admin console
The embedded React / Vite dashboard covers account import and testing, API keys, proxy pools, image studio (text-to-image + image-to-image), prompt filtering, usage analytics, operations, scheduler board, and system settings.
Two deployment shapes
Use PostgreSQL + Redis for production or SQLite + Memory for lightweight single-node deployments; Docker images, source builds, local development, and the interactive deploy script are ready to use. SQLite mode binds to 127.0.0.1 by default for security.
Billing and observability
Per-account 5h/7d windowed USD cost tracking, credit quota support, API key usage tracking, OAuth PKCE token acquisition, prompt filtering, and a usage dashboard with request logs and trend charts.
Quality check
Compare selected accounts, models, and reasoning effort with an editable pelican-on-a-bicycle HTML/SVG animation challenge. Run up to three background tests across accounts, keep persistent test history, and review isolated animation previews, source, timing/token metrics, and HTML downloads.
The demo is only for trying the admin dashboard and basic UI flows. Do not upload real Refresh Tokens, Access Tokens, API keys, or any other sensitive data.
Screenshots
Screenshots use demo data. The actual dashboard depends on your account pool, request logs, and runtime environment.
Before switching deployment modes, replace .env with the matching example file.
The SQLite lightweight mode runs a single codex2api container and stores data at /data/codex2api.db.
SQLite compose files bind to 127.0.0.1 by default for security. To expose the SQLite service on all interfaces, set BIND_HOST=0.0.0.0 in .env or override the port binding in the compose file. The standard compose files bind to 0.0.0.0 by default.
The image studio library is stored under /data/images; uploaded admin backgrounds are stored under /data/backgrounds; Docker configurations persist /data.
docker compose down does not delete named volumes by default. Data is removed only by commands such as docker compose down -v, docker volume rm, or docker volume prune.
Antigravity channel (experimental API Key path)
Antigravity accounts are managed as a dedicated Google channel with browser/imported OAuth credentials and an optional Google API Key credential shape. Admin tooling includes secret-bearing JSON/ZIP credential export plus sanitized state, explicit control-plane sync, and bounded capability probing. OAuth requests use the Cloud Code v1internal adapter. API Key requests target the Generative Language v1beta/interactions endpoint, but ordinary API-key dispatch is fail-closed by default and requires ANTIGRAVITY_ENABLE_EXPERIMENTAL_INTERACTIONS=true. The opt-in real-upstream integration test has not succeeded in this environment, so this path remains experimental rather than production-certified. See docs/ANTIGRAVITY.md for endpoints, test instructions, models, channel restrictions, plaintext credential-storage risk, and the certification checklist.
Kiro channel
Kiro accounts (social Google/GitHub, AWS Builder ID, Enterprise IAM Identity Center, external IdP, and Kiro API keys) are a dedicated upstream channel. The protocol layer is a Go port of ZyphrZero/kiro.rs: /v1/messages is served natively, while /v1/responses and /v1/chat/completions go through a dedicated Kiro bridge that restores custom tools, hosted web search and Codex inline compaction. The admin page imports kiro.rs, Kiro IDE and Kiro Account Manager credential files, supports social and device-code sign-in, syncs credits and model catalogs, and exports to Kiro Account Manager or kiro.rs format. See docs/KIRO.md.
Cloud Redis providers such as Aiven and Upstash often require TLS. Prefer a rediss://... URL when your provider gives one.
The standard .env.example declares DATABASE_DRIVER=postgres and CACHE_DRIVER=redis. For the lightweight SQLite mode, use .env.sqlite.example.
Runtime Settings
Runtime business settings are stored in the database SystemSettings table and can be updated from the admin settings page.
Examples include MaxConcurrency, GlobalRPM, TestModel, TestContent, TestConcurrency, ProxyURL, PgMaxConns, RedisPoolSize, AdminSecret, SchedulerMode, and auto-cleanup switches.
Default settings are written automatically on first startup.
Response Context Cache
Locally reconstructed HTTP Responses continuations that use previous_response_id are protected by a bounded, per-process L1 cache. Its defaults are 64 MiB of logical retained JSON payload, 8 MiB per admitted entry, 2,000 entries, a 10-minute absolute TTL, and at most 200 raw items per entry.
The Settings page exposes three persisted integer-MiB budgets:
Budget
Default
Allowed Range
Local L1 total
64 MiB
8-4096 MiB
Local L1 entry admission
8 MiB
1-256 MiB and no greater than the total
Backend reconstruction
64 MiB
8-512 MiB
With Redis, a shared context that is within the reconstruction limit but above the L1 admission budget can still serve the request; it is not promoted into the local cache. Memory mode has no shared response-context fallback, so a dependent continuation whose context was oversized or evicted can return HTTP 409 response_context_unavailable. A dependent continuation can return HTTP 503 when its shared backend is temporarily unavailable and no eligible relay fallback can preserve previous_response_id.
Each successful budget change receives a read-only generation and is polled by every instance every five seconds. Operations shows effective/applied generations, synchronization state, logical cache bytes and counters, process memory, Go heap fields, and GC count. Logical cache bytes do not include Go/container overhead and are not an RSS or process-memory hard limit. During a rolling upgrade, a newer frontend tolerates an older backend that omits the new settings or Operations fields.
API Keys and Admin Secret
Public API keys come from the database API Keys table. If no key is configured, /v1/* skips API key authentication.
Admin Secret priority:
If ADMIN_SECRET is set in .env, the environment variable wins.
Otherwise, the database AdminSecret value is used.
If neither is set, /admin opens the first-run setup page. It requires the one-time bootstrap token printed in the service log (docker compose logs codex2api | grep "bootstrap token"); the token is per-process, regenerated on restart, and revoked once setup succeeds.
After login, the frontend sends X-Admin-Key when calling /api/admin/*.
Public API
Endpoint
Description
POST /v1/chat/completions
Chat Completions style endpoint
POST /v1/responses
Responses style endpoint
POST /v1/images/generations
OpenAI Images generation endpoint (gpt-image-2 / gpt-image-2.5 / gpt-image-2.6 via Codex, grok-imagine via Grok)
POST /v1/images/edits
OpenAI Images edit endpoint
POST /v1/videos/generations
Grok Imagine video generation (async, returns request_id)
POST /v1/videos/edits / POST /v1/videos/extensions
Grok Imagine video edit / extension
GET /v1/videos/:id
Poll video task status (video.url rewritten to the gateway content proxy)
GET /v1/videos/:id/content
Download the generated video through the gateway (Range supported)
GET /v1/models
List available models (includes gpt-6-astra/sol/luna, gpt-5.6-sol/terra/luna, gpt-5.5, gpt-5.3-codex-spark, gpt-image-2, grok-imagine-*, etc.)
GET /health
Health check
Pricing: gpt-5.5 is billed at $5.00/M input and $30.00/M output (standard tier). Priority tier: $12.50/M input, $75.00/M output. Other models follow pricing rules in the billing engine.
See API.md for full request formats, response formats, and error codes.
Token Upload and Account Management
The following admin endpoints require the X-Admin-Key header.
Add Refresh Token Accounts
# Single account
curl -X POST http://localhost:8080/api/admin/accounts \
-H "X-Admin-Key: your-admin-secret" \
-H "Content-Type: application/json" \
-d '{"name": "my-account", "refresh_token": "rt_xxxxxxxxxxxx"}'
# Batch import, newline separated, up to 100 tokens per request
curl -X POST http://localhost:8080/api/admin/accounts \
-H "X-Admin-Key: your-admin-secret" \
-H "Content-Type: application/json" \
-d '{"name": "batch", "refresh_token": "rt_xxx1\nrt_xxx2\nrt_xxx3"}'
The scheduler lives in auth.Store. It evaluates availability, scheduler priority, health tier, dynamic concurrency, historical errors, and recent usage before selecting an account.
Runtime state:
Status: ready, cooldown, error
HealthTier: healthy, warm, risky, banned
SchedulerScore: real-time scheduling score based on a baseline of 100
DynamicConcurrencyLimit: concurrency limit adjusted by health tier
SchedulerPriority: strict account priority; higher-priority accounts are considered before health tier, score, or current load
Selection strategy:
Filter unavailable accounts, including error, banned, cooldown accounts, and accounts without an Access Token.
Recompute health tier, scheduler score, and dynamic concurrency.
Exclude accounts that have reached their concurrency limit.
Prefer higher SchedulerPriority, then healthy > warm > risky > banned; within the same priority and tier, prefer higher score and lower concurrency.
In indexed mode, use a per-tier cursor or deterministic affinity offset inside the highest valid priority/health segment.
When multiple end users share one downstream API key, send X-Codex2API-Affinity-Key with a stable user or conversation identifier. Codex2API hashes it for local account affinity only and never forwards it upstream.
Concurrency rules:
Tier
Concurrency Limit
healthy
System MaxConcurrency
warm
Base concurrency / 2, at least 1
risky
Fixed at 1
banned
Fixed at 0, not schedulable
The persistent upstream WebSocket pool is also capped by each account’s current DynamicConcurrencyLimit, so connection reuse cannot grow beyond the account’s effective concurrency.
Observability:
GET /api/admin/accounts shows health tier, scheduler score, and penalty details.
GET /api/admin/ops/overview shows scheduler engine, indexed/legacy selections, scan volume, event waiters, sparse routing-cache state, shadow parity, and outbox lag in addition to runtime and connection-pool state.
/admin/ops/scheduler provides the scheduler board.
Scheduler engine (scheduler_engine, via Admin Settings, or CODEX_SCHEDULER_ENGINE):
Engine
Behavior
legacy
Compatibility path that scans the immutable account snapshot
shadow
Legacy remains authoritative while 1 in 64 requests compares indexed candidate availability
indexed
Priority/health buckets, sparse API-key sub-pools, and event-driven availability waits are authoritative
For a production rollout, use legacy → shadow → indexed. CODEX_SCHEDULER_ENGINE overrides the database setting and can pin an instance for a canary or emergency rollback. The old FAST_SCHEDULER_ENABLED=true switch remains a compatibility alias for indexed when no engine is configured.
Scheduler mode (scheduler_mode, via Admin Settings):
Mode
Behavior
round_robin (default)
Round-robin across available accounts per health tier, weighted by dispatch score
remaining_quota
Prioritizes accounts with lower usage percent; round-robin for ties
fill_first
Keeps draining the account with the least remaining quota until it is exhausted or rate-limited, then falls to the next (A → B → C)
Credit accounts (per-account flags):
When an account has a credit-based billing model instead of a usage-based Free/Pro plan, you can mark it so the scheduler skips usage-window penalties:
Field
Type
Effect
credit_enabled
bool
Mark account as credit-based billing
credit_skip_usage_window
bool
When true, skip 7d/5h usage-window penalties for this account
Windowed USD cost: The accounts table displays per-account billed cost over two windows – the past 5 hours and the past 7 days – aligned with each account’s usage reset boundaries. This shows actual spending per account rather than estimated token costs.
docker-compose.yml pulls the GHCR image for deployment. docker-compose.local.yml uses build: . for local source builds.
The frontend base path is fixed at /admin/ for both local development and production.
Before manually building the Go binary, run npm run build in frontend/.
For manual builds, pass the same version through VITE_APP_VERSION and Go’s -ldflags '-X github.com/codex2api/internal/version.Version=...', building the frontend first. For release builds, the dashboard uses the running backend version and shows the frontend build version with a rebuild hint when they differ. This hint does not replace embedded frontend assets; rebuild the frontend and then compile Go to update them.
.env controls physical runtime settings such as port, database, and Redis. Business settings are stored in the database and managed from the admin dashboard.
API keys are stored in the database and configured through the admin dashboard.
评论