erp-core/docs/04-modelado/requerimientos-funcionales/mgn-018/RF-MGN-018-006-analytics-metricas.md

22 KiB

RF-MGN-018-006: Analytics y Métricas

Módulo: MGN-018 - AI Agents & Chatbots Prioridad: P2 Story Points: 8 Estado: Definido Fecha: 2025-12-05

Descripción

El sistema debe proporcionar dashboards y reportes completos sobre el rendimiento de los agentes de IA, incluyendo métricas de conversaciones, satisfacción del usuario, consumo de recursos, y análisis de costos. Los dashboards permiten a los administradores tomar decisiones informadas sobre configuración y optimización.

Actores

  • Actor Principal: Tenant Admin
  • Actores Secundarios:
    • Supervisor (métricas operativas)
    • Sistema (recolección de datos)

Precondiciones

  1. Agente con conversaciones procesadas
  2. Permiso de ver analytics

Métricas Principales

1. Métricas de Conversación

interface ConversationMetrics {
  period: DateRange;

  // Volumen
  total_conversations: number;
  conversations_by_channel: Record<string, number>;
  conversations_by_day: Array<{ date: string; count: number }>;

  // Estados
  active_conversations: number;
  completed_conversations: number;
  escalated_conversations: number;
  expired_conversations: number;

  // Tasas
  resolution_rate: number;        // Completadas sin escalación
  escalation_rate: number;        // Escaladas a humano
  abandonment_rate: number;       // Expiradas

  // Duración
  avg_conversation_duration_minutes: number;
  avg_messages_per_conversation: number;
  avg_response_time_ms: number;
}

2. Métricas de Satisfacción

interface SatisfactionMetrics {
  period: DateRange;

  // Ratings
  total_ratings: number;
  average_rating: number;           // 1-5
  rating_distribution: Record<1|2|3|4|5, number>;

  // NPS
  nps_score: number;                // -100 a 100
  promoters: number;                // 9-10
  passives: number;                 // 7-8
  detractors: number;               // 0-6

  // Feedback
  helpful_percentage: number;
  would_recommend_percentage: number;

  // Trending
  rating_trend: 'improving' | 'stable' | 'declining';
  rating_by_day: Array<{ date: string; avg_rating: number }>;
}

3. Métricas de Consumo

interface UsageMetrics {
  period: DateRange;

  // Tokens
  total_tokens_used: number;
  input_tokens: number;
  output_tokens: number;
  tokens_by_model: Record<string, number>;
  tokens_by_day: Array<{ date: string; tokens: number }>;

  // Costos
  estimated_cost_usd: number;
  cost_by_model: Record<string, number>;
  cost_per_conversation: number;
  cost_per_message: number;

  // Budget
  monthly_budget_usd?: number;
  budget_used_percentage?: number;
  projected_month_end_cost?: number;

  // RAG
  rag_queries: number;
  rag_tokens_used: number;

  // Tools
  tool_executions: number;
  tool_executions_by_type: Record<string, number>;
}

4. Métricas de Rendimiento

interface PerformanceMetrics {
  period: DateRange;

  // Latencia
  avg_response_time_ms: number;
  p50_response_time_ms: number;
  p95_response_time_ms: number;
  p99_response_time_ms: number;

  // Disponibilidad
  uptime_percentage: number;
  failed_requests: number;
  timeout_rate: number;

  // LLM
  llm_success_rate: number;
  llm_avg_latency_ms: number;
  fallback_usage_count: number;

  // RAG
  rag_avg_search_time_ms: number;
  rag_hit_rate: number;          // % de queries con resultados útiles
}

5. Métricas de Knowledge Base

interface KBMetrics {
  period: DateRange;

  // Uso
  total_queries: number;
  queries_with_results: number;
  queries_without_results: number;
  hit_rate: number;

  // Por documento
  document_usage: Array<{
    document_id: string;
    document_name: string;
    times_referenced: number;
    avg_similarity_score: number;
  }>;

  // Gaps
  common_queries_without_results: Array<{
    query_pattern: string;
    frequency: number;
  }>;

  // Tamaño
  total_documents: number;
  total_chunks: number;
  storage_used_mb: number;
}

Dashboard Principal

┌─────────────────────────────────────────────────────────────────────────┐
│  📊 Analytics - Asistente de Ventas                  [Últimos 30 días ▼]│
├─────────────────────────────────────────────────────────────────────────┤
│                                                                          │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐│
│  │ Conversaciones│  │  Resolución  │  │ Satisfacción │  │    Costo     ││
│  │    1,234     │  │    78.5%     │  │   ⭐ 4.2     │  │  $45.67 USD  ││
│  │   ↑ 12%      │  │   ↑ 5%       │  │   ↑ 0.3      │  │   ↓ 8%       ││
│  └──────────────┘  └──────────────┘  └──────────────┘  └──────────────┘│
│                                                                          │
│  ┌─────────────────────────────────────────────────────────────────────┐│
│  │  Conversaciones por Día                                             ││
│  │  80 ┤                                          ╭─╮                  ││
│  │  60 ┤                   ╭─╮         ╭─╮       │ │   ╭─╮            ││
│  │  40 ┤     ╭─╮   ╭─╮   │ │  ╭─╮   │ │       │ │   │ │            ││
│  │  20 ┤ ╭─╮│ │   │ │   │ │  │ │   │ │  ╭─╮ │ │   │ │            ││
│  │   0 ┴─┴─┴┴─┴───┴─┴───┴─┴──┴─┴───┴─┴──┴─┴─┴─┴───┴─┴────────────── ││
│  │      1   3   5   7   9   11  13  15  17  19  21  23  25  27  29   ││
│  └─────────────────────────────────────────────────────────────────────┘│
│                                                                          │
│  ┌─────────────────────────────┐  ┌─────────────────────────────────────┐│
│  │ Distribución de Ratings     │  │ Uso por Canal                       ││
│  │                             │  │                                     ││
│  │ ⭐⭐⭐⭐⭐  ████████  45%   │  │ WhatsApp     ████████████  72%     ││
│  │ ⭐⭐⭐⭐    ██████    32%   │  │ Web Chat    █████          28%     ││
│  │ ⭐⭐⭐      ███       15%   │  │                                     ││
│  │ ⭐⭐        █          5%   │  │                                     ││
│  │ ⭐          █          3%   │  │                                     ││
│  └─────────────────────────────┘  └─────────────────────────────────────┘│
│                                                                          │
│  [Ver detalles]  [Exportar CSV]  [Programar reporte]                    │
└─────────────────────────────────────────────────────────────────────────┘

Dashboard de Costos

┌─────────────────────────────────────────────────────────────────────────┐
│  💰 Consumo y Costos - Diciembre 2025                                   │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                          │
│  Presupuesto Mensual: $100 USD                                          │
│  ┌─────────────────────────────────────────────────────────────────────┐│
│  │ Usado: $45.67 (46%)  █████████████████░░░░░░░░░░░░░░░░░░  Restante  ││
│  └─────────────────────────────────────────────────────────────────────┘│
│  Proyección fin de mes: $72.50 USD (✓ Dentro de presupuesto)           │
│                                                                          │
│  ┌─────────────────────────────────────────────────────────────────────┐│
│  │  Desglose por Modelo                                                ││
│  │                                                                      ││
│  │  gpt-4o-mini          $28.45   ████████████████████  62%            ││
│  │  text-embedding-3     $12.20   ████████             27%             ││
│  │  claude-3-haiku       $5.02    ████                 11%             ││
│  └─────────────────────────────────────────────────────────────────────┘│
│                                                                          │
│  ┌─────────────────────────────────────────────────────────────────────┐│
│  │  Tokens Consumidos                                                  ││
│  │                                                                      ││
│  │  Input tokens:    2,345,678   ($18.76)                              ││
│  │  Output tokens:   1,234,567   ($24.69)                              ││
│  │  Embeddings:        456,789   ($2.22)                               ││
│  │  ─────────────────────────────────                                   ││
│  │  Total:           4,037,034   ($45.67)                              ││
│  └─────────────────────────────────────────────────────────────────────┘│
│                                                                          │
│  Métricas de Eficiencia:                                                │
│  • Costo promedio por conversación: $0.037 USD                          │
│  • Costo promedio por mensaje: $0.012 USD                               │
│  • Tokens promedio por respuesta: 287                                   │
│                                                                          │
│  [Descargar factura]  [Configurar alertas]  [Optimización sugerida]    │
└─────────────────────────────────────────────────────────────────────────┘

Reportes Programados

Configuración de Reporte

interface ScheduledReportConfig {
  id: string;
  name: string;

  // Contenido
  metrics_to_include: string[];
  // ['conversations', 'satisfaction', 'costs', 'performance']

  // Filtros
  agent_ids?: string[];
  channels?: string[];

  // Programación
  frequency: 'daily' | 'weekly' | 'monthly';
  day_of_week?: number;         // 0-6 para weekly
  day_of_month?: number;        // 1-31 para monthly
  time_utc: string;             // "08:00"

  // Entrega
  delivery_method: 'email' | 'webhook';
  recipients?: string[];        // Emails
  webhook_url?: string;

  // Formato
  format: 'pdf' | 'csv' | 'json';

  is_active: boolean;
}

Template de Reporte Email

┌─────────────────────────────────────────────────────────────────┐
│  📊 Reporte Semanal - AI Agents                                 │
│  Período: 25 Nov - 1 Dic 2025                                   │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  Resumen Ejecutivo:                                             │
│  ─────────────────                                              │
│  • 1,234 conversaciones procesadas (+12% vs semana anterior)   │
│  • 78.5% tasa de resolución (+5%)                              │
│  • 4.2/5.0 satisfacción promedio (+0.3)                        │
│  • $45.67 USD en costos (-8%)                                  │
│                                                                  │
│  Top Insights:                                                   │
│  ─────────────                                                  │
│  ✓ Mejora en satisfacción gracias a nuevos documentos en KB    │
│  ⚠ 23% de escalaciones por "políticas de devolución"           │
│  ✓ Costo por conversación reducido 15% con modelo optimizado   │
│                                                                  │
│  Recomendaciones:                                               │
│  ────────────────                                               │
│  1. Agregar FAQ sobre políticas de devolución                  │
│  2. Considerar activar herramienta de consulta de sucursales   │
│                                                                  │
│  [Ver dashboard completo]  [Descargar PDF]                     │
└─────────────────────────────────────────────────────────────────┘

Reglas de Negocio

  • RN-1: Métricas se calculan en tiempo real con caché de 5 minutos
  • RN-2: Datos históricos disponibles hasta 12 meses
  • RN-3: Exportación de datos respeta límites (máx 10,000 registros)
  • RN-4: Reportes programados máximo 1 por día por tipo
  • RN-5: Alertas de presupuesto al 50%, 75%, 90% y 100%
  • RN-6: Comparativas solo disponibles con mínimo 7 días de datos

Criterios de Aceptación

  • Dashboard principal con métricas clave
  • Gráficos de tendencias temporales
  • Filtros por agente, canal, período
  • Dashboard de costos detallado
  • Alertas de presupuesto configurables
  • Reportes exportables (PDF, CSV)
  • Reportes programados por email
  • Comparativas período vs período
  • Drill-down a conversaciones individuales
  • API de métricas para integraciones

Entidades Involucradas

ai_agents.daily_metrics (Tabla agregada)

CREATE TABLE ai_agents.daily_metrics (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    agent_id UUID NOT NULL,
    date DATE NOT NULL,

    -- Conversaciones
    total_conversations INT DEFAULT 0,
    completed_conversations INT DEFAULT 0,
    escalated_conversations INT DEFAULT 0,
    expired_conversations INT DEFAULT 0,

    -- Mensajes
    total_messages INT DEFAULT 0,
    user_messages INT DEFAULT 0,
    agent_messages INT DEFAULT 0,

    -- Duración
    avg_duration_seconds INT,
    avg_messages_per_conversation DECIMAL(5,2),
    avg_response_time_ms INT,

    -- Satisfacción
    total_ratings INT DEFAULT 0,
    sum_ratings INT DEFAULT 0, -- Para calcular promedio
    rating_1_count INT DEFAULT 0,
    rating_2_count INT DEFAULT 0,
    rating_3_count INT DEFAULT 0,
    rating_4_count INT DEFAULT 0,
    rating_5_count INT DEFAULT 0,

    -- Consumo
    input_tokens BIGINT DEFAULT 0,
    output_tokens BIGINT DEFAULT 0,
    embedding_tokens BIGINT DEFAULT 0,
    estimated_cost_usd DECIMAL(10,4) DEFAULT 0,

    -- RAG
    rag_queries INT DEFAULT 0,
    rag_hits INT DEFAULT 0,

    -- Tools
    tool_executions INT DEFAULT 0,
    tool_successes INT DEFAULT 0,

    -- Performance
    p50_response_ms INT,
    p95_response_ms INT,
    p99_response_ms INT,
    failed_requests INT DEFAULT 0,

    -- Por canal
    conversations_whatsapp INT DEFAULT 0,
    conversations_webchat INT DEFAULT 0,
    conversations_email INT DEFAULT 0,

    created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT uq_daily_metrics UNIQUE (tenant_id, agent_id, date)
);

CREATE INDEX idx_daily_metrics_tenant ON ai_agents.daily_metrics(tenant_id);
CREATE INDEX idx_daily_metrics_agent ON ai_agents.daily_metrics(agent_id);
CREATE INDEX idx_daily_metrics_date ON ai_agents.daily_metrics(date);

ai_agents.scheduled_reports

CREATE TABLE ai_agents.scheduled_reports (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,

    name VARCHAR(200) NOT NULL,

    -- Contenido
    metrics_to_include TEXT[] NOT NULL,
    agent_ids UUID[],
    channels TEXT[],

    -- Programación
    frequency VARCHAR(20) NOT NULL, -- daily, weekly, monthly
    day_of_week INT, -- 0-6
    day_of_month INT, -- 1-31
    time_utc TIME NOT NULL,

    -- Entrega
    delivery_method VARCHAR(20) NOT NULL,
    recipients TEXT[],
    webhook_url VARCHAR(500),
    format VARCHAR(20) DEFAULT 'pdf',

    -- Estado
    is_active BOOLEAN DEFAULT true,
    last_run_at TIMESTAMPTZ,
    last_run_status VARCHAR(20),
    next_run_at TIMESTAMPTZ,

    created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
    created_by UUID,

    CONSTRAINT chk_frequency CHECK (frequency IN ('daily', 'weekly', 'monthly')),
    CONSTRAINT chk_delivery CHECK (delivery_method IN ('email', 'webhook'))
);

ai_agents.budget_alerts

CREATE TABLE ai_agents.budget_alerts (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,

    -- Configuración
    monthly_budget_usd DECIMAL(10,2) NOT NULL,
    alert_thresholds INT[] DEFAULT '{50, 75, 90, 100}', -- Porcentajes

    -- Notificaciones
    notify_emails TEXT[],
    notify_webhook VARCHAR(500),

    -- Estado
    current_month_usage_usd DECIMAL(10,2) DEFAULT 0,
    last_alert_threshold INT, -- Último umbral notificado
    last_alert_at TIMESTAMPTZ,

    is_active BOOLEAN DEFAULT true,

    created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);

API Endpoints

Obtener Métricas

// GET /api/v1/ai-agents/{id}/metrics
// Query params: period=30d, metrics=conversations,satisfaction,costs
interface GetMetricsResponse {
  period: {
    from: string;
    to: string;
  };
  conversations: ConversationMetrics;
  satisfaction: SatisfactionMetrics;
  usage: UsageMetrics;
  performance: PerformanceMetrics;
}

Comparar Períodos

// GET /api/v1/ai-agents/{id}/metrics/compare
// Query params: period1=2025-11-01:2025-11-30&period2=2025-10-01:2025-10-31
interface CompareMetricsResponse {
  period1: MetricsSummary;
  period2: MetricsSummary;
  changes: {
    conversations: number;    // Porcentaje de cambio
    resolution_rate: number;
    satisfaction: number;
    cost: number;
  };
}

Exportar Datos

// POST /api/v1/ai-agents/{id}/metrics/export
interface ExportRequest {
  format: 'csv' | 'json' | 'pdf';
  period: { from: string; to: string };
  metrics: string[];
  include_conversations?: boolean;
}

interface ExportResponse {
  download_url: string;
  expires_at: string;
}

Configurar Alertas

// PUT /api/v1/ai-agents/budget-alerts
interface BudgetAlertConfig {
  monthly_budget_usd: number;
  alert_thresholds: number[];
  notify_emails: string[];
  notify_webhook?: string;
}

Job de Agregación

// Ejecutar diariamente a las 00:05 UTC
async function aggregateDailyMetrics(date: Date): Promise<void> {
  const tenants = await getAllActiveAITenants();

  for (const tenant of tenants) {
    const agents = await getAgentsByTenant(tenant.id);

    for (const agent of agents) {
      const metrics = await calculateDailyMetrics(agent.id, date);
      await upsertDailyMetrics(tenant.id, agent.id, date, metrics);
    }
  }

  // Actualizar proyecciones de costos
  await updateCostProjections();

  // Verificar alertas de presupuesto
  await checkBudgetAlerts();
}

Referencias

Dependencias

  • RF Requeridos: RF-018-003 (Procesamiento), RF-018-005 (Feedback)
  • Bloqueante para: Ninguno (RF terminal del módulo)