- Add TelemetryTracker to record request fallback journeys, tracking step-by-step cascades across tiers, candidate error codes, cooldowns, and next actions - Add LiveWatcher for RAM-only interactive request inspection with 250-item FIFO safety cap and automatic memory flush on toggle off - Add REST and SSE streaming endpoints for real-time telemetry and live request logs - Upgrade Admin Telemetry tab with visual fallback breadcrumbs and live key health matrix - Add dedicated Live Logs tab with deep multi-tab inspector (Input, Output, Metadata, Debug), search, filters, and JSON export - Add unit and integration tests (test-live-watcher.ts, test-telemetry-fallback.ts)
13 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-alivecomment 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
-
Clone the repository and navigate to the project directory
-
Install dependencies:
npm install
- Configure environment variables:
cp .env.example .env
- Edit
.envwith 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
-
Create a Cloudflare Tunnel:
- Go to Cloudflare Zero Trust Dashboard
- Navigate to Access > Tunnels
- Create a new tunnel and copy the tunnel token
-
Configure the tunnel:
- Add your domain to the tunnel ingress rules
- Set the service to point to
http://gemini-revolver:3000
Docker Deployment
- Configure environment variables:
cp .env.example .env
- Edit
.envwith 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
- Build and start with Docker Compose:
docker-compose up -d
- Check status:
docker-compose ps
docker-compose logs -f
- 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/completionshttps://your-domain.com/v1/modelshttps://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:
- Streaming Requests (
stream: true):- HTTP response headers and
X-Accel-Buffering: noare 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.
- HTTP response headers and
- 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.
- If generation takes longer than 20 seconds, chunked transfer encoding (
- 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.
- Authentication: Enter your
API_PASSWORDto unlock the console. - Configure Providers: Add one or more providers:
- Google AI Studio (Gemini): Uses native
@google/generative-aiSDK - 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.
- Google AI Studio (Gemini): Uses native
- Configure Custom Models:
- Define a custom model name (e.g.,
gemini-flash-lite-latestormy-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.
- Define a custom model name (e.g.,
- Revolver Playground: Test prompt execution live and inspect trace metadata (which tier, provider, model, key, and latency were used).
- 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.
- 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:
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:
- Keys are rotated in sequence
- Rate-limited keys are temporarily skipped
- If all keys are rate-limited, the least recently used key is selected
- 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
.envfile 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.ymlor stop other services using port 3000
Permission issues with logs:
- Ensure the
./logsdirectory has proper write permissions
Cloudflare tunnel connection issues:
- Verify your
CLOUDFLARE_TUNNEL_TOKENis 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_PASSWORDmatches 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