feat(LIA): barra de tokens 1M con bloqueo al agotarse

- ai_chat.php: cuenta tokens reales desde Gemini usageMetadata, persiste en lab_config, bloquea con HTTP 402 al agotar 1.000.000
- dashboard.php: _actualizarTokens() actualiza barra visual, _bloquearLIA() deshabilita input+mic y muestra aviso de soporte

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Lizandro Guarnizo
2026-07-30 20:09:18 -05:00
co-authored by Claude Sonnet 4.6
parent 34d0fed21b
commit 320b47797a
2 changed files with 68 additions and 6 deletions
+23 -4
View File
@@ -14,12 +14,19 @@ $pregunta = trim($body['pregunta'] ?? '');
if ($pregunta === '') jsonError('Pregunta vacía', 400);
if (mb_strlen($pregunta) > 800) jsonError('Pregunta demasiado larga', 400);
define('LIA_TOKENS_MAX', 1_000_000);
$pdo = db();
// ── Clave Gemini ──────────────────────────────────────────────
$row = $pdo->query("SELECT valor FROM lab_config WHERE clave = 'gemini_api_key' LIMIT 1")->fetch();
$apiKey = trim($row['valor'] ?? '');
$cfg = $pdo->query("SELECT clave, valor FROM lab_config WHERE clave IN ('gemini_api_key','lia_tokens_usados')")->fetchAll(PDO::FETCH_KEY_PAIR);
$apiKey = trim($cfg['gemini_api_key'] ?? '');
$tokensUsados = (int)($cfg['lia_tokens_usados'] ?? 0);
if (!$apiKey) jsonError('Token de IA no configurado. Ve a Configuración del laboratorio.', 503);
if ($tokensUsados >= LIA_TOKENS_MAX) {
jsonError('⚠️ Se agotaron los tokens de LIA. Solicita tokens a soporte para continuar.', 402);
}
// ── Contexto del día ──────────────────────────────────────────
$hoy = date('Y-m-d');
@@ -207,5 +214,17 @@ if ($code !== 200 || empty($gemini['candidates'][0]['content']['parts'][0]['text
jsonError("Error IA: {$detail}", 502);
}
$respuesta = $gemini['candidates'][0]['content']['parts'][0]['text'];
jsonOk(['respuesta' => $respuesta]);
$respuesta = $gemini['candidates'][0]['content']['parts'][0]['text'];
$usage = $gemini['usageMetadata'] ?? [];
$tokensEsta = (int)($usage['totalTokenCount'] ?? (int)((mb_strlen($pregunta) + mb_strlen($respuesta)) / 4));
$tokensUsados += $tokensEsta;
$pdo->prepare("INSERT INTO lab_config (clave, valor) VALUES ('lia_tokens_usados', ?)
ON DUPLICATE KEY UPDATE valor = ?")->execute([$tokensUsados, $tokensUsados]);
jsonOk([
'respuesta' => $respuesta,
'tokens_usados' => $tokensUsados,
'tokens_restantes' => max(0, LIA_TOKENS_MAX - $tokensUsados),
'tokens_max' => LIA_TOKENS_MAX,
]);