diff --git a/.dockerignore b/.dockerignore index 54c31eb..1d2c838 100644 --- a/.dockerignore +++ b/.dockerignore @@ -11,10 +11,6 @@ dist/ .env.local .env.*.local -# Configuration and runtime data (contains API keys) -data/ -*.tmp - # Logs logs/ *.log diff --git a/.env.example b/.env.example index c641dbd..1665da9 100644 --- a/.env.example +++ b/.env.example @@ -1,11 +1,8 @@ -# API password that clients and admin must use as the API key +# API password that clients must use as the API key API_PASSWORD=your_secure_password_here -# Configuration persistence file (stores providers, API keys, and custom models) -CONFIG_FILE=./data/revolver-config.json - -# (Optional / Legacy) Gemini API keys for automatic migration on first launch -# GEMINI_API_KEYS=key1,key2,key3 +# Gemini API keys (comma-separated) +GEMINI_API_KEYS=key1,key2,key3 # Server configuration PORT=3000 diff --git a/.gitignore b/.gitignore index 3f0bdff..16ff31f 100644 --- a/.gitignore +++ b/.gitignore @@ -9,10 +9,6 @@ dist/ # Environment variables .env -# Configuration and runtime data (contains API keys) -data/ -*.tmp - # Logs logs/ *.log diff --git a/GeminiRevolver.code-workspace b/GeiminiRevolver.code-workspace similarity index 100% rename from GeminiRevolver.code-workspace rename to GeiminiRevolver.code-workspace diff --git a/README.md b/README.md index 1736485..3376887 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,15 @@ -# GeminiRevolver +# GeiminiRevolver 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 ...]` +- ๐Ÿ”„ **Automatic API key rotation** - Rotates across multiple Gemini API keys to avoid rate limiting - ๐Ÿ“Š **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 +- ๐ŸŽฏ **OpenAI v1 compatible** - Drop-in replacement for OpenAI API endpoints +- โšก **Rate limit handling** - Automatically handles rate limiting and rotates to available keys - ๐Ÿณ **Docker support** - Containerized deployment with Docker and Docker Compose - ๐ŸŒ **Cloudflare Tunnel integration** - Securely expose your API via Cloudflare tunnel @@ -76,7 +72,7 @@ npm start 2. **Configure the tunnel:** - Add your domain to the tunnel ingress rules - - Set the service to point to `http://gemini-revolver:3000` + - Set the service to point to `http://geimini-revolver:3000` ### Docker Deployment @@ -113,7 +109,7 @@ docker-compose down - **Build only:** `docker-compose build` - **Rebuild without cache:** `docker-compose build --no-cache` -- **View logs:** `docker-compose logs -f gemini-revolver` +- **View logs:** `docker-compose logs -f geimini-revolver` - **Restart services:** `docker-compose restart` - **Stop and remove containers:** `docker-compose down -v` @@ -126,32 +122,6 @@ With Cloudflare tunnel running, your API will be accessible at: Use the same authentication method with your configured `API_PASSWORD`. -## 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 @@ -257,7 +227,7 @@ The system uses a round-robin rotation strategy with rate limit awareness: ## Project Structure ``` -GeminiRevolver/ +GeiminiRevolver/ โ”œโ”€โ”€ src/ โ”‚ โ”œโ”€โ”€ index.ts # Main server entry point โ”‚ โ”œโ”€โ”€ config.ts # Configuration management @@ -296,7 +266,7 @@ GeminiRevolver/ **Container won't start:** ```bash -docker-compose logs gemini-revolver +docker-compose logs geimini-revolver ``` **Port conflicts:** diff --git a/docker-compose.yml b/docker-compose.yml index 4b179e3..d8a5b4d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,10 +1,10 @@ services: # Main application - gemini-revolver: + geimini-revolver: build: context: . dockerfile: Dockerfile - container_name: gemini-revolver + container_name: geimini-revolver restart: unless-stopped ports: - "3000:3000" @@ -13,15 +13,13 @@ services: - GEMINI_API_KEYS=${GEMINI_API_KEYS} - PORT=3000 - LOG_DIR=/app/logs - - CONFIG_FILE=/app/data/revolver-config.json - NODE_ENV=production - RATE_LIMIT_DURATION_MS=${RATE_LIMIT_DURATION_MS:-60000} volumes: - # Persist logs and configuration to host + # Persist logs to host - ./logs:/app/logs - - ./data:/app/data networks: - - gemini-network + - geimini-network healthcheck: test: ["CMD", "wget", "--spider", "-q", "http://localhost:3000/health"] interval: 30s @@ -38,11 +36,11 @@ services: environment: - TUNNEL_TOKEN=${CLOUDFLARE_TUNNEL_TOKEN} networks: - - gemini-network + - geimini-network depends_on: - gemini-revolver: + geimini-revolver: condition: service_healthy networks: - gemini-network: + geimini-network: driver: bridge diff --git a/example-client.js b/example-client.js index 5dffc85..19fc488 100644 --- a/example-client.js +++ b/example-client.js @@ -1,4 +1,4 @@ -// Example client for using the GeminiRevolver API +// Example client for using the GeiminiRevolver API // This demonstrates how to use the OpenAI v1 compatible endpoint const API_BASE_URL = 'http://localhost:3000'; @@ -51,7 +51,7 @@ async function getHealth() { // Example usage async function main() { try { - console.log('Testing GeminiRevolver API...\n'); + console.log('Testing GeiminiRevolver API...\n'); // Check health console.log('1. Health check:'); diff --git a/package.json b/package.json index 2427635..f63cea2 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "name": "gemini-revolver", + "name": "geimini-revolver", "version": "1.0.0", "description": "OpenAI v1 compatible API endpoint for Gemini API key rotation", "main": "dist/index.js", @@ -7,8 +7,7 @@ "build": "tsc", "start": "node dist/index.js", "dev": "ts-node src/index.ts", - "watch": "tsc --watch", - "test": "API_PASSWORD=test_password ts-node test-revolver.ts && API_PASSWORD=test_password ts-node test-integration.ts" + "watch": "tsc --watch" }, "keywords": ["openai", "gemini", "api", "rotation"], "author": "", diff --git a/src/adminRoutes.ts b/src/adminRoutes.ts deleted file mode 100644 index 6eb89bb..0000000 --- a/src/adminRoutes.ts +++ /dev/null @@ -1,190 +0,0 @@ -import { Router, Request, Response } from 'express'; -import { configStore } from './configStore'; -import { revolverEngine } from './revolverEngine'; -import { ProviderType } from './revolverTypes'; - -const router = Router(); - -// GET /api/admin/verify (Check if current auth key is valid) -router.get('/verify', (req: Request, res: Response) => { - res.json({ valid: true }); -}); - -// GET /api/admin/config (Full configuration) -router.get('/config', (req: Request, res: Response) => { - const includeKeys = req.query.include_keys === 'true'; - const rawConfig = configStore.getConfig(); - - if (!includeKeys) { - // Mask keys - rawConfig.providers = rawConfig.providers.map(p => ({ - ...p, - keys: p.keys.map(k => ({ - ...k, - key: configStore.maskKey(k.key) - })) - })); - } - - res.json(rawConfig); -}); - -// POST /api/admin/providers (Create or Update provider) -router.post('/providers', (req: Request, res: Response) => { - const { id, name, type, baseUrl, keys } = req.body; - - if (!name || typeof name !== 'string') { - res.status(400).json({ error: 'Provider name is required.' }); - return; - } - - const validTypes: ProviderType[] = ['gemini', 'groq', 'openai', 'custom']; - if (!type || !validTypes.includes(type)) { - res.status(400).json({ error: `Invalid provider type. Must be one of: ${validTypes.join(', ')}` }); - return; - } - - if (!Array.isArray(keys)) { - res.status(400).json({ error: 'Keys must be an array of API key strings or key objects.' }); - return; - } - - try { - const saved = configStore.saveProvider({ - id, - name, - type, - baseUrl, - keys - }); - res.json(saved); - } catch (err: any) { - res.status(500).json({ error: err.message || 'Failed to save provider.' }); - } -}); - -// DELETE /api/admin/providers/:id -router.delete('/providers/:id', (req: Request, res: Response) => { - const deleted = configStore.deleteProvider(req.params.id); - if (deleted) { - res.json({ success: true, message: 'Provider deleted successfully.' }); - } else { - res.status(404).json({ error: 'Provider not found.' }); - } -}); - -// POST /api/admin/providers/:id/test-key -router.post('/providers/:id/test-key', async (req: Request, res: Response) => { - const { key, modelOverride } = req.body; - - if (!key || typeof key !== 'string') { - res.status(400).json({ error: 'API key is required to test.' }); - return; - } - - try { - const result = await revolverEngine.testProviderKey({ - providerId: req.params.id, - key, - modelOverride - }); - res.json(result); - } catch (err: any) { - res.status(500).json({ success: false, message: err.message || 'Key test failed.' }); - } -}); - -// POST /api/admin/models (Create or Update custom model) -router.post('/models', (req: Request, res: Response) => { - const { id, name, description, isDefault, tiers } = req.body; - - if (!name || typeof name !== 'string') { - res.status(400).json({ error: 'Model name is required.' }); - return; - } - - if (!Array.isArray(tiers) || tiers.length === 0) { - res.status(400).json({ error: 'At least one tier (Tier 0: Main) is required.' }); - return; - } - - try { - const saved = configStore.saveCustomModel({ - id, - name, - description, - isDefault, - tiers - }); - res.json(saved); - } catch (err: any) { - res.status(500).json({ error: err.message || 'Failed to save custom model.' }); - } -}); - -// DELETE /api/admin/models/:id -router.delete('/models/:id', (req: Request, res: Response) => { - const deleted = configStore.deleteCustomModel(req.params.id); - if (deleted) { - res.json({ success: true, message: 'Custom model deleted successfully.' }); - } else { - res.status(404).json({ error: 'Custom model not found.' }); - } -}); - -// POST /api/admin/test-run (Test prompt through Revolver fallback pipeline) -router.post('/test-run', async (req: Request, res: Response) => { - const { customModelId, customModelName, prompt } = req.body; - - if (!prompt || typeof prompt !== 'string') { - res.status(400).json({ error: 'Prompt is required.' }); - return; - } - - try { - const result = await revolverEngine.executeTestPrompt({ - customModelId, - customModelName, - prompt - }); - res.json(result); - } catch (err: any) { - res.status(500).json({ - error: { - message: err.message || 'Test run failed', - type: 'revolver_test_error' - } - }); - } -}); - -// GET /api/admin/keys-status -router.get('/keys-status', (req: Request, res: Response) => { - const providers = configStore.getProviders(); - const now = Date.now(); - - const status = providers.map(p => ({ - id: p.id, - name: p.name, - type: p.type, - keys: p.keys.map((k, idx) => { - const isRateLimited = k.rateLimitedUntil ? now < k.rateLimitedUntil : false; - const cooldownRemainingSeconds = isRateLimited && k.rateLimitedUntil - ? Math.ceil((k.rateLimitedUntil - now) / 1000) - : 0; - return { - keyIndex: idx, - maskedKey: configStore.maskKey(k.key), - requestCount: k.requestCount || 0, - lastUsed: k.lastUsed ? new Date(k.lastUsed).toISOString() : null, - isRateLimited, - cooldownRemainingSeconds, - errorCount: k.errorCount || 0 - }; - }) - })); - - res.json({ providers: status, timestamp: new Date().toISOString() }); -}); - -export default router; diff --git a/src/adminView.ts b/src/adminView.ts deleted file mode 100644 index 7add5b6..0000000 --- a/src/adminView.ts +++ /dev/null @@ -1,1752 +0,0 @@ -export function renderAdminHtml(): string { - return ` - - - - - GeminiRevolver โ€” Admin Console & Model Orchestrator - - - - - -
-
- - -
- GeminiRevolver - Admin -
-
- -
-
- -
- -
-
- -
-

Admin Access

-

- Enter your master API password to configure providers, API keys, and custom model fallback revolvers. -

-
- - - -
-
- - - -
- - - - - - - - -
- - - -`; -} diff --git a/src/auth.ts b/src/auth.ts index 3830169..9057d4c 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -4,35 +4,15 @@ import { requestLogger } from './logger'; import { statsTracker } from './stats'; export const authenticateApiKey = (req: Request, res: Response, next: NextFunction): void => { - let providedKey: string | undefined; - const authHeader = req.headers.authorization; - if (authHeader) { - const parts = authHeader.split(' '); - if (parts.length === 2 && parts[0].toLowerCase() === 'bearer') { - providedKey = parts[1]; - } else if (parts.length === 1) { - providedKey = parts[0]; - } - } - - if (!providedKey) { - providedKey = (req.headers['x-api-key'] as string) || (req.headers['x-admin-key'] as string); - } - - if (!providedKey && req.query.api_key) { - providedKey = req.query.api_key as string; - } - - if (!providedKey) { - if (req.path.startsWith('/v1')) { - statsTracker.recordDirectFailure('missing_auth_header', req.path); - } + + if (!authHeader) { + statsTracker.recordDirectFailure('missing_auth_header', req.path); const requestId = requestLogger.generateRequestId(); - requestLogger.logError(requestId, { message: 'Missing Authorization', path: req.path }); + requestLogger.logError(requestId, { message: 'Missing Authorization header', path: req.path }); res.status(401).json({ error: { - message: 'Missing Authorization header or API key. Expected: Authorization: Bearer ', + message: 'Missing Authorization header', type: 'invalid_request_error', code: 'missing_api_key' } @@ -40,10 +20,26 @@ export const authenticateApiKey = (req: Request, res: Response, next: NextFuncti return; } + // OpenAI format: "Bearer " + const parts = authHeader.split(' '); + if (parts.length !== 2 || parts[0] !== 'Bearer') { + statsTracker.recordDirectFailure('invalid_auth_format', req.path); + const requestId = requestLogger.generateRequestId(); + requestLogger.logError(requestId, { message: 'Invalid Authorization format', path: req.path }); + res.status(401).json({ + error: { + message: 'Invalid Authorization format. Expected: Bearer ', + type: 'invalid_request_error', + code: 'invalid_api_key_format' + } + }); + return; + } + + const providedKey = parts[1]; + if (providedKey !== config.apiPassword) { - if (req.path.startsWith('/v1')) { - statsTracker.recordDirectFailure('invalid_api_key', req.path); - } + statsTracker.recordDirectFailure('invalid_api_key', req.path); const requestId = requestLogger.generateRequestId(); requestLogger.logError(requestId, { message: 'Invalid API key', path: req.path }); res.status(401).json({ diff --git a/src/config.ts b/src/config.ts index 87c3858..9ae92c8 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,14 +1,12 @@ import dotenv from 'dotenv'; -import path from 'path'; dotenv.config(); export const config = { apiPassword: process.env.API_PASSWORD, - geminiApiKeys: (process.env.GEMINI_API_KEYS || '').split(',').map(k => k.trim()).filter(Boolean), + geminiApiKeys: (process.env.GEMINI_API_KEYS || '').split(',').filter(key => key.trim()), port: parseInt(process.env.PORT || '3000', 10), logDir: process.env.LOG_DIR || './logs', - configFilePath: process.env.CONFIG_FILE || path.join(process.cwd(), 'data', 'revolver-config.json'), model: 'gemini-flash-lite-latest', rateLimitDurationMs: parseInt(process.env.RATE_LIMIT_DURATION_MS || '60000', 10) }; @@ -16,3 +14,7 @@ export const config = { if (!config.apiPassword) { throw new Error('API_PASSWORD is required. Please set it in .env file'); } + +if (config.geminiApiKeys.length === 0) { + throw new Error('No Gemini API keys configured. Please set GEMINI_API_KEYS in .env file'); +} diff --git a/src/configStore.ts b/src/configStore.ts deleted file mode 100644 index ac453b9..0000000 --- a/src/configStore.ts +++ /dev/null @@ -1,392 +0,0 @@ -import fs from 'fs'; -import path from 'path'; -import crypto from 'crypto'; -import { config } from './config'; -import { - RevolverConfigFile, - ProviderConfig, - ProviderKeyConfig, - CustomModelConfig, - ProviderType -} from './revolverTypes'; - -export class ConfigStore { - private configFilePath: string; - private data: RevolverConfigFile = { - version: 1, - defaultModelId: undefined, - providers: [], - customModels: [] - }; - private saveTimeout: NodeJS.Timeout | null = null; - - constructor(filePath?: string) { - this.configFilePath = filePath || config.configFilePath; - this.ensureDir(); - this.loadOrCreate(); - - process.on('SIGINT', () => this.saveSync()); - process.on('SIGTERM', () => this.saveSync()); - } - - private ensureDir(): void { - const dir = path.dirname(this.configFilePath); - if (!fs.existsSync(dir)) { - try { - fs.mkdirSync(dir, { recursive: true }); - } catch (err) { - console.error('[CONFIG_STORE] Failed to create directory for config:', err); - } - } - } - - private loadOrCreate(): void { - if (fs.existsSync(this.configFilePath)) { - try { - const raw = fs.readFileSync(this.configFilePath, 'utf8'); - this.data = JSON.parse(raw); - console.log(`[CONFIG_STORE] Loaded configuration from ${this.configFilePath} (${this.data.providers.length} providers, ${this.data.customModels.length} custom models)`); - return; - } catch (err) { - console.error(`[CONFIG_STORE] Error reading ${this.configFilePath}, creating backup and re-initializing:`, err); - try { - fs.copyFileSync(this.configFilePath, `${this.configFilePath}.bak-${Date.now()}`); - } catch {} - } - } - - // File does not exist or failed to parse: initialize - this.data = { - version: 1, - defaultModelId: undefined, - providers: [], - customModels: [] - }; - - // Auto-migrate from .env if GEMINI_API_KEYS are provided - if (config.geminiApiKeys && config.geminiApiKeys.length > 0) { - console.log(`[CONFIG_STORE] Initializing config with ${config.geminiApiKeys.length} Gemini API keys from .env`); - const providerId = 'provider-gemini-default'; - const defaultProvider: ProviderConfig = { - id: providerId, - name: 'Google AI Studio (Migrated)', - type: 'gemini', - baseUrl: 'https://generativelanguage.googleapis.com', - keys: config.geminiApiKeys.map(k => ({ - key: k, - lastUsed: 0, - requestCount: 0, - rateLimitedUntil: null, - errorCount: 0 - })), - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString() - }; - this.data.providers.push(defaultProvider); - - const modelId = 'model-gemini-default'; - const defaultCustomModel: CustomModelConfig = { - id: modelId, - name: config.model || 'gemini-flash-lite-latest', - description: 'Default Gemini Model (auto-migrated from .env)', - isDefault: true, - tiers: [ - { - tierIndex: 0, - name: 'Main Tier', - targets: [ - { - providerId: providerId, - model: config.model || 'gemini-flash-lite-latest' - } - ] - } - ], - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString() - }; - this.data.customModels.push(defaultCustomModel); - this.data.defaultModelId = modelId; - } - - this.saveSync(); - } - - public saveSync(): void { - try { - this.ensureDir(); - const tmpPath = `${this.configFilePath}.tmp`; - fs.writeFileSync(tmpPath, JSON.stringify(this.data, null, 2), 'utf8'); - fs.renameSync(tmpPath, this.configFilePath); - } catch (err) { - console.error('[CONFIG_STORE] Error saving config to file:', err); - } - } - - public scheduleSave(): void { - if (this.saveTimeout) return; - this.saveTimeout = setTimeout(() => { - this.saveTimeout = null; - this.saveSync(); - }, 1000); - } - - public getConfig(): RevolverConfigFile { - return JSON.parse(JSON.stringify(this.data)); - } - - public getProviders(): ProviderConfig[] { - return this.data.providers; - } - - public getProviderById(id: string): ProviderConfig | undefined { - return this.data.providers.find(p => p.id === id); - } - - public saveProvider(providerInput: { - id?: string; - name: string; - type: ProviderType; - baseUrl?: string; - keys: (string | ProviderKeyConfig)[]; - }): ProviderConfig { - const now = new Date().toISOString(); - const existingIndex = providerInput.id ? this.data.providers.findIndex(p => p.id === providerInput.id) : -1; - - // Convert string keys to ProviderKeyConfig if needed, preserving existing stats - const existingProvider = existingIndex >= 0 ? this.data.providers[existingIndex] : undefined; - const existingKeysMap = new Map(); - if (existingProvider) { - for (const k of existingProvider.keys) { - existingKeysMap.set(k.key, k); - } - } - - const processedKeys: ProviderKeyConfig[] = providerInput.keys - .map(k => { - const keyString = typeof k === 'string' ? k.trim() : k.key.trim(); - if (!keyString) return null; - if (typeof k === 'object' && k.key) { - return { - key: keyString, - lastUsed: k.lastUsed || 0, - requestCount: k.requestCount || 0, - rateLimitedUntil: k.rateLimitedUntil ?? null, - errorCount: k.errorCount || 0 - }; - } - const existing = existingKeysMap.get(keyString); - if (existing) return existing; - return { - key: keyString, - lastUsed: 0, - requestCount: 0, - rateLimitedUntil: null, - errorCount: 0 - }; - }) - .filter((k): k is ProviderKeyConfig => k !== null); - - const defaultBaseUrl = this.getDefaultBaseUrl(providerInput.type); - - if (existingIndex >= 0) { - const updated: ProviderConfig = { - ...this.data.providers[existingIndex], - name: providerInput.name.trim(), - type: providerInput.type, - baseUrl: providerInput.baseUrl?.trim() || defaultBaseUrl, - keys: processedKeys, - updatedAt: now - }; - this.data.providers[existingIndex] = updated; - this.saveSync(); - return updated; - } else { - const newProvider: ProviderConfig = { - id: providerInput.id || `prov-${crypto.randomBytes(6).toString('hex')}`, - name: providerInput.name.trim(), - type: providerInput.type, - baseUrl: providerInput.baseUrl?.trim() || defaultBaseUrl, - keys: processedKeys, - createdAt: now, - updatedAt: now - }; - this.data.providers.push(newProvider); - this.saveSync(); - return newProvider; - } - } - - public deleteProvider(id: string): boolean { - const initialLen = this.data.providers.length; - this.data.providers = this.data.providers.filter(p => p.id !== id); - if (this.data.providers.length !== initialLen) { - // Remove any target referencing this deleted provider in custom models - for (const model of this.data.customModels) { - for (const tier of model.tiers) { - tier.targets = tier.targets.filter(t => t.providerId !== id); - } - } - this.saveSync(); - return true; - } - return false; - } - - public getCustomModels(): CustomModelConfig[] { - return this.data.customModels; - } - - public getCustomModelById(id: string): CustomModelConfig | undefined { - return this.data.customModels.find(m => m.id === id); - } - - public getCustomModelByName(name: string): CustomModelConfig | undefined { - return this.data.customModels.find(m => m.name.toLowerCase() === name.toLowerCase()); - } - - public getDefaultModel(): CustomModelConfig | undefined { - if (this.data.defaultModelId) { - const found = this.data.customModels.find(m => m.id === this.data.defaultModelId); - if (found) return found; - } - const explicitlyDefault = this.data.customModels.find(m => m.isDefault); - if (explicitlyDefault) return explicitlyDefault; - return this.data.customModels[0]; - } - - public saveCustomModel(modelInput: { - id?: string; - name: string; - description?: string; - isDefault?: boolean; - tiers: { - tierIndex: number; - name?: string; - targets: { providerId: string; model: string }[]; - }[]; - }): CustomModelConfig { - const now = new Date().toISOString(); - const existingIndex = modelInput.id ? this.data.customModels.findIndex(m => m.id === modelInput.id) : -1; - - // Normalize tiers and targets - const processedTiers = (modelInput.tiers || []).map((t, idx) => ({ - tierIndex: typeof t.tierIndex === 'number' ? t.tierIndex : idx, - name: t.name || (idx === 0 ? 'Main Tier' : `Fallback Tier ${idx}`), - targets: (t.targets || []).map(tg => ({ - providerId: tg.providerId.trim(), - model: tg.model.trim() - })).filter(tg => tg.providerId && tg.model) - })); - - // If marked default, unmark others - if (modelInput.isDefault) { - for (const m of this.data.customModels) { - m.isDefault = false; - } - } - - if (existingIndex >= 0) { - const updated: CustomModelConfig = { - ...this.data.customModels[existingIndex], - name: modelInput.name.trim(), - description: modelInput.description?.trim(), - isDefault: !!modelInput.isDefault, - tiers: processedTiers, - updatedAt: now - }; - this.data.customModels[existingIndex] = updated; - if (updated.isDefault) { - this.data.defaultModelId = updated.id; - } - this.saveSync(); - return updated; - } else { - const newModelId = modelInput.id || `model-${crypto.randomBytes(6).toString('hex')}`; - const isFirstModel = this.data.customModels.length === 0; - const isDefault = modelInput.isDefault !== undefined ? modelInput.isDefault : isFirstModel; - - const newModel: CustomModelConfig = { - id: newModelId, - name: modelInput.name.trim(), - description: modelInput.description?.trim(), - isDefault: isDefault, - tiers: processedTiers, - createdAt: now, - updatedAt: now - }; - this.data.customModels.push(newModel); - if (isDefault || !this.data.defaultModelId) { - this.data.defaultModelId = newModelId; - } - this.saveSync(); - return newModel; - } - } - - public deleteCustomModel(id: string): boolean { - const initialLen = this.data.customModels.length; - this.data.customModels = this.data.customModels.filter(m => m.id !== id); - if (this.data.customModels.length !== initialLen) { - if (this.data.defaultModelId === id) { - this.data.defaultModelId = this.data.customModels[0]?.id; - if (this.data.customModels[0]) { - this.data.customModels[0].isDefault = true; - } - } - this.saveSync(); - return true; - } - return false; - } - - public updateKeyStats( - providerId: string, - apiKey: string, - updates: { - incrementCount?: boolean; - rateLimitedUntil?: number | null; - incrementError?: boolean; - } - ): void { - const provider = this.data.providers.find(p => p.id === providerId); - if (!provider) return; - - const keyConfig = provider.keys.find(k => k.key === apiKey); - if (!keyConfig) return; - - if (updates.incrementCount) { - keyConfig.requestCount = (keyConfig.requestCount || 0) + 1; - keyConfig.lastUsed = Date.now(); - } - if (updates.rateLimitedUntil !== undefined) { - keyConfig.rateLimitedUntil = updates.rateLimitedUntil; - } - if (updates.incrementError) { - keyConfig.errorCount = (keyConfig.errorCount || 0) + 1; - } - - this.scheduleSave(); - } - - public getDefaultBaseUrl(type: ProviderType): string { - switch (type) { - case 'gemini': - return 'https://generativelanguage.googleapis.com'; - case 'groq': - return 'https://api.groq.com/openai/v1'; - case 'openai': - return 'https://api.openai.com/v1'; - case 'custom': - return 'https://api.openai.com/v1'; - } - } - - public maskKey(key: string): string { - if (!key) return ''; - if (key.length <= 8) return '****'; - return `${key.slice(0, 4)}...${key.slice(-4)}`; - } -} - -export const configStore = new ConfigStore(); diff --git a/src/index.ts b/src/index.ts index 09da2fc..fb179d9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -66,17 +66,14 @@ app.use((err: any, req: express.Request, res: express.Response, next: express.Ne }); }); -// Start server if executed directly +// Start server const PORT = config.port; -if (require.main === module) { - app.listen(PORT, () => { - console.log(`๐Ÿš€ OpenAI v1 Compatible API Server running on port ${PORT}`); - console.log(`๐Ÿ“ Default model: ${config.model}`); - console.log(`โš™๏ธ Admin Console accessible at /admin`); - console.log(`๐Ÿ’พ Configuration persisted at: ${config.configFilePath}`); - console.log(`๐Ÿ“ Logging to: ${config.logDir}`); - console.log(`๐Ÿ”’ API requires password authentication`); - }); -} +app.listen(PORT, () => { + console.log(`๐Ÿš€ OpenAI v1 Compatible API Server running on port ${PORT}`); + console.log(`๐Ÿ“ Using model: ${config.model}`); + console.log(`๐Ÿ”‘ Configured ${config.geminiApiKeys.length} Gemini API keys for rotation`); + console.log(`๐Ÿ“ Logging to: ${config.logDir}`); + console.log(`๐Ÿ”’ API requires password authentication`); +}); export default app; diff --git a/src/revolverEngine.ts b/src/revolverEngine.ts deleted file mode 100644 index 279b5c0..0000000 --- a/src/revolverEngine.ts +++ /dev/null @@ -1,858 +0,0 @@ -import { Response } from 'express'; -import { GoogleGenerativeAI } from '@google/generative-ai'; -import { config } from './config'; -import { configStore, ConfigStore } from './configStore'; -import { - CustomModelConfig, - ProviderConfig, - ProviderKeyConfig, - ModelTarget, - FallbackTier, - ExecutionDiagnosticTrace -} from './revolverTypes'; -import { OpenAIChatRequest, OpenAIChatResponse } from './openaiTypes'; - -interface CandidateExecution { - tier: FallbackTier; - target: ModelTarget; - provider: ProviderConfig; - keyConfig: ProviderKeyConfig; - keyIndex: number; -} - -export class RevolverEngine { - private store: ConfigStore; - private geminiClients: Map = new Map(); - // Per-tier round-robin pointer: Map<`${modelId}_tier_${tierIndex}`, number> - private roundRobinPointers: Map = new Map(); - - constructor(store?: ConfigStore) { - this.store = store || configStore; - } - - private getGeminiClient(apiKey: string): GoogleGenerativeAI { - let client = this.geminiClients.get(apiKey); - if (!client) { - client = new GoogleGenerativeAI(apiKey); - this.geminiClients.set(apiKey, client); - } - return client; - } - - public resolveCustomModel(requestedModel?: string): { - customModel: CustomModelConfig; - requestedModelName: string; - } { - let customModel: CustomModelConfig | undefined; - - if (requestedModel) { - customModel = this.store.getCustomModelByName(requestedModel); - } - - if (!customModel) { - customModel = this.store.getDefaultModel(); - } - - if (!customModel) { - const allModels = this.store.getCustomModels(); - if (allModels.length > 0) { - customModel = allModels[0]; - } - } - - if (!customModel) { - throw new Error( - 'No custom models configured in the Revolver. Please configure a custom model in the Admin Menu (/admin).' - ); - } - - return { - customModel, - requestedModelName: requestedModel || customModel.name - }; - } - - private isKeyRateLimited(keyConfig: ProviderKeyConfig): boolean { - if (!keyConfig.rateLimitedUntil) return false; - return Date.now() < keyConfig.rateLimitedUntil; - } - - private getCandidatesForTier(tier: FallbackTier, modelId: string): CandidateExecution[] { - const candidates: CandidateExecution[] = []; - - for (const target of tier.targets) { - const provider = this.store.getProviderById(target.providerId); - if (!provider || provider.keys.length === 0) continue; - - provider.keys.forEach((keyConfig, keyIdx) => { - candidates.push({ - tier, - target, - provider, - keyConfig, - keyIndex: keyIdx - }); - }); - } - - if (candidates.length === 0) return []; - - // Separate available vs rate-limited candidates - const available = candidates.filter(c => !this.isKeyRateLimited(c.keyConfig)); - - const tierKey = `${modelId}_tier_${tier.tierIndex}`; - const pointer = this.roundRobinPointers.get(tierKey) || 0; - - if (available.length > 0) { - // Rotate starting from pointer - const startIdx = pointer % available.length; - this.roundRobinPointers.set(tierKey, (startIdx + 1) % available.length); - return [ - ...available.slice(startIdx), - ...available.slice(0, startIdx) - ]; - } - - // If all are rate-limited, sort by least-recently-used / earliest rate-limited expiry - const sorted = [...candidates].sort((a, b) => { - const aTime = a.keyConfig.rateLimitedUntil || a.keyConfig.lastUsed || 0; - const bTime = b.keyConfig.rateLimitedUntil || b.keyConfig.lastUsed || 0; - return aTime - bTime; - }); - - return sorted; - } - - private convertToGeminiContent(messages: any[]): { - systemInstruction?: string; - geminiMessages: any[]; - } { - let systemInstruction = ''; - const geminiMessages: any[] = []; - - for (const msg of messages) { - if (msg.role === 'system') { - systemInstruction += (systemInstruction ? '\n\n' : '') + (typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content)); - } else { - geminiMessages.push({ - role: msg.role === 'assistant' ? 'model' : 'user', - parts: [{ text: typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content) }] - }); - } - } - - return { systemInstruction, geminiMessages }; - } - - private isRateLimitOrQuotaError(error: any): boolean { - const msg = (error?.message || '').toLowerCase(); - const status = error?.status || error?.statusCode || error?.code; - return ( - status === 429 || - status === '429' || - status === 403 || - msg.includes('rate limit') || - msg.includes('quota') || - msg.includes('resource_exhausted') || - msg.includes('too many requests') - ); - } - - private isServerError(error: any): boolean { - const status = error?.status || error?.statusCode || error?.code; - return ( - status === 500 || - status === 502 || - status === 503 || - status === 504 || - status === 'ECONNRESET' || - status === 'ETIMEDOUT' - ); - } - - public async executeChatCompletion(params: { - requestBody: OpenAIChatRequest; - requestId: string; - res: Response; - isStreaming: boolean; - onSuccess?: (tokens: { input: number; output: number }) => void; - onFailure?: (reason?: string) => void; - onCancelled?: () => void; - }): Promise { - const { requestBody, requestId, res, isStreaming, onSuccess, onFailure, onCancelled } = params; - const { customModel, requestedModelName } = this.resolveCustomModel(requestBody.model); - - let streamStarted = false; - let isCancelled = false; - - res.on('close', () => { - if (!res.writableEnded) { - isCancelled = true; - if (onCancelled) onCancelled(); - } - }); - - // Sort tiers by tierIndex - const sortedTiers = [...customModel.tiers].sort((a, b) => a.tierIndex - b.tierIndex); - if (sortedTiers.length === 0) { - throw new Error(`Custom model '${customModel.name}' has no fallback tiers defined.`); - } - - let lastError: any = null; - - // Traverse tiers: Tier 0 -> Tier 1 -> Tier 2... - for (const tier of sortedTiers) { - const candidates = this.getCandidatesForTier(tier, customModel.id); - if (candidates.length === 0) { - console.warn(`[REVOLVER] No candidates found in Tier ${tier.tierIndex} ('${tier.name || 'Tier ' + tier.tierIndex}') for model '${customModel.name}'. Skipping tier.`); - continue; - } - - console.log(`[REVOLVER] Attempting Tier ${tier.tierIndex} ('${tier.name || 'Tier ' + tier.tierIndex}') with ${candidates.length} candidate(s)...`); - - // Try candidates in this tier - for (const candidate of candidates) { - if (isCancelled || res.destroyed) return; - - try { - console.log(`[REVOLVER] Routing to Provider '${candidate.provider.name}' (${candidate.provider.type}) with model '${candidate.target.model}' [Key ${candidate.keyIndex + 1}/${candidate.provider.keys.length}]`); - - if (isStreaming) { - await this.executeStreaming({ - candidate, - requestBody, - requestedModelName, - requestId, - res, - onStreamStart: () => { - streamStarted = true; - }, - onSuccess - }); - // If stream finished successfully, return - return; - } else { - const responseData = await this.executeNonStreaming({ - candidate, - requestBody, - requestedModelName, - requestId - }); - - if (isCancelled || res.destroyed) return; - - // Success! Update stats - this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, { - incrementCount: true, - rateLimitedUntil: null - }); - - if (onSuccess) { - const promptTokens = responseData.usage?.prompt_tokens || 0; - const completionTokens = responseData.usage?.completion_tokens || 0; - onSuccess({ input: promptTokens, output: completionTokens }); - } - - res.json(responseData); - return; - } - } catch (err: any) { - lastError = err; - console.error(`[REVOLVER] Candidate failed (Provider: '${candidate.provider.name}', Model: '${candidate.target.model}'):`, err.message); - - // If stream has already started sending bytes to the client, we cannot fail over cleanly - if (streamStarted) { - if (onFailure) onFailure('stream_interrupted'); - throw err; - } - - // Mark key rate limited or increment error - const isRateLimit = this.isRateLimitOrQuotaError(err); - const isServerErr = this.isServerError(err); - - if (isRateLimit || isServerErr) { - const cooldown = isRateLimit ? config.rateLimitDurationMs : 15000; - console.warn(`[REVOLVER] Marking key ${this.store.maskKey(candidate.keyConfig.key)} rate-limited for ${cooldown / 1000}s`); - this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, { - rateLimitedUntil: Date.now() + cooldown, - incrementError: true - }); - } else { - this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, { - incrementError: true - }); - } - - // Continue loop to try next candidate in this tier - } - } - - console.warn(`[REVOLVER] All candidates in Tier ${tier.tierIndex} ('${tier.name || 'Tier ' + tier.tierIndex}') exhausted or failed. Falling back to next tier...`); - } - - // If we reached here, all tiers and all candidates failed - if (onFailure) onFailure('all_tiers_exhausted'); - const finalErrorMessage = lastError ? lastError.message : 'All model tiers and provider keys are exhausted or rate-limited.'; - res.status(503).json({ - error: { - message: `[Revolver Fallback Error]: ${finalErrorMessage}`, - type: 'revolver_exhausted_error', - code: 'all_tiers_exhausted' - } - }); - } - - private async executeNonStreaming(params: { - candidate: CandidateExecution; - requestBody: OpenAIChatRequest; - requestedModelName: string; - requestId: string; - }): Promise { - const { candidate, requestBody, requestedModelName, requestId } = params; - - if (candidate.provider.type === 'gemini') { - return this.executeGeminiNonStreaming({ - candidate, - requestBody, - requestedModelName, - requestId - }); - } else { - return this.executeOpenAICompatibleNonStreaming({ - candidate, - requestBody, - requestedModelName, - requestId - }); - } - } - - private async executeGeminiNonStreaming(params: { - candidate: CandidateExecution; - requestBody: OpenAIChatRequest; - requestedModelName: string; - requestId: string; - }): Promise { - const { candidate, requestBody, requestedModelName, requestId } = params; - const genAI = this.getGeminiClient(candidate.keyConfig.key); - - const { systemInstruction, geminiMessages } = this.convertToGeminiContent(requestBody.messages); - - const modelInstance = genAI.getGenerativeModel({ - model: candidate.target.model, - systemInstruction: systemInstruction || undefined - }); - - const lastMessage = geminiMessages[geminiMessages.length - 1]; - if (!lastMessage || lastMessage.role !== 'user') { - throw new Error('Last message must be from user for Gemini chat completion.'); - } - - const chat = modelInstance.startChat({ - history: geminiMessages.slice(0, -1), - generationConfig: { - temperature: requestBody.temperature ?? 0.7, - maxOutputTokens: requestBody.max_tokens ?? 2048, - topP: requestBody.top_p ?? 0.8 - } - }); - - const result = await chat.sendMessage(lastMessage.parts[0].text); - const response = await result.response; - const content = response?.candidates?.[0]?.content?.parts?.[0]?.text || ''; - - const promptTokens = response?.usageMetadata?.promptTokenCount || 0; - const completionTokens = response?.usageMetadata?.candidatesTokenCount || Math.ceil(content.length / 4); - - return { - id: `chatcmpl-${requestId}`, - object: 'chat.completion', - created: Math.floor(Date.now() / 1000), - model: requestedModelName, - choices: [ - { - index: 0, - message: { - role: 'assistant', - content: content - }, - finish_reason: 'stop' - } - ], - usage: { - prompt_tokens: promptTokens, - completion_tokens: completionTokens, - total_tokens: promptTokens + completionTokens - } - }; - } - - private async executeOpenAICompatibleNonStreaming(params: { - candidate: CandidateExecution; - requestBody: OpenAIChatRequest; - requestedModelName: string; - requestId: string; - }): Promise { - const { candidate, requestBody, requestedModelName, requestId } = params; - - const baseUrl = (candidate.provider.baseUrl || this.store.getDefaultBaseUrl(candidate.provider.type)).replace(/\/+$/, ''); - const url = `${baseUrl}/chat/completions`; - - // Forward the body, setting model to candidate.target.model and stream to false - const forwardedBody = { - ...requestBody, - model: candidate.target.model, - stream: false - }; - - const response = await fetch(url, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${candidate.keyConfig.key}` - }, - body: JSON.stringify(forwardedBody) - }); - - if (!response.ok) { - const errBody = await response.text(); - let errorDetails = errBody; - try { - const parsed = JSON.parse(errBody); - errorDetails = parsed.error?.message || errBody; - } catch {} - const err = new Error(`Provider API error (${response.status}): ${errorDetails}`); - (err as any).status = response.status; - throw err; - } - - const json = (await response.json()) as OpenAIChatResponse; - // Overwrite returned model with requestedModelName for client fidelity - json.model = requestedModelName; - if (!json.id) { - json.id = `chatcmpl-${requestId}`; - } - return json; - } - - private async executeStreaming(params: { - candidate: CandidateExecution; - requestBody: OpenAIChatRequest; - requestedModelName: string; - requestId: string; - res: Response; - onStreamStart: () => void; - onSuccess?: (tokens: { input: number; output: number }) => void; - }): Promise { - const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params; - - if (candidate.provider.type === 'gemini') { - return this.executeGeminiStreaming({ - candidate, - requestBody, - requestedModelName, - requestId, - res, - onStreamStart, - onSuccess - }); - } else { - return this.executeOpenAICompatibleStreaming({ - candidate, - requestBody, - requestedModelName, - requestId, - res, - onStreamStart, - onSuccess - }); - } - } - - private async executeGeminiStreaming(params: { - candidate: CandidateExecution; - requestBody: OpenAIChatRequest; - requestedModelName: string; - requestId: string; - res: Response; - onStreamStart: () => void; - onSuccess?: (tokens: { input: number; output: number }) => void; - }): Promise { - const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params; - const genAI = this.getGeminiClient(candidate.keyConfig.key); - - const { systemInstruction, geminiMessages } = this.convertToGeminiContent(requestBody.messages); - - const modelInstance = genAI.getGenerativeModel({ - model: candidate.target.model, - systemInstruction: systemInstruction || undefined - }); - - const lastMessage = geminiMessages[geminiMessages.length - 1]; - if (!lastMessage || lastMessage.role !== 'user') { - throw new Error('Last message must be from user for Gemini chat completion.'); - } - - const chat = modelInstance.startChat({ - history: geminiMessages.slice(0, -1), - generationConfig: { - temperature: requestBody.temperature ?? 0.7, - maxOutputTokens: requestBody.max_tokens ?? 2048, - topP: requestBody.top_p ?? 0.8 - } - }); - - // Start streaming from Gemini - const result = await chat.sendMessageStream(lastMessage.parts[0].text); - - // If we got here without throwing, commit headers to client - onStreamStart(); - res.setHeader('Content-Type', 'text/event-stream'); - res.setHeader('Cache-Control', 'no-cache'); - res.setHeader('Connection', 'keep-alive'); - - let fullContent = ''; - let promptTokens = 0; - let completionTokens = 0; - - for await (const chunk of result.stream) { - if (res.destroyed) break; - const text = chunk.text(); - fullContent += text; - - const chunkResponse = { - id: `chatcmpl-${requestId}`, - object: 'chat.completion.chunk', - created: Math.floor(Date.now() / 1000), - model: requestedModelName, - choices: [ - { - index: 0, - delta: { content: text }, - finish_reason: null - } - ] - }; - - res.write(`data: ${JSON.stringify(chunkResponse)}\n\n`); - } - - if (!res.destroyed) { - const finalChunk = { - id: `chatcmpl-${requestId}`, - object: 'chat.completion.chunk', - created: Math.floor(Date.now() / 1000), - model: requestedModelName, - choices: [ - { - index: 0, - delta: {}, - finish_reason: 'stop' - } - ] - }; - res.write(`data: ${JSON.stringify(finalChunk)}\n\n`); - res.write('data: [DONE]\n\n'); - res.end(); - } - - // Try to get token counts from final response - try { - const finalResp = await result.response; - if (finalResp?.usageMetadata) { - promptTokens = finalResp.usageMetadata.promptTokenCount || 0; - completionTokens = finalResp.usageMetadata.candidatesTokenCount || 0; - } - } catch {} - - if (!promptTokens) promptTokens = Math.ceil(JSON.stringify(requestBody.messages).length / 4); - if (!completionTokens) completionTokens = Math.ceil(fullContent.length / 4); - - this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, { - incrementCount: true, - rateLimitedUntil: null - }); - - if (onSuccess) { - onSuccess({ input: promptTokens, output: completionTokens }); - } - } - - private async executeOpenAICompatibleStreaming(params: { - candidate: CandidateExecution; - requestBody: OpenAIChatRequest; - requestedModelName: string; - requestId: string; - res: Response; - onStreamStart: () => void; - onSuccess?: (tokens: { input: number; output: number }) => void; - }): Promise { - const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params; - - const baseUrl = (candidate.provider.baseUrl || this.store.getDefaultBaseUrl(candidate.provider.type)).replace(/\/+$/, ''); - const url = `${baseUrl}/chat/completions`; - - const forwardedBody = { - ...requestBody, - model: candidate.target.model, - stream: true - }; - - const response = await fetch(url, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${candidate.keyConfig.key}` - }, - body: JSON.stringify(forwardedBody) - }); - - if (!response.ok) { - const errBody = await response.text(); - let errorDetails = errBody; - try { - const parsed = JSON.parse(errBody); - errorDetails = parsed.error?.message || errBody; - } catch {} - const err = new Error(`Provider API error (${response.status}): ${errorDetails}`); - (err as any).status = response.status; - throw err; - } - - if (!response.body) { - throw new Error('Response body is null from provider stream.'); - } - - // Stream started successfully! - onStreamStart(); - res.setHeader('Content-Type', 'text/event-stream'); - res.setHeader('Cache-Control', 'no-cache'); - res.setHeader('Connection', 'keep-alive'); - - const reader = response.body.getReader(); - const decoder = new TextDecoder(); - let buffer = ''; - let totalOutputChars = 0; - - try { - while (true) { - if (res.destroyed) break; - const { done, value } = await reader.read(); - if (done) break; - - const text = decoder.decode(value, { stream: true }); - buffer += text; - - const lines = buffer.split('\n'); - buffer = lines.pop() || ''; - - for (const line of lines) { - const trimmed = line.trim(); - if (!trimmed) { - res.write('\n'); - continue; - } - - if (trimmed.startsWith('data: ')) { - const dataStr = trimmed.slice(6); - if (dataStr === '[DONE]') { - res.write('data: [DONE]\n\n'); - continue; - } - - try { - const parsed = JSON.parse(dataStr); - parsed.model = requestedModelName; - if (parsed.choices?.[0]?.delta?.content) { - totalOutputChars += parsed.choices[0].delta.content.length; - } - res.write(`data: ${JSON.stringify(parsed)}\n\n`); - } catch { - res.write(`${line}\n`); - } - } else { - res.write(`${line}\n`); - } - } - } - } finally { - if (!res.destroyed) { - res.end(); - } - } - - const estimatedInput = Math.ceil(JSON.stringify(requestBody.messages).length / 4); - const estimatedOutput = Math.ceil(totalOutputChars / 4); - - this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, { - incrementCount: true, - rateLimitedUntil: null - }); - - if (onSuccess) { - onSuccess({ input: estimatedInput, output: estimatedOutput }); - } - } - - // Diagnostic Test Prompt Runner for the Admin Playground - public async executeTestPrompt(params: { - customModelId?: string; - customModelName?: string; - prompt: string; - }): Promise<{ - trace: ExecutionDiagnosticTrace; - content: string; - fullResponse?: any; - }> { - const startTime = Date.now(); - let customModel: CustomModelConfig | undefined; - - if (params.customModelId) { - customModel = this.store.getCustomModelById(params.customModelId); - } - if (!customModel && params.customModelName) { - customModel = this.store.getCustomModelByName(params.customModelName); - } - if (!customModel) { - customModel = this.store.getDefaultModel(); - } - if (!customModel) { - throw new Error('No custom model found to test.'); - } - - const sortedTiers = [...customModel.tiers].sort((a, b) => a.tierIndex - b.tierIndex); - let lastError: any = null; - - for (const tier of sortedTiers) { - const candidates = this.getCandidatesForTier(tier, customModel.id); - for (const candidate of candidates) { - const candidateStart = Date.now(); - try { - const testRequest: OpenAIChatRequest = { - model: candidate.target.model, - messages: [{ role: 'user', content: params.prompt }] - }; - - const resp = await this.executeNonStreaming({ - candidate, - requestBody: testRequest, - requestedModelName: customModel.name, - requestId: `test-${Date.now()}` - }); - - const content = resp.choices?.[0]?.message?.content || ''; - const duration = Date.now() - candidateStart; - - this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, { - incrementCount: true, - rateLimitedUntil: null - }); - - const trace: ExecutionDiagnosticTrace = { - tierIndex: tier.tierIndex, - tierName: tier.name || `Tier ${tier.tierIndex}`, - providerId: candidate.provider.id, - providerName: candidate.provider.name, - providerType: candidate.provider.type, - model: candidate.target.model, - keyIndex: candidate.keyIndex, - maskedKey: this.store.maskKey(candidate.keyConfig.key), - durationMs: duration, - tokens: { - promptTokens: resp.usage?.prompt_tokens || 0, - completionTokens: resp.usage?.completion_tokens || 0, - totalTokens: resp.usage?.total_tokens || 0 - } - }; - - return { trace, content, fullResponse: resp }; - } catch (err: any) { - lastError = err; - const isRateLimit = this.isRateLimitOrQuotaError(err); - if (isRateLimit) { - this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, { - rateLimitedUntil: Date.now() + config.rateLimitDurationMs, - incrementError: true - }); - } - } - } - } - - throw new Error(lastError ? lastError.message : 'All tiers and candidates failed during test run.'); - } - - // Quick single-key test method for the Admin Provider page - public async testProviderKey(params: { - providerId: string; - key: string; - modelOverride?: string; - }): Promise<{ success: boolean; latencyMs: number; message: string }> { - const provider = this.store.getProviderById(params.providerId); - if (!provider) { - throw new Error(`Provider not found: ${params.providerId}`); - } - - const start = Date.now(); - const type = provider.type; - const model = params.modelOverride || (type === 'gemini' ? 'gemini-1.5-flash-latest' : type === 'groq' ? 'llama-3.3-70b-versatile' : 'gpt-4o-mini'); - - try { - if (type === 'gemini') { - const genAI = new GoogleGenerativeAI(params.key); - const m = genAI.getGenerativeModel({ model }); - const res = await m.generateContent('ping'); - const text = res.response.text(); - return { - success: true, - latencyMs: Date.now() - start, - message: `Connected successfully! Response: "${text.trim().slice(0, 50)}"` - }; - } else { - const baseUrl = (provider.baseUrl || this.store.getDefaultBaseUrl(type)).replace(/\/+$/, ''); - const res = await fetch(`${baseUrl}/chat/completions`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${params.key}` - }, - body: JSON.stringify({ - model, - messages: [{ role: 'user', content: 'ping' }], - max_tokens: 5 - }) - }); - - if (!res.ok) { - const body = await res.text(); - let errText = body; - try { - const parsed = JSON.parse(body); - errText = parsed.error?.message || body; - } catch {} - return { - success: false, - latencyMs: Date.now() - start, - message: `API returned ${res.status}: ${errText}` - }; - } - - const data = (await res.json()) as any; - const text = data.choices?.[0]?.message?.content || 'OK'; - return { - success: true, - latencyMs: Date.now() - start, - message: `Connected successfully! Response: "${text.trim().slice(0, 50)}"` - }; - } - } catch (err: any) { - return { - success: false, - latencyMs: Date.now() - start, - message: err.message || 'Connection failed' - }; - } - } -} - -export const revolverEngine = new RevolverEngine(); diff --git a/src/revolverTypes.ts b/src/revolverTypes.ts deleted file mode 100644 index 1a1e21e..0000000 --- a/src/revolverTypes.ts +++ /dev/null @@ -1,64 +0,0 @@ -export type ProviderType = 'gemini' | 'groq' | 'openai' | 'custom'; - -export interface ProviderKeyConfig { - key: string; - lastUsed?: number; - requestCount?: number; - rateLimitedUntil?: number | null; - errorCount?: number; -} - -export interface ProviderConfig { - id: string; - name: string; - type: ProviderType; - baseUrl?: string; - keys: ProviderKeyConfig[]; - createdAt: string; - updatedAt: string; -} - -export interface ModelTarget { - providerId: string; - model: string; -} - -export interface FallbackTier { - tierIndex: number; - name?: string; - targets: ModelTarget[]; -} - -export interface CustomModelConfig { - id: string; - name: string; // The model identifier passed by client e.g. "my-smart-model" - description?: string; - isDefault?: boolean; - tiers: FallbackTier[]; // Tier 0 = Main, Tier 1 = Fallback 1, Tier 2 = Fallback 2... - createdAt: string; - updatedAt: string; -} - -export interface RevolverConfigFile { - version: number; - defaultModelId?: string; - providers: ProviderConfig[]; - customModels: CustomModelConfig[]; -} - -export interface ExecutionDiagnosticTrace { - tierIndex: number; - tierName?: string; - providerId: string; - providerName: string; - providerType: ProviderType; - model: string; - keyIndex: number; - maskedKey: string; - durationMs: number; - tokens?: { - promptTokens: number; - completionTokens: number; - totalTokens: number; - }; -} diff --git a/src/routes.ts b/src/routes.ts index 3fd9af7..f7a8e95 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -1,43 +1,98 @@ import { Router, Request, Response } from 'express'; +import { GoogleGenerativeAI } from '@google/generative-ai'; +import { keyRotationManager } from './keyRotation'; import { requestLogger } from './logger'; import { config } from './config'; -import { statsTracker } from './stats'; -import { configStore } from './configStore'; -import { revolverEngine } from './revolverEngine'; -import { authenticateApiKey } from './auth'; -import adminRoutes from './adminRoutes'; -import { renderAdminHtml } from './adminView'; +import { statsTracker, estimateMessagesTokens } from './stats'; import { OpenAIChatRequest, + OpenAIChatResponse, OpenAIModelsResponse } from './openaiTypes'; const router = Router(); -// Mount Admin API routes with authentication -router.use('/api/admin', authenticateApiKey, adminRoutes); +// Cache for model instances to avoid recreation +const modelCache = new Map(); -// Admin Web UI Console -router.get('/admin', (req: Request, res: Response) => { - res.setHeader('Content-Type', 'text/html; charset=utf-8'); - res.send(renderAdminHtml()); -}); +// Convert OpenAI format to Gemini format +function convertToGeminiMessages(messages: any[]): any[] { + return messages + .filter(msg => msg.role !== 'system') // Gemini doesn't have system messages + .map(msg => ({ + role: msg.role === 'assistant' ? 'model' : 'user', + parts: [{ text: msg.content }] + })); +} + +// Convert Gemini response to OpenAI format +function convertToOpenAIResponse(geminiResponse: any, model: string, requestId: string): OpenAIChatResponse { + const content = geminiResponse.response?.candidates?.[0]?.content?.parts?.[0]?.text || ''; + + return { + id: `chatcmpl-${requestId}`, + object: 'chat.completion', + created: Math.floor(Date.now() / 1000), + model: model, + choices: [ + { + index: 0, + message: { + role: 'assistant', + content: content + }, + finish_reason: 'stop' + } + ], + usage: { + prompt_tokens: geminiResponse.response?.usageMetadata?.promptTokenCount || 0, + completion_tokens: geminiResponse.response?.usageMetadata?.candidatesTokenCount || 0, + total_tokens: geminiResponse.response?.usageMetadata?.totalTokenCount || 0 + } + }; +} // POST /v1/chat/completions router.post('/v1/chat/completions', async (req: Request, res: Response) => { const requestId = requestLogger.generateRequestId(); const requestTracker = statsTracker.startRequest(req.path); let isFinished = false; + let isCancelled = false; + let estimatedInputTokens = 0; + let outputTokensSoFar = 0; + let apiKey = ''; + let requestedModel = ''; + const startTime = Date.now(); + // Listen for client disconnect/cancellation on response + res.on('close', () => { + if (!isFinished && !res.writableEnded) { + isCancelled = true; + requestTracker.recordCancelled({ + input: estimatedInputTokens, + output: outputTokensSoFar + }); + requestLogger.logError(requestId, { + message: 'Client cancelled request', + path: req.path + }); + } + }); + try { const body: OpenAIChatRequest = req.body; - - console.log('[DEBUG] Incoming completion request:', { + + // Log the request with full details for debugging + console.log('[DEBUG] Incoming request:', { requestId, - model: body?.model, - stream: !!body?.stream + headers: { + 'content-type': req.headers['content-type'], + 'authorization': req.headers.authorization ? 'Bearer ***' : 'missing', + 'user-agent': req.headers['user-agent'] + }, + body: body }); - + requestLogger.logRequest(requestId, { path: req.path, method: req.method, @@ -46,75 +101,264 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { // Validate request if (!body.messages || !Array.isArray(body.messages)) { - requestTracker.recordFailure('invalid_messages'); - res.status(400).json({ - error: { - message: 'Invalid or missing messages array', - type: 'invalid_request_error', - code: 'invalid_payload' - } - }); - return; + throw new Error('Invalid or missing messages array'); } - // Delegate to Revolver Engine - await revolverEngine.executeChatCompletion({ - requestBody: body, - requestId, - res, - isStreaming: !!body.stream, - onSuccess: (tokens) => { - isFinished = true; - requestTracker.recordSuccess(tokens); - requestLogger.logResponse(requestId, { - statusCode: 200, - response: { - streaming: !!body.stream, - usage: { - prompt_tokens: tokens.input, - completion_tokens: tokens.output, - total_tokens: tokens.input + tokens.output - } - } - }); - }, - onFailure: (reason) => { - if (!isFinished) { - isFinished = true; - requestTracker.recordFailure(reason); - } - }, - onCancelled: () => { - if (!isFinished) { - isFinished = true; - requestTracker.recordCancelled(); - requestLogger.logError(requestId, { - message: 'Client cancelled request', - path: req.path - }); - } + // Estimate input tokens from prompt messages + estimatedInputTokens = estimateMessagesTokens(body.messages); + + // Get Gemini client with rotated key + const keyRotationStart = Date.now(); + const { client: genAI, apiKey: currentApiKey } = keyRotationManager.createGenerativeAI(); + apiKey = currentApiKey; + console.log('[TIMING] Key rotation took:', Date.now() - keyRotationStart, 'ms'); + + // Always use the configured Gemini model internally, but return the requested model name in response + requestedModel = body.model || config.model; + + // Use cached model instance if available + const cacheKey = `${apiKey}_${config.model}`; + let model; + if (modelCache.has(cacheKey)) { + model = modelCache.get(cacheKey); + } else { + model = genAI.getGenerativeModel({ model: config.model }); + modelCache.set(cacheKey, model); + } + + // Convert messages + const geminiMessages = convertToGeminiMessages(body.messages); + + // Start chat + const chat = model.startChat({ + history: geminiMessages.slice(0, -1), + generationConfig: { + temperature: body.temperature || 0.7, + maxOutputTokens: body.max_tokens || 1024, + topP: body.top_p || 0.8 } }); - } catch (error: any) { - if (!isFinished) { + // Get the last user message + const lastMessage = geminiMessages[geminiMessages.length - 1]; + if (!lastMessage || lastMessage.role !== 'user') { + throw new Error('Last message must be from user'); + } + + // Handle streaming requests + if (body.stream) { + console.log('[DEBUG] Streaming response requested'); + + // Set headers for streaming + res.setHeader('Content-Type', 'text/event-stream'); + res.setHeader('Cache-Control', 'no-cache'); + res.setHeader('Connection', 'keep-alive'); + + // Generate streaming response + const geminiStart = Date.now(); + const result = await chat.sendMessageStream(lastMessage.parts[0].text); + console.log('[TIMING] Gemini API call started:', Date.now() - geminiStart, 'ms'); + + let fullContent = ''; + let chunkIndex = 0; + const firstChunkTime = Date.now(); + + for await (const chunk of result.stream) { + if (isCancelled || res.destroyed) { + isCancelled = true; + break; + } + + const chunkText = chunk.text(); + fullContent += chunkText; + outputTokensSoFar = Math.ceil(fullContent.length / 4); + + if (chunkIndex === 0) { + console.log('[TIMING] First chunk received:', Date.now() - firstChunkTime, 'ms'); + } + + // Send OpenAI-format chunk + const chunkResponse = { + id: `chatcmpl-${requestId}`, + object: 'chat.completion.chunk', + created: Math.floor(Date.now() / 1000), + model: requestedModel, + choices: [{ + index: 0, + delta: { + content: chunkText + }, + finish_reason: null + }] + }; + + res.write(`data: ${JSON.stringify(chunkResponse)}\n\n`); + chunkIndex++; + } + + if (isCancelled) { + return; + } + + // Send final chunk + const finalChunk = { + id: `chatcmpl-${requestId}`, + object: 'chat.completion.chunk', + created: Math.floor(Date.now() / 1000), + model: requestedModel, + choices: [{ + index: 0, + delta: {}, + finish_reason: 'stop' + }] + }; + + res.write(`data: ${JSON.stringify(finalChunk)}\n\n`); + res.write('data: [DONE]\n\n'); isFinished = true; - requestTracker.recordFailure(error.message); + res.end(); + + const totalTime = Date.now() - startTime; + console.log('[TIMING] Streaming response completed:', { + requestId, + totalChunks: chunkIndex, + contentLength: fullContent.length, + totalTime: totalTime + 'ms', + avgTimePerChunk: (totalTime / chunkIndex).toFixed(2) + 'ms' + }); + + // Extract accurate usageMetadata if available from aggregated stream response + let finalPromptTokens = estimatedInputTokens; + let finalCompletionTokens = outputTokensSoFar; + try { + const finalResponse = await result.response; + if (finalResponse?.usageMetadata) { + if (finalResponse.usageMetadata.promptTokenCount) { + finalPromptTokens = finalResponse.usageMetadata.promptTokenCount; + } + if (finalResponse.usageMetadata.candidatesTokenCount) { + finalCompletionTokens = finalResponse.usageMetadata.candidatesTokenCount; + } + } + } catch { + // Fallback to estimated tokens + } + + isFinished = true; + requestTracker.recordSuccess({ + input: finalPromptTokens, + output: finalCompletionTokens + }); + + requestLogger.logResponse(requestId, { + statusCode: 200, + response: { + streaming: true, + chunks: chunkIndex, + contentLength: fullContent.length, + usage: { + prompt_tokens: finalPromptTokens, + completion_tokens: finalCompletionTokens, + total_tokens: finalPromptTokens + finalCompletionTokens + } + } + }); + + return; + } + + // Generate non-streaming response + const geminiStart = Date.now(); + const result = await chat.sendMessage(lastMessage.parts[0].text); + if (isCancelled || res.destroyed) return; + + const response = await result.response; + if (isCancelled || res.destroyed) return; + + console.log('[TIMING] Gemini API call took:', Date.now() - geminiStart, 'ms'); + + // Convert to OpenAI format + const openaiResponse = convertToOpenAIResponse({ response }, requestedModel, requestId); + + // Compute input & output tokens + const promptTokens = response?.usageMetadata?.promptTokenCount || estimatedInputTokens; + const completionTokens = response?.usageMetadata?.candidatesTokenCount || Math.ceil((openaiResponse.choices[0]?.message?.content || '').length / 4); + + isFinished = true; + requestTracker.recordSuccess({ + input: promptTokens, + output: completionTokens + }); + + // Log the response + const totalTime = Date.now() - startTime; + console.log('[TIMING] Non-streaming response completed:', { + requestId, + statusCode: 200, + model: requestedModel, + contentLength: openaiResponse.choices[0]?.message?.content?.length || 0, + totalTime: totalTime + 'ms' + }); + + requestLogger.logResponse(requestId, { + statusCode: 200, + response: openaiResponse + }); + + res.json(openaiResponse); + + } catch (error: any) { + if (!isCancelled && !isFinished) { + isFinished = true; + const isRateLimit = + error.status === 429 || + error.message?.includes('RATE_LIMIT_EXCEEDED') || + error.message?.includes('quota') || + error.message?.includes('limit') || + error.code === 429 || + error.statusCode === 429; + requestTracker.recordFailure(isRateLimit ? 'rate_limit' : 'error'); } console.error('[ERROR] Error in chat completion:', { requestId, error: error.message, - stack: error.stack + stack: error.stack, + name: error.name, + status: error.status, + code: error.code }); - + + // Log the error requestLogger.logError(requestId, { error: error.message, stack: error.stack }); - if (!res.headersSent) { - res.status(error.status || 500).json({ + // Check if it's a rate limit error + const isRateLimitError = + error.status === 429 || + error.message?.includes('RATE_LIMIT_EXCEEDED') || + error.message?.includes('quota') || + error.message?.includes('limit') || + error.code === 429 || + error.statusCode === 429; + + if (isRateLimitError) { + // Mark the key as rate limited if we have the API key + if (apiKey) { + keyRotationManager.markKeyAsRateLimited(apiKey); + } + + res.status(429).json({ + error: { + message: 'Rate limit exceeded. Please try again later.', + type: 'rate_limit_error', + code: 'rate_limit_exceeded' + } + }); + } else { + res.status(500).json({ error: { message: error.message || 'Internal server error', type: 'server_error', @@ -129,33 +373,22 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { router.get('/v1/models', (req: Request, res: Response) => { const requestId = requestLogger.generateRequestId(); statsTracker.recordDirectSuccess({ input: 0, output: 0 }, req.path); - + requestLogger.logRequest(requestId, { path: req.path, method: req.method }); - const customModels = configStore.getCustomModels(); - const modelsData = customModels.map(m => ({ - id: m.name, - object: 'model' as const, - created: Math.floor(new Date(m.createdAt || Date.now()).getTime() / 1000), - owned_by: 'revolver' - })); - - // If no custom models are defined, provide default fallback - if (modelsData.length === 0) { - modelsData.push({ - id: config.model, - object: 'model' as const, - created: Math.floor(Date.now() / 1000), - owned_by: 'google' - }); - } - const modelsResponse: OpenAIModelsResponse = { object: 'list', - data: modelsData + data: [ + { + id: config.model, + object: 'model', + created: Math.floor(Date.now() / 1000), + owned_by: 'google' + } + ] }; requestLogger.logResponse(requestId, { @@ -168,25 +401,14 @@ router.get('/v1/models', (req: Request, res: Response) => { // GET /health router.get('/health', (req: Request, res: Response) => { - const providers = configStore.getProviders(); - const now = Date.now(); - - const keyStats = providers.flatMap(p => - p.keys.map(k => ({ - provider: p.name, - type: p.type, - maskedKey: configStore.maskKey(k.key), - lastUsed: k.lastUsed ? new Date(k.lastUsed).toISOString() : null, - requestCount: k.requestCount || 0, - rateLimited: !!(k.rateLimitedUntil && now < k.rateLimitedUntil) - })) - ); - + const keyStats = keyRotationManager.getKeyStats(); res.json({ status: 'healthy', - providersCount: providers.length, - customModelsCount: configStore.getCustomModels().length, - keys: keyStats + keys: keyStats.map(k => ({ + lastUsed: new Date(k.lastUsed).toISOString(), + requestCount: k.requestCount, + rateLimited: k.rateLimitedUntil ? true : false + })) }); }); diff --git a/src/stats.ts b/src/stats.ts index 411b7ec..f8cfe94 100644 --- a/src/stats.ts +++ b/src/stats.ts @@ -1,7 +1,6 @@ import fs from 'fs'; import path from 'path'; import { config } from './config'; -import { configStore } from './configStore'; export interface StatsData { totalRequests: number; @@ -311,11 +310,6 @@ export class StatsTracker { const uptimeSeconds = Math.floor((Date.now() - this.serverStartedAt.getTime()) / 1000); const uptimeFormatted = this.formatUptime(uptimeSeconds); - const providers = configStore.getProviders(); - const totalKeys = providers.reduce((sum, p) => sum + p.keys.length, 0); - const keysCount = totalKeys > 0 ? totalKeys : config.geminiApiKeys.length; - const activeModel = configStore.getDefaultModel()?.name || config.model; - return { requests: { total, @@ -335,8 +329,8 @@ export class StatsTracker { startedAt: this.serverStartedAt.toISOString(), lastRequestAt: this.stats.lastRequestAt, server: { - model: activeModel, - configuredKeysCount: keysCount + model: config.model, + configuredKeysCount: config.geminiApiKeys.length } }; } @@ -1143,7 +1137,6 @@ export class StatsTracker {