fix: GeminiVisionService tries v1+v1beta, shows real API error in Telegram

- Rewrote extraerPago() to try v1 then v1beta for model compatibility
- Returns __error key with actual API message when both fail
- TelegramBotService shows that error in chat instead of generic message
- Also ensures model is read fresh from config (no hardcoded URL in constructor)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Lizandro
2026-07-15 16:13:10 +00:00
co-authored by Claude Sonnet 4.6
parent cfa38e51df
commit 2acb80a7d2
2 changed files with 69 additions and 84 deletions
+38 -58
View File
@@ -10,33 +10,14 @@ use Illuminate\Support\Facades\Log;
class GeminiVisionService class GeminiVisionService
{ {
private string $apiKey; private string $apiKey;
private string $apiUrl;
private string $model; private string $model;
public function __construct() public function __construct()
{ {
$this->apiKey = ChatConfig::get('gemini_api_key', ''); $this->apiKey = ChatConfig::get('gemini_api_key', '');
$this->model = ChatConfig::get('gemini_model', 'gemini-3.5-flash'); $this->model = ChatConfig::get('gemini_model', 'gemini-3.5-flash');
$ver = preg_match('/gemini-(2\.5|3[\.\d]*)/', $this->model) ? 'v1' : 'v1beta';
$this->apiUrl = "https://generativelanguage.googleapis.com/{$ver}/models/{$this->model}:generateContent";
} }
private function buildRequest(array $contents, array $genConfig = []): array
{
return [
'contents' => $contents,
'generationConfig' => array_merge(['temperature' => 0.1, 'maxOutputTokens' => 200], $genConfig),
];
}
/**
* Extrae datos de pago de una imagen de comprobante.
*
* @param string $base64 Imagen en base64
* @param string $mimeType MIME type (image/jpeg, image/png, etc.)
* @return array|null ['banco', 'valor', 'referencia', 'fecha', 'hora', 'remitente'] o null
*/
public function extraerPago(string $base64, string $mimeType, ?int $usuarioId = null, string $canal = 'telegram'): ?array public function extraerPago(string $base64, string $mimeType, ?int $usuarioId = null, string $canal = 'telegram'): ?array
{ {
if (! $this->apiKey) { if (! $this->apiKey) {
@@ -44,34 +25,53 @@ class GeminiVisionService
return null; return null;
} }
$prompt = $this->buildPrompt();
$inicio = microtime(true);
try {
$contents = [[ $contents = [[
'parts' => [ 'parts' => [
['text' => $prompt], ['text' => $this->buildPrompt()],
['inline_data' => ['mime_type' => $mimeType, 'data' => $base64]], ['inline_data' => ['mime_type' => $mimeType, 'data' => $base64]],
], ],
]]; ]];
$response = Http::withHeaders(['Content-Type' => 'application/json']) $body = [
->timeout(15) 'contents' => $contents,
->post("{$this->apiUrl}?key={$this->apiKey}", $this->buildRequest($contents)); 'generationConfig' => ['temperature' => 0.1, 'maxOutputTokens' => 200],
];
$inicio = microtime(true);
$response = null;
$lastError = '';
foreach (['v1', 'v1beta'] as $ver) {
$url = "https://generativelanguage.googleapis.com/{$ver}/models/{$this->model}:generateContent";
try {
$resp = Http::withHeaders(['Content-Type' => 'application/json'])
->timeout(20)
->post("{$url}?key={$this->apiKey}", $body);
if ($resp->successful()) {
$response = $resp;
break;
}
$lastError = "[{$ver}] " . ($resp->json('error.message') ?? substr($resp->body(), 0, 200));
} catch (\Throwable $e) {
$lastError = "[{$ver}] " . $e->getMessage();
}
}
$tiempoMs = (int) ((microtime(true) - $inicio) * 1000); $tiempoMs = (int) ((microtime(true) - $inicio) * 1000);
if (! $response->successful()) { if (! $response) {
Log::warning('[Gemini Vision] API error: ' . $response->body()); Log::warning('[Gemini Vision] API failed: ' . $lastError);
AiUsageLog::registrar([ AiUsageLog::registrar([
'servicio' => 'gemini_vision', 'servicio' => 'gemini_vision',
'canal' => $canal, 'canal' => $canal,
'usuario_id'=> $usuarioId, 'usuario_id' => $usuarioId,
'tiempo_ms' => $tiempoMs, 'tiempo_ms' => $tiempoMs,
'resultado' => 'error', 'resultado' => 'error',
'detalle' => ['error' => substr($response->body(), 0, 300)], 'detalle' => ['error' => $lastError, 'modelo' => $this->model],
]); ]);
return null; // Return error info so caller can show it
return ['__error' => $lastError];
} }
$inputTokens = $response->json('usageMetadata.promptTokenCount', 0); $inputTokens = $response->json('usageMetadata.promptTokenCount', 0);
@@ -84,27 +84,15 @@ class GeminiVisionService
'canal' => $canal, 'canal' => $canal,
'usuario_id' => $usuarioId, 'usuario_id' => $usuarioId,
'input_tokens' => $inputTokens, 'input_tokens' => $inputTokens,
'output_tokens'=> $outputTokens, 'output_tokens' => $outputTokens,
'tiempo_ms' => $tiempoMs, 'tiempo_ms' => $tiempoMs,
'resultado' => $resultado ? 'ok' : 'error', 'resultado' => $resultado ? 'ok' : 'error',
'detalle' => $resultado ? ['banco' => $resultado['banco'], 'valor' => $resultado['valor']] : ['raw' => substr($text, 0, 200)], 'detalle' => $resultado
? ['banco' => $resultado['banco'], 'valor' => $resultado['valor']]
: ['raw' => substr($text, 0, 200), 'modelo' => $this->model],
]); ]);
return $resultado; return $resultado;
} catch (\Throwable $e) {
$tiempoMs = (int) ((microtime(true) - $inicio) * 1000);
Log::error('[Gemini Vision] Excepcion: ' . $e->getMessage());
AiUsageLog::registrar([
'servicio' => 'gemini_vision',
'canal' => $canal,
'usuario_id'=> $usuarioId,
'tiempo_ms' => $tiempoMs,
'resultado' => 'error',
'detalle' => ['error' => $e->getMessage()],
]);
return null;
}
} }
private function buildPrompt(): string private function buildPrompt(): string
@@ -130,21 +118,13 @@ PROMPT;
private function parseRespuesta(string $text): ?array private function parseRespuesta(string $text): ?array
{ {
$text = trim($text); $text = trim(preg_replace('/```json\s*|\s*```/', '', $text));
$text = preg_replace('/```json\s*|\s*```/', '', $text);
$text = trim($text);
$json = json_decode($text, true); $json = json_decode($text, true);
if (! is_array($json)) { if (! is_array($json) || isset($json['error'])) {
return null; return null;
} }
if (isset($json['error'])) {
return null;
}
// Normalizar valor a entero
if (isset($json['valor'])) { if (isset($json['valor'])) {
$json['valor'] = (int) preg_replace('/[^0-9]/', '', (string) $json['valor']); $json['valor'] = (int) preg_replace('/[^0-9]/', '', (string) $json['valor']);
} }
+5
View File
@@ -187,6 +187,11 @@ class TelegramBotService
return; return;
} }
if (isset($datosPago['__error'])) {
$this->send($chatId, "⚠️ Error al analizar el comprobante:\n`" . $datosPago['__error'] . "`");
return;
}
$resultado = app(PagoValidadorService::class)->validar($datosPago); $resultado = app(PagoValidadorService::class)->validar($datosPago);
$monto = number_format($datosPago['valor'] ?? 0); $monto = number_format($datosPago['valor'] ?? 0);
$ref = $datosPago['referencia'] ?? 'N/A'; $ref = $datosPago['referencia'] ?? 'N/A';