Skip to content
Proyek

Tentang

Codex2API adalah proyek proxy terbalik dan panel administrasi untuk Codex yang dibangun dengan Go + Gin + React/Vite.

Sistem dan infrastruktur

Cara angka ini diukur

2,417 bintang453 Fork +2 dalam 24 jam

Yang dapat Anda lakukan

  • Unified Protocol Gateway - Exposes OpenAI Chat Completions, Responses (HTTP & WebSocket), Images, Videos, and Anthropic Messages—plus prefixless compatibility routes and native Codex Responses forwarding.
  • Multi-Channel Account Pools - Manages Codex, Claude, Grok, Antigravity, Kiro, and OpenCode credentials with automated OAuth PKCE / device-code flows, batch import/export, and per-account token lifecycle maintenance.
  • Health-Aware Scheduler - Selects accounts by strict priority, health tier (healthy / warm / risky / banned), real-time score, dynamic concurrency, and cooldown recovery. Supports round_robin, remaining_quota, and fill_first modes across legacy, shadow, and indexed engines.
  • Embedded Admin Console & Portals - Built-in React 19 + Vite 8 dashboard covering accounts, API keys, proxy pools, Image Studio, prompt filtering, payload rules, model pricing, usage analytics, channel monitoring, and operations—plus standalone non-admin portals (/image-studio, /key-usage, /account-portal).

Pertumbuhan bintang terukur

dalam 24 jam
+2
dalam 7 hari
+17
dalam 15 hari
+35
dalam 1 bulan
+76

Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.

README.md

Asli

Codex2API

English · 简体中文

Go 1.26 Gin 1.12 React 19 Vite 8 Database Cache OpenAI and Anthropic API Docker Ready MIT License

Quick Start · Live Demo · Channels · Public API · Admin Console · Documentation


Turn multi-channel AI account pools into an observable, schedulable, production-ready OpenAI & Anthropic gateway.

Codex2API is a long-running AI access hub written in Go with an embedded React admin console. Rather than acting as a thin reverse proxy, it unifies Codex, Claude, Grok, Antigravity, Kiro, and OpenCode upstream channels behind a single gateway—exposing /v1/chat/completions, /v1/responses (HTTP & WebSocket), /v1/messages, Images, Videos, and Models while managing OAuth/token lifecycles, health-scored scheduling, dynamic concurrency, proxy pools, billing, prompt filtering, and operational telemetry.

Deploy it as a scalable PostgreSQL + Redis cluster for production, or as a single-container SQLite + in-memory cache node for lightweight environments. Point Codex CLI, Claude Code, OpenAI SDK, or any compatible client at one Base URL.

Highlights

Capability Description
Unified Protocol Gateway Exposes OpenAI Chat Completions, Responses (HTTP & WebSocket), Images, Videos, and Anthropic Messages—plus prefixless compatibility routes and native Codex Responses forwarding.
Multi-Channel Account Pools Manages Codex, Claude, Grok, Antigravity, Kiro, and OpenCode credentials with automated OAuth PKCE / device-code flows, batch import/export, and per-account token lifecycle maintenance.
Health-Aware Scheduler Selects accounts by strict priority, health tier (healthy / warm / risky / banned), real-time score, dynamic concurrency, and cooldown recovery. Supports round_robin, remaining_quota, and fill_first modes across legacy, shadow, and indexed engines.
Embedded Admin Console & Portals Built-in React 19 + Vite 8 dashboard covering accounts, API keys, proxy pools, Image Studio, prompt filtering, payload rules, model pricing, usage analytics, channel monitoring, and operations—plus standalone non-admin portals (/image-studio, /key-usage, /account-portal).
Billing, Budgets & Quality Checks Windowed 5h/7d USD cost tracking, per-account credit billing flags, API key quota and weekly model request budgets, automated degradation checks (Intelligence Check), and interactive SVG/HTML quality comparisons.
Flexible Deployment Prebuilt multi-arch Docker images (PostgreSQL + Redis or single-container SQLite + Memory), one-command interactive deploy script (deploy.sh), source builds, and Render cloud deployment.

Live Demo

[!WARNING] The live demo is strictly for previewing the admin interface and workflows. Never upload real Refresh Tokens, Access Tokens, API keys, or any sensitive credentials.


Screenshots

Demo data is shown below. Actual metrics, charts, and logs reflect your runtime account pool and traffic.

Codex2API Dashboard

View more admin console screenshots
Accounts Dashboard Trends
Accounts Dashboard Trends
Image Studio Prompt Filter
Image Studio Prompt Filter
Operations Usage Analytics
Operations Usage Analytics
Usage Guide API Reference
Usage Guide API Reference

Supported Channels

Codex2API organizes upstream providers into dedicated channels that share unified routing, API key permissions, billing, and observability:

Channel Credential Types Primary Protocols & Capabilities Reference
Codex (OpenAI) Refresh Token (OAuth PKCE), Access Token (AT-only), Responses Relay /v1/responses (HTTP & WS), /v1/chat/completions, /v1/messages bridge, /v1/images/*, /v1/responses/compact, /v1/alpha/search API.md · USAGE.md
Claude (Anthropic) OAuth, Setup Token, API Key + Base URL Native /v1/messages passthrough, protocol bridge fallback, subscription usage sampling API.md
Grok (xAI) Grok credentials Chat/Responses, Grok Imagine Images (/v1/images/*) & Videos (/v1/videos/*) API.md
Antigravity (Google) Browser/imported OAuth (v1internal), optional API Key (experimental, fail-closed) Gemini / Cloud Code adapter, secret-bearing JSON/ZIP export, sanitized state & capability probing. API Key path (v1beta/interactions) requires ANTIGRAVITY_ENABLE_EXPERIMENTAL_INTERACTIONS=true and is not production-certified. ANTIGRAVITY.md
Kiro Social OAuth (Google/GitHub), AWS Builder ID, IAM Identity Center, external IdP, API Key Go port of kiro.rs; native /v1/messages, dedicated /v1/responses & /v1/chat/completions bridge with custom tools & web search KIRO.md
OpenCode OpenCode channel accounts OpenCode upstream routing, model sync, usage queries API.md

Quick Start

For production hardening, reverse proxy templates, Render deployment, and backup/restore runbooks, see docs/DEPLOYMENT.md.

Option 1: One-Click Interactive Script (Recommended)

deploy.sh walks you through a 6-step setup (port, bind address, database mode, secrets, build strategy, confirmation), generates .env, and starts the stack. Re-running it automatically loads your existing .env values as defaults.

# Run directly without cloning first
bash <(curl -sSL https://raw.githubusercontent.com/james-6-23/codex2api/main/deploy.sh)

Or run from a local clone:

git clone https://github.com/james-6-23/codex2api.git
cd codex2api
bash deploy.sh

Option 2: Docker Compose

Deployment Mode Compose File Stack Default Bind Best For
Standard (Prebuilt Image) docker-compose.yml PostgreSQL 18 + Redis 7 0.0.0.0 Production & multi-user servers
Standard (Local Build) docker-compose.local.yml PostgreSQL 18 + Redis 7 0.0.0.0 Verifying local source changes
SQLite (Prebuilt Image) docker-compose.sqlite.yml Single container (SQLite + Memory) 127.0.0.1 Lightweight single-node setups
SQLite (Local Build) docker-compose.sqlite.local.yml Single container (SQLite + Memory) 127.0.0.1 Local source verification (SQLite)

Standard PostgreSQL + Redis (recommended for production):

git clone https://github.com/james-6-23/codex2api.git
cd codex2api
cp .env.example .env
# Edit .env to set strong passwords and ADMIN_SECRET
docker compose pull && docker compose up -d
docker compose logs -f codex2api

Lightweight SQLite + Memory (single container):

cp .env.sqlite.example .env
docker compose -f docker-compose.sqlite.yml pull
docker compose -f docker-compose.sqlite.yml up -d
docker compose -f docker-compose.sqlite.yml logs -f codex2api

First-Run Access

  • Admin Console: http://localhost:8080/admin/
  • Health Check: http://localhost:8080/health

[!IMPORTANT]

  • SQLite security default: SQLite compose files bind to 127.0.0.1 by default. Set BIND_HOST=0.0.0.0 in .env if you need external network access.
  • Switching modes: Replace .env with the matching template (.env.example vs .env.sqlite.example) before switching between PostgreSQL and SQLite compose files. Named volumes are isolated per compose project; docker compose down preserves volumes unless -v is passed.
  • Persistent storage: Docker setups persist /data (SQLite database, Image Studio library /data/images, uploaded backgrounds /data/backgrounds).

Architecture & Scheduling

flowchart LR
    Clients["Clients<br/>Codex CLI / Claude Code / OpenAI SDK / Browser"] --> Ingress["HTTP & WS Router (Gin)<br/>RPM Limiter · Request Memory Budget · Auth"]
    Ingress --> Public["Proxy Handler (/v1/* · /admin)"]
    Ingress --> Admin["Admin API (/api/admin/*)<br/>Embedded React SPA (/admin/)"]
    Public --> Scheduler["Account Pool & Scheduler (auth.Store)<br/>Priority · Health Tier · Dynamic Concurrency · Cooldown"]
    Scheduler --> Upstream["Multi-Channel Upstreams<br/>Codex · Claude · Grok · Antigravity · Kiro · OpenCode"]
    Public --> Data["Persistence & Cache<br/>PostgreSQL / SQLite · Redis / Memory"]
    Admin --> Data

Scheduler Core (auth.Store)

Every request is routed through a health-aware scheduler that evaluates strict SchedulerPriority, health tier, real-time score (100 baseline with decaying error penalties), dynamic concurrency, and session affinity:

Health Tier Effective Concurrency Behavior
healthy System / group / account MaxConcurrency Preferred tier for scheduling
warm max(1, base / 2) Degraded capacity under soft pressure
risky Fixed 1 Minimal probe traffic until recovered
banned 0 (not schedulable) Periodic low-frequency background recovery probes
  • Scheduler Modes (scheduler_mode):
    • round_robin (default): Score-weighted round-robin within the highest valid priority/health tier.
    • remaining_quota: Prefers accounts with lower usage percentage; ties break via round-robin.
    • fill_first: Drains the account with the least remaining quota until exhausted or rate-limited, then moves to the next (A → B → C).
  • Scheduler Engines (scheduler_engine / CODEX_SCHEDULER_ENGINE):
    • legacy → shadow (1-in-64 parity sampling) → indexed (priority/health buckets, sparse API-key sub-pools, event-driven availability waits).
  • Multi-user Affinity: Pass X-Codex2API-Affinity-Key with a stable end-user or conversation ID when sharing one API key; Codex2API hashes it locally for sticky routing and never forwards it upstream.
  • Credit & Cost Controls: Per-account credit_enabled / credit_skip_usage_window flags bypass 5h/7d usage-window penalties for credit-billed accounts, while the Accounts view tracks real 5h and 7d windowed USD spending aligned to reset boundaries.

For deep architectural internals, see docs/ARCHITECTURE.md.


Public API

All public endpoints are available under /v1/* and also as prefixless routes (for clients whose base_url already omits /v1). Codex native passthrough is also exposed under /backend-api/codex/*.

Endpoint Protocol / Purpose
POST /v1/chat/completions OpenAI Chat Completions (streaming SSE & JSON)
POST /v1/responses OpenAI Responses API (streaming SSE, JSON, previous_response_id)
GET /v1/responses Native Responses WebSocket (response.create, response.interrupt)
POST /v1/responses/compact Context compaction endpoint
POST /v1/messages Anthropic Messages API (native Claude passthrough or Codex/Kiro bridge)
POST /v1/images/generations · /v1/images/edits Synchronous image generation & editing (gpt-image-*, grok-imagine)
POST /v1/images/jobs · GET /v1/images/jobs/:id Asynchronous image generation jobs & asset downloads
POST /v1/videos/generations · /edits · /extensions Grok Imagine async video workflows (GET /v1/videos/:id, /content with Range)
POST /v1/messages/count_tokens · /v1/responses/input_tokens Local token estimation compatibility endpoints
GET /v1/models OpenAI model list (or Codex client manifest when client_version is sent)
GET /health Service health check

Full request/response schemas, pricing, error codes, and rate-limit semantics are documented in docs/API.md and docs/USAGE.md.

Quick Admin API examples: adding accounts & OAuth PKCE

All /api/admin/* endpoints authenticate with X-Admin-Key: <ADMIN_SECRET>.

# Add Refresh Token account(s) (newline-separated for batch, up to 100 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": "my-account", "refresh_token": "rt_xxxxxxxxxxxx"}'

# Add Access Token (AT-only) account(s)
curl -X POST http://localhost:8080/api/admin/accounts/at \
  -H "X-Admin-Key: your-admin-secret" \
  -H "Content-Type: application/json" \
  -d '{"name": "my-at", "access_token": "eyJhbGciOiJSUzI1NiIs..."}'

# Batch file import (format: txt | json | at_txt; automatic deduplication)
curl -X POST http://localhost:8080/api/admin/accounts/import \
  -H "X-Admin-Key: your-admin-secret" \
  -F "[email protected]" \
  -F "format=txt"

# OAuth PKCE: Step 1 — generate auth URL; Step 2 — exchange callback code
curl -X POST http://localhost:8080/api/admin/oauth/generate-auth-url \
  -H "X-Admin-Key: your-admin-secret" -H "Content-Type: application/json" -d '{}'
curl -X POST http://localhost:8080/api/admin/oauth/exchange-code \
  -H "X-Admin-Key: your-admin-secret" -H "Content-Type: application/json" \
  -d '{"session_id": "...", "code": "...", "state": "..."}'

Admin Console

Visit /admin/ for the built-in management dashboard, plus standalone API-key-scoped portals for end users:

Section Path Purpose
Dashboard /admin/ Overview KPIs, request & latency trends, token breakdown, model rankings
Accounts (Multi-Channel) /admin/accounts (+ /claude, /grok, /antigravity, /kiro, /opencode) Import, OAuth sign-in, testing, batch operations, credit flags, scheduler state
API Keys /admin/api-keys Key lifecycle, channel/model/group scoping, USD quotas, weekly model request budgets
Proxies /admin/proxies Managed proxy pool, sticky bindings, Resin egress status, connectivity checks
Image Studio /admin/images/studio Text-to-image, image-to-image, prompt templates, async job history, server gallery
Intelligence & Quality Checks /admin/intelligence-check · /admin/quality-test Automated degradation checks with auto-actions; side-by-side HTML/SVG pelican quality tests
Prompt Filter & Payload Rules /admin/prompt-filter/overview · /admin/payload-rules/editor Guardrail rules, audit hit logs, JSON request body override/default rules
Usage & Model Pricing /admin/usage · /admin/model-pricing Request logs, cost analytics, automated official model & price sync, per-image pricing
Operations & Monitoring /admin/ops/overview · /ops/scheduler · /ops/runtime · /ops/errors · /admin/channel-monitor Scheduler board, response-context cache metrics, Go heap/GC, error diagnostics, channel health
Settings & Built-in Docs /admin/settings · /admin/docs Runtime parameters, response-context budgets, interactive client integration guide & API reference
Standalone User Portals /image-studio · /key-usage · /account-portal Non-admin portals for teammates using their own API keys (image generation, quota lookup, account submission)

Configuration & Security Model

Codex2API separates infrastructure configuration (.env / environment variables) from business runtime settings (stored in the SystemSettings database table and editable live in /admin/settings).

Core Environment Variables

See docs/CONFIGURATION.md for the complete reference, including Responses context cache budgets, WebSocket pools, continuous retry policies, and model/price auto-sync.

Variable Default Description
CODEX_PORT 8080 HTTP listen port
BIND_HOST 0.0.0.0 (PG) / 127.0.0.1 (SQLite) Docker host interface bind address
ADMIN_SECRET — Admin console secret (overrides database AdminSecret)
CODEX_ALLOW_ANONYMOUS false Set true only for trusted private tests to allow /v1/* when no API keys exist
CODEX_MAX_REQUEST_BODY_SIZE_MB 48 Max HTTP request body size (MiB)
DATABASE_DRIVER postgres postgres or sqlite
DATABASE_HOST / PORT / USER / PASSWORD / NAME — PostgreSQL connection parameters (DATABASE_SSLMODE defaults to disable)
DATABASE_PATH — SQLite file path when DATABASE_DRIVER=sqlite (e.g. /data/codex2api.db)
CACHE_DRIVER redis redis or memory
REDIS_ADDR / USERNAME / PASSWORD / DB / TLS — Redis connection (rediss://... recommended for managed TLS Redis such as Aiven/Upstash)
TZ UTC Container/runtime timezone (e.g. Asia/Shanghai)

Authentication Priority

  • Public API (/v1/*): Authenticated by API keys created in the admin console (Authorization: Bearer <key>, or x-api-key for /v1/messages). Closed by default—when no API key exists, /v1/* rejects requests unless CODEX_ALLOW_ANONYMOUS=true is explicitly set (async image jobs always require a valid API key).
  • Admin Console (/admin & /api/admin/*):
    1. ADMIN_SECRET environment variable takes highest precedence.
    2. Falls back to SystemSettings.AdminSecret in the database.
    3. If neither is configured, /admin opens the first-run setup wizard, which requires the one-time per-process bootstrap token logged on startup (docker compose logs codex2api | grep "bootstrap token").

Documentation

Browse the full documentation index in docs/README.md:

Document Audience & Topics
Usage Guide (docs/USAGE.md) First-time client onboarding (Codex CLI, Claude Code, SDKs), streaming, media jobs, error matrix
Deployment Guide (docs/DEPLOYMENT.md) deploy.sh, Docker Compose modes, Nginx reverse proxy, Render deployment, upgrade & backup/restore
Configuration Guide (docs/CONFIGURATION.md) All env vars, database settings, Responses context cache budgets, scheduler & retry policies, weekly model budgets
API Reference (docs/API.md) Complete public & admin API specification, schemas, error codes, rate limits
Architecture (docs/ARCHITECTURE.md) System architecture, multi-channel routing, scheduler algorithm, storage & security design
Troubleshooting (docs/TROUBLESHOOTING.md) Diagnostics, common failure playbooks, token refresh recovery, WS 1009, performance tuning
Antigravity Integration (docs/ANTIGRAVITY.md) Google OAuth & experimental API Key channel, models, security risks, certification checklist
Kiro Integration (docs/KIRO.md) Kiro credential formats, sign-in flows, protocol bridge, credit & catalog sync
Codex Multi-Agent v2 (docs/CODEX_MULTI_AGENT_V2_COMPAT.md) Opt-in compatibility for third-party subagents, rollout & rollback
Contributing (docs/CONTRIBUTING.md) Development workflow, Go/TypeScript standards, testing & PR checklist

Upgrade & Local Development

Upgrading Docker Deployments

Back up your database before upgrading, then pull and recreate in place (avoid docker compose down during normal upgrades so named volumes remain intact):

# 1. Backup PostgreSQL
docker exec codex2api-postgres pg_dump -U codex2api codex2api > backup_$(date +%Y%m%d_%H%M%S).sql

# 2. Pull and rolling restart
git pull && docker compose pull && docker compose up -d && docker compose logs -f codex2api

Local Development

Prerequisites: Go 1.26.11+, Node.js 22.12+.

# Build embedded frontend (required before first `go run .`)
cp .env.example .env
cd frontend && npm ci && npm run build && cd ..

# Run backend
go run .

For frontend hot-reload development (Vite proxies /api, /v1, and /health to :8080, served at http://localhost:5173/admin/):

cd frontend && npm run dev
Project Structure & Manual Versioned Builds
codex2api/
├── main.go                          # Application entrypoint & embedded SPA mount
├── deploy.sh                        # Interactive 6-step deployment script
├── Dockerfile                       # Multi-stage Go + Vite container build
├── docker-compose.yml               # Production PostgreSQL + Redis (prebuilt image)
├── docker-compose.local.yml         # Production stack (local source build)
├── docker-compose.sqlite.yml        # Lightweight single-container SQLite (prebuilt image)
├── docker-compose.sqlite.local.yml  # Lightweight SQLite (local source build)
├── .env.example / .env.sqlite.example
├── admin/                           # Admin REST API, accounts, usage, ops, settings
├── api/                             # Shared API middleware, errors, validation
├── auth/                            # Multi-channel account pools, scheduler, proxy pool
├── cache/                           # Redis & in-memory cache drivers
├── config/                          # Environment configuration loader
├── database/                        # PostgreSQL & SQLite repositories and migrations
├── internal/                        # Shared internal utilities & version metadata
├── proxy/                           # Public gateway handlers, protocol bridges, streaming
├── security/                        # Prompt filtering, audit logging, redaction
├── frontend/                        # React 19 + Vite 8 + Tailwind 4 admin console
│   ├── src/pages/                   # Dashboard, Accounts, API Keys, Studio, Ops, Settings, Docs...
│   ├── src/components/              # Reusable UI components
│   ├── src/locales/                 # zh / en i18n bundles
│   └── vite.config.js               # Vite & dev proxy configuration
└── docs/                            # User, operator, and architecture documentation

For manual binary builds, pass the same version to both frontend (VITE_APP_VERSION) and Go (-ldflags '-X github.com/codex2api/internal/version.Version=...'), building frontend/ first so go:embed embeds matching assets.


Community


Disclaimer & License

  • This project is intended for learning, research, and technical exchange only.
  • Licensed under the MIT License.
  • Provided "as is" without warranty of any kind; production usage is at your own risk.

Star History


Links

Jelajahi proyek terkait

Memuat…