GeminiRevolver/src/revolverEngine.ts
tyuXX 299c5f4c9e feat(admin): add live key+model fallback telemetry and RAM-buffered live request log watcher
- Add TelemetryTracker to record request fallback journeys, tracking step-by-step cascades across tiers, candidate error codes, cooldowns, and next actions
- Add LiveWatcher for RAM-only interactive request inspection with 250-item FIFO safety cap and automatic memory flush on toggle off
- Add REST and SSE streaming endpoints for real-time telemetry and live request logs
- Upgrade Admin Telemetry tab with visual fallback breadcrumbs and live key health matrix
- Add dedicated Live Logs tab with deep multi-tab inspector (Input, Output, Metadata, Debug), search, filters, and JSON export
- Add unit and integration tests (test-live-watcher.ts, test-telemetry-fallback.ts)
2026-11-04 19:31:02 +00:00

1234 lines
42 KiB
TypeScript

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';
import { telemetryTracker, FallbackStep, RequestFallbackJourney } from './telemetryTracker';
import { liveWatcher } from './liveWatcher';
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;
}
public convertToGeminiContent(messages: any[]): {
systemInstruction?: string;
geminiMessages: any[];
} {
let systemInstruction = '';
const rawMessages: { role: 'user' | 'model'; parts: { text: string }[] }[] = [];
for (const msg of messages) {
if (msg.role === 'system') {
const text = typeof msg.content === 'string' ? msg.content : (msg.content != null ? JSON.stringify(msg.content) : '');
systemInstruction += (systemInstruction ? '\n\n' : '') + text;
} else {
const text = typeof msg.content === 'string' ? msg.content : (msg.content != null ? JSON.stringify(msg.content) : '');
rawMessages.push({
role: msg.role === 'assistant' ? 'model' : 'user',
parts: [{ text }]
});
}
}
// Step 1: Prepend empty user placeholder if the first non-system message is from 'model' (Option 1)
if (rawMessages.length > 0 && rawMessages[0].role === 'model') {
rawMessages.unshift({
role: 'user',
parts: [{ text: '' }]
});
}
// Step 2: Ensure normalization by merging consecutive messages with the same role (Option 3)
const geminiMessages: { role: 'user' | 'model'; parts: { text: string }[] }[] = [];
for (const msg of rawMessages) {
if (geminiMessages.length === 0) {
geminiMessages.push({ role: msg.role, parts: [{ text: msg.parts[0]?.text ?? '' }] });
} else {
const prevMsg = geminiMessages[geminiMessages.length - 1];
if (prevMsg.role === msg.role) {
const prevText = prevMsg.parts[0]?.text ?? '';
const currText = msg.parts[0]?.text ?? '';
const mergedText = !prevText ? currText : (!currText ? prevText : `${prevText}\n\n${currText}`);
prevMsg.parts = [{ text: mergedText }];
} else {
geminiMessages.push({ role: msg.role, parts: [{ text: msg.parts[0]?.text ?? '' }] });
}
}
}
// Ensure the conversation ends with a user message for Gemini chat completion
if (geminiMessages.length > 0 && geminiMessages[geminiMessages.length - 1].role === 'model') {
geminiMessages.push({
role: 'user',
parts: [{ text: '' }]
});
}
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;
let keepAliveTimer: NodeJS.Timeout | null = null;
let nonStreamingTimer: NodeJS.Timeout | null = null;
const cleanupTimers = () => {
if (keepAliveTimer) {
clearInterval(keepAliveTimer);
keepAliveTimer = null;
}
if (nonStreamingTimer) {
clearInterval(nonStreamingTimer);
nonStreamingTimer = null;
}
};
res.on('close', () => {
cleanupTimers();
if (!res.writableEnded) {
isCancelled = true;
if (onCancelled) onCancelled();
liveWatcher.cancelRequest(requestId);
}
});
if (isStreaming) {
// Send SSE headers immediately to establish connection with Cloudflare and prevent 524 timeouts
if (!res.headersSent) {
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
res.setHeader('Cache-Control', 'no-cache, no-transform');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no');
if (typeof res.flushHeaders === 'function') {
res.flushHeaders();
}
}
// Immediately transmit an initial SSE comment ping so Cloudflare Edge receives response bytes instantly
if (!res.destroyed && !res.writableEnded) {
res.write(': keep-alive\n\n');
liveWatcher.recordKeepAlive(requestId, 'sse_comment');
}
// Keep connection active with periodic SSE comments while waiting for model thinking / generation
keepAliveTimer = setInterval(() => {
if (!res.destroyed && !res.writableEnded) {
res.write(': keep-alive\n\n');
liveWatcher.recordKeepAlive(requestId, 'sse_comment');
}
}, config.keepAliveIntervalMs);
} else if (config.enableNonStreamingKeepAlive) {
// For non-streaming requests: start emitting whitespace chunks if request takes longer than nonStreamingKeepAliveDelayMs
nonStreamingTimer = setInterval(() => {
if (res.destroyed || res.writableEnded) {
cleanupTimers();
return;
}
if (!res.headersSent) {
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Transfer-Encoding', 'chunked');
res.setHeader('Cache-Control', 'no-cache, no-transform');
res.setHeader('X-Accel-Buffering', 'no');
if (typeof res.flushHeaders === 'function') {
res.flushHeaders();
}
}
res.write(' ');
liveWatcher.recordKeepAlive(requestId, 'whitespace');
}, config.nonStreamingKeepAliveDelayMs);
}
// Sort tiers by tierIndex
const sortedTiers = [...customModel.tiers].sort((a, b) => a.tierIndex - b.tierIndex);
if (sortedTiers.length === 0) {
cleanupTimers();
throw new Error(`Custom model '${customModel.name}' has no fallback tiers defined.`);
}
const journeyStart = Date.now();
const fallbackSteps: FallbackStep[] = [];
let totalHops = 0;
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) {
cleanupTimers();
return;
}
const candidateStart = Date.now();
totalHops++;
const isLastCandidateInTier = candidate === candidates[candidates.length - 1];
const isLastTier = tier === sortedTiers[sortedTiers.length - 1];
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) {
const streamResult = await this.executeStreaming({
candidate,
requestBody,
requestedModelName,
requestId,
res,
onStreamStart: () => {
streamStarted = true;
},
onSuccess
});
cleanupTimers();
const stepDuration = Date.now() - candidateStart;
const successStep: FallbackStep = {
stepIndex: totalHops,
timestamp: new Date().toISOString(),
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: stepDuration,
status: 'success',
statusCode: 200,
nextAction: 'Served successfully'
};
fallbackSteps.push(successStep);
liveWatcher.recordCandidateStep(requestId, successStep);
const promptTokens = streamResult?.promptTokens || Math.ceil(JSON.stringify(requestBody.messages).length / 4);
const completionTokens = streamResult?.completionTokens || 0;
const journey: RequestFallbackJourney = {
requestId,
timestamp: new Date().toISOString(),
requestedModel: requestBody.model || requestedModelName,
resolvedModelName: customModel.name,
resolvedModelId: customModel.id,
finalStatus: fallbackSteps.length > 1 ? 'success_fallback' : 'success_direct',
totalDurationMs: Date.now() - journeyStart,
totalHops,
fallbackOccurred: fallbackSteps.length > 1,
finalServedBy: {
tierIndex: tier.tierIndex,
tierName: tier.name || `Tier ${tier.tierIndex}`,
providerName: candidate.provider.name,
providerType: candidate.provider.type,
model: candidate.target.model,
maskedKey: this.store.maskKey(candidate.keyConfig.key)
},
tokens: {
promptTokens,
completionTokens,
totalTokens: promptTokens + completionTokens
},
steps: fallbackSteps
};
telemetryTracker.recordJourney(journey);
telemetryTracker.broadcastKeyStatus();
liveWatcher.completeRequest({
requestId,
statusCode: 200,
journey,
tokens: { promptTokens, completionTokens, totalTokens: promptTokens + completionTokens },
finishReason: streamResult?.finishReason || 'stop'
});
return;
} else {
const responseData = await this.executeNonStreaming({
candidate,
requestBody,
requestedModelName,
requestId
});
cleanupTimers();
if (isCancelled || res.destroyed) return;
// Success! Update stats
this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, {
incrementCount: true,
rateLimitedUntil: null
});
const promptTokens = responseData.usage?.prompt_tokens || 0;
const completionTokens = responseData.usage?.completion_tokens || 0;
if (onSuccess) {
onSuccess({ input: promptTokens, output: completionTokens });
}
const stepDuration = Date.now() - candidateStart;
const successStep: FallbackStep = {
stepIndex: totalHops,
timestamp: new Date().toISOString(),
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: stepDuration,
status: 'success',
statusCode: 200,
nextAction: 'Served successfully'
};
fallbackSteps.push(successStep);
liveWatcher.recordCandidateStep(requestId, successStep);
const journey: RequestFallbackJourney = {
requestId,
timestamp: new Date().toISOString(),
requestedModel: requestBody.model || requestedModelName,
resolvedModelName: customModel.name,
resolvedModelId: customModel.id,
finalStatus: fallbackSteps.length > 1 ? 'success_fallback' : 'success_direct',
totalDurationMs: Date.now() - journeyStart,
totalHops,
fallbackOccurred: fallbackSteps.length > 1,
finalServedBy: {
tierIndex: tier.tierIndex,
tierName: tier.name || `Tier ${tier.tierIndex}`,
providerName: candidate.provider.name,
providerType: candidate.provider.type,
model: candidate.target.model,
maskedKey: this.store.maskKey(candidate.keyConfig.key)
},
tokens: {
promptTokens,
completionTokens,
totalTokens: promptTokens + completionTokens
},
steps: fallbackSteps
};
telemetryTracker.recordJourney(journey);
telemetryTracker.broadcastKeyStatus();
liveWatcher.completeRequest({
requestId,
statusCode: 200,
journey,
responseData,
tokens: { promptTokens, completionTokens, totalTokens: promptTokens + completionTokens },
finishReason: responseData.choices?.[0]?.finish_reason || 'stop'
});
if (res.headersSent) {
// Chunked keep-alive headers were already emitted
res.write(JSON.stringify(responseData));
res.end();
} else {
res.json(responseData);
}
return;
}
} catch (err: any) {
lastError = err;
console.error(`[REVOLVER] Candidate failed (Provider: '${candidate.provider.name}', Model: '${candidate.target.model}'):`, err.message);
const stepDuration = Date.now() - candidateStart;
const isRateLimit = this.isRateLimitOrQuotaError(err);
const isServerErr = this.isServerError(err);
const cooldown = isRateLimit ? config.rateLimitDurationMs : (isServerErr ? 15000 : undefined);
const statusType = isRateLimit ? 'rate_limited' : (isServerErr ? 'server_error' : 'failed');
let nextAction = '';
if (!isLastCandidateInTier) {
nextAction = `Rotating to next key in Tier ${tier.tierIndex}`;
} else if (!isLastTier) {
nextAction = `Tier ${tier.tierIndex} exhausted. Cascading to Fallback Tier ${sortedTiers[sortedTiers.indexOf(tier) + 1]?.tierIndex ?? 'next'}`;
} else {
nextAction = 'All tiers and candidates exhausted';
}
const failedStep: FallbackStep = {
stepIndex: totalHops,
timestamp: new Date().toISOString(),
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: stepDuration,
status: statusType,
statusCode: err.status || (isRateLimit ? 429 : 500),
errorMessage: err.message,
rateLimitedUntil: cooldown ? Date.now() + cooldown : null,
cooldownSeconds: cooldown ? Math.ceil(cooldown / 1000) : undefined,
nextAction
};
fallbackSteps.push(failedStep);
liveWatcher.recordCandidateStep(requestId, failedStep);
// If stream has already started sending content bytes to the client, we cannot fail over cleanly
if (streamStarted) {
cleanupTimers();
if (onFailure) onFailure('stream_interrupted');
const journey: RequestFallbackJourney = {
requestId,
timestamp: new Date().toISOString(),
requestedModel: requestBody.model || requestedModelName,
resolvedModelName: customModel.name,
resolvedModelId: customModel.id,
finalStatus: 'all_tiers_exhausted',
totalDurationMs: Date.now() - journeyStart,
totalHops,
fallbackOccurred: true,
steps: fallbackSteps
};
telemetryTracker.recordJourney(journey);
telemetryTracker.broadcastKeyStatus();
liveWatcher.failRequest({
requestId,
statusCode: 500,
error: err,
journey
});
if (!res.destroyed && !res.writableEnded) {
res.write(`data: ${JSON.stringify({
error: {
message: err.message || 'Stream interrupted',
type: 'server_error',
code: 'stream_interrupted'
}
})}\n\n`);
res.write('data: [DONE]\n\n');
res.end();
}
throw err;
}
// Mark key rate limited or increment error
if (isRateLimit || isServerErr) {
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
});
}
telemetryTracker.broadcastKeyStatus();
// 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
cleanupTimers();
if (onFailure) onFailure('all_tiers_exhausted');
const finalErrorMessage = lastError ? lastError.message : 'All model tiers and provider keys are exhausted or rate-limited.';
const journey: RequestFallbackJourney = {
requestId,
timestamp: new Date().toISOString(),
requestedModel: requestBody.model || requestedModelName,
resolvedModelName: customModel.name,
resolvedModelId: customModel.id,
finalStatus: 'all_tiers_exhausted',
totalDurationMs: Date.now() - journeyStart,
totalHops,
fallbackOccurred: true,
steps: fallbackSteps
};
telemetryTracker.recordJourney(journey);
telemetryTracker.broadcastKeyStatus();
liveWatcher.failRequest({
requestId,
statusCode: 503,
error: lastError || new Error(finalErrorMessage),
journey
});
if (isStreaming) {
if (!res.destroyed && !res.writableEnded) {
res.write(`data: ${JSON.stringify({
error: {
message: `[Revolver Fallback Error]: ${finalErrorMessage}`,
type: 'revolver_exhausted_error',
code: 'all_tiers_exhausted'
}
})}\n\n`);
res.write('data: [DONE]\n\n');
res.end();
}
} else {
if (res.headersSent) {
res.write(JSON.stringify({
error: {
message: `[Revolver Fallback Error]: ${finalErrorMessage}`,
type: 'revolver_exhausted_error',
code: 'all_tiers_exhausted'
}
}));
res.end();
} else {
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
}, { timeout: config.candidateTimeoutMs });
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),
signal: AbortSignal.timeout(config.candidateTimeoutMs)
});
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<{ promptTokens: number; completionTokens: number; finishReason: string }> {
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<{ promptTokens: number; completionTokens: number; finishReason: string }> {
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
}, { timeout: config.candidateTimeoutMs });
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 headers haven't been committed, commit them now
if (!res.headersSent) {
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
res.setHeader('Cache-Control', 'no-cache, no-transform');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no');
if (typeof res.flushHeaders === 'function') {
res.flushHeaders();
}
}
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;
liveWatcher.appendStreamChunk(requestId, text);
onStreamStart();
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 });
}
return {
promptTokens,
completionTokens,
finishReason: 'stop'
};
}
private async executeOpenAICompatibleStreaming(params: {
candidate: CandidateExecution;
requestBody: OpenAIChatRequest;
requestedModelName: string;
requestId: string;
res: Response;
onStreamStart: () => void;
onSuccess?: (tokens: { input: number; output: number }) => void;
}): Promise<{ promptTokens: number; completionTokens: number; finishReason: string }> {
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),
signal: AbortSignal.timeout(config.candidateTimeoutMs)
});
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.');
}
// If headers haven't been committed, commit them now
if (!res.headersSent) {
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
res.setHeader('Cache-Control', 'no-cache, no-transform');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no');
if (typeof res.flushHeaders === 'function') {
res.flushHeaders();
}
}
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) {
onStreamStart();
const delta = parsed.choices[0].delta.content;
totalOutputChars += delta.length;
liveWatcher.appendStreamChunk(requestId, delta);
}
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 });
}
return {
promptTokens: estimatedInput,
completionTokens: estimatedOutput,
finishReason: 'stop'
};
}
// 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();