Update: 2026-05-08 00:43:22
This commit is contained in:
@@ -10,7 +10,9 @@ use App\Services\InvoiceExtractionService;
|
||||
*/
|
||||
class AI
|
||||
{
|
||||
private static string $baseUrl = "https://generativelanguage.googleapis.com/v1beta/models/gemini-flash-lite-latest:generateContent";
|
||||
private static string $baseUrl = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent";
|
||||
|
||||
private static int $maxRetries = 3;
|
||||
|
||||
/**
|
||||
* Extract Data from Invoice Image or PDF (Base64)
|
||||
@@ -45,18 +47,49 @@ class AI
|
||||
]
|
||||
];
|
||||
|
||||
$ch = curl_init(self::$baseUrl . "?key=" . $apiKey);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_POST, true);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
// Retry with exponential backoff for 503/429 errors
|
||||
for ($attempt = 1; $attempt <= self::$maxRetries; $attempt++) {
|
||||
$ch = curl_init(self::$baseUrl . "?key=" . $apiKey);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_POST, true);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
|
||||
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$curlError = curl_error($ch);
|
||||
curl_close($ch);
|
||||
|
||||
if ($curlError) {
|
||||
error_log("AI Error: cURL failed (attempt $attempt): $curlError");
|
||||
if ($attempt < self::$maxRetries) {
|
||||
$wait = pow(2, $attempt) + rand(1, 3);
|
||||
echo " Retrying in {$wait}s (cURL error)...\n";
|
||||
sleep($wait);
|
||||
continue;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($httpCode === 200) {
|
||||
break; // Success
|
||||
}
|
||||
|
||||
// Retry on 503 (overloaded) or 429 (rate limit)
|
||||
if (in_array($httpCode, [503, 429]) && $attempt < self::$maxRetries) {
|
||||
$wait = pow(2, $attempt) + rand(1, 3);
|
||||
echo " Gemini $httpCode — retrying in {$wait}s (attempt $attempt/" . self::$maxRetries . ")...\n";
|
||||
sleep($wait);
|
||||
continue;
|
||||
}
|
||||
|
||||
error_log("AI Error: Gemini API returned code $httpCode. Response: " . $response);
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($httpCode !== 200) {
|
||||
error_log("AI Error: Gemini API returned code $httpCode. Response: " . $response);
|
||||
error_log("AI Error: All retries exhausted. Last code: $httpCode");
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user