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.
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:#2e34404.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.
1. Traceability and Attribution History Panel (Line Chart)
Sección titulada «1. Panel de Trazabilidad e Historial de Atribución (Gráfico de Líneas)»- Purpose: Monitor whether the impact of a specific business variable (e.g.,
tickets_soporte_abiertos) changes drastically over time. - SQL Query for Grafana:
SELECTp.predicted_at AS "time",a.shap_value AS "Valor SHAP: Tickets Soporte"FROM model_predictions pJOIN shap_attributions a ON p.prediction_id = a.prediction_idWHERE a.feature_name = 'tickets_soporte_abiertos'AND p.portel_user_id = $portel_user_idORDER BY p.predicted_at ASC;
2. Predictive Drift Forensic Panel (Control Table)
Sección titulada «2. Panel Forense de Desvíos Predictivos (Tabla de Control)»- Purpose: Show prediction breakdowns where the model failed by the largest error margin.
- SQL Query for Grafana:
SELECTp.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 pJOIN shap_attributions a ON p.prediction_id = a.prediction_idWHERE p.actual_outcome IS NOT NULLAND (p.output_probability > 0.5) != p.actual_outcome -- DiscordanciaORDER BY ABS(a.shap_value) DESCLIMIT 20;
4.3. Automated Forensic Diagnosis with Gemini
Sección titulada «4.3. Diagnóstico Forense Automatizado con Gemini»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.
Automation Script: analisis_forense_ia.py
Sección titulada «Script de Automatización: analisis_forense_ia.py»This script interacts with the telemetry database and uses the Google GenAI unified SDK (google-genai) to generate diagnoses in structured natural language.
import osimport sqlite3from google import genaifrom 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 laboratorioif __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}")4.4. Ecosystem Validation Checklist
Sección titulada «4.4. Checklist de Validación del Ecosistema»Ensure that the integration flows end-to-end before closing the pipeline:
- Grafana queries are indexed to avoid full table scans on the
portelcore.comdatabases. ✓ - The
analisis_forense_ia.pyscript exclusively uses thegoogle-genaiunified SDK (genai.Client()). ✓ - The Gemini generative model temperature is set conservatively ($0.2$) to avoid analytical hallucinations in production. ✓

