feat: add admin menu, persistent json config, multi-provider support, and custom model fallback revolver
This commit is contained in:
parent
637a3cf255
commit
1c955619e7
21 changed files with 3742 additions and 388 deletions
190
src/adminRoutes.ts
Normal file
190
src/adminRoutes.ts
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
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;
|
||||
1752
src/adminView.ts
Normal file
1752
src/adminView.ts
Normal file
File diff suppressed because it is too large
Load diff
52
src/auth.ts
52
src/auth.ts
|
|
@ -4,15 +4,35 @@ 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) {
|
||||
statsTracker.recordDirectFailure('missing_auth_header', req.path);
|
||||
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);
|
||||
}
|
||||
const requestId = requestLogger.generateRequestId();
|
||||
requestLogger.logError(requestId, { message: 'Missing Authorization header', path: req.path });
|
||||
requestLogger.logError(requestId, { message: 'Missing Authorization', path: req.path });
|
||||
res.status(401).json({
|
||||
error: {
|
||||
message: 'Missing Authorization header',
|
||||
message: 'Missing Authorization header or API key. Expected: Authorization: Bearer <api_key>',
|
||||
type: 'invalid_request_error',
|
||||
code: 'missing_api_key'
|
||||
}
|
||||
|
|
@ -20,26 +40,10 @@ export const authenticateApiKey = (req: Request, res: Response, next: NextFuncti
|
|||
return;
|
||||
}
|
||||
|
||||
// OpenAI format: "Bearer <api_key>"
|
||||
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 <api_key>',
|
||||
type: 'invalid_request_error',
|
||||
code: 'invalid_api_key_format'
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const providedKey = parts[1];
|
||||
|
||||
if (providedKey !== config.apiPassword) {
|
||||
statsTracker.recordDirectFailure('invalid_api_key', req.path);
|
||||
if (req.path.startsWith('/v1')) {
|
||||
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({
|
||||
|
|
|
|||
|
|
@ -1,12 +1,14 @@
|
|||
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(',').filter(key => key.trim()),
|
||||
geminiApiKeys: (process.env.GEMINI_API_KEYS || '').split(',').map(k => k.trim()).filter(Boolean),
|
||||
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)
|
||||
};
|
||||
|
|
@ -14,7 +16,3 @@ 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');
|
||||
}
|
||||
|
|
|
|||
392
src/configStore.ts
Normal file
392
src/configStore.ts
Normal file
|
|
@ -0,0 +1,392 @@
|
|||
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<string, ProviderKeyConfig>();
|
||||
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();
|
||||
19
src/index.ts
19
src/index.ts
|
|
@ -66,14 +66,17 @@ app.use((err: any, req: express.Request, res: express.Response, next: express.Ne
|
|||
});
|
||||
});
|
||||
|
||||
// Start server
|
||||
// Start server if executed directly
|
||||
const PORT = config.port;
|
||||
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`);
|
||||
});
|
||||
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`);
|
||||
});
|
||||
}
|
||||
|
||||
export default app;
|
||||
|
|
|
|||
858
src/revolverEngine.ts
Normal file
858
src/revolverEngine.ts
Normal file
|
|
@ -0,0 +1,858 @@
|
|||
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<string, GoogleGenerativeAI> = new Map();
|
||||
// Per-tier round-robin pointer: Map<`${modelId}_tier_${tierIndex}`, number>
|
||||
private roundRobinPointers: Map<string, number> = 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<void> {
|
||||
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<OpenAIChatResponse> {
|
||||
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<OpenAIChatResponse> {
|
||||
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<OpenAIChatResponse> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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();
|
||||
64
src/revolverTypes.ts
Normal file
64
src/revolverTypes.ts
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
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;
|
||||
};
|
||||
}
|
||||
428
src/routes.ts
428
src/routes.ts
|
|
@ -1,98 +1,43 @@
|
|||
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, estimateMessagesTokens } from './stats';
|
||||
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 {
|
||||
OpenAIChatRequest,
|
||||
OpenAIChatResponse,
|
||||
OpenAIModelsResponse
|
||||
} from './openaiTypes';
|
||||
|
||||
const router = Router();
|
||||
|
||||
// Cache for model instances to avoid recreation
|
||||
const modelCache = new Map<string, any>();
|
||||
// Mount Admin API routes with authentication
|
||||
router.use('/api/admin', authenticateApiKey, adminRoutes);
|
||||
|
||||
// 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
|
||||
}
|
||||
};
|
||||
}
|
||||
// Admin Web UI Console
|
||||
router.get('/admin', (req: Request, res: Response) => {
|
||||
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
||||
res.send(renderAdminHtml());
|
||||
});
|
||||
|
||||
// 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;
|
||||
|
||||
// Log the request with full details for debugging
|
||||
console.log('[DEBUG] Incoming request:', {
|
||||
|
||||
console.log('[DEBUG] Incoming completion request:', {
|
||||
requestId,
|
||||
headers: {
|
||||
'content-type': req.headers['content-type'],
|
||||
'authorization': req.headers.authorization ? 'Bearer ***' : 'missing',
|
||||
'user-agent': req.headers['user-agent']
|
||||
},
|
||||
body: body
|
||||
model: body?.model,
|
||||
stream: !!body?.stream
|
||||
});
|
||||
|
||||
|
||||
requestLogger.logRequest(requestId, {
|
||||
path: req.path,
|
||||
method: req.method,
|
||||
|
|
@ -101,264 +46,75 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => {
|
|||
|
||||
// Validate request
|
||||
if (!body.messages || !Array.isArray(body.messages)) {
|
||||
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();
|
||||
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
|
||||
}
|
||||
});
|
||||
|
||||
// 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;
|
||||
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
|
||||
}
|
||||
requestTracker.recordFailure('invalid_messages');
|
||||
res.status(400).json({
|
||||
error: {
|
||||
message: 'Invalid or missing messages array',
|
||||
type: 'invalid_request_error',
|
||||
code: 'invalid_payload'
|
||||
}
|
||||
});
|
||||
|
||||
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:', {
|
||||
// Delegate to Revolver Engine
|
||||
await revolverEngine.executeChatCompletion({
|
||||
requestBody: body,
|
||||
requestId,
|
||||
statusCode: 200,
|
||||
model: requestedModel,
|
||||
contentLength: openaiResponse.choices[0]?.message?.content?.length || 0,
|
||||
totalTime: totalTime + 'ms'
|
||||
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
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
requestLogger.logResponse(requestId, {
|
||||
statusCode: 200,
|
||||
response: openaiResponse
|
||||
});
|
||||
|
||||
res.json(openaiResponse);
|
||||
|
||||
} catch (error: any) {
|
||||
if (!isCancelled && !isFinished) {
|
||||
if (!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');
|
||||
requestTracker.recordFailure(error.message);
|
||||
}
|
||||
|
||||
console.error('[ERROR] Error in chat completion:', {
|
||||
requestId,
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
name: error.name,
|
||||
status: error.status,
|
||||
code: error.code
|
||||
stack: error.stack
|
||||
});
|
||||
|
||||
// Log the error
|
||||
|
||||
requestLogger.logError(requestId, {
|
||||
error: error.message,
|
||||
stack: error.stack
|
||||
});
|
||||
|
||||
// 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({
|
||||
if (!res.headersSent) {
|
||||
res.status(error.status || 500).json({
|
||||
error: {
|
||||
message: error.message || 'Internal server error',
|
||||
type: 'server_error',
|
||||
|
|
@ -373,22 +129,33 @@ 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: [
|
||||
{
|
||||
id: config.model,
|
||||
object: 'model',
|
||||
created: Math.floor(Date.now() / 1000),
|
||||
owned_by: 'google'
|
||||
}
|
||||
]
|
||||
data: modelsData
|
||||
};
|
||||
|
||||
requestLogger.logResponse(requestId, {
|
||||
|
|
@ -401,14 +168,25 @@ router.get('/v1/models', (req: Request, res: Response) => {
|
|||
|
||||
// GET /health
|
||||
router.get('/health', (req: Request, res: Response) => {
|
||||
const keyStats = keyRotationManager.getKeyStats();
|
||||
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)
|
||||
}))
|
||||
);
|
||||
|
||||
res.json({
|
||||
status: 'healthy',
|
||||
keys: keyStats.map(k => ({
|
||||
lastUsed: new Date(k.lastUsed).toISOString(),
|
||||
requestCount: k.requestCount,
|
||||
rateLimited: k.rateLimitedUntil ? true : false
|
||||
}))
|
||||
providersCount: providers.length,
|
||||
customModelsCount: configStore.getCustomModels().length,
|
||||
keys: keyStats
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
11
src/stats.ts
11
src/stats.ts
|
|
@ -1,6 +1,7 @@
|
|||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { config } from './config';
|
||||
import { configStore } from './configStore';
|
||||
|
||||
export interface StatsData {
|
||||
totalRequests: number;
|
||||
|
|
@ -310,6 +311,11 @@ 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,
|
||||
|
|
@ -329,8 +335,8 @@ export class StatsTracker {
|
|||
startedAt: this.serverStartedAt.toISOString(),
|
||||
lastRequestAt: this.stats.lastRequestAt,
|
||||
server: {
|
||||
model: config.model,
|
||||
configuredKeysCount: config.geminiApiKeys.length
|
||||
model: activeModel,
|
||||
configuredKeysCount: keysCount
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
@ -1138,6 +1144,7 @@ export class StatsTracker {
|
|||
|
||||
<div class="nav-actions">
|
||||
<div class="nav-links">
|
||||
<a href="/admin" title="Admin Menu & Model Revolver">Admin Console</a>
|
||||
<a href="/api/stats" target="_blank" title="View raw JSON API">JSON API</a>
|
||||
<a href="/health" target="_blank" title="View gateway health status">Health</a>
|
||||
</div>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue