本文由 GitRead 中文社区 使用 AI 辅助生成,基于项目 README 与公开资料整理成中文解读, 并结合中文开发者的常见使用场景补充技术选型参考。内容可能存在疏漏,具体以项目官方文档为准。
当订阅制撞上碎片化:Sub2API 的中转哲学与技术解构
项目背景与痛点
2025 年的 AI 开发者面临一个荒诞的困境:钱没少花,API 却不够用。Claude 的对话能力、OpenAI 的生态兼容、Gemini 的长上下文、Grok 的实时性——每个模型都有不可替代的优势,但每个官方订阅都是一笔不菲的固定支出。
更麻烦的是,这些订阅通常绑定单一账号、单一 IP、单一支付方式,且存在调用频率限制。个人开发者为了测试一个功能,往往要维护四五个账号;小团队想共享资源,却受制于官方 ToS 的"禁止转售"条款。
Sub2API 的切入点非常精准:它不是又一个模型聚合代理,而是一套"订阅资源池化"的基础设施。它把"订阅"本身变成了一种可拆解、可分配、可计量的资源,让 Claude 的订阅额度、OpenAI 的 API 配额、Gemini 的免费层、Grok 的实时通道,能够在一个统一网关下被多个用户、多个应用、多种协议并发消费。
核心技术揭秘
要理解 Sub2API 的架构,首先要抓住它的核心抽象:将"账号会话"提升为"可调度资源"。
官方 API 的认证模式是"Key 换 Token",而订阅制的认证模式是"账号登录拿 Cookie/Token"。Sub2API 的关键技术难点在于:如何把后者的状态化会话(带有效期、带速率限制、带并发约束)包装成前者的无状态接口(OpenAI 兼容的 /v1/chat/completions)。
graph TD
A[客户端请求<br/>OpenAI 兼容格式] --> B[统一网关层<br/>协议转换与鉴权]
B --> C{"路由策略<br/>模型/优先级/配额"}
C -->|"Claude 订阅池"| D[Claude 适配器<br/>Cookie 会话管理]
C -->|"OpenAI 订阅池"| E[OpenAI 适配器<br/>Token 分发]
C -->|"Gemini 订阅池"| F[Gemini 适配器<br/>免费层调度]
D --> G[上游响应]
E --> G
F --> G
G --> H[统一响应处理<br/>SSE 流式转发]
H --> A
Please read the following carefully before using this project:
🚨 Terms of Service Risk: Using this project may violate the terms of service of Anthropic and other upstream providers. Please review the relevant providers’ user agreements before use; all risks arising from such use are borne solely by the user.
⚖️ Compliant Use: Use this project only in compliance with the laws and regulations of your country or region. Any unlawful use is strictly prohibited.
📖 Disclaimer: This project is provided for technical learning and research purposes only. The authors assume no liability for account bans, service interruptions, data loss, or any other direct or indirect damages resulting from the use of this project.
🚫 No Commercial Authorization: The developers of this project have never authorized any individual or organization to conduct any form of commercial operation based on this project. Any commercial activity conducted in the name of or based on this project is unrelated to this project and its developers, and all resulting disputes, losses, and legal liabilities shall be borne solely by the party conducting such activity.
WandAPI — an enterprise-grade, stable AI model API gateway built by a core contributor to this project. One API key gives you access to Claude, GPT, Gemini and other leading models, natively compatible with the OpenAI and Anthropic protocols, so Claude Code, Codex and your existing SDKs work by simply changing the Base URL. Real-time routing by latency and upstream health with millisecond-level automatic failover keeps requests online, backed by 99.99% service availability. Pay as you go, with per-request token and cost breakdowns.
Free trial credits: sign up via this exclusive link to claim free trial credits.
Thanks to CCTK.AI for sponsoring this project! CCTK.AI is an AI API gateway focused on stability and cost-effectiveness, offering fast relay services for Claude, OpenAI, Gemini, and other popular models. It works seamlessly with Claude Code, Codex, and other mainstream coding tools, delivering the same model capabilities at a fraction of the official cost. Register via this link for faster, more stable, and more affordable AI API access.
One API, every top model! OpenModel is a production-grade, high-availability AI API gateway that makes your applications truly fast and stable: automatic failover, smart routing to the best-performing channel, and a production-grade SLA. An SLA that far surpasses any single provider — making stability your core competitive advantage. Works directly with Claude Code, Codex, and Gemini CLI. Register via this link to get started.
Thanks to ETok.ai for sponsoring this project! ETok.ai is dedicated to building a one-stop AI programming tool service platform. We offer professional Claude Code packages and technical community services, with support for Google Gemini and OpenAI Codex. Through carefully designed plans and a professional tech community, we provide developers with reliable service guarantees and continuous technical support, making AI-assisted programming a true productivity tool. Click here to register!
Thanks to APIKEY.FUN for sponsoring this project! APIKEY.FUN is one of the core contributors to the sub2api open-source project, dedicated to providing open, stable, and cost-effective AI API access. The platform supports API relay services for Claude, OpenAI, Gemini, and other popular models, with pricing starting from as low as 7% of the original rate. Register via the exclusive link: APIKEY to enjoy up to 5% off on all recharges.
Thanks to AIGoCode for sponsoring this project! A subscription-based AI coding platform, not just pay-per-token. One account, one monthly plan for Claude Code, Codex and Gemini, with direct connection on the mainland and fast responses. Subscribe via this link to get an extra 10% credits!
Real GPT-5.6 series at 3% of OpenAI pricing — CodexEverywhere is democratizing access to frontier models for developers worldwide. We believe in transparency and honesty, with model quality verified by active community oversight for months. USD and crypto friendly. Start with a free $20 trial at codex-everywhere.com.
Thanks to Bestproxy for sponsoring this project! Bestproxy provides high-purity residential IPs with dedicated one-IP-per-account support. By combining real home networks with fingerprint isolation, it enables link environment isolation and reduces the probability of association-based risk control.
Thanks to PatewayAI for sponsoring this project! PatewayAI is a premium API relay built for heavy AI developers, offering the full Claude and Codex series sourced 100% from official providers, with transparent token-level billing. Enterprise plans include high concurrency, dedicated management, contracts, and invoicing. Register now to get $3 in trial credits, top-ups from 60% off, and referral bonuses up to $150.
Thanks to PPToken.cc for sponsoring this project! PPToken.cc specializes in GPT model API relay services, supporting Codex, Claude Code, OpenAI-compatible clients, and Gemini CLI integration. Top-ups are 1:1 (¥1 = $1 credit); GPT models start at 0.16x rate multiplier, with overall cost at roughly 2.2% of official pricing and first-token latency around 1 second — ideal for developers seeking low-cost, high-speed access to GPT model capabilities. Technical support: 24/7 real human responses (no bots), @tech in the group chat and get a reply within 10 minutes. Sponsor benefit: the first 200 users who register via the exclusive registration link and enter promo code `SUB2API` can claim free Codex / Claude Code trial credits — no minimum spend, no card required.
Thanks to Veilx for sponsoring this project! Veilx CDN is purpose-built for large-scale AI API traffic, deeply optimized for relay services and call chains across OpenAI, Claude, Gemini, and scenarios like chat, image generation, embeddings, and streaming — delivering lower latency and higher stability under heavy concurrency. It also offers China three-network optimized return lines, making it ideal for global AI relay platforms, overseas AI SaaS, and cross-border high-concurrency deployments.
Thanks to RoxyBrowser for sponsoring this project! RoxyBrowser RoxyBrowser is the perfect partner for Sub2API: it features a built-in native Roxy AI Agent and high-quality native residential IPs, supports batch automation via simple commands, and significantly boosts security and efficiency for multi-account management! Click this link to sign up and receive a free residential IP package plus a 10% lifetime discount.
Nagora is a multi-model AI API gateway built for developers and teams. With a single account and API key, you can access more than 26 leading text and image models through one unified interface. It is compatible with OpenAI, Anthropic, and Gemini protocols and integrates seamlessly with development tools such as Claude Code, Codex, and Gemini CLI. The platform provides intelligent routing, automatic failover, transparent pricing, and consolidated billing, along with budget management, rate limiting, and concurrency controls. This makes AI usage more reliable and manageable across individual development, team collaboration, and production environments. No changes to your existing application are required. Simply replace the Base URL and API key to complete the integration in as little as one minute.
Thanks to Qiniu AI for sponsoring this project! Qiniu AI is the enterprise-grade large-model MaaS platform under Qiniu Cloud (02567.HK), offering one-stop access to 150+ mainstream models worldwide, compatible with the protocols of major global model providers, and covering full-modality capabilities including text, image, audio, video, and file processing, serving over 1.69 million enterprises and developers. Qiniu AI offers an exclusive benefit for Sub2API users: register via this link — enterprise users get 12 million tokens free, and developers get 3 million tokens free.
Thanks to FennoAI for sponsoring this project! FennoAI is a high-stability, high-performance API relay provider for enterprise R&D teams and developers, compatible with the OpenAI and Anthropic protocols and seamlessly integrating with mainstream AI coding tools such as Codex, Claude Code, and OpenCode. The platform delivers enterprise-grade stability, supporting call volumes of 100 billion tokens per day, and supports business-to-business settlement and invoicing for both domestic and overseas entities to meet enterprise R&D and procurement needs. As an exclusive benefit for Sub2API users, purchase a subscription via the exclusive link to get $50 worth of Coding Plan credit for only $1.99. Referral rewards are also available: invite friends to purchase and earn up to 20% commission — the more you invite, the more you earn.
RapidProxy is a data collection proxy solution built for developers, providing stable and reliable residential proxy services. With 90M+ global residential IPs and 200+ country coverage, intelligent rotation, and precise geo-targeting, it helps projects such as web scraping, AI data training, SEO monitoring, and e-commerce data analysis break through access restrictions and improve data collection efficiency. It supports mainstream automation frameworks such as Playwright, Selenium, and Puppeteer, with prices as low as $0.65/GB — start your free test now.
hao.ai is a high-speed, stable unified large-model API gateway for developers and teams. With a single API Key and a unified interface, you can access mainstream models such as GPT, Claude, and xAI Grok, with compatibility for common protocols and SDKs including OpenAI and Anthropic. The platform provides model routing, failover, team management, and complete request logs, with model prices as low as 15% of official reference pricing, helping users build AI applications more simply, more reliably, and at lower cost.
Swiftproxy is a high-performance proxy solution built for developers, providing stable and reliable residential and static residential proxy services. With 90M+ clean residential IPs, global coverage, flexible rotation, and precise geo-targeting, it helps projects such as web scraping, AI automation, browser automation, SEO monitoring, and multi-account management overcome access restrictions and improve workflow efficiency. It supports HTTP(S) and SOCKS5 protocols, integrates with popular automation tools like Playwright, Selenium, and Puppeteer, with dynamic proxy traffic that never expires until used and free testing available — start your free test now!
Protect and accelerate your Sub2API with AxisNow Optimized routes for users in mainland China, WAF and rate limiting to protect your API entry point, and support for self-hosted or subscription CDN edge nodes. View the Sub2API integration guide →
PP.dog is a source-level API gateway with its own massive account pool, purpose-built as an upstream relay for downstream transit stations and high-frequency developers — saving you the hassle of building and maintaining your own account pool. ✅ Direct from source: self-operated account pool with no middleman markup; 🧧 Cost crusher: combined rate multiplier as low as 0.03x, just 0.35% of official pricing; 🚀 Blazing fast: first-token latency < 1s, on par with the official native API. Get started with PP.dog now
ColaProxy provides high-quality residential proxies built for web scraping, automation, and multi-account management. Get a free trial with non-expiring traffic, pricing starting as low as $0.3/GB, unlimited concurrent connections, and intelligent IP rotation for a smoother, more stable proxy experience. Use discount code COLA10 to get 10% off and start scaling your projects with reliable residential proxies today. Get started with ColaProxy
Modelflare: Full strength, stable, nothing watered down. Global SOTA models at a lower cost. Operated by US-based Havenbyte LLC, Modelflare supports GPT, Claude, Gemini, Grok, and other leading models through common compatible protocols, plus 40+ image and video models. Cache compensation is a highlight: selected OpenAI groups (price-first, stable, and premium) guarantee daily cache hit rates of 65%, 75%, or 85%, and if eligible requests fall short, Modelflare refunds the difference, visible on the usage dashboard after settlement. Special offers: a single top-up of US$20 unlocks the GPT discount group at a 0.015x price multiplier, and a single top-up of US$50 unlocks the Claude discount group at a 0.03x multiplier. Register via this exclusive link to get started.
Thanks to Chenju for sponsoring this project! This is probably the only ad slot in this section that doesn't ask you to sign up for anything. Good open-source projects deserve to be paid for, so Chenju is chipping in a gift and raising a glass to the author. Find Chenju on X to chat about API relays, upstream providers, or just shoot the breeze.
🔑 Buying AI accounts at top prices | Gemini · Claude · GPT | Main and alt accounts all welcome, any channel wanted | Pay-per-usage supported | Seeking first-hand resources from major providers, I'll bring the KEY. WeChat: Liuyou-zawd | Telegram: AACC8888888
Thanks to SoleAPI for supporting this project! SoleAPI is an AI model gateway for developers and enterprises: one API key gives you access to 30+ leading models including Claude, GPT and Gemini. It is natively compatible with the OpenAI and Anthropic protocols, so Claude Code, Codex, Cursor and your existing SDKs work by simply changing the Base URL. Requests are routed in real time by latency and upstream health, with millisecond-level automatic failover to backup channels, 99.99% service availability and 24/7 technical support. Every call lands on a single bill with per-request token and cost breakdowns you can inspect at any time. Sign up through this project's referral link to receive free trial credits, and earn ongoing cashback by inviting friends who top up!
MaruCode — a small, no-frills API site that does a bit of charity now and then. 🍟 Every Thursday it runs limited-time rate-multiplier events. In operation for over half a year, with a 3K-member main group, focused on stability and welcoming collaboration with universities, enterprises, and more — thank you 🙇. It runs a self-operated account pool with no top-up marketing gimmicks, mainly offering mainstream models such as Codex (GPT 6.2 Astra), Claude Code (Claude Opus 5.5), and GPT Image 2.6, with WebSocket protocol support, clearly published pricing (Codex 0.3x, CC 1.7x), and a transparent exchange rate (1:1).
Massive Tokens supplies Claude API access at wholesale per-token prices to businesses and high-volume developers. It serves the standard Anthropic Messages API, so it works with Claude Code, Sub2API, LiteLLM and One API without code changes. Sign up with code SUB2API for 5% off every call, then join our Telegram group @massivetokens (https://t.me/massivetokens) and ask an admin for $10 in credits.
DataEyesAI is an all-in-one AI API platform for developers and businesses, offering unified access to leading models including OpenAI, Claude, and Gemini for AI coding and text, image, audio, and video generation. It supports popular AI coding tools such as Claude Code and Codex, with pay-as-you-go pricing, real-time usage and cost monitoring, and 24/7 technical support to simplify model integration and keep development costs under control. New users can sign up through this link to claim usage credits. From coding to multimodal creation, start your AI journey in one place!
Overview
Sub2API is an AI API gateway platform designed to distribute and manage API quotas from AI product subscriptions. Users can access upstream AI services through platform-generated API Keys, while the platform handles authentication, billing, load balancing, and request forwarding.
Features
Multi-Account Management - Support multiple upstream account types (OAuth, API Key)
API Key Distribution - Generate and manage API Keys for users
Precise Billing - Token-level usage tracking and cost calculation
Smart Scheduling - Intelligent account selection with sticky sessions
Concurrency Control - Per-user and per-account concurrency limits
Rate Limiting - Configurable request and token rate limits
Built-in Payment System - Supports EasyPay, Alipay, WeChat Pay, and Stripe for user self-service top-up, no separate payment service needed (Configuration Guide)
Admin Dashboard - Web interface for monitoring and management
Composite Groups - Admin routing layer that resolves requested models to concrete providers for multi-provider groups (Operator Guide)
External System Integration - Embed external systems (e.g. ticketing) via iframe to extend the admin dashboard
Ecosystem
Community projects that extend or integrate with Sub2API:
Cross-platform app (iOS/Android/Web) for user management, account management, monitoring dashboard, and multi-backend switching; built with Expo + React Native
Tech Stack
Component
Technology
Backend
Go 1.27.0, Gin, Ent
Frontend
Vue 3.4+, Vite 5+, TailwindCSS
Database
PostgreSQL 15+
Cache/Queue
Redis 7+
Nginx Reverse Proxy Note
When using Nginx as a reverse proxy for Sub2API (or CRS) with Codex CLI, add the following to the http block in your Nginx configuration:
underscores_in_headers on;
Nginx drops headers containing underscores by default (e.g. session_id), which breaks sticky session routing in multi-account setups.
Deployment
Method 1: Script Installation (Recommended)
One-click installation script that downloads pre-built binaries from GitHub Releases.
# PostgreSQL password (REQUIRED)
POSTGRES_PASSWORD=your_secure_password_here
# JWT Secret (RECOMMENDED - keeps users logged in after restart)
JWT_SECRET=your_jwt_secret_here
# TOTP Encryption Key (RECOMMENDED - preserves 2FA after restart)
TOTP_ENCRYPTION_KEY=your_totp_key_here
# Optional: Admin account
# Leave empty to auto-generate a random email (login username) and password, shown in logs on first startup.
# Avoid guessable values such as [email protected]: they are brute-force targets.
ADMIN_EMAIL=
ADMIN_PASSWORD=
# Optional: Custom port
SERVER_PORT=8080
# Pull latest image and recreate container
docker compose -f docker-compose.local.yml pull
docker compose -f docker-compose.local.yml up -d
Easy Migration (Local Directory Version)
When using docker-compose.local.yml, migrate to a new server easily:
# On source server
docker compose -f docker-compose.local.yml down
cd ..
tar czf sub2api-complete.tar.gz sub2api-deploy/
# Transfer to new server
scp sub2api-complete.tar.gz user@new-server:/path/
# On new server
tar xzf sub2api-complete.tar.gz
cd sub2api-deploy/
docker compose -f docker-compose.local.yml up -d
Useful Commands
# Stop all services
docker compose -f docker-compose.local.yml down
# Restart
docker compose -f docker-compose.local.yml restart
# View all logs
docker compose -f docker-compose.local.yml logs -f
# Remove all data (caution!)
docker compose -f docker-compose.local.yml down
rm -rf data/ postgres_data/ redis_data/
Method 3: Apple container (macOS)
Apple-silicon Macs running macOS 26 can run the full Sub2API, PostgreSQL, and Redis stack with Apple container 1.1.0 or newer:
git clone https://github.com/Wei-Shaw/sub2api.git
cd sub2api/deploy
./apple-container.sh init
./apple-container.sh up
./apple-container.sh status
This is an operator-managed local workflow; Docker Compose remains the recommended production path. See deploy/APPLE_CONTAINER.md for lifecycle commands, persistence, upgrades, and runtime limitations.
Method 4: Build from Source
Build and run from source code for development or customization.
Prerequisites
Go 1.21+
Node.js 18+
PostgreSQL 15+
Redis 7+
Build Steps
# 1. Clone the repository
git clone https://github.com/Wei-Shaw/sub2api.git
cd sub2api
# 2. Install pnpm (if not already installed)
npm install -g pnpm
# 3. Build frontend
cd frontend
pnpm install
pnpm run build
# Output will be in ../backend/internal/web/dist/
# 4. Build backend with embedded frontend
cd ../backend
VERSION="$(./scripts/resolve-version.sh)"
go build -tags embed -ldflags="-X main.Version=${VERSION}" -o sub2api ./cmd/server
# 5. Create configuration file
cp ../deploy/config.example.yaml ./config.yaml
# 6. Edit configuration
nano config.yaml
Note: The -tags embed flag embeds the frontend into the binary. Without this flag, the binary will not serve the frontend UI.
security.csp to control Content-Security-Policy headers
billing.circuit_breaker to fail closed on billing errors
security.trust_forwarded_ip_for_api_key_acl enables legacy raw forwarded-header takeover (enabled by default for upgrade compatibility); disable it to enforce server.trusted_proxies, which should contain only the exact proxy CIDRs that connect directly to Sub2API
security.forwarded_client_ip_headers configures up to 16 third-party CDN client-IP header names; they are checked in order before the built-in headers only while legacy takeover is enabled
turnstile.required to require Turnstile in release mode
Custom client-IP headers can be set in YAML or as a comma-separated environment variable:
Header names are validated, canonicalized, and de-duplicated. The admin security settings can update the list without a restart; new installations persist YAML/environment defaults and existing installations backfill a missing database value. When legacy takeover is disabled, all custom and built-in raw forwarding headers are ignored and Gin uses only server.trusted_proxies. While takeover is enabled, firewall the origin to CDN/proxy addresses and make the edge overwrite every trusted client-IP header. See deploy/EDGE_SECURITY.md for the complete migration and trust-boundary rules.
⚠️ Security Warning: HTTP URL Configuration
When security.url_allowlist.enabled=false, the system performs minimal URL validation and allows HTTP URLs by default (dev-friendly mode; Docker Compose deployments use the same default). For production, explicitly tighten this to HTTPS-only:
security:
url_allowlist:
enabled: false # Disable allowlist checks
allow_insecure_http: false # HTTPS only (recommended for production)
✅ Testing account connectivity before obtaining HTTPS
❌ Production environments (use HTTPS only)
Example error for HTTP URLs when allow_insecure_http: false is set:
Invalid base URL: invalid url scheme: http
If you disable URL validation or response header filtering, harden your network layer:
Enforce an egress allowlist for upstream domains/IPs
Block private/loopback/link-local ranges
Enforce TLS-only outbound traffic
Strip sensitive upstream response headers at the proxy
OpenAI Responses WebSocket ingress limits
gateway.openai_ws bounds the lifetime and aggregate count of client-facing
Responses WebSocket sessions. These safeguards apply independently from
per-turn user and account concurrency slots, which are released between turns.
gateway:
openai_ws:
# Total time to receive and decompress the first client message.
client_first_message_timeout_seconds: 30
# Close a client socket idle between completed turns; 0 disables this safeguard.
ingress_inter_turn_idle_timeout_seconds: 300
# Distributed API-key limit for live client ingress sessions; 0 disables it.
max_ingress_connections_per_api_key: 64
The first-message timeout is a total read deadline. Deployments that accept
large contexts or image-heavy requests over slower links can raise it to
120-300 seconds. It expires before HTTP bridge routing, so bridge mode does not
override this limit.
The connection cap is coordinated through Redis using a 60-second lease that
is refreshed every 20 seconds. A process that cannot confirm a lease for a
full lease lifetime closes its local WebSocket rather than continuing outside
the global cap.
Enable the v2 mode router before selecting an account-level WS mode such as
http_bridge:
gateway:
openai_ws:
mode_router_v2_enabled: true
Or set GATEWAY_OPENAI_WS_MODE_ROUTER_V2_ENABLED=true in the environment.
Use http_bridge for client-WebSocket/upstream-HTTP operation when rolling out
or mitigating upstream WebSocket issues.
Force OpenAI upstream HTTP/SSE
When an egress proxy or network repeatedly reconnects OpenAI Responses
WebSockets, set the global fallback in the persisted deployment configuration:
gateway:
openai_ws:
force_http: true
For Compose and Apple container deployments, the equivalent .env setting is:
GATEWAY_OPENAI_WS_FORCE_HTTP=true
This selects HTTP/SSE for OpenAI upstream Responses traffic that would
otherwise use WebSocket. It does not change the client-facing protocol or force
HTTP/1.1; configure gateway.openai_http2.enabled (or
GATEWAY_OPENAI_HTTP2_ENABLED=false) separately when a proxy is incompatible
with HTTP/2. Unlike the account-level http_bridge mode, this global fallback
takes effect without enabling mode_router_v2_enabled. Keep the setting in the
deployment’s persisted .env or config.yaml, rather than inside a running
container, so it is read again after an image update or container recreation.
⚠️ Important: Creating the Admin Account
The initial admin account is only created via the setup wizard (served at http://<host>:8080 on first run). The default.admin_email / default.admin_password fields in config.yaml are not used to create it — they exist in the template for historical reasons.
Because step 5 above pre-creates config.yaml, the setup wizard will be skipped on first run: the server detects an existing config and boots straight into normal mode with an empty users table, so the first login attempt fails with invalid email or password.
Two ways to create the admin account:
Recommended — let the wizard generate config.yaml: Skip step 5 (do not run the cp). Start ./sub2api directly; the setup wizard at http://localhost:8080 walks you through database, Redis, and admin account setup, then writes config.yaml for you.
If you already created config.yaml: Temporarily move it aside so the wizard can trigger on first run, then restore it afterwards:
mv config.yaml config.yaml.bak
./sub2api # wizard runs at http://localhost:8080 and writes a fresh config.yaml
# stop the server (Ctrl+C) once the wizard completes, then restore your config:
mv config.yaml.bak config.yaml
./sub2api # restart in normal mode and log in with the admin you just created
# 6. Run the application
./sub2api
Development Mode
# Backend (with hot reload)
cd backend
go run ./cmd/server
# Frontend (with hot reload)
cd frontend
pnpm run dev
Code Generation
When editing backend/ent/schema, regenerate Ent + Wire:
cd backend
go generate ./ent
go generate ./cmd/server
Simple Mode
Simple Mode is designed for individual developers or internal teams who want quick access without full SaaS features.
Enable: Set environment variable RUN_MODE=simple
Default groups are seeded on each startup. Set SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS=false (or YAML simple_mode.auto_create_default_groups: false) to manage groups yourself. The default is true; disabling it does not delete existing groups or change runtime auto-binding or admin concurrency setup.
Difference: Hides SaaS-related features and skips billing process
Optional key windows: Set SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED=true to enforce each API key’s configured 5-hour, daily, and 7-day spending windows. The default is false; balance and subscription debit remain bypassed when enabled.
Window enforcement uses the database as its source of truth and records only API-key window usage. It is a post-request soft cap, so concurrent in-flight requests can overshoot by their final costs. Historical simple-mode usage is not backfilled.
Security note: In production, you must also set SIMPLE_MODE_CONFIRM=true to allow startup
OpenAI Image Output Formats
On /v1/images/generations and /v1/images/edits, OAuth / Setup Token requests use the Codex-native Images endpoints when the mapped upstream model is a supported GPT Image 1.5, 2, 2.5, or 2.6 model. Models before 2.6 can fall back to Responses if the native endpoint returns 404 or 405.
Sub2API forwards output_format and output_compression, but whether they take effect depends on the upstream account and endpoint. An upstream may reject a format with a 4xx error or return HTTP 200 with a different format: for example, requesting jpeg or svg can yield output_format: "png" and PNG data. This behavior has also been reported for gpt-image-2.5-flare requests for jpeg.
Before saving or serving an image, compare the returned output_format (including any per-image value) with the request and verify the actual image format. Use the actual output format for the filename extension and MIME type. A successful response containing a different format retains its status, image content, and usage; it can still incur charges. Automatically retrying may generate and bill another image.
Asynchronous Image Tasks
Long-running OpenAI/Grok image generation and editing can be submitted through /v1/images/generations/async or /v1/images/edits/async, then polled at /v1/images/tasks/{task_id} without holding a CDN connection open. See Asynchronous Image Tasks for request and response examples.
Grok / xAI Support
Sub2API supports both Grok subscription accounts through xAI OAuth and standard xAI API-key accounts. Both account types forward OpenAI-compatible Responses traffic to xAI.
Supported Scope
Platform name: grok
Account types: OAuth subscription accounts and xAI API-key accounts
Public Responses targets: /v1/responses, /responses, and /backend-api/codex/responses, forwarded to the Grok subscription proxy for OAuth accounts or https://api.x.ai/v1/responses for API-key accounts
Public Claude-compatible target: /v1/messages, converted to xAI Responses and returned as Anthropic Messages output for Claude CLI style clients
Public Chat Completions targets: /v1/chat/completions and /chat/completions, forwarded to the account-type-specific xAI upstream
Codex CLI style Responses WebSocket ingress is accepted on the Responses targets and bridged to xAI HTTP/SSE Responses upstream
Text models: grok-4.5, grok-4.3, grok-build-0.1, grok-composer-2.5-fast, grok-4.20-0309-reasoning, grok-4.20-0309-non-reasoning, and grok-4.20-multi-agent-0309
Media targets for Grok groups: /v1/images/generations, /images/generations, /v1/images/edits, /images/edits, /v1/videos/generations, /videos/generations, /v1/videos/edits, /videos/edits, /v1/videos/extensions, /videos/extensions, /v1/videos/{request_id}, and /videos/{request_id}. Generation, editing, and extension requests require the group image-generation permission.
Media models: grok-imagine, grok-imagine-image-quality, grok-imagine-image, grok-imagine-image-2.0, grok-imagine-edit, grok-imagine-video, and grok-imagine-video-1.5
JSON image-edit and video-generation requests accept image references in image, images, reference_images, and mask objects. Use url for xAI-compatible payloads; the legacy image_url field remains accepted and is normalized to url before forwarding.
Out of scope for this provider: TTS, transcription, browser automation, cookies, and Grok web scraping
OAuth Configuration
The Grok OAuth flow uses PKCE and does not require committing private secrets. The default client details follow the public xAI OAuth flow used by compatible clients, and every value can be overridden by environment variable:
0.2.114; optional override for the client identity sent to cli-chat-proxy.grok.com. The pinned value is also the floor: an override below it is dropped
Administrators can create Grok OAuth or API-key accounts from the dashboard. OAuth authorization and reauthorization are also available through the admin API:
Endpoint
Purpose
POST /api/v1/admin/grok/oauth/auth-url
Generate an xAI OAuth authorization URL
POST /api/v1/admin/grok/oauth/exchange-code
Exchange a callback URL, query string, or code for OAuth credentials
POST /api/v1/admin/grok/oauth/refresh-token
Validate or refresh a Grok refresh token
POST /api/v1/admin/grok/accounts/:id/refresh
Refresh an existing Grok account
OAuth credential storage reuses the existing account JSON fields: access_token, refresh_token, token_type, expires_at, base_url, optional email, optional subscription_tier, and entitlement_status. OAuth inference defaults to https://cli-chat-proxy.grok.com/v1; existing OAuth accounts that stored the old https://api.x.ai/v1 default are redirected to the subscription proxy at runtime. Explicit custom upstreams remain unchanged.
For API-key accounts, select Grok → API Key in the create-account dialog. The official base URL defaults to https://api.x.ai/v1; credentials use the existing base_url and api_key account fields. OAuth accounts continue to use the subscription flow above.
Grok Build CLI Configuration
In the Sub2API admin dashboard, add either a grok OAuth account and complete xAI authorization, or add a Grok API-key account.
Create a Grok group, attach the account to it, then create a Sub2API API key assigned to that group.
In the user API-key page, click Use Key and select Grok CLI. The modal generates the correct file and base URL for macOS/Linux or Windows. It also provides an OpenCode configuration on the OpenCode tab.
If configuring manually, save the following as ~/.grok/config.toml (Windows: %USERPROFILE%\.grok\config.toml):
Back up an existing config.toml before merging the entry. The file contains a Sub2API API key, so keep it private and restrict its permissions where supported. Verify the effective configuration and make a smoke request:
grok inspect
grok -p "Reply with sub2api-ok" -m grok
The base_url above is the public Sub2API URL ending in /v1, not api.x.ai or the internal xAI OAuth proxy URL.
Usage And Quota Display
xAI quota is passive. Sub2API does not invent subscription quota values; it records whitelisted xAI rate-limit headers from successful or rate-limited upstream responses when xAI sends them. Before the first usable upstream response, the dashboard shows quota as unknown and still displays local Sub2API usage stats.
401 responses temporarily remove accounts with invalid credentials from scheduling. 403 responses are treated as access or entitlement failures instead of token-refresh loops. 429 responses use Retry-After or a short cooldown to temporarily remove the account from scheduling.
New Grok image and video generation requests use a media-specific eligibility check. API-key accounts remain eligible. OAuth accounts with explicit Free or forbidden billing evidence are excluded from new media generation. Missing or malformed observations are probed before dispatch; a successful but incomplete billing response is treated as billing_inconclusive and remains eligible for backwards compatibility, because an unknown billing schema is not proof that the account lacks media entitlement. Operators can quarantine a known-bad account with extra.grok_media_eligible=false or force-enable a verified account with true. Imports run the billing-first quota probe proactively. Chat requests and video status lookups are not affected by this media-only quarantine. If no eligible account remains, the media endpoint returns HTTP 503 with error type grok_media_no_eligible_account.
Administrators can override automatic media eligibility through the account create/update API by setting extra.grok_media_eligible to false (exclude) or true (force eligible). On update, set it to null to remove the override and return to automatic probe-based behavior; omitting the field preserves the current override. A weekly allowance period alone is not treated as a paid tier signal. Successful image responses must contain at least one actual image output; empty HTTP 200 responses trigger account failover instead of being counted and returned as successful generations.
TypeSafe / Jev Support
Sub2API supports TypeSafe API-key accounts through Jev’s native, non-streaming System One protocol.
Platform: typesafe; account type: API Key
Default upstream: https://api.typesafe.ai
Public endpoint: POST /v1/systemone
Model: jev-latest, also returned by /v1/models for TypeSafe groups
Questions: noul, choice, and score
Requests and successful responses retain the native System One JSON structure. This endpoint is not compatible with Chat Completions, Responses, Anthropic Messages, or streaming clients.
Question validation follows the TypeSafe OpenAPI wire schema (also used by SDK v0.5.7). instructions may be omitted or null for all question types. Noul criteria may be omitted or null; its true/false descriptions and Choice descriptions accept strings, objects, arrays, or null. Score criteria must be a non-empty array of string, object, or array descriptions; a single level is valid. SDK integer-keyed Score maps are normalized to arrays by the SDK before sending.
curl https://your-sub2api.example.com/v1/systemone \
-H 'Authorization: Bearer sk-your-sub2api-key' \
-H 'Content-Type: application/json' \
--data '{"model":"jev-latest","state":"Text to evaluate","questions":{"safety":{"type":"noul","instructions":"Evaluate whether the text is unsafe"}}}'
The built-in jev-latest price is $0.042 per million input tokens and $0 for output tokens. Channel pricing can override both values. Credential, billing, permission, rate-limit, overload, server, and network failures (401, 402, 403, 429, 529, 5xx, transport errors) use the existing account error policy (including custom error codes and temporary-unschedulable rules) and fail over to another account; request errors (400, 413, and 422) are returned without retrying another account and never change account state. TypeSafe groups (and Composite requests routed to TypeSafe) reject Messages, Chat Completions, Responses, and count_tokens requests with 404.
Antigravity Support
Sub2API supports Antigravity accounts. After authorization, dedicated endpoints are available for Claude and Gemini models.
Antigravity accounts support optional hybrid scheduling. When enabled, the general endpoints /v1/messages and /v1beta/ will also route requests to Antigravity accounts.
⚠️ Warning: Anthropic Claude and Antigravity Claude cannot be mixed within the same conversation context. Use groups to isolate them properly.
评论