From f984a7e8e210c41c2a74667669f2758f0efe2116 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sun, 11 Oct 2026 18:09:44 +0000 Subject: [PATCH] feat: add public stats dashboard and request/token tracking --- README.md | 7 + src/auth.ts | 4 + src/index.ts | 7 + src/routes.ts | 123 +++++- src/stats.ts | 1133 +++++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 1273 insertions(+), 1 deletion(-) create mode 100644 src/stats.ts diff --git a/README.md b/README.md index dba2b30..3376887 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ An OpenAI v1 compatible API endpoint that rotates Gemini API keys to avoid rate - 🔐 **Password-based API key authentication** - Clients must provide a configured password as their API key - 🔄 **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 - 🎯 **OpenAI v1 compatible** - Drop-in replacement for OpenAI API endpoints - ⚡ **Rate limit handling** - Automatically handles rate limiting and rotates to available keys @@ -181,6 +182,12 @@ Create chat completions (OpenAI v1 compatible) } ``` +#### `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 diff --git a/src/auth.ts b/src/auth.ts index b347c4f..9057d4c 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -1,11 +1,13 @@ import { Request, Response, NextFunction } from 'express'; import { config } from './config'; import { requestLogger } from './logger'; +import { statsTracker } from './stats'; export const authenticateApiKey = (req: Request, res: Response, next: NextFunction): void => { const authHeader = req.headers.authorization; if (!authHeader) { + statsTracker.recordDirectFailure('missing_auth_header', req.path); const requestId = requestLogger.generateRequestId(); requestLogger.logError(requestId, { message: 'Missing Authorization header', path: req.path }); res.status(401).json({ @@ -21,6 +23,7 @@ export const authenticateApiKey = (req: Request, res: Response, next: NextFuncti // 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({ @@ -36,6 +39,7 @@ export const authenticateApiKey = (req: Request, res: Response, next: NextFuncti const providedKey = parts[1]; if (providedKey !== config.apiPassword) { + 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/index.ts b/src/index.ts index 2e13a4d..fb179d9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,6 +2,7 @@ import express, { Application } from 'express'; import cors from 'cors'; import { config } from './config'; import { authenticateApiKey } from './auth'; +import { statsTracker } from './stats'; import routes from './routes'; const app: Application = express(); @@ -31,6 +32,9 @@ app.use('/', routes); // Catch-all route for debugging (must be after routes) app.use('*', (req, res) => { + if (req.path.startsWith('/v1')) { + statsTracker.recordDirectFailure('route_not_found', req.path); + } console.log('[DEBUG] Unmatched route:', { method: req.method, path: req.path, @@ -49,6 +53,9 @@ app.use('*', (req, res) => { // Error handling middleware app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => { + if (req.path.startsWith('/v1')) { + statsTracker.recordDirectFailure('unhandled_error', req.path); + } console.error('[ERROR] Unhandled error:', err); res.status(500).json({ error: { diff --git a/src/routes.ts b/src/routes.ts index a6ad16b..6f426f9 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -3,6 +3,7 @@ import { GoogleGenerativeAI } from '@google/generative-ai'; import { keyRotationManager } from './keyRotation'; import { requestLogger } from './logger'; import { config } from './config'; +import { statsTracker, estimateMessagesTokens } from './stats'; import { OpenAIChatRequest, OpenAIChatResponse, @@ -54,9 +55,29 @@ function convertToOpenAIResponse(geminiResponse: any, model: string, requestId: // 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 + req.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; @@ -83,6 +104,9 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { throw new Error('Invalid or missing messages array'); } + // 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(); @@ -140,8 +164,14 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { const firstChunkTime = Date.now(); for await (const chunk of result.stream) { + if (isCancelled || req.destroyed || 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'); @@ -165,6 +195,10 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { res.write(`data: ${JSON.stringify(chunkResponse)}\n\n`); chunkIndex++; } + + if (isCancelled) { + return; + } // Send final chunk const finalChunk = { @@ -191,10 +225,42 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { 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 } + response: { + streaming: true, + chunks: chunkIndex, + contentLength: fullContent.length, + usage: { + prompt_tokens: finalPromptTokens, + completion_tokens: finalCompletionTokens, + total_tokens: finalPromptTokens + finalCompletionTokens + } + } }); return; @@ -203,12 +269,26 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { // Generate non-streaming response const geminiStart = Date.now(); const result = await chat.sendMessage(lastMessage.parts[0].text); + if (isCancelled || req.destroyed) return; + const response = await result.response; + if (isCancelled || req.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:', { @@ -227,6 +307,18 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { 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, @@ -279,6 +371,7 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { // GET /v1/models 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, @@ -318,4 +411,32 @@ router.get('/health', (req: Request, res: Response) => { }); }); +// GET / (Public stats page at root) +router.get('/', (req: Request, res: Response) => { + const acceptsJson = req.accepts(['html', 'json']) === 'json' || req.query.format === 'json'; + const summary = statsTracker.getStatsSummary(); + if (acceptsJson) { + res.json(summary); + } else { + res.setHeader('Content-Type', 'text/html; charset=utf-8'); + res.send(statsTracker.renderStatsHtml(summary)); + } +}); + +// GET /api/stats (Public JSON stats API) +router.get('/api/stats', (req: Request, res: Response) => { + res.json(statsTracker.getStatsSummary()); +}); + +// GET /stats (Alias for root stats page) +router.get('/stats', (req: Request, res: Response) => { + res.redirect('/'); +}); + +// GET /favicon.ico (Avoid 404 logs from browser favicon requests) +router.get('/favicon.ico', (req: Request, res: Response) => { + res.setHeader('Content-Type', 'image/svg+xml'); + res.send(``); +}); + export default router; diff --git a/src/stats.ts b/src/stats.ts new file mode 100644 index 0000000..f2d10cf --- /dev/null +++ b/src/stats.ts @@ -0,0 +1,1133 @@ +import fs from 'fs'; +import path from 'path'; +import { config } from './config'; + +export interface StatsData { + totalRequests: number; + wentThrough: number; + failed: number; + cancelled: number; + inputTokens: number; + outputTokens: number; + totalTokens: number; + firstRequestAt: string | null; + lastRequestAt: string | null; +} + +export interface StatsSummary { + requests: { + total: number; + wentThrough: number; + failed: number; + cancelled: number; + successRate: number; + }; + tokens: { + total: number; + input: number; + output: number; + }; + activeRequests: number; + uptimeSeconds: number; + uptimeFormatted: string; + startedAt: string; + lastRequestAt: string | null; + server: { + model: string; + configuredKeysCount: number; + }; +} + +export interface RequestTracker { + recordSuccess: (tokens: { input: number; output: number }) => void; + recordFailure: (reason?: string) => void; + recordCancelled: (tokens?: { input: number; output: number }) => void; +} + +export function estimateTokens(text: string): number { + if (!text) return 0; + // Approximation: ~4 characters per token for typical text/code + return Math.max(1, Math.ceil(text.length / 4)); +} + +export function estimateMessagesTokens(messages: any[]): number { + if (!Array.isArray(messages) || messages.length === 0) return 0; + const fullText = messages + .map(m => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content || ''))) + .join('\n'); + return estimateTokens(fullText); +} + +export class StatsTracker { + private stats: StatsData = { + totalRequests: 0, + wentThrough: 0, + failed: 0, + cancelled: 0, + inputTokens: 0, + outputTokens: 0, + totalTokens: 0, + firstRequestAt: null, + lastRequestAt: null + }; + + private activeRequests: number = 0; + private serverStartedAt: Date = new Date(); + private statsFilePath: string; + private saveTimeout: NodeJS.Timeout | null = null; + + constructor() { + this.statsFilePath = path.join(config.logDir, 'stats.json'); + this.ensureLogDir(); + this.loadStats(); + + // Ensure save on process termination + process.on('SIGINT', () => this.saveSync()); + process.on('SIGTERM', () => this.saveSync()); + } + + private ensureLogDir(): void { + if (!fs.existsSync(config.logDir)) { + try { + fs.mkdirSync(config.logDir, { recursive: true }); + } catch (err) { + console.error('[STATS] Failed to create log directory:', err); + } + } + } + + private loadStats(): void { + try { + if (fs.existsSync(this.statsFilePath)) { + const raw = fs.readFileSync(this.statsFilePath, 'utf8'); + const parsed = JSON.parse(raw); + this.stats = { + totalRequests: Number(parsed.totalRequests) || 0, + wentThrough: Number(parsed.wentThrough) || 0, + failed: Number(parsed.failed) || 0, + cancelled: Number(parsed.cancelled) || 0, + inputTokens: Number(parsed.inputTokens) || 0, + outputTokens: Number(parsed.outputTokens) || 0, + totalTokens: Number(parsed.totalTokens) || 0, + firstRequestAt: parsed.firstRequestAt || null, + lastRequestAt: parsed.lastRequestAt || null + }; + // Sanity check total calculation + if (this.stats.totalRequests < (this.stats.wentThrough + this.stats.failed + this.stats.cancelled)) { + this.stats.totalRequests = this.stats.wentThrough + this.stats.failed + this.stats.cancelled; + } + if (this.stats.totalTokens < (this.stats.inputTokens + this.stats.outputTokens)) { + this.stats.totalTokens = this.stats.inputTokens + this.stats.outputTokens; + } + console.log('[STATS] Loaded existing stats from disk:', { + requests: this.stats.totalRequests, + tokens: this.stats.totalTokens + }); + return; + } + + // If stats.json does not exist, check if there are historical log files + this.rebuildFromExistingLogs(); + } catch (err) { + console.error('[STATS] Error loading stats file, initializing fresh stats:', err); + } + } + + private rebuildFromExistingLogs(): void { + try { + if (!fs.existsSync(config.logDir)) return; + const files = fs.readdirSync(config.logDir).filter(f => f.startsWith('api-logs-') && f.endsWith('.json')); + if (files.length === 0) return; + + console.log(`[STATS] Scanning ${files.length} existing log file(s) to aggregate initial stats...`); + for (const file of files) { + const filePath = path.join(config.logDir, file); + const content = fs.readFileSync(filePath, 'utf8'); + const lines = content.split('\n'); + + for (const line of lines) { + if (!line.trim()) continue; + try { + const entry = JSON.parse(line); + if (entry.type === 'response') { + const status = entry.data?.statusCode || 200; + if (status >= 200 && status < 400) { + this.stats.wentThrough++; + const usage = entry.data?.response?.usage; + if (usage) { + this.stats.inputTokens += Number(usage.prompt_tokens) || 0; + this.stats.outputTokens += Number(usage.completion_tokens) || 0; + } + } else { + this.stats.failed++; + } + if (!this.stats.firstRequestAt || entry.timestamp < this.stats.firstRequestAt) { + this.stats.firstRequestAt = entry.timestamp; + } + if (!this.stats.lastRequestAt || entry.timestamp > this.stats.lastRequestAt) { + this.stats.lastRequestAt = entry.timestamp; + } + } else if (entry.type === 'error') { + this.stats.failed++; + if (!this.stats.lastRequestAt || entry.timestamp > this.stats.lastRequestAt) { + this.stats.lastRequestAt = entry.timestamp; + } + } + } catch { + // ignore malformed line + } + } + } + + this.stats.totalRequests = this.stats.wentThrough + this.stats.failed + this.stats.cancelled; + this.stats.totalTokens = this.stats.inputTokens + this.stats.outputTokens; + this.saveSync(); + console.log('[STATS] Rebuilt historical stats successfully:', { + requests: this.stats.totalRequests, + tokens: this.stats.totalTokens + }); + } catch (err) { + console.error('[STATS] Error scanning historical logs:', err); + } + } + + private scheduleSave(): void { + if (this.saveTimeout) return; + this.saveTimeout = setTimeout(() => { + this.saveTimeout = null; + this.saveSync(); + }, 1000); + } + + public saveSync(): void { + try { + this.ensureLogDir(); + const tmpPath = `${this.statsFilePath}.tmp`; + fs.writeFileSync(tmpPath, JSON.stringify(this.stats, null, 2), 'utf8'); + fs.renameSync(tmpPath, this.statsFilePath); + } catch (err) { + console.error('[STATS] Error saving stats to file:', err); + } + } + + private updateTimestamps(): void { + const now = new Date().toISOString(); + if (!this.stats.firstRequestAt) { + this.stats.firstRequestAt = now; + } + this.stats.lastRequestAt = now; + } + + public startRequest(endpoint?: string): RequestTracker { + this.activeRequests++; + let resolved = false; + + return { + recordSuccess: (tokens: { input: number; output: number }) => { + if (resolved) return; + resolved = true; + this.activeRequests = Math.max(0, this.activeRequests - 1); + this.stats.totalRequests++; + this.stats.wentThrough++; + const safeInput = Math.max(0, Math.round(tokens.input || 0)); + const safeOutput = Math.max(0, Math.round(tokens.output || 0)); + this.stats.inputTokens += safeInput; + this.stats.outputTokens += safeOutput; + this.stats.totalTokens += safeInput + safeOutput; + this.updateTimestamps(); + this.scheduleSave(); + }, + + recordFailure: (_reason?: string) => { + if (resolved) return; + resolved = true; + this.activeRequests = Math.max(0, this.activeRequests - 1); + this.stats.totalRequests++; + this.stats.failed++; + this.updateTimestamps(); + this.scheduleSave(); + }, + + recordCancelled: (tokens?: { input: number; output: number }) => { + if (resolved) return; + resolved = true; + this.activeRequests = Math.max(0, this.activeRequests - 1); + this.stats.totalRequests++; + this.stats.cancelled++; + if (tokens) { + const safeInput = Math.max(0, Math.round(tokens.input || 0)); + const safeOutput = Math.max(0, Math.round(tokens.output || 0)); + this.stats.inputTokens += safeInput; + this.stats.outputTokens += safeOutput; + this.stats.totalTokens += safeInput + safeOutput; + } + this.updateTimestamps(); + this.scheduleSave(); + } + }; + } + + public recordDirectSuccess(tokens: { input: number; output: number }, _endpoint?: string): void { + this.stats.totalRequests++; + this.stats.wentThrough++; + const safeInput = Math.max(0, Math.round(tokens.input || 0)); + const safeOutput = Math.max(0, Math.round(tokens.output || 0)); + this.stats.inputTokens += safeInput; + this.stats.outputTokens += safeOutput; + this.stats.totalTokens += safeInput + safeOutput; + this.updateTimestamps(); + this.scheduleSave(); + } + + public recordDirectFailure(_reason?: string, _endpoint?: string): void { + this.stats.totalRequests++; + this.stats.failed++; + this.updateTimestamps(); + this.scheduleSave(); + } + + public recordDirectCancelled(tokens?: { input: number; output: number }, _endpoint?: string): void { + this.stats.totalRequests++; + this.stats.cancelled++; + if (tokens) { + const safeInput = Math.max(0, Math.round(tokens.input || 0)); + const safeOutput = Math.max(0, Math.round(tokens.output || 0)); + this.stats.inputTokens += safeInput; + this.stats.outputTokens += safeOutput; + this.stats.totalTokens += safeInput + safeOutput; + } + this.updateTimestamps(); + this.scheduleSave(); + } + + public getStatsSummary(): StatsSummary { + const total = this.stats.totalRequests; + const wentThrough = this.stats.wentThrough; + const failed = this.stats.failed; + const cancelled = this.stats.cancelled; + const successRate = total > 0 ? Number(((wentThrough / total) * 100).toFixed(1)) : 100.0; + + const uptimeSeconds = Math.floor((Date.now() - this.serverStartedAt.getTime()) / 1000); + const uptimeFormatted = this.formatUptime(uptimeSeconds); + + return { + requests: { + total, + wentThrough, + failed, + cancelled, + successRate + }, + tokens: { + total: this.stats.totalTokens, + input: this.stats.inputTokens, + output: this.stats.outputTokens + }, + activeRequests: this.activeRequests, + uptimeSeconds, + uptimeFormatted, + startedAt: this.serverStartedAt.toISOString(), + lastRequestAt: this.stats.lastRequestAt, + server: { + model: config.model, + configuredKeysCount: config.geminiApiKeys.length + } + }; + } + + private formatUptime(seconds: number): string { + const d = Math.floor(seconds / 86400); + const h = Math.floor((seconds % 86400) / 3600); + const m = Math.floor((seconds % 3600) / 60); + const s = seconds % 60; + if (d > 0) return `${d}d ${h}h ${m}m`; + if (h > 0) return `${h}h ${m}m ${s}s`; + if (m > 0) return `${m}m ${s}s`; + return `${s}s`; + } + + public renderStatsHtml(summary: StatsSummary): string { + const { requests, tokens, activeRequests, uptimeFormatted, lastRequestAt, server } = summary; + + const wentThroughPct = requests.total > 0 ? ((requests.wentThrough / requests.total) * 100).toFixed(1) : '100.0'; + const failedPct = requests.total > 0 ? ((requests.failed / requests.total) * 100).toFixed(1) : '0.0'; + const cancelledPct = requests.total > 0 ? ((requests.cancelled / requests.total) * 100).toFixed(1) : '0.0'; + + const inputTokensPct = tokens.total > 0 ? ((tokens.input / tokens.total) * 100).toFixed(1) : '50.0'; + const outputTokensPct = tokens.total > 0 ? ((tokens.output / tokens.total) * 100).toFixed(1) : '50.0'; + + return ` + + + + + GeminiRevolver — Public API Statistics + + + +
+ +
+
+
+ + + +
+
+
+ GeminiRevolver + + + Live Stats + +
+
Public Request & Token Metrics • OpenAI v1 Compatible Gateway
+
+
+ +
+ + +
+
+ + +
+ +
+
+ Total Requests + + + +
+
${requests.total.toLocaleString()}
+
+ ${requests.wentThrough.toLocaleString()} went through + ${requests.failed.toLocaleString()} failed + ${requests.cancelled.toLocaleString()} cancelled +
+
+ + +
+
+ Total Tokens + + + +
+
${tokens.total.toLocaleString()}
+
+ Input: ${tokens.input.toLocaleString()} + Output: ${tokens.output.toLocaleString()} +
+
+ + +
+
+ Success Rate + + + +
+
${requests.successRate}%
+
+ Went through vs all incoming requests +
+
+ + +
+
+ Active In-Flight + + + +
+
${activeRequests}
+
+ ${activeRequests === 0 ? 'Currently idle' : 'Processing completions'} +
+
+
+ + +
+ +
+
+
+ + + + Request Breakdown +
+ + ${requests.total.toLocaleString()} total + +
+ +
+
+
+
+
+ +
+
+
+ + Went Through (Completed) +
+
+ ${requests.wentThrough.toLocaleString()} + ${wentThroughPct}% +
+
+ +
+
+ + Failed (Error / Rate Limit) +
+
+ ${requests.failed.toLocaleString()} + ${failedPct}% +
+
+ +
+
+ + Cancelled (Client Disconnected) +
+
+ ${requests.cancelled.toLocaleString()} + ${cancelledPct}% +
+
+
+
+ + +
+
+
+ + + + Token Breakdown +
+ + ${tokens.total.toLocaleString()} tokens + +
+ +
+
+
+
+ +
+
+
+ + Input Tokens (Prompt) +
+
+ ${tokens.input.toLocaleString()} + ${inputTokensPct}% +
+
+ +
+
+ + Output Tokens (Completion) +
+
+ ${tokens.output.toLocaleString()} + ${outputTokensPct}% +
+
+ +
+
+ + Total Combined Tokens +
+
+ ${tokens.total.toLocaleString()} + 100.0% +
+
+
+
+
+ + +
+
+ Active Model Engine + ${server.model} +
+
+ API Key Pool + ${server.configuredKeysCount} keys rotating +
+
+ Gateway Uptime + ${uptimeFormatted} +
+
+ Last Request Received + ${lastRequestAt ? new Date(lastRequestAt).toLocaleTimeString() : 'None yet'} +
+
+ + +
+ + + + +
+ Privacy & Security Guarantee: This public dashboard provides high-level request counts and token volume stats only. + In compliance with privacy standards, no request bodies, prompt messages, completion texts, sender IPs, client headers, or API secrets are ever stored or exposed on this page. +
+
+ + +
+
GeminiRevolver — High Availability OpenAI v1 to Google Gemini Gateway
+
API Endpoint: POST /v1/chat/completions • Raw Stats API: /api/stats
+
+
+ + + +`; + } +} + +export const statsTracker = new StatsTracker();