feat: add public stats dashboard and request/token tracking
This commit is contained in:
parent
9850334202
commit
f984a7e8e2
5 changed files with 1273 additions and 1 deletions
|
|
@ -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
|
- 🔐 **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
|
- 🔄 **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
|
- 📝 **Request/response logging** - Logs all API requests and responses to JSON files
|
||||||
- 🎯 **OpenAI v1 compatible** - Drop-in replacement for OpenAI API endpoints
|
- 🎯 **OpenAI v1 compatible** - Drop-in replacement for OpenAI API endpoints
|
||||||
- ⚡ **Rate limit handling** - Automatically handles rate limiting and rotates to available keys
|
- ⚡ **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`
|
#### `GET /v1/models`
|
||||||
List available models
|
List available models
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,13 @@
|
||||||
import { Request, Response, NextFunction } from 'express';
|
import { Request, Response, NextFunction } from 'express';
|
||||||
import { config } from './config';
|
import { config } from './config';
|
||||||
import { requestLogger } from './logger';
|
import { requestLogger } from './logger';
|
||||||
|
import { statsTracker } from './stats';
|
||||||
|
|
||||||
export const authenticateApiKey = (req: Request, res: Response, next: NextFunction): void => {
|
export const authenticateApiKey = (req: Request, res: Response, next: NextFunction): void => {
|
||||||
const authHeader = req.headers.authorization;
|
const authHeader = req.headers.authorization;
|
||||||
|
|
||||||
if (!authHeader) {
|
if (!authHeader) {
|
||||||
|
statsTracker.recordDirectFailure('missing_auth_header', req.path);
|
||||||
const requestId = requestLogger.generateRequestId();
|
const requestId = requestLogger.generateRequestId();
|
||||||
requestLogger.logError(requestId, { message: 'Missing Authorization header', path: req.path });
|
requestLogger.logError(requestId, { message: 'Missing Authorization header', path: req.path });
|
||||||
res.status(401).json({
|
res.status(401).json({
|
||||||
|
|
@ -21,6 +23,7 @@ export const authenticateApiKey = (req: Request, res: Response, next: NextFuncti
|
||||||
// OpenAI format: "Bearer <api_key>"
|
// OpenAI format: "Bearer <api_key>"
|
||||||
const parts = authHeader.split(' ');
|
const parts = authHeader.split(' ');
|
||||||
if (parts.length !== 2 || parts[0] !== 'Bearer') {
|
if (parts.length !== 2 || parts[0] !== 'Bearer') {
|
||||||
|
statsTracker.recordDirectFailure('invalid_auth_format', req.path);
|
||||||
const requestId = requestLogger.generateRequestId();
|
const requestId = requestLogger.generateRequestId();
|
||||||
requestLogger.logError(requestId, { message: 'Invalid Authorization format', path: req.path });
|
requestLogger.logError(requestId, { message: 'Invalid Authorization format', path: req.path });
|
||||||
res.status(401).json({
|
res.status(401).json({
|
||||||
|
|
@ -36,6 +39,7 @@ export const authenticateApiKey = (req: Request, res: Response, next: NextFuncti
|
||||||
const providedKey = parts[1];
|
const providedKey = parts[1];
|
||||||
|
|
||||||
if (providedKey !== config.apiPassword) {
|
if (providedKey !== config.apiPassword) {
|
||||||
|
statsTracker.recordDirectFailure('invalid_api_key', req.path);
|
||||||
const requestId = requestLogger.generateRequestId();
|
const requestId = requestLogger.generateRequestId();
|
||||||
requestLogger.logError(requestId, { message: 'Invalid API key', path: req.path });
|
requestLogger.logError(requestId, { message: 'Invalid API key', path: req.path });
|
||||||
res.status(401).json({
|
res.status(401).json({
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ import express, { Application } from 'express';
|
||||||
import cors from 'cors';
|
import cors from 'cors';
|
||||||
import { config } from './config';
|
import { config } from './config';
|
||||||
import { authenticateApiKey } from './auth';
|
import { authenticateApiKey } from './auth';
|
||||||
|
import { statsTracker } from './stats';
|
||||||
import routes from './routes';
|
import routes from './routes';
|
||||||
|
|
||||||
const app: Application = express();
|
const app: Application = express();
|
||||||
|
|
@ -31,6 +32,9 @@ app.use('/', routes);
|
||||||
|
|
||||||
// Catch-all route for debugging (must be after routes)
|
// Catch-all route for debugging (must be after routes)
|
||||||
app.use('*', (req, res) => {
|
app.use('*', (req, res) => {
|
||||||
|
if (req.path.startsWith('/v1')) {
|
||||||
|
statsTracker.recordDirectFailure('route_not_found', req.path);
|
||||||
|
}
|
||||||
console.log('[DEBUG] Unmatched route:', {
|
console.log('[DEBUG] Unmatched route:', {
|
||||||
method: req.method,
|
method: req.method,
|
||||||
path: req.path,
|
path: req.path,
|
||||||
|
|
@ -49,6 +53,9 @@ app.use('*', (req, res) => {
|
||||||
|
|
||||||
// Error handling middleware
|
// Error handling middleware
|
||||||
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
|
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);
|
console.error('[ERROR] Unhandled error:', err);
|
||||||
res.status(500).json({
|
res.status(500).json({
|
||||||
error: {
|
error: {
|
||||||
|
|
|
||||||
123
src/routes.ts
123
src/routes.ts
|
|
@ -3,6 +3,7 @@ import { GoogleGenerativeAI } from '@google/generative-ai';
|
||||||
import { keyRotationManager } from './keyRotation';
|
import { keyRotationManager } from './keyRotation';
|
||||||
import { requestLogger } from './logger';
|
import { requestLogger } from './logger';
|
||||||
import { config } from './config';
|
import { config } from './config';
|
||||||
|
import { statsTracker, estimateMessagesTokens } from './stats';
|
||||||
import {
|
import {
|
||||||
OpenAIChatRequest,
|
OpenAIChatRequest,
|
||||||
OpenAIChatResponse,
|
OpenAIChatResponse,
|
||||||
|
|
@ -54,9 +55,29 @@ function convertToOpenAIResponse(geminiResponse: any, model: string, requestId:
|
||||||
// POST /v1/chat/completions
|
// POST /v1/chat/completions
|
||||||
router.post('/v1/chat/completions', async (req: Request, res: Response) => {
|
router.post('/v1/chat/completions', async (req: Request, res: Response) => {
|
||||||
const requestId = requestLogger.generateRequestId();
|
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 apiKey = '';
|
||||||
let requestedModel = '';
|
let requestedModel = '';
|
||||||
const startTime = Date.now();
|
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 {
|
try {
|
||||||
const body: OpenAIChatRequest = req.body;
|
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');
|
throw new Error('Invalid or missing messages array');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Estimate input tokens from prompt messages
|
||||||
|
estimatedInputTokens = estimateMessagesTokens(body.messages);
|
||||||
|
|
||||||
// Get Gemini client with rotated key
|
// Get Gemini client with rotated key
|
||||||
const keyRotationStart = Date.now();
|
const keyRotationStart = Date.now();
|
||||||
const { client: genAI, apiKey: currentApiKey } = keyRotationManager.createGenerativeAI();
|
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();
|
const firstChunkTime = Date.now();
|
||||||
|
|
||||||
for await (const chunk of result.stream) {
|
for await (const chunk of result.stream) {
|
||||||
|
if (isCancelled || req.destroyed || res.destroyed) {
|
||||||
|
isCancelled = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
const chunkText = chunk.text();
|
const chunkText = chunk.text();
|
||||||
fullContent += chunkText;
|
fullContent += chunkText;
|
||||||
|
outputTokensSoFar = Math.ceil(fullContent.length / 4);
|
||||||
|
|
||||||
if (chunkIndex === 0) {
|
if (chunkIndex === 0) {
|
||||||
console.log('[TIMING] First chunk received:', Date.now() - firstChunkTime, 'ms');
|
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`);
|
res.write(`data: ${JSON.stringify(chunkResponse)}\n\n`);
|
||||||
chunkIndex++;
|
chunkIndex++;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (isCancelled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// Send final chunk
|
// Send final chunk
|
||||||
const finalChunk = {
|
const finalChunk = {
|
||||||
|
|
@ -191,10 +225,42 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => {
|
||||||
totalTime: totalTime + 'ms',
|
totalTime: totalTime + 'ms',
|
||||||
avgTimePerChunk: (totalTime / chunkIndex).toFixed(2) + '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, {
|
requestLogger.logResponse(requestId, {
|
||||||
statusCode: 200,
|
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;
|
return;
|
||||||
|
|
@ -203,12 +269,26 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => {
|
||||||
// Generate non-streaming response
|
// Generate non-streaming response
|
||||||
const geminiStart = Date.now();
|
const geminiStart = Date.now();
|
||||||
const result = await chat.sendMessage(lastMessage.parts[0].text);
|
const result = await chat.sendMessage(lastMessage.parts[0].text);
|
||||||
|
if (isCancelled || req.destroyed) return;
|
||||||
|
|
||||||
const response = await result.response;
|
const response = await result.response;
|
||||||
|
if (isCancelled || req.destroyed) return;
|
||||||
|
|
||||||
console.log('[TIMING] Gemini API call took:', Date.now() - geminiStart, 'ms');
|
console.log('[TIMING] Gemini API call took:', Date.now() - geminiStart, 'ms');
|
||||||
|
|
||||||
// Convert to OpenAI format
|
// Convert to OpenAI format
|
||||||
const openaiResponse = convertToOpenAIResponse({ response }, requestedModel, requestId);
|
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
|
// Log the response
|
||||||
const totalTime = Date.now() - startTime;
|
const totalTime = Date.now() - startTime;
|
||||||
console.log('[TIMING] Non-streaming response completed:', {
|
console.log('[TIMING] Non-streaming response completed:', {
|
||||||
|
|
@ -227,6 +307,18 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => {
|
||||||
res.json(openaiResponse);
|
res.json(openaiResponse);
|
||||||
|
|
||||||
} catch (error: any) {
|
} 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:', {
|
console.error('[ERROR] Error in chat completion:', {
|
||||||
requestId,
|
requestId,
|
||||||
error: error.message,
|
error: error.message,
|
||||||
|
|
@ -279,6 +371,7 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => {
|
||||||
// GET /v1/models
|
// GET /v1/models
|
||||||
router.get('/v1/models', (req: Request, res: Response) => {
|
router.get('/v1/models', (req: Request, res: Response) => {
|
||||||
const requestId = requestLogger.generateRequestId();
|
const requestId = requestLogger.generateRequestId();
|
||||||
|
statsTracker.recordDirectSuccess({ input: 0, output: 0 }, req.path);
|
||||||
|
|
||||||
requestLogger.logRequest(requestId, {
|
requestLogger.logRequest(requestId, {
|
||||||
path: req.path,
|
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(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#38bdf8"><path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/></svg>`);
|
||||||
|
});
|
||||||
|
|
||||||
export default router;
|
export default router;
|
||||||
|
|
|
||||||
1133
src/stats.ts
Normal file
1133
src/stats.ts
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue