From 55daeea0cd9681ecbb4bb170529b70d3743f3007 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sun, 27 Sep 2026 16:35:20 +0300 Subject: [PATCH] Optimise --- src/keyRotation.ts | 16 +++++++++++++++- src/routes.ts | 14 +++++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/keyRotation.ts b/src/keyRotation.ts index 6107c07..91ce1c3 100644 --- a/src/keyRotation.ts +++ b/src/keyRotation.ts @@ -11,6 +11,7 @@ interface KeyUsage { class KeyRotationManager { private keys: KeyUsage[] = []; private currentIndex = 0; + private clientCache: Map = new Map(); constructor() { this.initializeKeys(); @@ -73,8 +74,21 @@ class KeyRotationManager { createGenerativeAI(): { client: GoogleGenerativeAI; apiKey: string } { const apiKey = this.getNextAvailableKey(); + + // Check cache first + if (this.clientCache.has(apiKey)) { + return { + client: this.clientCache.get(apiKey)!, + apiKey + }; + } + + // Create new client and cache it + const client = new GoogleGenerativeAI(apiKey); + this.clientCache.set(apiKey, client); + return { - client: new GoogleGenerativeAI(apiKey), + client, apiKey }; } diff --git a/src/routes.ts b/src/routes.ts index 6d87cd8..a6ad16b 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -11,6 +11,9 @@ import { const router = Router(); +// Cache for model instances to avoid recreation +const modelCache = new Map(); + // Convert OpenAI format to Gemini format function convertToGeminiMessages(messages: any[]): any[] { return messages @@ -88,7 +91,16 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { // Always use the configured Gemini model internally, but return the requested model name in response requestedModel = body.model || config.model; - const model = genAI.getGenerativeModel({ 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);