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
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();
|
||||
Loading…
Add table
Add a link
Reference in a new issue