Optimise
This commit is contained in:
parent
1521fffecc
commit
55daeea0cd
2 changed files with 28 additions and 2 deletions
|
|
@ -11,6 +11,7 @@ interface KeyUsage {
|
|||
class KeyRotationManager {
|
||||
private keys: KeyUsage[] = [];
|
||||
private currentIndex = 0;
|
||||
private clientCache: Map<string, GoogleGenerativeAI> = 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
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,9 @@ import {
|
|||
|
||||
const router = Router();
|
||||
|
||||
// Cache for model instances to avoid recreation
|
||||
const modelCache = new Map<string, any>();
|
||||
|
||||
// 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);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue