# GeminiRevolver An OpenAI v1 compatible API endpoint that rotates Gemini API keys to avoid rate limiting. Built with TypeScript and Node.js. ## Features - ๐Ÿ” **Password-based API key authentication** - Clients must provide a configured password as their API key - โš™๏ธ **Interactive Admin Console (`/admin`)** - Full web interface secured with your master API key for managing providers, keys, and model routing pipelines - ๐Ÿ’พ **Single JSON Persistence (`data/revolver-config.json`)** - API keys and provider definitions are persisted cleanly in a single JSON file with atomic writes - ๐ŸŒ **Multi-Provider Key Revolver** - Add Google AI Studio (Gemini), Groq Cloud, OpenAI, or any Custom OpenAI-compatible endpoints with multiple rotating API keys - ๐ŸŽฏ **Custom Model Fallback Chains** - Define custom model names with multi-tier failovers: `[Main Model (revolving keys) -> Fallback Tier 1 (revolving keys) -> Fallback Tier 2 ...]` - ๐Ÿ“Š **Public statistics dashboard** - Live metrics page at the root (`/`) showing request count (went through, failed, cancelled) and token usage (input + output) with zero-knowledge privacy - ๐Ÿ“ **Request/response logging** - Logs all API requests and responses to JSON files - โšก **Automated Rate Limit & Error Failover** - Automatically detects `429`, quota exhaustion, or server errors before streaming begins and rotates keys or cascades to fallback tiers - ๐Ÿงช **Live Playground & Key Verifier** - Test individual provider keys and inspect step-by-step trace metadata directly from the Admin console - ๐Ÿณ **Docker support** - Containerized deployment with Docker and Docker Compose - ๐ŸŒ **Cloudflare Tunnel integration** - Securely expose your API via Cloudflare tunnel - โฑ๏ธ **Cloudflare 524 Anti-Timeout Engine** - Prevents Cloudflare Free/Pro/Biz 100s proxy timeouts on long generations via immediate SSE header flushing, periodic `: keep-alive` comment heartbeats, and RFC 8259 chunked whitespace keep-alives for non-streaming requests ## Setup ### Prerequisites - Node.js (v18 or higher) - npm or yarn - Gemini API keys (get free keys from [Google AI Studio](https://makersuite.google.com/app/apikey)) ### Installation 1. Clone the repository and navigate to the project directory 2. Install dependencies: ```bash npm install ``` 3. Configure environment variables: ```bash cp .env.example .env ``` 4. Edit `.env` with your configuration: ```env API_PASSWORD=your_secure_password_here GEMINI_API_KEYS=key1,key2,key3 PORT=3000 LOG_DIR=./logs ``` ### Running the Server Development mode with auto-reload: ```bash npm run dev ``` Production mode: ```bash npm run build npm start ``` ## Docker Deployment ### Prerequisites - Docker and Docker Compose installed - Cloudflare account (for tunnel setup) ### Cloudflare Tunnel Setup 1. **Create a Cloudflare Tunnel:** - Go to [Cloudflare Zero Trust Dashboard](https://dash.cloudflare.com/) - Navigate to Access > Tunnels - Create a new tunnel and copy the tunnel token 2. **Configure the tunnel:** - Add your domain to the tunnel ingress rules - Set the service to point to `http://gemini-revolver:3000` ### Docker Deployment 1. **Configure environment variables:** ```bash cp .env.example .env ``` 2. **Edit `.env` with your configuration:** ```env API_PASSWORD=your_secure_password_here GEMINI_API_KEYS=key1,key2,key3 CLOUDFLARE_TUNNEL_TOKEN=your_cloudflare_tunnel_token_here CLOUDFLARE_DOMAIN=your-domain.com ``` 3. **Build and start with Docker Compose:** ```bash docker-compose up -d ``` 4. **Check status:** ```bash docker-compose ps docker-compose logs -f ``` 5. **Stop the services:** ```bash docker-compose down ``` ### Docker Commands - **Build only:** `docker-compose build` - **Rebuild without cache:** `docker-compose build --no-cache` - **View logs:** `docker-compose logs -f gemini-revolver` - **Restart services:** `docker-compose restart` - **Stop and remove containers:** `docker-compose down -v` ### Accessing the API With Cloudflare tunnel running, your API will be accessible at: - `https://your-domain.com/v1/chat/completions` - `https://your-domain.com/v1/models` - `https://your-domain.com/health` Use the same authentication method with your configured `API_PASSWORD`. ### Cloudflare 524 Timeout Prevention (Free Plan Compatible) Cloudflare Free, Pro, and Business plans enforce a non-configurable **100-second idle proxy timeout** (Error 524). Long LLM generations (thinking models, large prompts, or slow outputs) can exceed this limit. GeminiRevolver solves this at the application level: 1. **Streaming Requests (`stream: true`)**: - HTTP response headers and `X-Accel-Buffering: no` are flushed immediately upon initiation. - Periodic SSE comment pings (`: keep-alive\n\n`) are transmitted every 15 seconds. These reset Cloudflare's 100-second timer continuously while being silently ignored by SSE client parsers per the W3C spec. 2. **Non-Streaming Requests (`stream: false`)**: - If generation takes longer than 20 seconds, chunked transfer encoding (`Transfer-Encoding: chunked`) is activated, and periodic whitespace keep-alives (` `) are emitted. - Standard JSON parsers (RFC 8259) automatically ignore leading whitespace when parsing the final JSON payload. 3. **Configurable Settings (`.env`)**: - `KEEPALIVE_INTERVAL_MS` (default: `15000`): Interval between SSE comment heartbeats. - `ENABLE_NON_STREAMING_KEEPALIVE` (default: `true`): Enables chunked whitespace keep-alives for non-streaming calls. - `NON_STREAMING_KEEPALIVE_DELAY_MS` (default: `20000`): Wait time before activating non-streaming keep-alives. - `CANDIDATE_TIMEOUT_MS` (default: `60000`): Timeout per individual key/provider before triggering automatic failover. ## Admin Console & Model Revolver Navigate to `http://localhost:3000/admin` in your web browser. 1. **Authentication:** Enter your `API_PASSWORD` to unlock the console. 2. **Configure Providers:** Add one or more providers: - **Google AI Studio (Gemini):** Uses native `@google/generative-ai` SDK - **Groq Cloud:** High-speed Llama models via OpenAI-compatible endpoint - **OpenAI:** Official OpenAI API - **Custom:** Any OpenAI-compatible provider (e.g. DeepSeek, Ollama, Together, Cerebras) - Paste in your API keys (one per line). Multiple keys will be rotated automatically. - Use the **Test Key** button to immediately verify API credentials. 3. **Configure Custom Models:** - Define a custom model name (e.g., `gemini-flash-lite-latest` or `my-smart-pipeline`). - Set up your **Fallback Tiers**: - **Tier 0 (Main):** Select primary provider(s) and model ID. - **Tier 1 (Fallback 1):** Select secondary provider(s) and model ID. - **Tier 2 (Fallback 2):** Additional fallbacks if defined. - Designate a **Default Model** to handle requests that omit or supply an unknown model identifier. 4. **Revolver Playground:** Test prompt execution live and inspect trace metadata (which tier, provider, model, key, and latency were used). 5. **Live Key & Model Fallback Telemetry:** Real-time visibility into active keys, rate-limit cooldown timers, success rates, and live visual breadcrumb tracking of model routing cascades showing where and why models failed, how it fell back across keys and tiers, and what happened next. 6. **Live Request Log Watcher:** In-memory (RAM-only) interactive request inspector. Toggle ON to capture live incoming and served requests with full input prompts, assistant completions (including real-time streaming chunks), metadata, and debug failover traces. Safely capped in a 250-item FIFO buffer, and completely flushes RAM upon toggling OFF. Includes real-time search, status/model filters, and JSON export. All provider credentials and custom model definitions are persisted automatically in `data/revolver-config.json`. --- ## API Usage ### Authentication Use your configured `API_PASSWORD` as the Bearer token: ```bash curl -X POST http://localhost:3000/v1/chat/completions \ -H "Authorization: Bearer your_secure_password_here" \ -H "Content-Type: application/json" \ -d '{ "model": "gemini-flash-lite-latest", "messages": [ {"role": "user", "content": "Hello, how are you?"} ] }' ``` ### Endpoints #### `POST /v1/chat/completions` Create chat completions (OpenAI v1 compatible) **Request body:** ```json { "model": "gemini-flash-lite-latest", "messages": [ {"role": "user", "content": "Your message here"} ], "temperature": 0.7, "max_tokens": 1024 } ``` **Response:** ```json { "id": "chatcmpl-req_1234567890_abc123", "object": "chat.completion", "created": 1234567890, "model": "gemini-flash-lite-latest", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "Response from Gemini" }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 10, "completion_tokens": 20, "total_tokens": 30 } } ``` #### `GET /` Public stats dashboard (HTML in web browsers, JSON if `Accept: application/json` is provided). Does not require authentication and reveals only aggregate statistics (no prompt contents, completions, headers, or sender data). #### `GET /api/stats` Public JSON statistics endpoint returning request counts (went through, failed, cancelled) and token metrics (input, output, total). #### `GET /v1/models` List available models #### `GET /health` Health check endpoint with key rotation statistics ## Logging All requests and responses are logged to JSON files in the configured `LOG_DIR`. Log files are named by date: `api-logs-YYYY-MM-DD.json` Each log entry contains: - timestamp - request ID - type (request/response/error) - full request/response data ## Key Rotation Strategy The system uses a round-robin rotation strategy with rate limit awareness: 1. Keys are rotated in sequence 2. Rate-limited keys are temporarily skipped 3. If all keys are rate-limited, the least recently used key is selected 4. Request counts and last-used timestamps are tracked for monitoring ## Configuration | Environment Variable | Description | Default | |---------------------|-------------|---------| | `API_PASSWORD` | Password clients must use as API key | (required) | | `GEMINI_API_KEYS` | Comma-separated list of Gemini API keys | (required) | | `PORT` | Server port | 3000 | | `LOG_DIR` | Directory for log files | ./logs | | `CLOUDFLARE_TUNNEL_TOKEN` | Cloudflare tunnel token (Docker only) | (required for Docker) | | `CLOUDFLARE_DOMAIN` | Domain for Cloudflare tunnel (Docker only) | (required for Docker) | ## Project Structure ``` GeminiRevolver/ โ”œโ”€โ”€ src/ โ”‚ โ”œโ”€โ”€ index.ts # Main server entry point โ”‚ โ”œโ”€โ”€ config.ts # Configuration management โ”‚ โ”œโ”€โ”€ auth.ts # Authentication middleware โ”‚ โ”œโ”€โ”€ keyRotation.ts # API key rotation logic โ”‚ โ”œโ”€โ”€ logger.ts # Request/response logging โ”‚ โ”œโ”€โ”€ routes.ts # API route handlers โ”‚ โ””โ”€โ”€ openaiTypes.ts # OpenAI type definitions โ”œโ”€โ”€ logs/ # Log files (created at runtime) โ”œโ”€โ”€ dist/ # Compiled JavaScript (created at build) โ”œโ”€โ”€ .env # Environment variables (not in git) โ”œโ”€โ”€ .env.example # Environment variables template โ”œโ”€โ”€ .dockerignore # Docker ignore rules โ”œโ”€โ”€ Dockerfile # Docker image configuration โ”œโ”€โ”€ docker-compose.yml # Docker Compose configuration โ”œโ”€โ”€ cloudflared-config.yml # Cloudflare tunnel configuration โ”œโ”€โ”€ package.json # Project dependencies โ”œโ”€โ”€ tsconfig.json # TypeScript configuration โ”œโ”€โ”€ test-api.sh # API testing script โ”œโ”€โ”€ example-client.js # Example client implementation โ””โ”€โ”€ README.md # This file ``` ## Security Notes - Never commit `.env` file to version control - Use strong passwords for `API_PASSWORD` - Rotate your Gemini API keys regularly - Keep the server behind proper authentication in production - Log files may contain sensitive data - secure them appropriately - When using Cloudflare Tunnel, enable additional authentication in Cloudflare Access ## Troubleshooting ### Docker Issues **Container won't start:** ```bash docker-compose logs gemini-revolver ``` **Port conflicts:** - Change the port mapping in `docker-compose.yml` or stop other services using port 3000 **Permission issues with logs:** - Ensure the `./logs` directory has proper write permissions **Cloudflare tunnel connection issues:** - Verify your `CLOUDFLARE_TUNNEL_TOKEN` is correct - Check that the tunnel is active in your Cloudflare dashboard - Ensure the domain is properly configured in Cloudflare DNS ### Application Issues **Rate limiting still occurring:** - Add more Gemini API keys to your configuration - Check the health endpoint for key usage statistics - Consider implementing additional rate limiting at the application level **Authentication failures:** - Verify the `API_PASSWORD` matches between client and server - Check that the Authorization header format is correct: `Bearer ` **TypeScript build errors:** - Ensure all dependencies are installed: `npm install` - Clear build cache: `rm -rf dist/ && npm run build` ## License MIT