### Compile and Install CoAI from Source Source: https://github.com/mathematrix/coai/blob/main/README.md This method involves cloning the CoAI repository, installing Node.js dependencies, building the application, and then compiling the Go binary. The compiled binary can be run directly or managed using services like nohup, systemd, or other service managers. Configuration can be overridden using environment variables. ```shell git clone https://github.com/Deeptrain-Community/chatnio.git cd chatnio cd app npm install -g pnpm pnpm install pnpm build cd .. go build -o chatnio # e.g. using nohup (you can also use systemd or other service manager) nohup ./chatnio > output.log & ``` -------------------------------- ### Install CoAI using standalone Docker Source: https://github.com/mathematrix/coai/blob/main/README.md This lightweight Docker installation is suitable for running CoAI, especially when using external MySQL/RDS services. It requires setting environment variables for database connections, JWT secret, and static file serving. Update instructions involve stopping, removing, and re-pulling the Docker image. ```shell docker run -d --name chatnio \ --network host \ -v ~/config:/config \ -v ~/logs:/logs \ -v ~/storage:/storage \ -e MYSQL_HOST=localhost \ -e MYSQL_PORT=3306 \ -e MYSQL_DB=chatnio \ -e MYSQL_USER=root \ -e MYSQL_PASSWORD=chatnio123456 \ -e REDIS_HOST=localhost \ -e REDIS_PORT=6379 \ -e SECRET=secret \ -e SERVE_STATIC=true \ programzmh/chatnio:latest ``` ```shell docker stop chatnio docker rm chatnio docker pull programzmh/chatnio:latest ``` -------------------------------- ### Deploy CoAI using Docker Compose Source: https://github.com/mathematrix/coai/blob/main/README.md This method uses Docker Compose for a recommended installation of CoAI. It involves cloning the repository and running the service with docker-compose. Additional options for stable versions and automatic updates with Watchtower are provided. Mount directories for databases and configurations are also specified. ```shell git clone --depth=1 --branch=main --single-branch https://github.com/Deeptrain-Community/chatnio.git cd chatnio docker-compose up -d # Run the service # To use the stable version, use docker-compose -f docker-compose.stable.yaml up -d instead # To use Watchtower for automatic updates, use docker-compose -f docker-compose.watch.yaml up -d instead ``` ```shell docker-compose down docker-compose pull docker-compose up -d ``` -------------------------------- ### Configure Billing Rules (Bash) Source: https://context7.com/mathematrix/coai/llms.txt Sets up flexible billing rules per model, supporting non-billing, per-request (times-billing), and per-token (token-billing) methods. Examples include token-billing for GPT models, times-billing for image generation, and a free tier for basic models. Supports anonymous access and minimum charge requirements. ```bash curl -X POST https://your-domain.com/api/admin/charge/set \ -H "Authorization: Bearer admin-jwt-token" \ -H "Content-Type: application/json" \ -d '{ "id": 0, "type": "token-billing", "models": ["gpt-4", "gpt-4-turbo"], "input": 0.03, "output": 0.06, "anonymous": false }' # Response { "status": true, "id": 5, "message": "Charge rule created successfully" } # Create times-based billing for image generation curl -X POST https://your-domain.com/api/admin/charge/set \ -H "Authorization: Bearer admin-jwt-token" \ -H "Content-Type: application/json" \ -d '{ "id": 0, "type": "times-billing", "models": ["dall-e-3"], "input": 0, "output": 0.04, "anonymous": true }' # Create free tier for basic models curl -X POST https://your-domain.com/api/admin/charge/set \ -H "Authorization: Bearer admin-jwt-token" \ -H "Content-Type: application/json" \ -d '{ "id": 0, "type": "non-billing", "models": ["gpt-3.5-turbo", "claude-instant"], "input": 0, "output": 0, "anonymous": true }' # List all charge rules curl -X GET https://your-domain.com/api/admin/charge/list \ -H "Authorization: Bearer admin-jwt-token" # Response { "status": true, "data": [ { "id": 5, "type": "token-billing", "models": ["gpt-4", "gpt-4-turbo"], "input": 0.03, "output": 0.06, "anonymous": false }, { "id": 6, "type": "times-billing", "models": ["dall-e-3"], "input": 0, "output": 0.04, "anonymous": true }, { "id": 7, "type": "non-billing", "models": ["gpt-3.5-turbo", "claude-instant"], "input": 0, "output": 0, "anonymous": true } ] } ``` -------------------------------- ### GET /api/v1/plans Source: https://context7.com/mathematrix/coai/llms.txt Retrieves a list of available subscription plans, including their pricing, features, and usage limits. ```APIDOC ## GET /api/v1/plans ### Description Retrieve available subscription tiers with pricing and usage limits. Plans support monthly/yearly billing with automatic discounts. ### Method GET ### Endpoint /api/v1/plans ### Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (boolean) - Indicates if the request was successful. - **data** (array) - An array of subscription plan objects. - **level** (integer) - The tier level of the plan. - **name** (string) - The name of the plan (e.g., "Basic", "Standard", "Pro"). - **price** (float) - The monthly price of the plan. - **items** (array) - A list of features included in the plan. - **id** (string) - The unique identifier for the feature. - **name** (string) - The display name of the feature. - **icon** (string) - An icon representing the feature. - **value** (integer) - The limit or quantity of the feature (e.g., number of calls, images). -1 indicates unlimited. - **models** (array) - A list of models associated with this feature. #### Response Example ```json { "status": true, "data": [ { "level": 1, "name": "Basic", "price": 9.99, "items": [ { "id": "gpt4_calls", "name": "GPT-4 Calls", "icon": "🚀", "value": 100, "models": ["gpt-4", "gpt-4-turbo"] }, { "id": "dalle_images", "name": "DALL-E Images", "icon": "🎨", "value": 50, "models": ["dall-e-3"] } ] }, { "level": 2, "name": "Standard", "price": 19.99, "items": [ { "id": "gpt4_calls", "name": "GPT-4 Calls", "icon": "🚀", "value": 500, "models": ["gpt-4", "gpt-4-turbo"] }, { "id": "dalle_images", "name": "DALL-E Images", "icon": "🎨", "value": 200, "models": ["dall-e-3"] } ] }, { "level": 3, "name": "Pro", "price": 49.99, "items": [ { "id": "unlimited", "name": "Unlimited Access", "icon": "⭐", "value": -1, "models": ["*"] } ] } ] } ``` ``` -------------------------------- ### GET /api/admin/charge/list Source: https://context7.com/mathematrix/coai/llms.txt Retrieves a list of all configured billing rules. ```APIDOC ## GET /api/admin/charge/list ### Description Lists all configured billing rules for AI models. ### Method GET ### Endpoint /api/admin/charge/list ### Parameters None ### Request Example ```bash curl -X GET https://your-domain.com/api/admin/charge/list \ -H "Authorization: Bearer admin-jwt-token" ``` ### Response #### Success Response (200) - **status** (boolean) - Indicates success of the operation. - **data** (array of objects) - A list of charge rules. - **id** (integer) - The unique identifier of the charge rule. - **type** (string) - The type of billing rule. - **models** (array of strings) - List of models to which this rule applies. - **input** (number) - Cost per input token or 0. - **output** (number) - Cost per output token/request or 0. - **anonymous** (boolean) - Whether anonymous users are allowed. #### Response Example ```json { "status": true, "data": [ { "id": 5, "type": "token-billing", "models": ["gpt-4", "gpt-4-turbo"], "input": 0.03, "output": 0.06, "anonymous": false }, { "id": 6, "type": "times-billing", "models": ["dall-e-3"], "input": 0, "output": 0.04, "anonymous": true }, { "id": 7, "type": "non-billing", "models": ["gpt-3.5-turbo", "claude-instant"], "input": 0, "output": 0, "anonymous": true } ] } ``` ``` -------------------------------- ### Get Subscription Plans Source: https://context7.com/mathematrix/coai/llms.txt Retrieves available subscription tiers, including pricing and usage limits for different services like GPT-4 calls and DALL-E images. Supports monthly and yearly billing with discounts. ```bash curl -X GET https://your-domain.com/api/v1/plans \ -H "Authorization: Bearer your-jwt-token" # Response { "status": true, "data": [ { "level": 1, "name": "Basic", "price": 9.99, "items": [ { "id": "gpt4_calls", "name": "GPT-4 Calls", "icon": "🚀", "value": 100, "models": ["gpt-4", "gpt-4-turbo"] }, { "id": "dalle_images", "name": "DALL-E Images", "icon": "🎨", "value": 50, "models": ["dall-e-3"] } ] }, { "level": 2, "name": "Standard", "price": 19.99, "items": [ { "id": "gpt4_calls", "name": "GPT-4 Calls", "icon": "🚀", "value": 500, "models": ["gpt-4", "gpt-4-turbo"] }, { "id": "dalle_images", "name": "DALL-E Images", "icon": "🎨", "value": 200, "models": ["dall-e-3"] } ] }, { "level": 3, "name": "Pro", "price": 49.99, "items": [ { "id": "unlimited", "name": "Unlimited Access", "icon": "⭐", "value": -1, "models": ["*"] } ] } ] } ``` -------------------------------- ### Create AI Provider Channel (Bash) Source: https://context7.com/mathematrix/coai/llms.txt Configures a new AI provider channel with support for load balancing, retry logic, model mapping, multiple API keys, priority routing, and user group restrictions. Includes examples for OpenAI and Azure OpenAI, demonstrating proxy and model exclusion settings. ```bash curl -X POST https://your-domain.com/api/admin/channel/create \ -H "Authorization: Bearer admin-jwt-token" \ -H "Content-Type: application/json" \ -d '{ "name": "OpenAI GPT-4 Primary", "type": "openai", "priority": 10, "weight": 100, "models": ["gpt-4", "gpt-4-turbo", "gpt-4-vision-preview"], "retry": 3, "secret": "sk-proj-abc123xyz789\nsk-proj-def456uvw012", "endpoint": "https://api.openai.com", "mapper": "gpt-4>gpt-4-0613\ngpt-4-turbo>gpt-4-turbo-2024-04-09", "state": true, "group": ["basic", "standard", "pro"], "proxy": { "proxy_type": 0, "proxy": "", "username": "", "password": "" } }' # Response { "status": true, "id": 15, "message": "Channel created successfully" } # Create channel with proxy and model exclusions curl -X POST https://your-domain.com/api/admin/channel/create \ -H "Authorization: Bearer admin-jwt-token" \ -H "Content-Type: application/json" \ -d '{ "name": "Azure OpenAI Backup", "type": "azure", "priority": 5, "weight": 50, "models": ["gpt-4", "gpt-35-turbo"], "retry": 2, "secret": "azure-api-key-here", "endpoint": "https://your-resource.openai.azure.com", "mapper": "!gpt-4-32k>\ngpt-35-turbo>gpt-35-turbo-16k", "state": true, "group": ["standard", "pro"], "proxy": { "proxy_type": 1, "proxy": "http://proxy.example.com:8080", "username": "proxyuser", "password": "proxypass" } }' # List all channels curl -X GET https://your-domain.com/api/admin/channel/list \ -H "Authorization: Bearer admin-jwt-token" # Response { "status": true, "data": [ { "id": 15, "name": "OpenAI GPT-4 Primary", "type": "openai", "priority": 10, "weight": 100, "models": ["gpt-4", "gpt-4-turbo", "gpt-4-vision-preview"], "state": true, "group": ["basic", "standard", "pro"] }, { "id": 16, "name": "Azure OpenAI Backup", "type": "azure", "priority": 5, "weight": 50, "models": ["gpt-4", "gpt-35-turbo"], "state": true, "group": ["standard", "pro"] } ] } ``` -------------------------------- ### GET /api/admin/channel/list Source: https://context7.com/mathematrix/coai/llms.txt Retrieves a list of all configured AI provider channels. ```APIDOC ## GET /api/admin/channel/list ### Description Lists all configured AI provider channels. ### Method GET ### Endpoint /api/admin/channel/list ### Parameters None ### Request Example ```bash curl -X GET https://your-domain.com/api/admin/channel/list \ -H "Authorization: Bearer admin-jwt-token" ``` ### Response #### Success Response (200) - **status** (boolean) - Indicates success of the operation. - **data** (array of objects) - A list of AI channels. - **id** (integer) - The unique identifier of the channel. - **name** (string) - The name of the AI channel. - **type** (string) - The type of the AI provider. - **priority** (integer) - The priority of the channel. - **weight** (integer) - The weight for load balancing. - **models** (array of strings) - List of models supported by this channel. - **state** (boolean) - Whether the channel is enabled or disabled. - **group** (array of strings) - User groups allowed to access this channel. #### Response Example ```json { "status": true, "data": [ { "id": 15, "name": "OpenAI GPT-4 Primary", "type": "openai", "priority": 10, "weight": 100, "models": ["gpt-4", "gpt-4-turbo", "gpt-4-vision-preview"], "state": true, "group": ["basic", "standard", "pro"] }, { "id": 16, "name": "Azure OpenAI Backup", "type": "azure", "priority": 5, "weight": 50, "models": ["gpt-4", "gpt-35-turbo"], "state": true, "group": ["standard", "pro"] } ] } ``` ``` -------------------------------- ### Get System Information (JSON Response) Source: https://context7.com/mathematrix/coai/llms.txt The response contains various system metrics such as online users, total users, daily and monthly revenue, request counts, active channels, and the error rate. ```json { "status": true, "data": { "online_users": 45, "total_users": 1250, "today_revenue": 350.50, "monthly_revenue": 8420.75, "today_requests": 15420, "monthly_requests": 425680, "active_channels": 12, "error_rate": 0.02 } } ``` -------------------------------- ### Get Model Usage Analysis (cURL Request) Source: https://context7.com/mathematrix/coai/llms.txt Fetches model usage analytics for a specified time period. Requires an admin JWT token and query parameters for start and end times. ```bash curl -X GET "https://your-domain.com/api/admin/analytics/model?start_time=2024-01-01&end_time=2024-01-31" \ -H "Authorization: Bearer admin-jwt-token" ``` -------------------------------- ### Get System Information (cURL Request) Source: https://context7.com/mathematrix/coai/llms.txt Retrieves key system analytics, including user counts, revenue, request statistics, active channels, and error rates. Requires an admin JWT token. ```bash curl -X GET https://your-domain.com/api/admin/analytics/info \ -H "Authorization: Bearer admin-jwt-token" ``` -------------------------------- ### GET /api/subscription Source: https://context7.com/mathematrix/coai/llms.txt Retrieves the current subscription status and usage details for the authenticated user. ```APIDOC ## GET /api/subscription ### Description Check current subscription status and view usage details for your active plan. ### Method GET ### Endpoint /api/subscription ### Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (boolean) - Indicates if the request was successful. - **subscription** (object) - Details of the current subscription. - **level** (integer) - The level of the current subscription plan. - **name** (string) - The name of the current subscription plan. - **expired** (string) - The expiration date of the subscription in ISO 8601 format. - **usage** (object) - An object detailing the usage of different features within the plan. - **feature_id** (object) - Usage details for a specific feature (e.g., "gpt4_calls", "dalle_images"). - **used** (integer) - The amount of the feature consumed. - **limit** (integer) - The total limit for the feature. -1 indicates unlimited. - **percentage** (float) - The percentage of the limit that has been used. #### Response Example ```json { "status": true, "subscription": { "level": 2, "name": "Standard", "expired": "2025-01-06T00:00:00Z", "usage": { "gpt4_calls": { "used": 23, "limit": 500, "percentage": 4.6 }, "dalle_images": { "used": 8, "limit": 200, "percentage": 4.0 } } } } ``` ``` -------------------------------- ### Get API Key and Use for Chat Completions - Bash Source: https://context7.com/mathematrix/coai/llms.txt Retrieves an existing API key or generates a new one for programmatic access. The API key, formatted as `sk-{hash}`, is then used to authenticate requests to the OpenAI-compatible API endpoints, such as chat completions. Dependencies: User authentication. ```bash curl -X GET https://your-domain.com/api/apikey \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." # Response { "status": true, "key": "sk-a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6a7b8c9d0e1f2" } # Use the API key in subsequent requests curl -X POST https://your-domain.com/api/v1/chat/completions \ -H "Authorization: Bearer sk-a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6a7b8c9d0e1f2" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4", "messages": [{"role": "user", "content": "Hello"}] }' ``` -------------------------------- ### Get Billing Analysis Source: https://context7.com/mathematrix/coai/llms.txt Retrieves a billing analysis for a specified time range. This endpoint provides total revenue, subscription revenue, usage revenue, and a daily breakdown. ```APIDOC ## GET /api/admin/analytics/billing ### Description Retrieves a billing analysis for a specified time range. ### Method GET ### Endpoint `/api/admin/analytics/billing` ### Query Parameters - **start_time** (string) - Required - The start date for the analysis (YYYY-MM-DD). - **end_time** (string) - Required - The end date for the analysis (YYYY-MM-DD). ### Request Example ``` GET /api/admin/analytics/billing?start_time=2024-01-01&end_time=2024-01-31 ``` ### Response #### Success Response (200) - **status** (boolean) - Indicates if the request was successful. - **data** (object) - Contains the billing analysis details: - **total_revenue** (number) - The total revenue for the period. - **subscription_revenue** (number) - The revenue generated from subscriptions. - **usage_revenue** (number) - The revenue generated from usage. - **daily_breakdown** (array) - An array of objects, each representing a day's revenue and requests: - **date** (string) - The date of the breakdown (YYYY-MM-DD). - **revenue** (number) - The revenue for that day. - **requests** (integer) - The number of requests for that day. #### Response Example ```json { "status": true, "data": { "total_revenue": 8420.75, "subscription_revenue": 4500.00, "usage_revenue": 3920.75, "daily_breakdown": [ {"date": "2024-01-01", "revenue": 250.50, "requests": 12500}, {"date": "2024-01-02", "revenue": 280.75, "requests": 13200}, {"date": "2024-01-03", "revenue": 310.25, "requests": 14800} ] } } ``` ``` -------------------------------- ### Get Billing Analysis API Request Source: https://context7.com/mathematrix/coai/llms.txt This API endpoint retrieves billing analytics for a specified time range. It requires an administrator JWT token for authorization. The response includes total revenue, subscription and usage revenue, and a daily breakdown. ```bash curl -X GET "https://your-domain.com/api/admin/analytics/billing?start_time=2024-01-01&end_time=2024-01-31" \ -H "Authorization: Bearer admin-jwt-token" ``` -------------------------------- ### GET /api/conversation/load Source: https://context7.com/mathematrix/coai/llms.txt Loads a specific conversation by its ID. Requires authentication. ```APIDOC ## GET /api/conversation/load ### Description Loads a specific conversation by its ID. Requires authentication. ### Method GET ### Endpoint /api/conversation/load ### Parameters #### Query Parameters - **id** (integer) - Required - The ID of the conversation to load. #### Request Body None ### Request Example ```bash curl -X GET "https://your-domain.com/api/conversation/load?id=1" \ -H "Authorization: Bearer your-jwt-token" ``` ### Response #### Success Response (200) - **status** (boolean) - Indicates if the request was successful. - **data** (object) - Contains the conversation details. - **id** (integer) - The unique identifier of the conversation. - **name** (string) - The name of the conversation. - **messages** (array) - An array of message objects. - **role** (string) - The role of the sender (e.g., 'user', 'assistant'). - **content** (string) - The message content. - **timestamp** (string) - The time the message was sent (ISO 8601 format). #### Response Example ```json { "status": true, "data": { "id": 1, "name": "Quantum Computing Discussion", "messages": [ { "role": "user", "content": "Explain quantum computing", "timestamp": "2024-01-05T10:30:00Z" }, { "role": "assistant", "content": "Quantum computing is...", "timestamp": "2024-01-05T10:30:15Z" } ] } } ``` ``` -------------------------------- ### User Registration API - Bash Source: https://context7.com/mathematrix/coai/llms.txt Registers a new user account by first requesting a verification code via email, then submitting the username, password, email, and verification code. Returns a JWT token and initial quota upon successful registration. Dependencies: Email verification service. ```bash curl -X POST https://your-domain.com/api/verify \ -H "Content-Type: application/json" \ -d '{ "email": "user@example.com" }' # Response: { "status": true } # Then register with the code curl -X POST https://your-domain.com/api/register \ -H "Content-Type: application/json" \ -d '{ "username": "newuser", "password": "SecurePass123!", "email": "user@example.com", "code": "123456" }' # Response { "status": true, "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Im5ld3VzZXIiLCJwYXNzd29yZCI6Imhhc2giLCJleHAiOjE3MDk5OTk5OTl9.signature", "quota": 5.0 } ``` -------------------------------- ### GET /api/conversation/view Source: https://context7.com/mathematrix/coai/llms.txt Views a shared conversation using its hash. No authentication required. ```APIDOC ## GET /api/conversation/view ### Description Views a shared conversation using its hash. No authentication required. ### Method GET ### Endpoint /api/conversation/view ### Parameters #### Query Parameters - **hash** (string) - Required - The hash of the shared conversation. #### Request Body None ### Request Example ```bash curl -X GET "https://your-domain.com/api/conversation/view?hash=abc123xyz789" ``` ### Response #### Success Response (200) - **status** (boolean) - Indicates if the request was successful. - **data** (object) - Contains the conversation details. - **name** (string) - The name of the conversation. - **messages** (array) - An array of message objects. - **role** (string) - The role of the sender (e.g., 'user', 'assistant'). - **content** (string) - The message content. #### Response Example ```json { "status": true, "data": { "name": "My Quantum Computing Discussion", "messages": [ {"role": "user", "content": "Explain quantum computing"}, {"role": "assistant", "content": "Quantum computing is..."}, {"role": "user", "content": "What are practical applications?"}, {"role": "assistant", "content": "Practical applications include..."} ] } } ``` ``` -------------------------------- ### GET /api/conversation/list Source: https://context7.com/mathematrix/coai/llms.txt Retrieves a list of user's conversation history with pagination support. ```APIDOC ## GET /api/conversation/list ### Description Retrieves a list of user's conversation history. Supports pagination. ### Method GET ### Endpoint /api/conversation/list ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number to retrieve. - **limit** (integer) - Optional - The number of conversations per page. ### Request Example ```bash curl -X GET https://your-domain.com/api/conversation/list \ -H "Authorization: Bearer your-jwt-token" ``` ### Response #### Success Response (200) - **status** (boolean) - Indicates success of the operation. - **data** (array of objects) - A list of conversations. - **id** (string) - The unique identifier of the conversation. - **title** (string) - The title of the conversation. - **createdAt** (string) - The timestamp when the conversation was created. #### Response Example ```json { "status": true, "data": [ { "id": "conv-123abc", "title": "My first conversation", "createdAt": "2023-10-27T10:00:00Z" }, { "id": "conv-456def", "title": "AI prompt ideas", "createdAt": "2023-10-26T15:30:00Z" } ] } ``` ``` -------------------------------- ### System Configuration File (config.yaml) Source: https://context7.com/mathematrix/coai/llms.txt This file contains the complete system configuration for Chat Nio, including server settings, database connection details (MySQL), Redis configuration, security secrets, and initial user quota. It also includes options to control user registration and relay services. ```yaml server: port: "8000" serve_static: true allow_origins: ["https://yourdomain.com"] secret: "your-jwt-secret-key-min-32-chars" database: type: "mysql" host: "localhost" port: 3306 username: "root" password: "password" database: "chatnio" redis: host: "localhost" port: 6379 password: "" db: 0 close_registration: false close_relay: false initial_quota: 5.0 ``` -------------------------------- ### User Login API - Bash Source: https://context7.com/mathematrix/coai/llms.txt Authenticates a user using their username or email and password. Upon successful authentication, it returns a JWT token valid for 30 days and the user's current information, including their quota balance. Dependencies: User database. ```bash curl -X POST https://your-domain.com/api/login \ -H "Content-Type: application/json" \ -d '{ "username": "newuser", "password": "SecurePass123!" }' # Response { "status": true, "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "user": { "username": "newuser", "email": "user@example.com", "admin": false, "quota": 5.0, "subscription": { "level": 0, "expired": null } } } ``` -------------------------------- ### Docker Compose Deployment Configuration Source: https://context7.com/mathematrix/coai/llms.txt This Docker Compose file defines the services for deploying the Chat Nio stack, including the main application, MySQL database, and Redis cache. It manages container networking, volumes for persistent data, and environment variables for configuration. Automatic database initialization is handled. ```yaml version: '3.8' services: chatnio: image: programzmh/chatnio:latest container_name: chatnio ports: - "8000:8000" volumes: - ./config:/config - ./logs:/logs - ./storage:/storage environment: MYSQL_HOST: mysql MYSQL_PORT: 3306 MYSQL_DB: chatnio MYSQL_USER: root MYSQL_PASSWORD: chatnio123456 REDIS_HOST: redis REDIS_PORT: 6379 SECRET: your-jwt-secret-change-this SERVE_STATIC: "true" depends_on: - mysql - redis mysql: image: mysql:8.0 container_name: chatnio-mysql volumes: - ./db:/var/lib/mysql environment: MYSQL_ROOT_PASSWORD: chatnio123456 MYSQL_DATABASE: chatnio command: --default-authentication-plugin=mysql_native_password redis: image: redis:alpine container_name: chatnio-redis volumes: - ./redis:/data # Start services # docker-compose up -d # View logs # docker-compose logs -f chatnio # Update to latest version # docker-compose pull && docker-compose up -d ``` -------------------------------- ### Get Error Analysis Source: https://context7.com/mathematrix/coai/llms.txt Retrieves an error analysis for a specified duration. This endpoint provides total errors, error rate, and breakdowns by type and channel. ```APIDOC ## GET /api/admin/analytics/error ### Description Retrieves an error analysis for a specified duration. ### Method GET ### Endpoint `/api/admin/analytics/error` ### Query Parameters - **hours** (integer) - Required - The duration in hours for the error analysis. ### Request Example ``` GET /api/admin/analytics/error?hours=24 ``` ### Response #### Success Response (200) - **status** (boolean) - Indicates if the request was successful. - **data** (object) - Contains the error analysis details: - **total_errors** (integer) - The total number of errors. - **error_rate** (number) - The overall error rate. - **by_type** (array) - An array of objects detailing errors by type: - **type** (string) - The type of error (e.g., "rate_limit"). - **count** (integer) - The number of errors of this type. - **percentage** (number) - The percentage of total errors of this type. - **by_channel** (array) - An array of objects detailing errors by channel: - **channel** (string) - The channel where errors occurred. - **errors** (integer) - The number of errors for this channel. #### Response Example ```json { "status": true, "data": { "total_errors": 320, "error_rate": 0.021, "by_type": [ {"type": "rate_limit", "count": 150, "percentage": 46.9}, {"type": "timeout", "count": 85, "percentage": 26.6}, {"type": "invalid_key", "count": 50, "percentage": 15.6}, {"type": "server_error", "count": 35, "percentage": 10.9} ], "by_channel": [ {"channel": "OpenAI GPT-4 Primary", "errors": 120}, {"channel": "Azure OpenAI Backup", "errors": 80}, {"channel": "Claude Primary", "errors": 120} ] } } ``` ``` -------------------------------- ### POST /api/admin/channel/create Source: https://context7.com/mathematrix/coai/llms.txt Configures a new AI provider channel with specified settings like load balancing, retry logic, model mapping, and access restrictions. Supports multiple API keys and priority-based routing. ```APIDOC ## POST /api/admin/channel/create ### Description Configures a new AI provider channel with load balancing, retry logic, and model mapping. Supports multiple API keys, priority-based routing, and user group restrictions. ### Method POST ### Endpoint /api/admin/channel/create ### Parameters #### Request Body - **name** (string) - Required - The name of the AI channel. - **type** (string) - Required - The type of the AI provider (e.g., "openai", "azure"). - **priority** (integer) - Optional - The priority of the channel (higher value means higher priority). - **weight** (integer) - Optional - The weight for load balancing. - **models** (array of strings) - Required - List of models supported by this channel. - **retry** (integer) - Optional - Number of retries on failure. - **secret** (string) - Required - API key(s) for the provider, separated by newline for multiple keys. - **endpoint** (string) - Required - The API endpoint for the AI provider. - **mapper** (string) - Optional - Model mapping rules (e.g., "model_a>model_b"). - **state** (boolean) - Optional - Whether the channel is enabled (true) or disabled (false). - **group** (array of strings) - Optional - User groups allowed to access this channel. - **proxy** (object) - Optional - Proxy configuration. - **proxy_type** (integer) - Required - Type of proxy (0: None, 1: HTTP, 2: SOCKS4, 3: SOCKS5). - **proxy** (string) - Optional - Proxy address. - **username** (string) - Optional - Proxy username. - **password** (string) - Optional - Proxy password. ### Request Example ```json { "name": "OpenAI GPT-4 Primary", "type": "openai", "priority": 10, "weight": 100, "models": ["gpt-4", "gpt-4-turbo", "gpt-4-vision-preview"], "retry": 3, "secret": "sk-proj-abc123xyz789\nsk-proj-def456uvw012", "endpoint": "https://api.openai.com", "mapper": "gpt-4>gpt-4-0613\ngpt-4-turbo>gpt-4-turbo-2024-04-09", "state": true, "group": ["basic", "standard", "pro"], "proxy": { "proxy_type": 0, "proxy": "", "username": "", "password": "" } } ``` ### Response #### Success Response (200) - **status** (boolean) - Indicates success of the operation. - **id** (integer) - The unique identifier of the created channel. - **message** (string) - A confirmation message. #### Response Example ```json { "status": true, "id": 15, "message": "Channel created successfully" } ``` ``` -------------------------------- ### User Registration API Source: https://context7.com/mathematrix/coai/llms.txt Allows users to register for a new account. This involves two steps: requesting a verification code via email and then completing registration with the provided code. ```APIDOC ## POST /api/verify ### Description Requests a verification code to be sent to the specified email address for user registration. ### Method POST ### Endpoint /api/verify ### Parameters #### Request Body - **email** (string) - Required - The email address to send the verification code to. ### Request Example ```json { "email": "user@example.com" } ``` ### Response #### Success Response (200) - **status** (boolean) - Indicates if the verification code request was successful. #### Response Example ```json { "status": true } ``` ## POST /api/register ### Description Registers a new user account using a verification code previously sent to their email. Upon successful registration, a JWT token and initial quota are provided. ### Method POST ### Endpoint /api/register ### Parameters #### Request Body - **username** (string) - Required - The desired username for the new account. - **password** (string) - Required - The password for the new account. - **email** (string) - Required - The email address associated with the account. - **code** (string) - Required - The verification code received via email. ### Request Example ```json { "username": "newuser", "password": "SecurePass123!", "email": "user@example.com", "code": "123456" } ``` ### Response #### Success Response (200) - **status** (boolean) - Indicates if the registration was successful. - **token** (string) - JWT token for user authentication. - **quota** (float) - The initial quota allocated to the new user. #### Response Example ```json { "status": true, "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Im5ld3VzZXIiLCJwYXNzd29yZCI6Imhhc2giLCJleHAiOjE3MDk5OTk5OTl9.signature", "quota": 5.0 } ``` ``` -------------------------------- ### Vision/Image Understanding with CoAI API (Bash) Source: https://context7.com/mathematrix/coai/llms.txt Demonstrates how to enable multimodal capabilities by sending images with user messages. Images can be provided either as base64-encoded strings or public URLs. This allows the model to analyze and interpret image content. The `gpt-4-vision-preview` model is used for this functionality. ```bash curl -X POST https://your-domain.com/api/v1/chat/completions \ -H "Authorization: Bearer sk-your-api-key" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4-vision-preview", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "What is in this image?" }, { "type": "image_url", "image_url": { "url": "https://example.com/image.jpg" } } ] } ], "max_tokens": 500 }' ``` ```json { "choices": [{ "message": { "role": "assistant", "content": "This image shows a beautiful sunset over a mountain range. The sky displays vibrant orange and pink hues, with silhouetted peaks in the foreground..." }, "finish_reason": "stop" }], "usage": {"prompt_tokens": 1285, "completion_tokens": 89, "total_tokens": 1374} } ```