### Install Frontend Dependencies and Start Dev Server Source: https://github.com/basketikun/chatgpt2api/blob/main/docs/deployment.md Navigate to the `web` directory, install frontend dependencies using `bun`, and start the development server. ```bash cd web bun install bun run dev ``` -------------------------------- ### Copy Environment Example for WARP Deployment Source: https://github.com/basketikun/chatgpt2api/blob/main/docs/deployment.md Before starting the WARP/FlareSolverr deployment, copy the example environment file to `.env` and configure it. ```bash cp .env.example .env ``` -------------------------------- ### Get Available Models Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/README.md Example of how to retrieve a list of available models from the API. ```bash # 获取可用模型 curl http://localhost:3000/v1/models \ -H "Authorization: Bearer your-auth-key" ``` -------------------------------- ### Full config.json Example Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/configuration.md This comprehensive `config.json` example demonstrates all available settings, including image retention, caching, proxy runtime, and backup configurations. ```json { "auth-key": "your_secure_auth_key", "refresh_account_interval_minute": 5, "image_retention_days": 30, "image_poll_timeout_secs": 120, "image_cleanup_batch_size": 100, "image_storage": { "enabled": false, "mode": "local", "webdav_url": "", "webdav_username": "", "webdav_password": "", "webdav_root_path": "chatgpt2api/images", "public_base_url": "" }, "chat_completion_cache": { "enabled": true, "ttl_seconds": 60, "max_entries": 256, "dedupe_inflight": true, "stream_cache": true, "normalize_messages": true, "drop_adjacent_duplicates": true, "drop_assistant_history": false }, "proxy_runtime": { "enabled": false, "egress_mode": "direct", "proxy_url": "", "resource_proxy_url": "", "skip_ssl_verify": false, "reset_session_status_codes": [403], "clearance": { "enabled": false, "mode": "none", "cf_cookies": "", "cf_clearance": "", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", "browser": "chrome", "flaresolverr_url": "", "timeout_sec": 60, "refresh_interval": 3600, "warm_up_on_start": false } }, "backup": { "enabled": false, "provider": "cloudflare_r2", "account_id": "", "access_key_id": "", "secret_access_key": "", "bucket": "", "prefix": "backups", "interval_minutes": 360, "rotation_keep": 10, "encrypt": false, "passphrase": "", "include": { "config": true, "cpa": true, "sub2api": true, "logs": true, "image_tasks": true, "accounts_snapshot": true, "auth_keys_snapshot": true, "images": false } }, "third_party_apps": { "infinite_canvas": { "enabled": false, "url": "https://canvas.best" } } } ``` -------------------------------- ### System Settings Response Example Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/system-admin.md Example JSON response showing system configuration parameters, some of which may be redacted. ```json { "config": { "auth-key": "***", "refresh_account_interval_minute": 5, "image_retention_days": 30, "image_storage": {...}, "proxy_runtime": {...} } } ``` -------------------------------- ### Version Response Example Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/system-admin.md Example JSON response containing the application version. ```json { "version": "0.1.0" } ``` -------------------------------- ### System Settings Update Request Body Example Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/system-admin.md Example JSON body for updating system settings. Only fields to be changed need to be included. ```json { "refresh_account_interval_minute": 10, "image_retention_days": 60 } ``` -------------------------------- ### Run Backend from Source Source: https://github.com/basketikun/chatgpt2api/blob/main/docs/deployment.md Start the backend server using `uv run` for local development. ```bash uv run main.py ``` -------------------------------- ### Login Response Example Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/system-admin.md Example JSON response upon successful authentication, including user role and ID. ```json { "ok": true, "version": "0.1.0", "role": "admin", "subject_id": "user-id-12345", "name": "Administrator" } ``` -------------------------------- ### Generate Single Image with Python Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/README.md Python example using httpx to generate a single image. Ensure you have the httpx library installed. ```python import httpx async with httpx.AsyncClient() as client: response = await client.post( "http://localhost:3000/v1/images/generations", headers={"Authorization": "Bearer your-key"}, json={ "prompt": "美丽的风景", "model": "gpt-image-2", "n": 1 } ) data = response.json() image_b64 = data["data"][0]["b64_json"] ``` -------------------------------- ### WARP Proxy Deployment with Docker Compose Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/README.md Deploy the application with WARP proxy support. This command first copies the environment example file and then starts the services in detached mode, rebuilding the images if necessary. ```bash cp .env.example .env docker compose -f docker-compose.warp.yml up -d --build ``` -------------------------------- ### Install Python Dependencies for Source Execution Source: https://github.com/basketikun/chatgpt2api/blob/main/docs/deployment.md Synchronize and install Python dependencies using `uv` for running the application from source. ```bash uv sync ``` -------------------------------- ### Install and Run ChatGPT2API Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/README.md Instructions for cloning the repository and running the API using Docker or local development with uv. ```bash # 克隆仓库 git clone https://github.com/basketikun/chatgpt2api.git cd chatgpt2api # Docker 方式 docker compose up -d # 或本地开发 uv sync uv run main.py ``` -------------------------------- ### Minimal config.json Example Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/configuration.md This is the most basic configuration for `config.json`, requiring only an authentication key. ```json { "auth-key": "your_secure_auth_key_here" } ``` -------------------------------- ### System Prompt Definition (String) Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/anthropic-messages.md Example of defining a system prompt as a simple string to guide model behavior. ```json { "system": "你是一个专业的数据分析师" } ``` -------------------------------- ### Image Generation Request Example Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/responses-api.md This Python code snippet demonstrates how to use the `httpx` library to send a POST request to the /v1/responses endpoint for image generation. Ensure you have the `httpx` library installed. ```python import httpx async with httpx.AsyncClient() as client: response = await client.post( "http://localhost:3000/v1/responses", headers={ "Authorization": "Bearer your-auth-key", "Content-Type": "application/json", }, json={ "model": "gpt-5", "input": "生成一张未来感城市天际线图片", "tools": [ { "type": "image_generation" } ] } ) result = response.json() print(result["output"]) ``` -------------------------------- ### System Prompt Best Practice: Output Format Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/anthropic-messages.md Example of specifying the desired output format for the AI using the system prompt. ```json "system": "以 JSON 格式返回结果,包含 name 和 description 字段" ``` -------------------------------- ### Login API Usage Example Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/system-admin.md Demonstrates how to call the login API using curl, including the necessary Authorization header. ```bash curl -X POST http://localhost:3000/auth/login \ -H "Authorization: Bearer your-auth-key" ``` -------------------------------- ### Start Standard Docker Deployment Source: https://github.com/basketikun/chatgpt2api/blob/main/docs/deployment.md Launch the ChatGPT2API services in detached mode using Docker Compose. ```bash docker compose up -d ``` -------------------------------- ### System Prompt Best Practice: Behavior Specification Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/anthropic-messages.md Example of setting behavioral guidelines for the AI using the system prompt. ```json "system": "使用简洁的语言回答问题,避免长篇幅的解释" ``` -------------------------------- ### Get Current Configuration Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/system-admin.md Retrieve the current system configuration by making a GET request to the /api/settings endpoint. ```bash # 获取当前配置 curl http://localhost:3000/api/settings \ -H "Authorization: Bearer $CHATGPT2API_AUTH_KEY" | jq . ``` -------------------------------- ### Web Search Integration Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/README.md Python example demonstrating how to enable web search functionality within chat completions by specifying the 'web_search' tool. ```python response = await client.post( "http://localhost:3000/v1/chat/completions", headers={"Authorization": "Bearer key"}, json={ "model": "auto", "messages": [ {"role": "user", "content": "最近的科技新闻?"} ], "tools": [{"type": "web_search"}] } ) ``` -------------------------------- ### Verify Deployment Prerequisites Source: https://github.com/basketikun/chatgpt2api/blob/main/docs/deployment.md Before the initial deployment, verify that Docker, Docker Compose v2, and Git are installed and accessible by checking their versions. ```bash docker version docker compose version git --version ``` -------------------------------- ### System Prompt Best Practice: Role Definition Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/anthropic-messages.md Example of setting a specific role for the AI using the system prompt. ```json "system": "你是一个精通 Python 的软件工程师" ``` -------------------------------- ### Image Generation Response Example Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/endpoints.md Example of a non-streaming response from the image generation endpoint, containing creation timestamp and image data in b64_json format. ```json { "created": 1234567890, "data": [ { "b64_json": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==", "index": 0 } ], "usage": { "prompt_tokens": 10, "completion_tokens": 0 } } ``` -------------------------------- ### System Prompt Configuration Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/anthropic-messages.md Illustrates how to configure system prompts to guide the model's behavior, supporting both simple strings and structured formats. ```APIDOC ## System Prompt Configuration ### Description System prompts are used to guide the model's behavior. They support string or structured formats. ### Examples **String format:** ```json { "system": "You are a professional data analyst" } ``` **Structured format:** ```json { "system": [ { "type": "text", "text": "You are a professional data analyst" } ] } ``` ### Best Practices 1. **Define Role Clearly** ``` "system": "You are a software engineer proficient in Python" ``` 2. **Set Behavior Guidelines** ``` "system": "Answer questions concisely, avoiding lengthy explanations" ``` 3. **Specify Output Format** ``` "system": "Return results in JSON format, including 'name' and 'description' fields" ``` ``` -------------------------------- ### Get System Settings Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/system-admin.md Retrieves the current system configuration. Requires administrator privileges. ```APIDOC ## GET /api/settings ### Description Retrieves the system configuration. Requires administrator privileges. ### Method GET ### Endpoint /api/settings ### Parameters #### Header Parameters - **authorization** (string) - Required - Administrator authorization key ### Response #### Success Response (200) - **config** (object) - The system configuration object - **auth-key** (string) - Authentication key (masked) - **refresh_account_interval_minute** (integer) - Interval in minutes for account refresh - **image_retention_days** (integer) - Number of days to retain images - **image_storage** (object) - Image storage configuration - **proxy_runtime** (object) - Proxy runtime configuration #### Response Example ```json { "config": { "auth-key": "***", "refresh_account_interval_minute": 5, "image_retention_days": 30, "image_storage": {...}, "proxy_runtime": {...} } } ``` ### Error Handling - HTTPException: 401 - Authentication failed - HTTPException: 403 - No administrator privileges ``` -------------------------------- ### Generate Image API Call Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/README.md Example of how to generate an image using the API. Requires a prompt, model, and quantity. ```bash # 生成图像 curl -X POST http://localhost:3000/v1/images/generations \ -H "Authorization: Bearer your-auth-key" \ -H "Content-Type: application/json" \ -d '{ "prompt": "一只太空猫", "model": "gpt-image-2", "n": 1 }' ``` -------------------------------- ### Resume Image Generation Task Polling Example Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/image-tasks.md This Python example demonstrates how to poll for the status and results of an image generation task using httpx. It continuously polls the API until the task is completed or fails, printing progress updates. ```python import httpx async def wait_for_task(task_id: str, auth_key: str, timeout: float = 120.0): async with httpx.AsyncClient() as client: while True: # 继续轮询任务结果 response = await client.post( f"http://localhost:3000/api/image-tasks/{task_id}/resume-poll", headers={"Authorization": f"Bearer {auth_key}"}, json={"extra_timeout_secs": 30.0} ) result = response.json() if result["status"] == "completed": return result["result"] elif result["status"] == "failed": raise RuntimeError(f"任务失败: {result.get('error')}") else: # 任务仍在处理,继续等待 progress = result.get("progress", 0) print(f"进度: {progress:.1%}") await asyncio.sleep(5) ``` -------------------------------- ### Update System Settings API Usage Example Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/system-admin.md Demonstrates how to update system settings using curl, including the Authorization header and JSON content type. ```bash curl -X POST http://localhost:3000/api/settings \ -H "Authorization: Bearer admin-key" \ -H "Content-Type: application/json" \ -d ફો'{ "refresh_account_interval_minute": 10 }' ``` -------------------------------- ### Rebuild Frontend Static Assets Source: https://github.com/basketikun/chatgpt2api/blob/main/docs/deployment.md If necessary, rebuild the frontend static assets by installing dependencies and running the build command. ```bash cd web bun install bun run build ``` -------------------------------- ### System Prompt Definition (Structured) Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/anthropic-messages.md Example of defining a system prompt using a structured format, allowing for more complex instructions. ```json { "system": [ { "type": "text", "text": "你是一个专业的数据分析师" } ] } ``` -------------------------------- ### Start WARP / FlareSolverr Docker Deployment Source: https://github.com/basketikun/chatgpt2api/blob/main/docs/deployment.md Deploy ChatGPT2API with WARP and FlareSolverr support using a specific Docker Compose file, building the images if necessary. ```bash docker compose -f docker-compose.warp.yml up -d --build ``` -------------------------------- ### Get System Settings Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/system-admin.md Retrieves the current system configuration. Requires administrator privileges and an 'Authorization' header with a Bearer token. ```python async def get_settings( authorization: str | None = Header(default=None) ) -> dict[str, Any] ``` -------------------------------- ### Chat Completion API Call Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/README.md Example of how to perform a chat completion. Requires a model and a list of messages. ```bash # 聊天完成 curl -X POST http://localhost:3000/v1/chat/completions \ -H "Authorization: Bearer your-auth-key" \ -H "Content-Type: application/json" \ -d '{ "model": "auto", "messages": [ {"role": "user", "content": "你好"} ] }' ``` -------------------------------- ### Edit Image with Python Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/README.md Python example for editing an image. This requires uploading the image file and providing a prompt for the edit. ```python # 上传文件编辑 with open("input.png", "rb") as f: response = await client.post( "http://localhost:3000/v1/images/edits", headers={"Authorization": "Bearer key"}, files={ "image": ("input.png", f, "image/png"), "prompt": (None, "改成赛博朋克风格"), "model": (None, "gpt-image-2"), } ) ``` -------------------------------- ### Query System Logs Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/system-admin.md Fetch system logs by making a GET request to the /api/logs endpoint, optionally filtering by date. ```bash curl "http://localhost:3000/api/logs?start_date=2025-01-01" \ -H "Authorization: Bearer $CHATGPT2API_AUTH_KEY" | jq . ``` -------------------------------- ### Web Search Request Example Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/responses-api.md This Python code snippet shows how to make a POST request to the /v1/responses endpoint for performing a web search using the `web_search_preview` tool. The `httpx` library is used for the HTTP request. ```python import httpx async with httpx.AsyncClient() as client: response = await client.post( "http://localhost:3000/v1/responses", headers={ "Authorization": "Bearer your-auth-key", "Content-Type": "application/json", }, json={ "model": "gpt-5", "input": "最近有什么关于 AI 的新闻?", "tools": [ { "type": "web_search_preview" } ] } ) result = response.json() ``` -------------------------------- ### Python: Generate Images with httpx Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/image-generation.md Example of how to generate images using the /v1/images/generations endpoint with Python's httpx library. Includes setting authorization headers and specifying generation parameters like prompt, model, number of images, and response format. ```python import httpx async with httpx.AsyncClient() as client: response = await client.post( "http://localhost:3000/v1/images/generations", headers={ "Authorization": "Bearer your-auth-key", "Content-Type": "application/json", }, json={ "prompt": "一只漂浮在太空里的猫", "model": "gpt-image-2", "n": 1, "response_format": "b64_json" } ) result = response.json() print(f"生成了 {len(result['data'])} 张图像") ``` -------------------------------- ### View Configuration Settings Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/00-START-HERE.md Retrieve the current system configuration settings by making a GET request to the API settings endpoint. This requires an administrator key for authentication. ```bash curl http://localhost:3000/api/settings \ -H "Authorization: Bearer admin-key" ``` -------------------------------- ### Asynchronous Image Task Generation Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/README.md Python example for submitting an asynchronous image generation task and polling for results. It includes submitting the task and then resuming polling. ```python # 1. 提交任务 response = await client.post( "http://localhost:3000/api/image-tasks/generations", json={ "client_task_id": "my-task-1", "prompt": "太空中的猫", "model": "gpt-image-2" } ) task_id = response.json()["task_id"] # 2. 轮询结果 response = await client.post( f"http://localhost:3000/api/image-tasks/{task_id}/resume-poll", json={"extra_timeout_secs": 30} ) result = response.json() if result["status"] == "completed": images = result["result"]["data"] ``` -------------------------------- ### Multi-modal Content Message Format Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/anthropic-messages.md Example of a user message containing both text and image content, demonstrating multi-modal capabilities. ```json { "role": "user", "content": [ { "type": "text", "text": "这张图片是什么?" }, { "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "base64_encoded_data" } } ] } ``` -------------------------------- ### Text Incremental Update Examples Source: https://github.com/basketikun/chatgpt2api/blob/main/docs/upstream-sse-conversation.md Shows how text content is incrementally updated using SSE patches. This includes appending text to existing parts, replacing fields, and handling batch patches. ```json {"p":"/message/content/parts/0","o":"append","v":"Hello"} ``` ```json {"v":" world"} ``` ```json {"p":"","o":"patch","v":[ {"p":"/message/content/parts/0","o":"append","v":"!"}, {"p":"/message/status","o":"replace","v":"finished_successfully"}, {"p":"/message/end_turn","o":"replace","v":true} ]} ``` -------------------------------- ### Basic SSE Payload Examples Source: https://github.com/basketikun/chatgpt2api/blob/main/docs/upstream-sse-conversation.md Illustrates the common formats of data payloads received over the SSE stream, including version markers, JSON objects for events, JSON strings for patches, and the end-of-stream marker. ```text "v1" {"type":"resume_conversation_token",...} {"p":"","o":"add","v":{...}} {"v":{...}} {"p":"/message/content/parts/0","o":"append","v":"..."} {"type":"server_ste_metadata","metadata":{...}} [DONE] ``` -------------------------------- ### Chat Conversation with Python Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/README.md Python example for conducting a chat conversation. It sends a user message and retrieves the model's response. ```python response = await client.post( "http://localhost:3000/v1/chat/completions", headers={"Authorization": "Bearer key"}, json={ "model": "auto", "messages": [ {"role": "user", "content": "什么是人工智能?"} ] } ) content = response.json()["choices"][0]["message"]["content"] ``` -------------------------------- ### Get Current Settings via API Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/configuration.md Retrieve the current application settings using the API. Ensure you include the Authorization header with your bearer token. ```bash curl http://localhost:3000/api/settings \ -H "Authorization: Bearer your-auth-key" ``` -------------------------------- ### Log API Errors with Context Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/errors.md This example demonstrates how to log detailed information about API errors, including status code and specific error details from the response body. Ensure the logger is configured appropriately. ```python import logging logger = logging.getLogger(__name__) async def handle_api_call(request): try: response = await client.post(...) # Assuming 'client' is defined elsewhere response.raise_for_status() return response.json() except httpx.HTTPStatusError as e: error_data = e.response.json().get("error", {}) logger.error( "API Error", extra={ "status_code": e.response.status_code, "error_type": error_data.get("type"), "error_code": error_data.get("code"), "message": error_data.get("message"), } ) raise ``` -------------------------------- ### Streaming Response Handling Example (Python) Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/chat-completion.md Demonstrates how to handle streaming responses from the chat completion API using httpx. It iterates over Server-Sent Events (SSE) and yields parsed JSON chunks until the stream is done. ```python import json async with httpx.AsyncClient() as client: with client.stream( "POST", "http://localhost:3000/v1/chat/completions", json={"model": "auto", "messages": [...], "stream": True} ) as response: for line in response.iter_lines(): if line.startswith("data:"): data = line[5:].strip() if data == "[DONE]": break try: chunk = json.loads(data) yield chunk except json.JSONDecodeError: continue ``` -------------------------------- ### Streaming Response Example Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/responses-api.md This Python code demonstrates how to handle streaming responses from the /v1/responses endpoint. It uses `httpx` to stream data and `json` to parse chunks. The `stream` parameter must be set to `True` in the request. ```python import httpx import json async with httpx.AsyncClient() as client: with client.stream( "POST", "http://localhost:3000/v1/responses", headers={"Authorization": "Bearer your-auth-key"}, json={ "model": "gpt-5", "input": "生成内容", "tools": [{"type": "image_generation"}], "stream": True } ) as response: async for line in response.aiter_lines(): if line.startswith("data:"): data = line[5:].strip() if data == "[DONE]": break chunk = json.loads(data) yield chunk ``` -------------------------------- ### Get Application Version Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/system-admin.md Retrieves the current version of the application. ```APIDOC ## GET /version ### Description Retrieves the application version. ### Method GET ### Endpoint /version ### Response #### Success Response (200) - **version** (string) - The application version #### Response Example ```json { "version": "0.1.0" } ``` ``` -------------------------------- ### Get Available Models Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/README.md Retrieves a list of models available for use with the API. ```APIDOC ## GET /v1/models ### Description Retrieves a list of available models. ### Method GET ### Endpoint /v1/models ### Request Example ```bash curl http://localhost:3000/v1/models \ -H "Authorization: Bearer your-auth-key" ``` ``` -------------------------------- ### GET /api/image-tasks Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/endpoints.md Lists image tasks for a specified identity. Requires an Authorization header. ```APIDOC ## GET /api/image-tasks ### Description Lists image tasks for a specified identity. ### Method GET ### Endpoint /api/image-tasks ### Parameters #### Path Parameters None #### Query Parameters - **ids** (string) - Optional - Comma-separated list of task IDs #### Request Body None ### Request Example None ### Response #### Success Response (200) - **tasks** (array) - List of image tasks #### Response Example None ### Headers - **Authorization** (string) - Required - Bearer token authentication key ``` -------------------------------- ### Get Application Version Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/system-admin.md Retrieves the current application version. This endpoint does not require authentication. ```python async def get_version() -> dict[str, str] ``` -------------------------------- ### Create Full Backup Archive Source: https://github.com/basketikun/chatgpt2api/blob/main/docs/deployment.md Create a timestamped tarball containing `config.json`, `.env`, and the `data/` directory for backup purposes. ```bash tar -czf backups/chatgpt2api-$(date +%Y%m%d-%H%M%S).tgz config.json .env data ``` -------------------------------- ### Initialize Admin API Key Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/system-admin.md Set the CHATGPT2API_AUTH_KEY environment variable to secure your administrative access. ```bash export CHATGPT2API_AUTH_KEY="secure_random_string" ``` -------------------------------- ### Simple Text Message Format Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/api-reference/anthropic-messages.md Example of a basic user message containing only text content. ```json { "role": "user", "content": "你好" } ``` -------------------------------- ### Create Backup Directory Source: https://github.com/basketikun/chatgpt2api/blob/main/docs/deployment.md Create a directory named `backups` to store compressed archives of configuration files and data. ```bash mkdir -p backups ``` -------------------------------- ### Set PostgreSQL Storage Backend Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/configuration.md Connect to an external PostgreSQL database by setting the `STORAGE_BACKEND` and `DATABASE_URL` environment variables. Ensure the `DATABASE_URL` follows the specified format. ```bash export STORAGE_BACKEND=postgres export DATABASE_URL=postgresql://user:password@host:5432/dbname ``` -------------------------------- ### Request Parameter Errors Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/errors.md Details on errors related to invalid or missing request parameters, including common scenarios and examples. ```APIDOC ## Request Parameter Errors **HTTP Status Code**: 400 | Error Code | Error Type | Condition | Source | |------------------------|------------------------|-----------------------------------------|---------------| | `bad_request` | `invalid_request_error` | General request parameter error | Various API endpoints | | `missing_required_field` | `invalid_request_error` | Required field is missing | Request validation | | `invalid_field_value` | `invalid_request_error` | Field value has incorrect type or format | Request validation | | `invalid_json` | `invalid_request_error` | JSON parsing failed | Request processing | **Common Error Scenarios:** 1. **Missing `prompt` field** - Endpoint: `POST /v1/images/generations` - Message: `prompt: ensure this value has at least 1 characters` ```bash curl -X POST http://localhost:3000/v1/images/generations \ -H "Authorization: Bearer key" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-image-2" }' ``` ```json { "error": { "message": "prompt: ensure this value has at least 1 characters", "type": "invalid_request_error", "code": "bad_request" } } ``` 2. **`n` value out of range** - Endpoint: `POST /v1/images/generations` - Message: `n: Input should be less than or equal to 4` 3. **Invalid `response_format`** - Endpoint: `POST /v1/images/generations` - Message: `response_format must be "b64_json" or "url"` ``` -------------------------------- ### Configure SQLite Storage Backend Source: https://github.com/basketikun/chatgpt2api/blob/main/docs/deployment.md Set the `STORAGE_BACKEND` to `sqlite` and specify the database file path in the `DATABASE_URL` environment variable. ```yaml environment: - STORAGE_BACKEND=sqlite - DATABASE_URL=sqlite:////app/data/accounts.db ``` -------------------------------- ### Set SQLite Storage Backend Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/configuration.md Configure the application to use a local SQLite database for data storage by setting the `STORAGE_BACKEND` environment variable. ```bash export STORAGE_BACKEND=sqlite ``` -------------------------------- ### Configure PostgreSQL Storage Backend Source: https://github.com/basketikun/chatgpt2api/blob/main/docs/deployment.md Set the `STORAGE_BACKEND` to `postgres` and provide the connection URL in the environment variables for PostgreSQL storage. ```yaml environment: - STORAGE_BACKEND=postgres - DATABASE_URL=postgresql://user:password@host:5432/dbname ``` -------------------------------- ### Set JSON Storage Backend Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/configuration.md Use this command to configure the application to store data in JSON files within the `./data/` directory. This is the default storage backend. ```bash export STORAGE_BACKEND=json ``` -------------------------------- ### Gateway Errors Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/errors.md Details on gateway errors, including HTTP status codes, error codes, types, common causes, and examples. ```APIDOC ## Gateway Errors **HTTP Status Code**: 502 | Error Code | Error Type | Condition | Source | |----------------|--------------|-------------------------------|------------------------| | `upstream_error` | `server_error` | Upstream service returned an error | OpenAI/Anthropic API | **Common Causes:** - Upstream service is unavailable. - Network connectivity issues. - Proxy configuration errors. - Blocked by Cloudflare. **Example Error:** ```json { "error": { "message": "failed to connect to upstream service", "type": "server_error", "code": "upstream_error" } } ``` ``` -------------------------------- ### List Available Models Source: https://github.com/basketikun/chatgpt2api/blob/main/README.md Use this endpoint to retrieve a list of currently exposed image models. Requires an Authorization header. ```bash curl http://localhost:8000/v1/models \ -H "Authorization: Bearer " ``` -------------------------------- ### Debug Authentication Error Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/errors.md Example of how to debug an authentication error by using an invalid API key. This will result in a 401 Unauthorized response. ```bash curl -H "Authorization: Bearer invalid_key" \ http://localhost:3000/v1/models ``` ```json { "error": { "message": "invalid api key", "type": "authentication_error", "code": "invalid_api_key" } } ``` -------------------------------- ### Clone Repository for Standard Docker Deployment Source: https://github.com/basketikun/chatgpt2api/blob/main/docs/deployment.md Clone the project repository to your server to begin the standard Docker deployment process. ```bash git clone git@github.com:basketikun/chatgpt2api.git cd chatgpt2api ``` -------------------------------- ### Image Edit API Response Example Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/endpoints.md This is a sample JSON response for a successful image editing request, showing creation timestamp and image data. ```json { "created": 1234567890, "data": [ { "b64_json": "base64_image_data_here", "index": 0 } ], "usage": { "prompt_tokens": 15, "completion_tokens": 0 } } ``` -------------------------------- ### View Configuration Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/errors.md Retrieve and view the API settings using curl. This command requires an 'admin-key' for authorization and pipes the output to jq for pretty-printing. ```bash curl -H "Authorization: Bearer admin-key" \ http://localhost:3000/api/settings | jq . ``` -------------------------------- ### Example Gateway Error Response Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/errors.md This JSON structure illustrates a 'server_error' with the code 'upstream_error', indicating an issue communicating with an upstream service like OpenAI or Anthropic. ```json { "error": { "message": "failed to connect to upstream service", "type": "server_error", "code": "upstream_error" } } ``` -------------------------------- ### Example Validation Error Response Source: https://github.com/basketikun/chatgpt2api/blob/main/_autodocs/errors.md This JSON structure represents a validation error, typically occurring when request parameters do not meet specified criteria, such as exceeding limits. ```json { "error": { "message": "n: Input should be less than or equal to 4", "type": "invalid_request_error", "code": "bad_request" } } ``` -------------------------------- ### View WARP Deployment Logs Source: https://github.com/basketikun/chatgpt2api/blob/main/docs/deployment.md Monitor logs for the main application and FlareSolverr in the WARP deployment. ```bash docker logs -f chatgpt2api-warp docker logs -f chatgpt2api-flaresolverr ``` -------------------------------- ### View Docker Logs Source: https://github.com/basketikun/chatgpt2api/blob/main/docs/deployment.md Monitor the application's activity and troubleshoot issues by tailing the Docker container logs. ```bash docker logs -f chatgpt2api ``` -------------------------------- ### Create Backup Archive Without .env Source: https://github.com/basketikun/chatgpt2api/blob/main/docs/deployment.md Create a backup archive excluding the `.env` file if it does not exist. ```bash tar -czf backups/chatgpt2api-$(date +%Y%m%d-%H%M%S).tgz config.json data ``` -------------------------------- ### Conversation Session Initiation Event Source: https://github.com/basketikun/chatgpt2api/blob/main/docs/upstream-sse-conversation.md Example of an SSE event used to initiate or resume a conversation, providing a token and conversation ID for context management. The token should not be exposed to users. ```json { "type": "resume_conversation_token", "kind": "topic", "token": "...", "conversation_id": "..." } ```