Ir al contenido

Integration into the Data Ecosystem (The 'Where')

Integration methodology of the SHAP pipeline with observability platforms such as Grafana and the Gemini unified SDK for automated diagnostics in Portelcore.

0views

4.1. The Analytical Virtuous Circle in Portelcore

Sección titulada «4.1. El Círculo Virtuoso Analítico en Portelcore»

The ultimate value of SHAP interpretability lies not only in passive telemetry collection but in its dynamic integration to optimize business decision-making.

graph TD
A["1. Inferencia & Telemetría<br>(Calcular Predicciones & SHAP)"] --> B["2. Almacenamiento Selectivo<br>(PostgreSQL / SQLite Indexado)"]
B --> C["3. Observabilidad & BI<br>(Grafana / Looker Studio)"]
C --> D["4. Diagnóstico por IA<br>(Gemini SDK Forensics)"]
D --> E["5. Optimización del Modelo<br>(Refactorización de Features)"]
E --> A
style A fill:#3b4252,stroke:#4c566a,stroke-width:1px,color:#d8dee9
style B fill:#3b4252,stroke:#4c566a,stroke-width:1px,color:#d8dee9
style C fill:#3b4252,stroke:#4c566a,stroke-width:1px,color:#d8dee9
style D fill:#a3be8c,stroke:#8fbcbb,stroke-width:2px,color:#2e3440
style E fill:#81a1c1,stroke:#5e81ac,stroke-width:1px,color:#2e3440

4.2. Observability Dashboards: Connection with Grafana

Sección titulada «4.2. Dashboards de Observabilidad: Conexión con Grafana»

The analytical telemetry relational schema is ideal for feeding interactive dashboards that allow monitoring model behavior and health.

  • Purpose: Monitor whether the impact of a specific business variable (e.g., tickets_soporte_abiertos) changes drastically over time.
  • SQL Query for Grafana:
    SELECT
    p.predicted_at AS "time",
    a.shap_value AS "Valor SHAP: Tickets Soporte"
    FROM model_predictions p
    JOIN shap_attributions a ON p.prediction_id = a.prediction_id
    WHERE a.feature_name = 'tickets_soporte_abiertos'
    AND p.portel_user_id = $portel_user_id
    ORDER BY p.predicted_at ASC;
  • Purpose: Show prediction breakdowns where the model failed by the largest error margin.
  • SQL Query for Grafana:
    SELECT
    p.predicted_at AS "Fecha",
    p.portel_user_id AS "Usuario",
    p.output_probability AS "Probabilidad Predicha",
    a.feature_name AS "Variable",
    a.feature_value AS "Valor Observado",
    a.shap_value AS "Contribución SHAP"
    FROM model_predictions p
    JOIN shap_attributions a ON p.prediction_id = a.prediction_id
    WHERE p.actual_outcome IS NOT NULL
    AND (p.output_probability > 0.5) != p.actual_outcome -- Discordancia
    ORDER BY ABS(a.shap_value) DESC
    LIMIT 20;

The highest level of analytical automation at Portelcore consists of using Google's Artificial Intelligence (Gemini) to audit and diagnose the logical failures of the predictive model interpreted by SHAP.

This script interacts with the telemetry database and uses the Google GenAI unified SDK (google-genai) to generate diagnoses in structured natural language.

import os
import sqlite3
from google import genai
from google.genai import types
# Inicialización segura del cliente unificado de Gemini API
# Recuerda exportar la variable de entorno: export GEMINI_API_KEY="tu_clave_de_pruebas"
client = genai.Client()
def generar_diagnostico_forense(prediction_id: str) -> str:
"""
Extrae las atribuciones SHAP de una predicción errónea y
genera un diagnóstico detallado utilizando Gemini 2.5 Flash.
"""
# Conexión a la base de datos local
conn = sqlite3.connect("data/portel_telemetry.db")
cursor = conn.cursor()
# 1. Obtener detalles de la predicción
cursor.execute("""
SELECT portel_user_id, output_probability, actual_outcome
FROM model_predictions
WHERE prediction_id = ?
""", (prediction_id,))
pred_info = cursor.fetchone()
if not pred_info:
return "ID de predicción no encontrado."
user_id, prob, actual = pred_info
# 2. Obtener atribuciones SHAP
cursor.execute("""
SELECT feature_name, feature_value, shap_value
FROM shap_attributions
WHERE prediction_id = ?
ORDER BY ABS(shap_value) DESC
""", (prediction_id,))
attributions = cursor.fetchall()
conn.close()
# 3. Construir el prompt analítico
desglose_txt = ""
for feat, val, shap in attributions:
desglose_txt += f"- {feat}: Valor Observado = {val:.2f}, Contribución SHAP = {shap:+.4f}\n"
prompt = f"""
Actúa como un experto Ingeniero de Machine Learning y Analista Cuantitativo en Portelcore.
Debemos auditar un fallo lógico en nuestro modelo de predicción de abandono (Churn) 'portel_user_churn'.
DETALLES DE LA PREDICCIÓN:
- ID Predicción: {prediction_id}
- ID Usuario: {user_id}
- Probabilidad Predicha por el Modelo: {prob:.4f} (Umbral de decisión > 0.5)
- Resultado Real: {'Abandono' if actual else 'Permanencia'}
- Estado de Predicción: FALLIDO (El modelo predijo {'Abandono' if prob > 0.5 else 'Permanencia'}, pero ocurrió lo contrario)
CONTRIBUCIONES DETALLADAS DE SHAP:
{desglose_txt}
TAREA:
1. Realiza una autopsia técnica del error. Explica por qué el modelo se equivocó basándote en las contribuciones de SHAP.
2. Determina si el modelo confió excesivamente en variables sesgadas o de ruido.
3. Recomienda acciones correctivas de ingeniería de datos para este usuario o para reentrenar el modelo en portelcore.com.
"""
# 4. Invocación al SDK unificado de Gemini
response = client.models.generate_content(
model='gemini-2.5-flash',
contents=prompt,
config=types.GenerateContentConfig(
temperature=0.2, # Baja temperatura para análisis consistentes y precisos
)
)
return response.text
# Demostración práctica de invocación en laboratorio
if __name__ == "__main__":
prediction_test_id = "pred_user_17222_40_231"
print("--- Iniciando Análisis Forense de Telemetría con Gemini ---")
try:
diagnostico = generar_diagnostico_forense(prediction_test_id)
print("\nDIAGNÓSTICO ENVIADO POR GEMINI API:")
print(diagnostico)
except Exception as e:
print(f"Error en la llamada al SDK GenAI: {e}")

Ensure that the integration flows end-to-end before closing the pipeline:

  • Grafana queries are indexed to avoid full table scans on the portelcore.com databases. ✓
  • The analisis_forense_ia.py script exclusively uses the google-genai unified SDK (genai.Client()). ✓
  • The Gemini generative model temperature is set conservatively ($0.2$) to avoid analytical hallucinations in production. ✓