### Build Frontend Assets Source: https://deepwiki.com/Wei-Shaw/sub2api/2-getting-started Navigates to the frontend directory, installs dependencies, and builds the frontend assets using pnpm. ```bash cd frontend pnpm install pnpm run build ``` -------------------------------- ### Install Sub2API using Script Source: https://deepwiki.com/Wei-Shaw/sub2api/2-getting-started Automates downloading the latest binary, setting up a system user, and configuring a systemd service for automatic restarts. ```bash curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/install.sh | sudo bash ``` -------------------------------- ### Start Docker Compose Services Source: https://deepwiki.com/Wei-Shaw/sub2api/2-getting-started Execute this command to launch the Sub2API application along with its PostgreSQL and Redis dependencies. The `sub2api` service will automatically configure itself on first launch if `AUTO_SETUP=true` is enabled. ```bash docker compose up -d ``` -------------------------------- ### Frontend Build Commands Source: https://deepwiki.com/Wei-Shaw/sub2api/9-development-guide Commands to install frontend dependencies and build the production assets using pnpm. The output is placed in `backend/internal/web/dist/`. ```bash # Navigate to frontend directory cd frontend   # Install dependencies pnpm install --frozen-lockfile   # Production build (outputs to backend/internal/web/dist/) pnpm run build ``` -------------------------------- ### Copy Environment File Source: https://deepwiki.com/Wei-Shaw/sub2api/2-getting-started Copy the example environment file to `.env` and edit it to set essential security variables like `POSTGRES_PASSWORD`, `JWT_SECRET`, and `TOTP_ENCRYPTION_KEY`. The `docker-deploy.sh` script can help generate these secrets. ```bash cp deploy/.env.example .env # Edit .env to set POSTGRES_PASSWORD, JWT_SECRET, and TOTP_ENCRYPTION_KEY nano .env ``` -------------------------------- ### GET /api/v1/admin/settings Source: https://deepwiki.com/Wei-Shaw/sub2api/8-api-reference Retrieves comprehensive system configuration settings. This endpoint is managed by the admin.SettingHandler. ```APIDOC ## GET /api/v1/admin/settings ### Description Retrieves comprehensive system configuration via `admin.SettingHandler`. ### Method GET ### Endpoint /api/v1/admin/settings ### Parameters #### Query Parameters None #### Path Parameters None ### Request Body None ### Response #### Success Response (200) - **Configuration Data** (object) - Comprehensive system configuration details. ### Request Example None ### Response Example ```json { "setting1": "value1", "setting2": "value2" } ``` ``` -------------------------------- ### Docker Multi-Stage Build Source: https://deepwiki.com/Wei-Shaw/sub2api/9-development-guide Example of a Dockerfile for a production build, utilizing a multi-stage process to compile both frontend and backend into a minimal Alpine-based image. ```dockerfile FROM golang:1.21-alpine AS builder WORKDIR /app # Install pnpm and Node.js RUN apk add --no-cache nodejs npm RUN npm install -g pnpm # Copy backend and download dependencies COPY ./backend . RUN go mod download # Copy frontend and install dependencies COPY ./frontend ./frontend RUN cd frontend && pnpm install --frozen-lockfile && pnpm run build # Build the Go application with embedded frontend RUN CGO_ENABLED=0 GOOS=linux go build -tags embed -o /sub2api ./cmd/server # --- Production Image --- FROM alpine:latest WORKDIR /app # Copy the compiled binary from the builder stage COPY --from=builder /sub2api . # Expose the port the application runs on EXPOSE 8080 # Command to run the application CMD ["./sub2api"] ``` -------------------------------- ### GET /api/v1/user/profile Source: https://deepwiki.com/Wei-Shaw/sub2api/8-api-reference Returns current user profile and balance information. ```APIDOC ## GET /api/v1/user/profile ### Description Returns current user profile and balance information. ### Method GET ### Endpoint /api/v1/user/profile ### Parameters #### Headers - **Authorization** (string) - Required - Bearer token for authentication (e.g., `Bearer `). ### Response #### Success Response (200) - **username** (string) - The user's username. - **balance** (number) - The user's current balance. #### Response Example ```json { "username": "testuser", "balance": 100.50 } ``` ``` -------------------------------- ### GET /api/v1/usage Source: https://deepwiki.com/Wei-Shaw/sub2api/8-api-reference Retrieves usage statistics and trends for the platform. ```APIDOC ## GET /api/v1/usage ### Description Retrieves usage statistics and trends for the platform. ### Method GET ### Endpoint /api/v1/usage ### Parameters #### Query Parameters - **start_date** (string) - Optional. The start date for the usage data (YYYY-MM-DD). - **end_date** (string) - Optional. The end date for the usage data (YYYY-MM-DD). #### Path Parameters None ### Request Body None ### Response #### Success Response (200) - **total_requests** (integer) - The total number of requests made. - **data_transfer_gb** (float) - The total data transferred in gigabytes. ### Request Example None ### Response Example ```json { "total_requests": 15000, "data_transfer_gb": 250.5 } ``` ``` -------------------------------- ### GET /api/v1/usage Source: https://deepwiki.com/Wei-Shaw/sub2api/8-api-reference Retrieves personal usage logs and token consumption statistics. ```APIDOC ## GET /api/v1/usage ### Description Retrieves personal usage logs and token consumption statistics. ### Method GET ### Endpoint /api/v1/usage ### Parameters #### Headers - **Authorization** (string) - Required - Bearer token for authentication (e.g., `Bearer `). ### Response #### Success Response (200) - **usage** (array) - A list of usage records. - **timestamp** (string) - The time of the usage record. - **tokens_consumed** (integer) - The number of tokens consumed. #### Response Example ```json { "usage": [ { "timestamp": "2023-10-27T10:00:00Z", "tokens_consumed": 50 }, { "timestamp": "2023-10-27T11:00:00Z", "tokens_consumed": 75 } ] } ``` ``` -------------------------------- ### GET /api/v1/user/profile Source: https://deepwiki.com/Wei-Shaw/sub2api/8-api-reference Retrieves the profile information for the currently authenticated user. ```APIDOC ## GET /api/v1/user/profile ### Description Retrieves the profile information for the currently authenticated user. ### Method GET ### Endpoint /api/v1/user/profile ### Parameters #### Query Parameters None #### Path Parameters None ### Request Body None ### Response #### Success Response (200) - **user_id** (string) - The unique identifier for the user. - **username** (string) - The username of the user. - **email** (string) - The email address of the user. ### Request Example None ### Response Example ```json { "user_id": "uuid-1234-abcd", "username": "user123", "email": "user123@example.com" } ``` ``` -------------------------------- ### Build Backend Binary Source: https://deepwiki.com/Wei-Shaw/sub2api/2-getting-started Navigates to the backend directory and compiles the Go application, embedding frontend assets into the binary. ```bash cd ../backend go build -o sub2api ./cmd/server ``` -------------------------------- ### Backend Build Commands Source: https://deepwiki.com/Wei-Shaw/sub2api/9-development-guide Commands to download Go dependencies and build the backend binary. Use `-tags embed` for production builds that include the frontend. ```bash # Navigate to backend directory cd backend   # Download dependencies go mod download   # Build without frontend embedding (development mode) go build -o sub2api ./cmd/server   # Build with frontend embedding (production mode) go build -tags embed -o sub2api ./cmd/server ``` -------------------------------- ### Application Initialization with Dependency Injection Source: https://deepwiki.com/Wei-Shaw/sub2api Details the dependency injection flow for initializing the Application struct, which serves as the top-level container for the HTTP server and background services. ```text Dependency Injection Flow ``` -------------------------------- ### Manage System Settings Source: https://deepwiki.com/Wei-Shaw/sub2api/6-administrator-guide System-wide configuration is managed through the SettingService and SettingsView. ```go SettingService ``` ```go SettingsView ``` -------------------------------- ### Manage Settings via Repository Source: https://deepwiki.com/Wei-Shaw/sub2api/6-administrator-guide Settings are stored as key-value pairs in the database and managed via SettingRepository. Uses singleflight and in-process caching for high-frequency settings. ```go SettingRepository ``` -------------------------------- ### Wire Provider Sets for Dependency Injection Source: https://deepwiki.com/Wei-Shaw/sub2api Lists the Wire provider sets used for dependency injection, covering configuration, repository clients, business logic services, and HTTP handlers. ```text Wire Provider Sets: * config.ProviderSet: Configuration loader 34 * repository.ProviderSet: Database clients, caches, and HTTP clients 37 * service.ProviderSet: Core business logic 38 * handler.ProviderSet: HTTP request handlers 41 ``` -------------------------------- ### List Proxies with Account Counts Source: https://deepwiki.com/Wei-Shaw/sub2api/6-administrator-guide Administrators can list proxies along with their associated account counts for load balancing purposes. ```go AdminService.ListProxiesWithAccountCounts() ``` -------------------------------- ### System Architecture Overview Source: https://deepwiki.com/Wei-Shaw/sub2api Illustrates the deployment topology and component interaction within the Sub2API system. This diagram helps understand the three-tier architecture and optional reverse proxy layer. ```text System Component Interaction ``` -------------------------------- ### Sub2API System Architecture Overview Source: https://deepwiki.com/Wei-Shaw/sub2api/1-overview Illustrates the deployment topology and component interaction in the Sub2API system, following a three-tier architecture. ```text ``` -------------------------------- ### Update User Balance and Concurrency Source: https://deepwiki.com/Wei-Shaw/sub2api/6-administrator-guide Demonstrates how administrators can modify user balances and concurrent request limits using specific service methods. Tracks balance history and recharge totals. ```go UpdateUserBalance(userId, amount) BatchUpdateConcurrency(userIds, limit) ``` -------------------------------- ### Account Selection - RPM Cache Source: https://deepwiki.com/Wei-Shaw/sub2api/4-architecture Provides a Redis-based cache for tracking requests per minute (RPM) using a sliding window approach for real-time load metrics. ```Go func NewRPMCache(redisClient redis.Client) RPMCache { return &redisRPMCache{client: redisClient} } ``` -------------------------------- ### Check Proxy Quality Source: https://deepwiki.com/Wei-Shaw/sub2api/6-administrator-guide Use the AdminService to check proxy quality, including exit IP information and latency. ```go AdminService.CheckProxyQuality(proxy) ``` -------------------------------- ### Test Proxy Connectivity Source: https://deepwiki.com/Wei-Shaw/sub2api/6-administrator-guide Use the AdminService to test proxy connectivity. ```go AdminService.TestProxy(proxy) ``` -------------------------------- ### Account Model with Scheduling and Status Source: https://deepwiki.com/Wei-Shaw/sub2api/3-core-concepts The Account entity stores upstream credentials and supports dynamic scheduling based on priority, concurrency, and load factor. It includes schedulability flags and a Status field for lifecycle tracking. ```Go type Account struct { priority int concurrency int load_factor float64 schedulable bool status string // e.g., active, inactive, error } ``` -------------------------------- ### Admin System Architecture Overview Source: https://deepwiki.com/Wei-Shaw/sub2api/6-administrator-guide Illustrates the layered architecture of the administrative interface, emphasizing the separation of concerns and the role of JWT authentication with admin privileges. ```text **Admin System Architecture** ``` ``` ``` -------------------------------- ### POST /v1/chat/completions Source: https://deepwiki.com/Wei-Shaw/sub2api/8-api-reference OpenAI-compatible Chat Completions endpoint. Routes to `OpenAIGateway.ChatCompletions` or `Gateway.ChatCompletions`. ```APIDOC ## POST /v1/chat/completions ### Description OpenAI-compatible Chat Completions endpoint. Routes to `OpenAIGateway.ChatCompletions` or `Gateway.ChatCompletions`. ### Method POST ### Endpoint /v1/chat/completions ### Parameters #### Request Body - **messages** (array) - Required - A list of messages comprising the conversation so far. - **model** (string) - Optional - ID of the model to use; please refer to the available models documentation. - **temperature** (number) - Optional - What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make output more random, while lower values like 0.2 will make it more focused and deterministic. ### Request Example ```json { "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who won the world series in 2020?"} ], "model": "gpt-3.5-turbo", "temperature": 0.7 } ``` ### Response #### Success Response (200) - **choices** (array) - A list of chat completion choices. - **message** (object) - The generated chat message. - **content** (string) - The content of the message. #### Response Example ```json { "choices": [ { "message": { "content": "The Los Angeles Dodgers won the World Series in 2020." } } ] } ``` ``` -------------------------------- ### POST /v1beta/models/*modelAction Source: https://deepwiki.com/Wei-Shaw/sub2api/8-api-reference Gemini native API compatibility layer. It normalizes inbound paths to `/v1beta/models` for upstream processing. ```APIDOC ## POST /v1beta/models/*modelAction ### Description Gemini native API compatibility layer. It normalizes inbound paths to `/v1beta/models` for upstream processing. ### Method POST ### Endpoint /v1beta/models/*modelAction ### Parameters #### Path Parameters - **modelAction** (string) - Required - The specific action to perform on the model (e.g., "generateContent"). #### Request Body - **contents** (array) - Required - The content to send to the model. - **generationConfig** (object) - Optional - Configuration for generation. ### Request Example ```json { "contents": [ { "parts": [ {"text": "Explain the concept of recursion."} ] } ], "generationConfig": { "maxOutputTokens": 200 } } ``` ### Response #### Success Response (200) - **candidates** (array) - List of model-generated candidates. - **content** (object) - The generated content. #### Response Example ```json { "candidates": [ { "content": { "parts": [ {"text": "Recursion is a method where the solution to a problem depends on smaller instances of the same problem..."} ] } } ] } ``` ``` -------------------------------- ### Account Selection - Concurrency Cache Source: https://deepwiki.com/Wei-Shaw/sub2api/4-architecture Implements a concurrency cache using a Redis ZSET to track active request IDs per account for load-aware scheduling. ```Go func ProvideConcurrencyCache(redisClient redis.Client) ConcurrencyCache { return NewConcurrencyCache(redisClient) } ``` -------------------------------- ### Project Directory Layout Source: https://deepwiki.com/Wei-Shaw/sub2api/9-development-guide Illustrates the directory structure of the Sub2API project, showing the organization of backend, frontend, and deployment-related files. ```plaintext sub2api/ ├── backend/ │ ├── cmd/ │ │ └── server/ # Application entry point │ │ ├── main.go # Main function, flag parsing │ │ └── VERSION # Version file for releases │ ├── internal/ │ │ ├── handler/ # HTTP handlers (Gin) │ │ ├── service/ # Business logic layer │ │ ├── repository/ # Data access layer (Ent) │ │ └── web/ # Embedded frontend assets │ ├── ent/ # Ent ORM generated code and schemas │ └── migrations/ # Raw SQL migration files ├── frontend/ │ ├── src/ # Vue source code ├── deploy/ │ ├── docker-compose.yml # Production Docker Compose │ └── install.sh # One-line install script └── Dockerfile # Multi-stage production build ``` -------------------------------- ### Usage Log with Cost Calculation Fields Source: https://deepwiki.com/Wei-Shaw/sub2api/3-core-concepts The UsageLog entity records input, output, and actual costs, incorporating various rate multipliers for billing and cost calculation. ```Go type UsageLog struct { input_cost float64 output_cost float64 actual_cost float64 } ``` -------------------------------- ### Verify Docker Deployment Source: https://deepwiki.com/Wei-Shaw/sub2api/2-getting-started Check the logs of the `sub2api` container to confirm a successful deployment. Any auto-generated credentials, such as `ADMIN_PASSWORD`, will be displayed here if not explicitly set in the environment variables. ```bash docker compose logs -f sub2api ``` -------------------------------- ### POST /v1beta/models/*modelAction Source: https://deepwiki.com/Wei-Shaw/sub2api/8-api-reference Allows performing specific actions on models, indicated by the wildcard path parameter. ```APIDOC ## POST /v1beta/models/*modelAction ### Description Allows performing specific actions on models. ### Method POST ### Endpoint /v1beta/models/*modelAction ### Parameters #### Path Parameters - **modelAction** (string) - The specific action to perform on the model. #### Query Parameters None #### Request Body - **action_details** (object) - Details specific to the model action. ### Request Example ```json { "action_details": { "param1": "value1" } } ``` ### Response #### Success Response (200) - **result** (object) - The outcome of the model action. #### Response Example ```json { "result": { "status": "completed" } } ``` ``` -------------------------------- ### Account Validation Logic Source: https://deepwiki.com/Wei-Shaw/sub2api/6-administrator-guide The AccountTestService allows administrators to validate account credentials and connectivity. ```go AccountTestService ``` -------------------------------- ### User Model with Billing and Concurrency Source: https://deepwiki.com/Wei-Shaw/sub2api/3-core-concepts The User entity includes fields for pay-as-you-go balance and concurrency limits. Administrators can use AdminUser DTO for notes and group-specific pricing overrides. ```Go type User struct { balance float64 concurrency int } type AdminUser struct { User notes string group_rates map[string]float64 role string } ``` -------------------------------- ### POST /api/v1/auth/login Source: https://deepwiki.com/Wei-Shaw/sub2api/8-api-reference Authenticates a user and returns a JWT token. ```APIDOC ## POST /api/v1/auth/login ### Description Authenticates a user and returns a JWT token. ### Method POST ### Endpoint /api/v1/auth/login ### Parameters #### Request Body - **username** (string) - Required - The user's username. - **password** (string) - Required - The user's password. ### Request Example ```json { "username": "testuser", "password": "password123" } ``` ### Response #### Success Response (200) - **token** (string) - The JWT token for authentication. #### Response Example ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } ``` ``` -------------------------------- ### Account Selection - Scheduler Cache Source: https://deepwiki.com/Wei-Shaw/sub2api/4-architecture Manages a cache for account metadata, optimized for fetching multiple accounts using chunked MGET operations in Redis. ```Go func ProvideSchedulerCache(redisClient redis.Client) SchedulerCache { return NewSchedulerCache(redisClient) } ``` -------------------------------- ### POST /api/v1/auth/login Source: https://deepwiki.com/Wei-Shaw/sub2api/8-api-reference Handles user login requests, likely for authentication and session establishment. ```APIDOC ## POST /api/v1/auth/login ### Description Handles user login requests. ### Method POST ### Endpoint /api/v1/auth/login ### Parameters #### Query Parameters None #### Path Parameters None #### Request Body - **username** (string) - The user's username. - **password** (string) - The user's password. ### Request Example ```json { "username": "user123", "password": "securepassword" } ``` ### Response #### Success Response (200) - **token** (string) - The authentication token upon successful login. #### Response Example ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } ``` ``` -------------------------------- ### POST /v1/chat/completions Source: https://deepwiki.com/Wei-Shaw/sub2api/8-api-reference Initiates a chat completion request, likely for conversational AI interactions. ```APIDOC ## POST /v1/chat/completions ### Description Initiates a chat completion request. ### Method POST ### Endpoint /v1/chat/completions ### Parameters #### Query Parameters None #### Path Parameters None #### Request Body - **prompt** (string) - The user's input prompt for the chat. - **model** (string) - The model to use for generating the completion. ### Request Example ```json { "prompt": "What is the weather today?", "model": "gpt-3.5-turbo" } ``` ### Response #### Success Response (200) - **completion** (string) - The generated response from the model. #### Response Example ```json { "completion": "The weather today is sunny." } ``` ``` -------------------------------- ### Account Types for Platform Integration Source: https://deepwiki.com/Wei-Shaw/sub2api/3-core-concepts The Account struct categorizes accounts using Platform and Type fields, supporting various integration methods like OAuth and API key-based access. ```Go type Account struct { Platform string Type string // e.g., AccountTypeOAuth, AccountTypeSetupToken, AccountTypeAPIKey } ``` -------------------------------- ### Confirm Mixed Channel Risk Source: https://deepwiki.com/Wei-Shaw/sub2api/6-administrator-guide Allows administrators to explicitly confirm the risk associated with binding accounts to groups of different platforms, overriding a safety check. ```go ConfirmMixedChannelRisk(accountId, groupId) ``` -------------------------------- ### Group Model for Account Pooling and Routing Source: https://deepwiki.com/Wei-Shaw/sub2api/3-core-concepts A Group defines a logical pool of accounts for a specific platform, managing rate multipliers, subscription types, model routing, and RPM limits. ```Go type Group struct { platform string rate_multiplier float64 subscription_type string model_routing map[string]string rpm_limit int } ``` -------------------------------- ### Gateway Request Flow - Unified Routing Source: https://deepwiki.com/Wei-Shaw/sub2api/4-architecture Handles platform-specific endpoints, manages request slots using ConcurrencyHelper, logs token consumption asynchronously with UsageRecordWorkerPool, and normalizes incoming request paths via InboundEndpointMiddleware. ```Go func (h *GatewayHandler) Handle(c *gin.Context) { // ... other handlers ... // Concurrency control var concurrencyHelper = ConcurrencyHelper{} concurrencyHelper.AcquireSlot(c) // Usage logging var usageRecordWorkerPool = UsageRecordWorkerPool{} usageRecordWorkerPool.LogUsage(c) // Unified routing and handling var inboundEndpointMiddleware = InboundEndpointMiddleware{} canonicalPath := inboundEndpointMiddleware.NormalizePath(c.Request.URL.Path) upstreamEndpoint := DeriveUpstreamEndpoint(canonicalPath, selectedAccount.Platform) // ... forward request ... } ``` -------------------------------- ### POST /v1/responses Source: https://deepwiki.com/Wei-Shaw/sub2api/8-api-reference OpenAI Responses API endpoint (used by Codex/ChatGPT internal API). Supports subpath routing (e.g., `/v1/responses/compact`). ```APIDOC ## POST /v1/responses ### Description OpenAI Responses API endpoint (used by Codex/ChatGPT internal API). Supports subpath routing (e.g., `/v1/responses/compact`). ### Method POST ### Endpoint /v1/responses ### Parameters #### Query Parameters - **subpath** (string) - Optional - Specifies a subpath for routing, e.g., "compact". #### Request Body - **prompt** (string) - Required - The prompt to send to the model. - **model** (string) - Optional - The model to use for generation. ### Request Example ```json { "prompt": "Write a short story about a robot.", "model": "text-davinci-003" } ``` ### Response #### Success Response (200) - **choices** (array) - List of generated text choices. - **text** (string) - The generated text. #### Response Example ```json { "choices": [ { "text": "Once upon a time, in a futuristic city, lived a robot named Bolt..." } ] } ``` ``` -------------------------------- ### API Key with Rate Limiting and IP Restrictions Source: https://deepwiki.com/Wei-Shaw/sub2api/3-core-concepts An APIKey serves as a gateway access credential, supporting binding to a group_id, multi-window rate limiting, quota tracking, and IP whitelisting/blacklisting. ```Go type APIKey struct { group_id string quotas map[string]int64 ip_whitelist []string ip_blacklist []string } ``` -------------------------------- ### POST /v1/responses Source: https://deepwiki.com/Wei-Shaw/sub2api/8-api-reference Handles the posting of responses, likely in a conversational or feedback context. ```APIDOC ## POST /v1/responses ### Description Handles the posting of responses. ### Method POST ### Endpoint /v1/responses ### Parameters #### Query Parameters None #### Path Parameters None #### Request Body - **response** (string) - The content of the response to be posted. ### Request Example ```json { "response": "Thank you for your message." } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the result of the response posting operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Test Suite Mapping Source: https://deepwiki.com/Wei-Shaw/sub2api/9-development-guide Overview of the testing architecture in Sub2API, outlining the different types of tests and their corresponding locations or responsibilities within the project. ```plaintext backend/internal/handler -> handler_test backend/internal/service -> service_test backend/internal/repository -> repository_test backend/ent -> ent_test frontend/src -> frontend_test ``` -------------------------------- ### API Key Authentication Headers Source: https://deepwiki.com/Wei-Shaw/sub2api/8-api-reference Gateway endpoints authenticate using API keys. The middleware validates the key and resolves the associated user, group, and subscription context. Use either the 'x-api-key' or 'Authorization: Bearer' header. ```http Request Headers: x-api-key: sk-ant-mirror-xxxxx OR Authorization: Bearer sk-ant-mirror-xxxxx ``` -------------------------------- ### POST /v1/messages Source: https://deepwiki.com/Wei-Shaw/sub2api/8-api-reference Handles the posting of messages, likely for processing or forwarding within the system. ```APIDOC ## POST /v1/messages ### Description Handles the posting of messages for processing. ### Method POST ### Endpoint /v1/messages ### Parameters #### Query Parameters None #### Path Parameters None #### Request Body - **message** (string) - The content of the message to be posted. ### Request Example ```json { "message": "Hello, world!" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the result of the message posting operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Replace User Group Source: https://deepwiki.com/Wei-Shaw/sub2api/6-administrator-guide Enables replacing a user's exclusive group, which includes migrating associated keys and permissions. ```go ReplaceUserGroup(userId, newGroupId) ``` -------------------------------- ### Service Layer Responsibilities Source: https://deepwiki.com/Wei-Shaw/sub2api Outlines the responsibilities of various services within the Sub2API's service layer, including authentication, billing, API key management, and concurrency control. ```text Service| Responsibility ---|--- `AuthService`| JWT authentication, registration, and TOTP 76 `BillingCacheService`| User balance caching and quota checks 68 `APIKeyService`| API key lifecycle and auth caching 70 `ConcurrencyService`| Multi-layer concurrency slot management 98 `TokenRefreshService`| Background OAuth token rotation 48-74 `DashboardAggregationService`| Statistics aggregation and caching 145-150 `OAuthService`| Platform-specific OAuth workflows 51 `PricingService`| Model pricing rules and remote data sync 24-31 ``` -------------------------------- ### Account and Group Entities Source: https://deepwiki.com/Wei-Shaw/sub2api/3-core-concepts The Account and Group entities form the backbone of the routing system in Sub2API. ```Go type Account struct { Platform string Type string } ``` -------------------------------- ### JWT Authentication Header Source: https://deepwiki.com/Wei-Shaw/sub2api/8-api-reference User and admin endpoints authenticate using JWT tokens passed in the 'Authorization: Bearer ' header. Tokens are obtained via login and contain user ID and role claims. ```http Authorization: Bearer ``` -------------------------------- ### Code Entity Space Mapping Source: https://deepwiki.com/Wei-Shaw/sub2api/9-development-guide Conceptual mapping of code entities within the Sub2API project, indicating the organization and relationships between different modules. ```plaintext backend/internal/handler -> handler backend/internal/service -> service backend/internal/repository -> repository backend/ent -> ent backend/migrations -> migrations frontend/src -> frontend ``` -------------------------------- ### POST /v1/messages Source: https://deepwiki.com/Wei-Shaw/sub2api/8-api-reference Anthropic Claude-compatible messages endpoint. It automatically routes to either GatewayHandler.Messages or OpenAIGateway.Messages based on the group's platform. ```APIDOC ## POST /v1/messages ### Description Anthropic Claude-compatible messages endpoint. It automatically routes to either `GatewayHandler.Messages` or `OpenAIGateway.Messages` based on the group's platform. ### Method POST ### Endpoint /v1/messages ### Parameters #### Request Body - **messages** (array) - Required - List of messages for the conversation. - **model** (string) - Optional - The model to use for generating the response. - **max_tokens** (integer) - Optional - The maximum number of tokens to generate. ### Request Example ```json { "messages": [ {"role": "user", "content": "Hello, world!"} ], "model": "claude-2.1", "max_tokens": 100 } ``` ### Response #### Success Response (200) - **content** (array) - The generated response content. - **role** (string) - The role of the message sender (e.g., "assistant"). #### Response Example ```json { "content": [ {"type": "text", "text": "Hi there! How can I help you today?"} ], "role": "assistant" } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.