### One-Click Interactive Deployment (Bash) Source: https://github.com/james-6-23/codex2api/blob/main/README.zh-CN.md Use this script for a guided, interactive deployment process. It handles cloning the repository, setting up environment variables, and starting Docker containers. It can also detect existing configurations to provide sensible defaults. ```bash bash <(curl -sSL https://raw.githubusercontent.com/james-6-23/codex2api/main/deploy.sh) ``` ```bash git clone https://github.com/james-6-23/codex2api.git cd codex2api bash deploy.sh ``` -------------------------------- ### GET /v1/models Response Example Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Example response listing available models. Each model includes its ID, object type, and owner. ```json { "object": "list", "data": [ { "id": "gpt-5.5", "object": "model", "owned_by": "openai" }, { "id": "gpt-5.5", "object": "model", "owned_by": "openai" }, { "id": "gpt-5.4-mini", "object": "model", "owned_by": "openai" }, { "id": "gpt-5.3-codex", "object": "model", "owned_by": "openai" }, { "id": "gpt-5.3-codex-spark", "object": "model", "owned_by": "openai" }, { "id": "gpt-5.2", "object": "model", "owned_by": "openai" }, { "id": "gpt-image-2", "object": "model", "owned_by": "openai" } ] } ``` -------------------------------- ### Startup Validation Checks Source: https://github.com/james-6-23/codex2api/blob/main/docs/CONFIGURATION.md Example output of successful startup validation checks, confirming successful connections and initialization. ```text ✓ 数据库连接成功: PostgreSQL ✓ 缓存连接成功: Redis ✓ 账号池初始化完成: 10/10 可用 ✓ 系统设置加载完成 ✓ HTTP 服务启动: http://0.0.0.0:8080 ``` -------------------------------- ### GET /health Response Example Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Example response from the health check endpoint, indicating the service status and counts of available and total resources. ```json { "status": "ok", "available": 5, "total": 8 } ``` -------------------------------- ### POST /v1/responses Request Example Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Send a request to the Codex native Responses interface. This example shows a system message and a user query. ```json { "model": "gpt-5.5", "input": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "Hello!" } ], "stream": false, "reasoning": { "effort": "medium" }, "service_tier": "fast", "include": ["reasoning.encrypted_content"] } ``` -------------------------------- ### POST /v1/responses Response Example Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Example response from the Codex native Responses interface, including model output and token usage. ```json { "id": "resp_xxxxxxxx", "object": "response", "created": 1712345678, "model": "gpt-5.5", "output": [ { "type": "message", "role": "assistant", "content": [ { "type": "output_text", "text": "Hello! How can I help you today?" } ] } ], "usage": { "input_tokens": 25, "output_tokens": 15, "total_tokens": 40 } } ``` -------------------------------- ### Local Backend Development Setup Source: https://github.com/james-6-23/codex2api/blob/main/README.zh-CN.md Steps to set up the backend for local development. This includes copying the environment file, building the frontend assets (which are then embedded), and running the Go application. ```bash cp .env.example .env cd frontend && npm ci && npm run build && cd .. go run . ``` -------------------------------- ### POST /v1/images/edits Response Example Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Example response for an image editing request, containing creation timestamp, model used, and image data. ```json { "created": 1710000000, "model": "gpt-image-2", "data": [ { "b64_json": "..." } ], "usage": { "images": 1 } } ``` -------------------------------- ### Standard Docker Image Deployment Source: https://github.com/james-6-23/codex2api/blob/main/README.zh-CN.md Use this for server or testing environments. It involves cloning the repository, setting up environment variables, pulling the pre-built Docker image, and starting the service. ```bash git clone https://github.com/james-6-23/codex2api.git cd codex2api cp .env.example .env docker compose pull docker compose up -d docker compose logs -f codex2api ``` -------------------------------- ### Start and Manage Health Checks Source: https://github.com/james-6-23/codex2api/blob/main/docs/proxy_pool.md Configures callbacks for health check events (failure, isolation, recovery) and starts the periodic health checking process. Use Stop() to halt. ```go // 设置回调 pool.SetOnHealthCheck(func(result *auth.HealthCheckResult) { if !result.Healthy { log.Printf("Proxy %s health check failed: %v", result.URL, result.Error) } }) pool.SetOnIsolation(func(entry *auth.ProxyEntry) { log.Printf("Proxy %s is isolated due to consecutive failures", entry.URL) }) pool.SetOnRecovery(func(entry *auth.ProxyEntry) { log.Printf("Proxy %s has recovered", entry.URL) }) // 启动定期健康检查 pool.StartHealthCheck() // 停止 pool.Stop() ``` -------------------------------- ### Add Account cURL Example (Single) Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md This cURL command demonstrates how to add a single account using the POST /api/admin/accounts endpoint. ```bash 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", "proxy_url": ""}' ``` -------------------------------- ### Import Response (SSE Progress) Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md This is an example of the Server-Sent Events (SSE) stream response during account import, showing progress updates. ```text data: {"type":"progress","current":5,"total":10,"success":3,"duplicate":1,"failed":1} data: {"type":"complete","current":10,"total":10,"success":8,"duplicate":1,"failed":1} ``` -------------------------------- ### GET /api/admin/settings Source: https://context7.com/james-6-23/codex2api/llms.txt Retrieves all current system configuration settings, including concurrency limits, RPM, database driver, and auto-clean status. ```APIDOC ## GET /api/admin/settings — 获取系统设置 ### Description 获取当前所有系统配置项,包括并发、RPM、数据库驱动、自动清理开关等。 ### Method GET ### Endpoint /api/admin/settings ### Response #### Success Response (200) - **max_concurrency** (integer) - Maximum concurrent requests allowed. - **global_rpm** (integer) - Global requests per minute limit. - **test_model** (string) - The model used for testing. - **test_concurrency** (integer) - Concurrency setting for tests. - **auto_clean_unauthorized** (boolean) - Whether to automatically clean unauthorized entries. - **auto_clean_rate_limited** (boolean) - Whether to automatically clean rate-limited entries. - **proxy_pool_enabled** (boolean) - Whether the proxy pool is enabled. - **fast_scheduler_enabled** (boolean) - Whether the fast scheduler is enabled. - **max_retries** (integer) - Maximum number of retries for operations. - **database_driver** (string) - The database driver being used. - **cache_driver** (string) - The cache driver being used. #### Response Example ```json { "max_concurrency": 2, "global_rpm": 0, "test_model": "gpt-5.5", "test_concurrency": 50, "auto_clean_unauthorized": false, "auto_clean_rate_limited": false, "proxy_pool_enabled": false, "fast_scheduler_enabled": false, "max_retries": 3, "database_driver": "postgres", "cache_driver": "redis" } ``` ``` -------------------------------- ### Curl Example for Importing RT (TXT) Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md This curl command demonstrates importing Refresh Tokens from a TXT file. The 'file' field should be a path to your tokens.txt. ```bash curl -X POST http://localhost:8080/api/admin/accounts/import \ -H "X-Admin-Key: your-admin-secret" \ -F "file=@tokens.txt" \ -F "format=txt" \ -F "proxy_url=http://proxy.example.com:8080" ``` -------------------------------- ### POST /v1/images/edits JSON Request Example Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md JSON request example for editing an image. Supports image URLs for the source image and mask. ```json { "model": "gpt-image-2", "prompt": "Replace the background with aurora lights", "images": [{ "image_url": "https://example.com/source.png" }], "output_format": "png" } ``` -------------------------------- ### Get Model List Source: https://context7.com/james-6-23/codex2api/llms.txt Retrieve a list of all enabled models in the system, formatted according to the OpenAI API specification. ```bash curl http://localhost:8080/v1/models \ -H "Authorization: Bearer sk-your-api-key" ``` ```json { "object": "list", "data": [ {"id": "gpt-5.5", "object": "model", "owned_by": "openai"}, {"id": "gpt-5.4", "object": "model", "owned_by": "openai"}, {"id": "gpt-5.4-mini", "object": "model", "owned_by": "openai"}, {"id": "gpt-5.3-codex", "object": "model", "owned_by": "openai"}, {"id": "gpt-5.3-codex-spark", "object": "model", "owned_by": "openai"}, {"id": "gpt-5.2", "object": "model", "owned_by": "openai"}, ] ``` -------------------------------- ### GET /v1/models Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Retrieve a list of available models. ```APIDOC ## GET /v1/models ### Description Get a list of supported models. ### Method GET ### Endpoint /v1/models ### Response #### Success Response (200) - **object** (string) - Description - **data** (array) - Description #### Response Example ```json { "object": "list", "data": [ { "id": "gpt-5.5", "object": "model", "owned_by": "openai" }, { "id": "gpt-5.5", "object": "model", "owned_by": "openai" }, { "id": "gpt-5.4-mini", "object": "model", "owned_by": "openai" }, { "id": "gpt-5.3-codex", "object": "model", "owned_by": "openai" }, { "id": "gpt-5.3-codex-spark", "object": "model", "owned_by": "openai" }, { "id": "gpt-5.2", "object": "model", "owned_by": "openai" }, { "id": "gpt-image-2", "object": "model", "owned_by": "openai" } ] } ``` ``` -------------------------------- ### Local Frontend Development Server Source: https://github.com/james-6-23/codex2api/blob/main/README.zh-CN.md Command to start the frontend development server using Vite. It automatically proxies API requests to the backend and is used for frontend-backend integration. ```bash cd frontend && npm ci && npm run dev ``` -------------------------------- ### Batch Test Accounts Response (SSE Progress) Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md This is an example of the Server-Sent Events (SSE) stream response for batch account testing, showing progress. ```text data: {"type":"progress","current":3,"total":3,"success":2,"failed":1} data: {"type":"complete","current":3,"total":3,"success":2,"failed":1} ``` -------------------------------- ### Start Health Check Source: https://github.com/james-6-23/codex2api/blob/main/docs/proxy_pool.md Initiates the background health checking process for proxies and sets up callbacks for health events. ```APIDOC ## Start Health Check ### Description Starts the periodic health checking of proxies in the pool and allows setting callbacks for health check events, isolation, and recovery. ### Methods - `SetOnHealthCheck(callback func(*HealthCheckResult))`: Sets a callback for health check results. - `SetOnIsolation(callback func(*ProxyEntry))`: Sets a callback for when a proxy is isolated. - `SetOnRecovery(callback func(*ProxyEntry))`: Sets a callback for when a proxy recovers. - `StartHealthCheck()`: Starts the health check process. - `Stop()`: Stops the health check process and cleans up resources. ### Request Example ```go // Set callbacks pool.SetOnHealthCheck(func(result *auth.HealthCheckResult) { if !result.Healthy { log.Printf("Proxy %s health check failed: %v", result.URL, result.Error) } }) pool.SetOnIsolation(func(entry *auth.ProxyEntry) { log.Printf("Proxy %s is isolated due to consecutive failures", entry.URL) }) pool.SetOnRecovery(func(entry *auth.ProxyEntry) { log.Printf("Proxy %s has recovered", entry.URL) }) // Start health checks pool.StartHealthCheck() // To stop later: pool.Stop() ``` ``` -------------------------------- ### POST /v1/images/generations Request Example Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Request to generate an image using the OpenAI Images compatible endpoint. Specify the model, prompt, size, quality, and response format. ```json { "model": "gpt-image-2", "prompt": "Draw a small orange cat", "size": "1024x1024", "quality": "high", "response_format": "b64_json" } ``` -------------------------------- ### Get System Settings Source: https://context7.com/james-6-23/codex2api/llms.txt Retrieve all current system configuration settings, including concurrency limits, RPM, database driver, and auto-cleaning options. Requires the admin secret. ```bash curl http://localhost:8080/api/admin/settings \ -H "X-Admin-Key: your-admin-secret" ``` -------------------------------- ### SQLite Docker Image Deployment Source: https://github.com/james-6-23/codex2api/blob/main/README.zh-CN.md A lightweight deployment option for single-machine setups that does not rely on PostgreSQL or Redis. It uses a specific compose file for SQLite. ```bash 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 ``` -------------------------------- ### GET /api/admin/health Response Example Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Example response for the extended admin health check endpoint, showing service status and resource availability. ```json { "status": "ok", "available": 8, "total": 10 } ``` -------------------------------- ### GET /api/admin/stats Response Example Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Example response for the admin stats endpoint, providing dashboard statistics like total, available, error counts, and today's requests. ```json { "total": 10, "available": 8, "error": 2, "today_requests": 1234 } ``` -------------------------------- ### Proxy Pool Initialization Source: https://github.com/james-6-23/codex2api/blob/main/docs/proxy_pool.md Demonstrates how to create a new proxy pool with custom configuration settings. ```APIDOC ## Create Proxy Pool ### Description Initializes a new proxy pool with specified configuration parameters. ### Method `NewProxyPool` ### Parameters - `config` (*auth.ProxyPoolConfig) - Required - Configuration for the proxy pool. - `Strategy` (auth.ProxyStrategy) - The proxy selection strategy (e.g., Round-robin, Weighted, Least Connections). - `CheckInterval` (time.Duration) - The interval for health checks. - `Timeout` (time.Duration) - The timeout for health check requests. - `IsolationThreshold` (int) - The number of consecutive failures before a proxy is isolated. - `IsolationDuration` (time.Duration) - The duration for which a proxy remains isolated. - `HealthCheckURL` (string) - The URL used for health checking. ### Request Example ```go config := &auth.ProxyPoolConfig{ Strategy: auth.StrategyRoundRobin, CheckInterval: 30 * time.Second, Timeout: 10 * time.Second, IsolationThreshold: 3, IsolationDuration: 5 * time.Minute, HealthCheckURL: "http://www.google.com/generate_204", } pool := auth.NewProxyPool(config) ``` ``` -------------------------------- ### Get Account Event Trend Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Retrieves the trend of account additions and deletions over a specified period. Requires start and end times in RFC3339 format. The bucket size can be adjusted. ```json { "trend": [{ "timestamp": "2024-01-01T00:00:00Z", "added": 5, "deleted": 0 }] } ``` -------------------------------- ### Initialize Validator and Validate Request in Go Source: https://github.com/james-6-23/codex2api/blob/main/api/docs/IMPLEMENTATION.md Demonstrates how to initialize a request validator and perform validation using predefined rules. Includes error handling for invalid requests. ```go import "github.com/codex2api/api" validator := api.NewValidator(body) result := validator.ValidateRequest(api.ChatCompletionValidationRules()) if !result.Valid { api.SendError(c, validator.ToAPIError()) return } ``` -------------------------------- ### Import Access Tokens from TXT File Source: https://github.com/james-6-23/codex2api/blob/main/README.zh-CN.md Import access tokens from a text file, with each token on a new line. Use 'at_txt' for the format parameter. ```bash curl -X POST http://localhost:8080/api/admin/accounts/import \ -H "X-Admin-Key: your-admin-secret" \ -F "file=@access_tokens.txt" \ -F "format=at_txt" ``` -------------------------------- ### Configuration Priority Order Source: https://github.com/james-6-23/codex2api/blob/main/docs/CONFIGURATION.md Illustrates the hierarchy of configuration sources, with environment variables having the highest priority and program defaults the lowest. ```text 1. 环境变量(最高优先级) ↓ 2. .env 文件中的变量 ↓ 3. 数据库 SystemSettings(业务配置) ↓ 4. 程序默认值(最低优先级) ``` -------------------------------- ### Add Account with Access Token (Single) Source: https://github.com/james-6-23/codex2api/blob/main/README.zh-CN.md Add a single account using only an access token. The 'X-Admin-Key' header must be included. ```bash 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..."}' ``` -------------------------------- ### Standard Local Source Build Deployment Source: https://github.com/james-6-23/codex2api/blob/main/README.zh-CN.md This method is for local development where you need to build the container from source after making code changes. It requires building the image during the up process. ```bash cp .env.example .env docker compose -f docker-compose.local.yml up -d --build docker compose -f docker-compose.local.yml logs -f codex2api ``` -------------------------------- ### Integrate Enhanced Proxy Pool with Store Source: https://github.com/james-6-23/codex2api/blob/main/docs/proxy_pool.md Demonstrates the integration of an enhanced proxy pool with a database store, including initialization, proxy acquisition, and status marking. ```go // 创建增强代理池 enhancedPool := auth.NewEnhancedProxyPool(db, config) // 初始化 err := enhancedPool.Init(ctx) // 获取代理 proxyURL := enhancedPool.NextProxy() // 标记成功/失败 enhancedPool.MarkProxySuccess(proxyURL) enhancedPool.MarkProxyFailure(proxyURL) ``` -------------------------------- ### GET /api/admin/stats Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Retrieve dashboard statistics. ```APIDOC ## GET /api/admin/stats ### Description Get dashboard statistics data. ### Method GET ### Endpoint /api/admin/stats ### Headers - **X-Admin-Key** (string) - Required - Authentication key for admin access ### Response #### Success Response (200) - **total** (integer) - Description - **available** (integer) - Description - **error** (integer) - Description - **today_requests** (integer) - Description #### Response Example ```json { "total": 10, "available": 8, "error": 2, "today_requests": 1234 } ``` ``` -------------------------------- ### Import Accounts (AT-TXT Format) Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Import AT-only accounts from a TXT file where each line contains an Access Token. ```text eyJhbGciOiJSUzI1NiIs...token1 eyJhbGciOiJSUzI1NiIs...token2 ``` -------------------------------- ### GET /api/admin/health Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Extended system health check. ```APIDOC ## GET /api/admin/health ### Description System health check (extended version). ### Method GET ### Endpoint /api/admin/health ### Headers - **X-Admin-Key** (string) - Required - Authentication key for admin access ### Response #### Success Response (200) - **status** (string) - Description - **available** (integer) - Description - **total** (integer) - Description #### Response Example ```json { "status": "ok", "available": 8, "total": 10 } ``` ``` -------------------------------- ### SQLite Lightweight Environment Configuration (.env) Source: https://github.com/james-6-23/codex2api/blob/main/docs/CONFIGURATION.md Configuration for a lightweight environment using SQLite for the database and in-memory caching. Suitable for testing or minimal deployments. ```bash # ============================================================ # Codex2API SQLite 轻量版配置 # ============================================================ # 服务配置 CODEX_PORT=8080 ADMIN_SECRET=your-admin-password TZ=Asia/Shanghai # 数据库配置 (SQLite) DATABASE_DRIVER=sqlite DATABASE_PATH=/data/codex2api.db IMAGE_ASSET_DIR=/data/images LOG_DIR=logs LOG_DISABLED=false # 缓存配置 (内存) CACHE_DRIVER=memory ``` -------------------------------- ### Get Account Groups Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Retrieves a list of all account groups. ```APIDOC ## GET /api/admin/account-groups ### Description Gets account groups. ### Method GET ### Endpoint /api/admin/account-groups ### Response #### Success Response (200) - **groups** (array) - An array of account group objects. - **id** (integer) - The unique identifier for the group. - **name** (string) - The name of the group. - **description** (string) - A description of the group. - **color** (string) - A color code associated with the group. - **sort_order** (integer) - The order in which to sort the groups. - **member_count** (integer) - The number of members in the group. - **created_at** (string) - The timestamp when the group was created. - **updated_at** (string) - The timestamp when the group was last updated. ### Response Example ```json { "groups": [ { "id": 1, "name": "Team", "description": "付费团队账号", "color": "#2563eb", "sort_order": 0, "member_count": 8, "created_at": "2026-05-13T00:00:00Z", "updated_at": "2026-05-13T00:00:00Z" } ] } ``` ``` -------------------------------- ### Create Proxy Pool Source: https://github.com/james-6-23/codex2api/blob/main/docs/proxy_pool.md Initializes a new proxy pool with specified configuration, including strategy, intervals, timeouts, and health check URL. ```go config := &auth.ProxyPoolConfig{ Strategy: auth.StrategyRoundRobin, CheckInterval: 30 * time.Second, Timeout: 10 * time.Second, IsolationThreshold: 3, IsolationDuration: 5 * time.Minute, HealthCheckURL: "http://www.google.com/generate_204", } pool := auth.NewProxyPool(config) ``` -------------------------------- ### Get Usage Statistics Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Retrieves overall usage statistics for the API. ```APIDOC ## GET /api/admin/usage/stats ### Description Gets usage statistics. ### Method GET ### Endpoint /api/admin/usage/stats ### Response #### Success Response (200) - **total_requests** (integer) - Total number of requests made. - **total_tokens** (integer) - Total number of tokens used. - **today_requests** (integer) - Number of requests made today. - **today_tokens** (integer) - Number of tokens used today. - **rpm** (integer) - Requests per minute. - **tpm** (integer) - Tokens per minute. - **error_rate** (number) - The rate of errors. ### Response Example ```json { "total_requests": 10000, "total_tokens": 500000, "today_requests": 500, "today_tokens": 25000, "rpm": 50, "tpm": 2500, "error_rate": 0.02 } ``` ``` -------------------------------- ### GET /health Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Health check endpoint to verify service status. ```APIDOC ## GET /health ### Description Health check endpoint, returns the service status. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **status** (string) - Description - **available** (integer) - Description - **total** (integer) - Description #### Response Example ```json { "status": "ok", "available": 5, "total": 8 } ``` ``` -------------------------------- ### Import Accounts (TXT Format) Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Import accounts from a TXT file where each line contains a Refresh Token. ```text rt_xxxxxx1 rt_xxxxxx2 rt_xxxxxx3 ``` -------------------------------- ### Get Proxy Statistics Source: https://github.com/james-6-23/codex2api/blob/main/docs/proxy_pool.md Retrieves statistical information about the proxies in the pool. ```APIDOC ## Get Statistics ### Description Retrieves detailed statistics for each proxy in the pool and the overall pool status. ### Methods - `GetStats() map[string]*ProxyStats`: Returns a map of proxy URLs to their statistics. - `GetPoolStatus() *PoolStatus`: Returns the overall status of the proxy pool. ### Returns - `map[string]*ProxyStats`: A map containing statistics for each proxy. - `*PoolStatus`: An object containing total, healthy, and isolated proxy counts. ### Request Example ```go stats := pool.GetStats() for url, stat := range stats { fmt.Printf("Proxy: %s, Success Rate: %.2f, Latency: %.2fms\n", url, stat.SuccessRate, stat.LatencyMs) } status := pool.GetPoolStatus() fmt.Printf("Total: %d, Healthy: %d, Isolated: %d\n", status.Total, status.Healthy, status.Isolated) ``` ``` -------------------------------- ### Get Usage Logs Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Retrieves logs of API usage, with filtering options. ```APIDOC ## GET /api/admin/usage/logs ### Description Gets usage logs. ### Method GET ### Endpoint /api/admin/usage/logs ### Query Parameters - **start** (string) - Required - Start time in RFC3339 format. - **end** (string) - Required - End time in RFC3339 format. - **page** (integer) - Optional - Page number. - **page_size** (integer) - Optional - Number of items per page (max 200). - **email** (string) - Optional - Filter by account email. - **model** (string) - Optional - Filter by model. - **endpoint** (string) - Optional - Filter by endpoint. - **api_key_id** (integer) - Optional - Filter by API key ID. - **fast** (boolean) - Optional - Filter by fast service (true/false). - **stream** (boolean) - Optional - Filter by stream (true/false). ### Response #### Success Response (200) - **logs** (array) - An array of log objects. - **id** (integer) - Log entry ID. - **account_id** (integer) - Account ID. - **account_email** (string) - Account email. - **api_key_id** (integer) - API key ID. - **api_key_name** (string) - API key name. - **api_key_masked** (string) - Masked API key. - **endpoint** (string) - The API endpoint used. - **model** (string) - The model used. - **status_code** (integer) - The HTTP status code of the request. - **duration_ms** (integer) - The duration of the request in milliseconds. - **first_token_ms** (integer) - Time in milliseconds to get the first token. - **prompt_tokens** (integer) - Number of prompt tokens. - **completion_tokens** (integer) - Number of completion tokens. - **total_tokens** (integer) - Total tokens used. - **created_at** (string) - Timestamp of when the log was created. - **total** (integer) - Total number of log entries. ### Response Example ```json { "logs": [ { "id": 1, "account_id": 1, "account_email": "user@example.com", "api_key_id": 3, "api_key_name": "Team A", "api_key_masked": "sk-t****...****1234", "endpoint": "/v1/chat/completions", "model": "gpt-5.5", "status_code": 200, "duration_ms": 523, "first_token_ms": 150, "prompt_tokens": 25, "completion_tokens": 15, "total_tokens": 40, "created_at": "2024-01-01T12:00:00Z" } ], "total": 1000 } ``` ``` -------------------------------- ### Chat Completions Non-Streaming Response (JSON) Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Example of a non-streaming response from the /v1/chat/completions endpoint. ```json { "id": "chatcmpl-xxxxxxxx", "object": "chat.completion", "created": 1712345678, "model": "gpt-5.5", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "Hello! How can I help you today?" }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 25, "completion_tokens": 15, "total_tokens": 40 } } ``` -------------------------------- ### API File Structure Overview Source: https://github.com/james-6-23/codex2api/blob/main/api/docs/IMPLEMENTATION.md Provides a hierarchical view of the API directory structure, detailing the purpose of key Go files and documentation assets. ```text api/ ├── errors.go # Standardized error handling ├── responses.go # Standardized response formats ├── validation.go # Request validation utilities ├── middleware.go # API middleware stack ├── swagger.go # Swagger/OpenAPI annotations ├── openapi.yaml # Complete OpenAPI specification ├── README.md # API documentation └── docs/ └── errors.md # Error codes reference ``` -------------------------------- ### Get Chart Aggregated Data Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Retrieves aggregated data for charts, with time-based bucketing. ```APIDOC ## GET /api/admin/usage/chart-data ### Description Gets chart aggregated data. ### Method GET ### Endpoint /api/admin/usage/chart-data ### Query Parameters - **start** (string) - Required - Start time in RFC3339 format. - **end** (string) - Required - End time in RFC3339 format. - **bucket_minutes** (integer) - Optional - Aggregation bucket size (default 5). ### Response #### Success Response (200) - **buckets** (array) - An array of aggregated data buckets. - **time** (string) - The timestamp for the bucket. - **requests** (integer) - Number of requests in the bucket. - **tokens** (integer) - Number of tokens used in the bucket. - **latency_ms** (integer) - Average latency in milliseconds for the bucket. - **total_requests** (integer) - Total requests across all buckets. - **total_tokens** (integer) - Total tokens across all buckets. ### Response Example ```json { "buckets": [ { "time": "2024-01-01T12:00:00Z", "requests": 50, "tokens": 2500, "latency_ms": 500 } ], "total_requests": 1000, "total_tokens": 50000 } ``` ``` -------------------------------- ### Get Single Account Usage Statistics Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Retrieves the usage statistics for a specific account. ```APIDOC ## GET /api/admin/accounts/:id/usage ### Description Retrieves the usage statistics for a specific account. ### Method GET ### Endpoint /api/admin/accounts/:id/usage ### Response #### Success Response (200) - **id** (integer) - The ID of the account. - **name** (string) - The name of the account. - **total_requests** (integer) - The total number of requests made by the account. - **total_tokens** (integer) - The total number of tokens used by the account. - **last_7d_requests** (integer) - The number of requests made in the last 7 days. - **last_7d_tokens** (integer) - The number of tokens used in the last 7 days. ### Response Example ```json { "id": 1, "name": "account-1", "total_requests": 100, "total_tokens": 5000, "last_7d_requests": 500, "last_7d_tokens": 25000 } ``` ``` -------------------------------- ### Get Account Event Trend Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Retrieves the trend of account additions and deletions over a specified period. ```APIDOC ## GET /api/admin/accounts/event-trend ### Description Gets the trend of account additions and deletions. ### Method GET ### Endpoint /api/admin/accounts/event-trend ### Query Parameters - **start** (string) - Required - Start time in RFC3339 format. - **end** (string) - Required - End time in RFC3339 format. - **bucket_minutes** (integer) - Optional - Aggregation bucket size (default 60). ### Response #### Success Response (200) - **trend** (array) - An array of objects, each containing timestamp, added, and deleted counts. - **timestamp** (string) - The time of the data point. - **added** (integer) - The number of accounts added. - **deleted** (integer) - The number of accounts deleted. ### Response Example ```json { "trend": [ { "timestamp": "2024-01-01T00:00:00Z", "added": 5, "deleted": 0 } ] } ``` ``` -------------------------------- ### Select Proxy Source: https://github.com/james-6-23/codex2api/blob/main/docs/proxy_pool.md Illustrates how to select a proxy from the pool based on the configured strategy. ```APIDOC ## Select Proxy ### Description Selects a proxy from the pool based on the currently active strategy (Round-robin, Weighted, Least Connections). ### Method `Select` ### Returns - `*ProxyEntry` - A pointer to the selected proxy entry, or nil if no proxy is available. ### Request Example ```go // Using default strategy (Round-robin) entry := pool.Select() if entry != nil { fmt.Println("Selected proxy:", entry.URL) } // Switching to Weighted strategy pool.SetStrategy(auth.StrategyWeighted) entry := pool.Select() // Switching to Least Connections strategy pool.SetStrategy(auth.StrategyLeastConnections) entry := pool.Select() ``` ``` -------------------------------- ### Import Access Tokens Source: https://context7.com/james-6-23/codex2api/llms.txt Imports Access Tokens from a file in AT-TXT format. Each token should be on a new line. ```APIDOC ## POST /api/admin/accounts/import ### Description Imports Access Tokens from a file in AT-TXT format. Each token should be on a new line. ### Method POST ### Endpoint /api/admin/accounts/import ### Parameters #### Form Data - **file** (file) - Required - The file containing access tokens (access_tokens.txt). - **format** (string) - Required - The format of the file, expected to be 'at_txt'. ### Request Headers - **X-Admin-Key**: your-admin-secret ### Response Example (SSE stream with progress and completion messages) ``` -------------------------------- ### GET /v1/models Source: https://context7.com/james-6-23/codex2api/llms.txt Retrieves a list of all currently enabled and available models, compatible with the OpenAI format. ```APIDOC ## GET /v1/models ### Description Retrieves a list of all currently enabled and available models, compatible with OpenAI format. ### Method GET ### Endpoint /v1/models ### Parameters #### Headers - **Authorization** (string) - Required - Bearer token for authentication. ### Request Example ```bash curl http://localhost:8080/v1/models \ -H "Authorization: Bearer sk-your-api-key" ``` ### Response #### Success Response (200) - **object** (string) - The object type, e.g., "list". - **data** (array) - An array of model objects. #### Response Example ```json { "object": "list", "data": [ {"id": "gpt-5.5", "object": "model", "owned_by": "openai"}, {"id": "gpt-5.4", "object": "model", "owned_by": "openai"}, {"id": "gpt-5.4-mini", "object": "model", "owned_by": "openai"}, {"id": "gpt-5.3-codex", "object": "model", "owned_by": "openai"}, {"id": "gpt-5.3-codex-spark", "object": "model", "owned_by": "openai"}, {"id": "gpt-5.2", "object": "model", "owned_by": "openai"} ] } ``` ``` -------------------------------- ### Import Refresh Tokens from TXT File Source: https://github.com/james-6-23/codex2api/blob/main/README.zh-CN.md Import refresh tokens from a text file where each token is on a new line. The 'format' parameter should be set to 'txt'. ```bash curl -X POST http://localhost:8080/api/admin/accounts/import \ -H "X-Admin-Key: your-admin-secret" \ -F "file=@tokens.txt" \ -F "format=txt" ``` -------------------------------- ### Add Account with Refresh Token (Single) Source: https://github.com/james-6-23/codex2api/blob/main/README.zh-CN.md Use this command to add a single account using its refresh token. Ensure the 'X-Admin-Key' header is set with your admin secret. ```bash 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"}' ``` -------------------------------- ### Development Environment Configuration (.env) Source: https://github.com/james-6-23/codex2api/blob/main/docs/CONFIGURATION.md Configuration for a development environment using local PostgreSQL and Redis. Admin Secret can be optionally set. ```bash # ============================================================ # Codex2API 开发环境配置 # ============================================================ CODEX_PORT=8080 # ADMIN_SECRET=dev # 开发环境可不设置 # 本地 PostgreSQL DATABASE_DRIVER=postgres DATABASE_HOST=localhost DATABASE_PORT=5432 DATABASE_USER=codex2api DATABASE_PASSWORD=codex2api DATABASE_NAME=codex2api # 本地 Redis CACHE_DRIVER=redis REDIS_ADDR=localhost:6379 REDIS_USERNAME= REDIS_PASSWORD= REDIS_DB=0 REDIS_TLS=false TZ=Asia/Shanghai ``` -------------------------------- ### GET /api/admin/proxies Source: https://context7.com/james-6-23/codex2api/llms.txt Retrieves a list of all proxies in the proxy pool, including their status, latency, and recent test results. ```APIDOC ## GET /api/admin/proxies — 获取代理列表 ### Description 获取代理池中所有代理及其状态、延迟和最近测试结果。 ### Method GET ### Endpoint /api/admin/proxies ### Response #### Success Response (200) - **proxies** (array of objects) - A list of proxies. - **id** (integer) - The unique identifier of the proxy. - **url** (string) - The URL of the proxy. - **label** (string) - A label for the proxy. - **enabled** (boolean) - Whether the proxy is currently enabled. - **last_test_result** (string) - The result of the last test performed on the proxy. - **latency_ms** (integer) - The latency in milliseconds for the proxy. #### Response Example ```json { "proxies": [{ "id": 1, "url": "http://proxy1.example.com:8080", "label": "US Proxy", "enabled": true, "last_test_result": "ok", "latency_ms": 150 }] } ``` ``` -------------------------------- ### Chat Completions Streaming Response (SSE) Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Example of a streaming response from the /v1/chat/completions endpoint, using Server-Sent Events (SSE). ```text data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1712345678,"model":"gpt-5.5","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]} data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1712345678,"model":"gpt-5.5","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]} data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1712345678,"model":"gpt-5.5","choices":[{"index":0,"delta":{"content":"!"},"finish_reason":null}]} data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1712345678,"model":"gpt-5.5","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]} data: [DONE] ``` -------------------------------- ### Connection Management Source: https://github.com/james-6-23/codex2api/blob/main/docs/proxy_pool.md Demonstrates how to acquire and release connections for a specific proxy. ```APIDOC ## Connection Management ### Description Manages the acquisition and release of connections to a specific proxy. ### Methods - `AcquireConnection(url string) bool`: Attempts to acquire a connection to the specified proxy. - `ReleaseConnection(url string)`: Releases a previously acquired connection to the specified proxy. ### Parameters - `url` (string) - Required - The URL of the proxy for which to manage connections. ### Returns - `AcquireConnection`: Returns `true` if a connection was successfully acquired, `false` otherwise. ### Request Example ```go // Acquire a connection if pool.AcquireConnection("http://proxy1:8080") { // Use the proxy... // Release the connection pool.ReleaseConnection("http://proxy1:8080") } ``` ``` -------------------------------- ### Get Account Groups Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Retrieves a list of all account groups. Each group has an ID, name, description, color, and sorting order. ```json { "groups": [ { "id": 1, "name": "Team", "description": "付费团队账号", "color": "#2563eb", "sort_order": 0, "member_count": 8, "created_at": "2026-05-13T00:00:00Z", "updated_at": "2026-05-13T00:00:00Z" } ] } ``` -------------------------------- ### Create API Key Source: https://github.com/james-6-23/codex2api/blob/main/docs/API.md Creates a new API key with specified configurations. ```APIDOC ## POST /api/admin/keys ### Description Creates a new API key. ### Method POST ### Endpoint /api/admin/keys ### Request Body - **name** (string) - Required - Display name for the API key. - **key** (string) - Optional - Custom API key. If omitted, one will be generated. - **quota_limit** (number) - Optional - Quota limit. 0 or omitted means unlimited. - **expires_at** (string) - Optional - Expiration date in RFC3339 or local date-time format. - **expires_in_days** (number) - Optional - Number of days until expiration. 0 means no expiration. - **allowed_group_ids** (integer[]) - Optional - Array of group IDs allowed to use this key. An empty array means all groups are allowed. ### Request Example ```json { "name": "production", "key": "sk-custom-key", "quota_limit": 10, "expires_in_days": 30, "allowed_group_ids": [1] } ``` ### Response #### Success Response (200) - **id** (integer) - The unique identifier for the created API key. - **key** (string) - The masked API key. - **name** (string) - The display name of the API key. - **quota_limit** (integer) - The quota limit for the API key. - **quota_used** (number) - The amount of quota used. - **expires_at** (string) - The expiration date and time of the API key. - **allowed_group_ids** (integer[]) - A list of group IDs allowed to use this key. ### Response Example ```json { "id": 2, "key": "sk-xxxxxxxxxxxxxxxxxxxxxxxx", "name": "production", "quota_limit": 10, "quota_used": 0, "expires_at": "2026-06-12T00:00:00Z", "allowed_group_ids": [1] } ``` ```