GeminiRevolver/README.md

12 KiB

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)

Installation

  1. Clone the repository and navigate to the project directory

  2. Install dependencies:

npm install
  1. Configure environment variables:
cp .env.example .env
  1. Edit .env with your configuration:
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:

npm run dev

Production mode:

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:

  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:
cp .env.example .env
  1. Edit .env with your configuration:
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
  1. Build and start with Docker Compose:
docker-compose up -d
  1. Check status:
docker-compose ps
docker-compose logs -f
  1. Stop the services:
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 Telemetry: Real-time visibility into active keys, rate-limit cooldown timers, and request/error counters.

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:

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:

{
  "model": "gemini-flash-lite-latest",
  "messages": [
    {"role": "user", "content": "Your message here"}
  ],
  "temperature": 0.7,
  "max_tokens": 1024
}

Response:

{
  "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:

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 <password>

TypeScript build errors:

  • Ensure all dependencies are installed: npm install
  • Clear build cache: rm -rf dist/ && npm run build

License

MIT