Métricas y Observabilidad
AIUsageMetric
Section titled “AIUsageMetric”Cada llamada al motor IA genera un registro en AIUsageMetric (modelo Prisma en apps/api):
// MetricsService registra después de cada respuesta LLMawait this.apiClient.post('/internal/ai-metrics', { useCase, provider, model, inputTokens, outputTokens, latencyMs, estimatedCostUsd: this.estimateCost(provider, model, inputTokens, outputTokens), userId, errorCode: null, // o el código de error si falló});Tabla de precios por token (TOKEN_PRICING)
Section titled “Tabla de precios por token (TOKEN_PRICING)”Archivo: apps/ai-backend/src/modules/metrics/pricing.constants.ts
| Proveedor | Modelo | Input (per 1K tokens) | Output (per 1K tokens) |
|---|---|---|---|
| Anthropic | claude-sonnet-4-5 | $0.003 | $0.015 |
| Anthropic | claude-haiku-4-5 | $0.00025 | $0.00125 |
| OpenAI | gpt-4o | $0.005 | $0.015 |
| OpenAI | gpt-4o-mini | $0.00015 | $0.0006 |
| OpenAI | text-embedding-3-small | $0.00002 | $0 |
| Gemini | gemini-1.5-pro | $0.0035 | $0.0105 |
| Gemini | gemini-1.5-flash | $0.000075 | $0.0003 |
CircuitBreakerService
Section titled “CircuitBreakerService”Archivo: apps/ai-backend/src/modules/router/circuit-breaker.service.ts
Protege contra proveedores degradados:
stateDiagram-v2 [*] --> CLOSED CLOSED --> OPEN: failures >= 5 en 60s OPEN --> HALF_OPEN: después de 30s HALF_OPEN --> CLOSED: request exitosa HALF_OPEN --> OPEN: fallo| Estado | Comportamiento |
|---|---|
CLOSED | Tráfico normal al proveedor |
OPEN | Redirige automáticamente al fallback |
HALF_OPEN | Prueba una request — si falla vuelve a OPEN |
interface CircuitStatus { isOpen: boolean; failures: number; // Contador de fallos en la ventana lastFailureAt: Date; nextRetryAt: Date; // Cuándo pasar a HALF_OPEN}AIAlert — Alertas automáticas
Section titled “AIAlert — Alertas automáticas”El sistema genera AIAlert en BD cuando detecta anomalías. Tipos:
| Tipo | Condición | Severidad |
|---|---|---|
PROVIDER_ERROR_RATE_HIGH | Tasa de error > 10% en 5 min | HIGH |
LATENCY_DEGRADED | P95 latencia > 5000ms | MEDIUM |
COST_THRESHOLD_EXCEEDED | Coste diario > umbral configurado | HIGH |
CIRCUIT_BREAKER_OPENED | Circuit breaker activado | HIGH |
Las alertas activas se muestran en /admin/ai/alerts y también aparecen en el dashboard de /admin/ai.
Panel de métricas en tiempo real
Section titled “Panel de métricas en tiempo real”Accesible en /admin/ai/metrics (solo SUPER_ADMIN). Permite filtrar por:
- Período (1h, 24h, 7d, 30d)
- Proveedor (Anthropic / OpenAI / Gemini / all)
- Caso de uso
- Modelo
Métricas disponibles:
- Número de llamadas totales
- Tokens consumidos (input + output)
- Coste estimado acumulado
- Latencia P50 / P95 / P99
- Tasa de error
- Uso por caso de uso (chart)