Files
sirpremiumv2/app/Services/GeminiVisionService.php
T
LizandroandClaude Sonnet 4.6 2acb80a7d2 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>
2026-07-15 16:13:10 +00:00

142 lines
4.9 KiB
PHP

<?php
namespace App\Services;
use App\Models\AiUsageLog;
use App\Models\ChatConfig;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class GeminiVisionService
{
private string $apiKey;
private string $model;
public function __construct()
{
$this->apiKey = ChatConfig::get('gemini_api_key', '');
$this->model = ChatConfig::get('gemini_model', 'gemini-3.5-flash');
}
public function extraerPago(string $base64, string $mimeType, ?int $usuarioId = null, string $canal = 'telegram'): ?array
{
if (! $this->apiKey) {
Log::warning('[Gemini Vision] No hay API key configurada.');
return null;
}
$contents = [[
'parts' => [
['text' => $this->buildPrompt()],
['inline_data' => ['mime_type' => $mimeType, 'data' => $base64]],
],
]];
$body = [
'contents' => $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);
if (! $response) {
Log::warning('[Gemini Vision] API failed: ' . $lastError);
AiUsageLog::registrar([
'servicio' => 'gemini_vision',
'canal' => $canal,
'usuario_id' => $usuarioId,
'tiempo_ms' => $tiempoMs,
'resultado' => 'error',
'detalle' => ['error' => $lastError, 'modelo' => $this->model],
]);
// Return error info so caller can show it
return ['__error' => $lastError];
}
$inputTokens = $response->json('usageMetadata.promptTokenCount', 0);
$outputTokens = $response->json('usageMetadata.candidatesTokenCount', 0);
$text = $response->json('candidates.0.content.parts.0.text', '');
$resultado = $this->parseRespuesta($text);
AiUsageLog::registrar([
'servicio' => 'gemini_vision',
'canal' => $canal,
'usuario_id' => $usuarioId,
'input_tokens' => $inputTokens,
'output_tokens' => $outputTokens,
'tiempo_ms' => $tiempoMs,
'resultado' => $resultado ? 'ok' : 'error',
'detalle' => $resultado
? ['banco' => $resultado['banco'], 'valor' => $resultado['valor']]
: ['raw' => substr($text, 0, 200), 'modelo' => $this->model],
]);
return $resultado;
}
private function buildPrompt(): string
{
return <<<PROMPT
Analiza esta imagen de comprobante de pago bancario o transferencia.
Extrae los siguientes campos:
- banco: nombre del banco (Bancolombia, Nequi, Davivienda, etc.)
- valor: monto en numeros enteros sin simbolos ni puntos (ej: 50000)
- referencia: numero de referencia o transaccion (si existe)
- fecha: fecha en formato dd/mm/yyyy
- hora: hora en formato HH:mm (si existe)
- remitente: nombre de quien envia el dinero (si aparece)
Responde UNICAMENTE con un JSON valido, sin markdown, sin explicacion:
{"banco": "...", "valor": 50000, "referencia": "...", "fecha": "...", "hora": "...", "remitente": "..."}
Si no encuentras un campo, usa null para ese campo.
Si la imagen NO es un comprobante de pago, responde exactamente: {"error": "no_es_comprobante"}
PROMPT;
}
private function parseRespuesta(string $text): ?array
{
$text = trim(preg_replace('/```json\s*|\s*```/', '', $text));
$json = json_decode($text, true);
if (! is_array($json) || isset($json['error'])) {
return null;
}
if (isset($json['valor'])) {
$json['valor'] = (int) preg_replace('/[^0-9]/', '', (string) $json['valor']);
}
return [
'banco' => $json['banco'] ?? null,
'valor' => $json['valor'] ?? null,
'referencia' => $json['referencia'] ?? null,
'fecha' => $json['fecha'] ?? null,
'hora' => $json['hora'] ?? null,
'remitente' => $json['remitente'] ?? null,
];
}
}