Add Gemini audio model failover logic to handle HTTP 429 rate limits

This commit is contained in:
Hamza-Ayed
2026-05-22 15:42:30 +03:00
parent df8d905da7
commit 51a3e92980

View File

@@ -218,7 +218,13 @@ class GeminiService
*/ */
public static function generateAudioResponse(string $apiKey, string $systemPrompt, string $userMessage, string $voiceName = 'Puck'): ?array public static function generateAudioResponse(string $apiKey, string $systemPrompt, string $userMessage, string $voiceName = 'Puck'): ?array
{ {
$url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-flash-tts-preview:generateContent?key=' . $apiKey; $models = [
'gemini-3.1-flash-tts-preview',
'gemini-2.5-flash-preview-tts'
];
foreach ($models as $model) {
$url = 'https://generativelanguage.googleapis.com/v1beta/models/' . $model . ':generateContent?key=' . $apiKey;
$parts = []; $parts = [];
if (!empty($systemPrompt)) { if (!empty($systemPrompt)) {
@@ -258,11 +264,7 @@ class GeminiService
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch); curl_close($ch);
if ($httpCode !== 200) { if ($httpCode === 200) {
error_log("[Gemini Audio API Error] HTTP " . $httpCode . " | Response: " . $response);
return null;
}
$data = json_decode($response, true); $data = json_decode($response, true);
$part = $data['candidates'][0]['content']['parts'][0] ?? null; $part = $data['candidates'][0]['content']['parts'][0] ?? null;
if ($part && isset($part['inlineData'])) { if ($part && isset($part['inlineData'])) {
@@ -271,6 +273,11 @@ class GeminiService
'mimeType' => $part['inlineData']['mimeType'] ?? 'audio/mp4' 'mimeType' => $part['inlineData']['mimeType'] ?? 'audio/mp4'
]; ];
} }
} else {
error_log("[Gemini Audio API Error] Model " . $model . " failed with HTTP " . $httpCode . " | Response: " . $response);
}
}
return null; return null;
} }