""" Cognitive Agent Evaluator v2.0 - Interactive Hugging Face Space Engineered by Fabio Torres (neurodeveloper11) Bilingual Behavioral Telemetry, 10-Axis Cognitive Bias Audit & AI Alignment Mitigation Engine """ import asyncio import json import plotly.graph_objects as go import gradio as gr from src.schemas import EvaluationRequest from src.agent import CognitiveEvaluationAgent from src.biases import BIAS_DEFINITIONS agent = CognitiveEvaluationAgent() ALL_BIAS_NAMES = list(BIAS_DEFINITIONS.keys()) def create_radar_chart(detected_biases): """ Creates a 10-axis Spider / Radar chart in Plotly visualizing the cognitive distortion profile. """ scores = {} for name in ALL_BIAS_NAMES: scores[name] = 0.0 for b in detected_biases: if b.bias_name in scores: weight = 1.0 if b.severity == "high" else 0.65 scores[b.bias_name] = round(b.confidence_score * weight, 2) categories = [ "Confirmation", "Anchoring", "Sunk Cost", "Availability", "Framing", "Catastrophizing", "All-or-Nothing", "Overconfidence", "Attribution", "Outcome Bias" ] values = [ scores.get("Confirmation Bias", 0), scores.get("Anchoring Bias", 0), scores.get("Sunk Cost Fallacy", 0), scores.get("Availability Heuristic", 0), scores.get("Framing Effect", 0), scores.get("Catastrophizing", 0), scores.get("All-or-Nothing Thinking", 0), scores.get("Overconfidence Bias", 0), scores.get("Fundamental Attribution Bias", 0), scores.get("Outcome Bias", 0), ] # Close polygon categories_closed = categories + [categories[0]] values_closed = values + [values[0]] fig = go.Figure() fig.add_trace(go.Scatterpolar( r=values_closed, theta=categories_closed, fill='toself', name='Distortion Footprint', fillcolor='rgba(99, 102, 241, 0.35)', line=dict(color='#4f46e5', width=2.5), marker=dict(size=6, color='#4338ca') )) fig.update_layout( polar=dict( radialaxis=dict( visible=True, range=[0, 1.0], tickvals=[0.25, 0.50, 0.75, 1.0], ticktext=["25%", "50%", "75%", "100%"], linecolor="#cbd5e1", gridcolor="#e2e8f0" ), angularaxis=dict( linecolor="#cbd5e1", gridcolor="#e2e8f0" ) ), showlegend=False, margin=dict(l=40, r=40, t=30, b=30), height=380, paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)" ) return fig def evaluate_text_sync(text: str, author_type: str): """ Synchronous wrapper for agent evaluation. """ if not text or len(text.strip()) < 5: return ( "⚠️ Por favor ingresa un texto con al menos 5 caracteres.", "N/A", "0.0", "0.0", "0.0", "0.0", create_radar_chart([]), "
Sin datos suficientes para evaluar.
", "Sin intervenciones requeridas.", "Sin directiva necesaria.", "{}" ) author_code = "llm" if "LLM" in author_type else ("human" if "Human" in author_type else "hybrid") req = EvaluationRequest(text=text, author_type=author_code) result = asyncio.run(agent.evaluate(req)) # Format KPI badges risk_color = "#10b981" if result.mitigation.alignment_risk_level == "nominal" else ( "#f59e0b" if result.mitigation.alignment_risk_level == "moderate" else "#ef4444" ) risk_html = f"El texto muestra un razonamiento balanceado y dentro de parámetros nominales.
\"{p}\"" for p in b.matched_patterns])
card = f"""
{b.explanation}
Presiona 'Auditar Sesgos' para ver el diagnóstico detallado.
") with gr.TabItem("🛡️ Directivas de Mitigación (Fabio Torres)"): mitigation_display = gr.Markdown("Las recomendaciones de des-sesgo aparecerán aquí.") with gr.TabItem("📋 Prompt de Red-Teaming (Listo para ChatGPT/Claude)"): red_teaming_display = gr.Textbox(label="Directiva de Re-prompting para Modelos de IA", lines=5, interactive=False) with gr.TabItem("💾 Telemetría JSON (API-Ready)"): json_display = gr.Code(label="Respuesta estructurada para consumo en producción", language="json") # Wire actions eval_btn.click( fn=evaluate_text_sync, inputs=[input_text, author_type], outputs=[ risk_output, cog_output, burnout_output, safety_output, valence_output, radar_plot, biases_display, mitigation_display, red_teaming_display, json_display ] ) # Wire Preset Buttons sample_1 = "This outage is a total disaster! Everything is broken and ruined, and we are completely doomed because the junior engineers are incompetent and it's entirely their fault! I am completely exhausted and this is urgent, fix it asap!" sample_2 = "We have already invested too much into this legacy architecture to turn back now. It would be wasted if we quit. Besides, the initial price estimate was $50,000, so our new budget must be close to that starting figure." sample_3 = "This algorithmic solution is 100% guaranteed and impossible to fail. It is obviously true and everyone knows it, so we can safely ignore opposing counterevidence because this confirms what I already knew." sample_4 = "The experimental data indicates a 12% improvement in latency under controlled load conditions. We will collaborate together as a team to support the rollout, learn from unexpected edge cases, and maintain transparent, constructive feedback." example_1.click(lambda: (sample_1, "Human Decision Maker (Humano)"), outputs=[input_text, author_type]).then( fn=evaluate_text_sync, inputs=[input_text, author_type], outputs=[risk_output, cog_output, burnout_output, safety_output, valence_output, radar_plot, biases_display, mitigation_display, red_teaming_display, json_display] ) example_2.click(lambda: (sample_2, "Human Decision Maker (Humano)"), outputs=[input_text, author_type]).then( fn=evaluate_text_sync, inputs=[input_text, author_type], outputs=[risk_output, cog_output, burnout_output, safety_output, valence_output, radar_plot, biases_display, mitigation_display, red_teaming_display, json_display] ) example_3.click(lambda: (sample_3, "LLM Reasoning Trace (Modelo de IA)"), outputs=[input_text, author_type]).then( fn=evaluate_text_sync, inputs=[input_text, author_type], outputs=[risk_output, cog_output, burnout_output, safety_output, valence_output, radar_plot, biases_display, mitigation_display, red_teaming_display, json_display] ) example_4.click(lambda: (sample_4, "Team Channel / Meeting Transcript (Equipo)"), outputs=[input_text, author_type]).then( fn=evaluate_text_sync, inputs=[input_text, author_type], outputs=[risk_output, cog_output, burnout_output, safety_output, valence_output, radar_plot, biases_display, mitigation_display, red_teaming_display, json_display] ) if __name__ == "__main__": demo.launch()