mirror of
https://github.com/christianvidalwolf-prog/Craze-Data-check.git
synced 2026-08-03 13:45:24 +02:00
fix(gemini): implement model fallback system for reliability
This commit is contained in:
+44
-22
@@ -13,29 +13,51 @@ export async function generateGemini(prompt: string, systemPrompt: string): Prom
|
||||
throw new Error('Gemini API Key not found. Please set VITE_GEMINI_API_KEY in .env or GEMINI_API_KEY in localStorage.');
|
||||
}
|
||||
|
||||
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=${apiKey}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
contents: [{
|
||||
parts: [{
|
||||
text: `${systemPrompt}\n\nTask: ${prompt}`
|
||||
}]
|
||||
}],
|
||||
generationConfig: {
|
||||
maxOutputTokens: 1000,
|
||||
temperature: 0.7
|
||||
}
|
||||
})
|
||||
});
|
||||
// Model fallback list - based on March 2026 status
|
||||
const modelOptions = [
|
||||
'gemini-2.0-flash',
|
||||
'gemini-1.5-flash',
|
||||
'gemini-pro'
|
||||
];
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.error?.message || 'Failed to generate text from Gemini API');
|
||||
let lastError: any = null;
|
||||
|
||||
for (const modelName of modelOptions) {
|
||||
try {
|
||||
console.log(`Trying Gemini model: ${modelName}...`);
|
||||
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${modelName}:generateContent?key=${apiKey}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
contents: [{
|
||||
parts: [{
|
||||
text: `${systemPrompt}\n\nTask: ${prompt}`
|
||||
}]
|
||||
}],
|
||||
generationConfig: {
|
||||
maxOutputTokens: 1000,
|
||||
temperature: 0.7
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
console.warn(`Model ${modelName} failed:`, errorData);
|
||||
lastError = errorData;
|
||||
continue; // Try next model
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
console.log(`Successfully used model: ${modelName}`);
|
||||
return data.candidates[0].content.parts[0].text;
|
||||
} catch (err) {
|
||||
console.error(`Fetch error with ${modelName}:`, err);
|
||||
lastError = err;
|
||||
}
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.candidates[0].content.parts[0].text;
|
||||
throw new Error(lastError?.error?.message || lastError?.message || 'All Gemini models failed. Check console for details.');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user