petter2025's picture
Update ui/components.py
adb7e74 verified
raw
history blame
17.7 kB
"""
Enhanced components with real ARF integration
"""
import streamlit as st
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
from typing import List, Dict, Any, Optional
import time
import json
# Mock imports for ARF objects (in real app, import from actual packages)
class MockHealingIntent:
"""Mock HealingIntent for demo purposes"""
def __init__(self, action, component, confidence, status, rag_similarity_score=None):
self.action = action
self.component = component
self.confidence = confidence
self.status = status
self.rag_similarity_score = rag_similarity_score
self.deterministic_id = f"intent_{int(time.time())}"
self.created_at = time.time()
def get_execution_summary(self):
return {
"intent_id": self.deterministic_id,
"action": self.action,
"component": self.component,
"confidence": self.confidence,
"status": self.status.value if hasattr(self.status, 'value') else self.status,
"rag_similarity_score": self.rag_similarity_score
}
def create_arf_enhanced_timeline(incident_data: Dict[str, Any], healing_intents: List[Dict[str, Any]] = None):
"""
Create an enhanced incident timeline with real ARF integration
"""
col1, col2 = st.columns([2, 1])
with col1:
st.markdown("### πŸ“ˆ ARF-Enhanced Incident Timeline")
# Create timeline events based on ARF processing pipeline
events = [
{"time": "-5m", "event": "πŸ“‘ Alert Triggered", "phase": "detection", "color": "#FF6B6B"},
{"time": "-4m", "event": "🧠 ARF Analysis Started", "phase": "analysis", "color": "#4ECDC4"},
{"time": "-3.5m", "event": "πŸ” RAG Similarity Search", "phase": "rag", "color": "#1E90FF"},
{"time": "-2.5m", "event": "🎯 Pattern Detection", "phase": "pattern", "color": "#9D4EDD"},
{"time": "-1.5m", "event": "πŸ’‘ HealingIntent Generated", "phase": "intent", "color": "#FFD166"},
{"time": "-1m", "event": "⚑ MCP Execution", "phase": "execution", "color": "#06D6A0"},
{"time": "Now", "event": "βœ… Resolution Complete", "phase": "resolution", "color": "#118AB2"}
]
# Create enhanced timeline with ARF phases
fig = go.Figure()
# Add ARF processing phases as background
phases = [
{"name": "Detection", "x_range": [0, 1], "color": "rgba(255, 107, 107, 0.1)"},
{"name": "Analysis", "x_range": [1, 2.5], "color": "rgba(78, 205, 196, 0.1)"},
{"name": "RAG Search", "x_range": [2.5, 3.5], "color": "rgba(30, 144, 255, 0.1)"},
{"name": "Intent Gen", "x_range": [3.5, 4.5], "color": "rgba(157, 78, 221, 0.1)"},
{"name": "Execution", "x_range": [4.5, 5.5], "color": "rgba(6, 214, 160, 0.1)"},
{"name": "Resolution", "x_range": [5.5, 6], "color": "rgba(17, 138, 178, 0.1)"}
]
for phase in phases:
fig.add_shape(
type="rect",
x0=phase["x_range"][0] - 0.5,
x1=phase["x_range"][1] - 0.5,
y0=-0.3,
y1=0.3,
fillcolor=phase["color"],
line=dict(width=0),
layer="below"
)
# Add phase labels
fig.add_annotation(
x=(phase["x_range"][0] + phase["x_range"][1] - 1) / 2,
y=0.4,
text=phase["name"],
showarrow=False,
font=dict(size=9, color="#64748B"),
yshift=10
)
# Add timeline line with markers
fig.add_trace(go.Scatter(
x=[i for i in range(len(events))],
y=[0] * len(events),
mode='lines+markers+text',
line=dict(color='#334155', width=2, dash='solid'),
marker=dict(
size=18,
color=[e['color'] for e in events],
line=dict(width=2, color='white')
),
text=[e['event'][0] for e in events], # Use emoji as marker text
textposition="middle center",
textfont=dict(size=10, color='white'),
hoverinfo='text',
hovertext=[f"<b>{e['event']}</b><br>Phase: {e['phase'].title()}<br>Time: {e['time']}" for e in events],
hovertemplate='%{hovertext}<extra></extra>'
))
# Add event descriptions
for i, event in enumerate(events):
fig.add_annotation(
x=i,
y=-0.2,
text=event['event'].split(' ')[1] if ' ' in event['event'] else event['event'][1:],
showarrow=False,
yshift=-30,
font=dict(size=9, color=event['color'])
)
fig.add_annotation(
x=i,
y=0.1,
text=event['time'],
showarrow=False,
yshift=25,
font=dict(size=8, color="#94A3B8")
)
# Update layout
fig.update_layout(
height=250,
showlegend=False,
plot_bgcolor='rgba(0,0,0,0)',
paper_bgcolor='rgba(0,0,0,0)',
xaxis=dict(
range=[-1, len(events)],
showticklabels=False,
showgrid=False,
zeroline=False
),
yaxis=dict(
range=[-0.5, 0.5],
showticklabels=False,
showgrid=False,
zeroline=False
),
margin=dict(l=20, r=20, t=20, b=50)
)
st.plotly_chart(fig, use_container_width=True)
# Add ARF processing metrics
if healing_intents:
cols = st.columns(4)
with cols[0]:
intent_conf = healing_intents[0].get('confidence', 0.7) if healing_intents else 0.7
st.metric(
label="🧠 ARF Confidence",
value=f"{intent_conf*100:.1f}%",
delta="+15% with RAG"
)
with cols[1]:
st.metric(
label="πŸ” Similar Incidents",
value=f"{len(healing_intents[0].get('similar_incidents', [])) if healing_intents else 0}",
delta="Pattern detected"
)
with cols[2]:
st.metric(
label="⚑ Resolution Time",
value="8.2min",
delta="-85% vs OSS"
)
with cols[3]:
cost_savings = incident_data.get('revenue_loss_per_hour', 8500) * 0.5 # 30min saved
st.metric(
label="πŸ’° Cost Avoided",
value=f"${cost_savings:,.0f}",
delta_color="normal"
)
with col2:
st.markdown("### 🎯 ARF Pattern Detection")
# Pattern confidence from ARF RAG similarity
rag_score = healing_intents[0].get('rag_similarity_score', 0.85) if healing_intents else 0.85
# Confidence gauge using actual ARF confidence
fig = go.Figure(go.Indicator(
mode="gauge+number",
value=rag_score * 100,
domain={'x': [0, 1], 'y': [0, 1]},
title={'text': "RAG Similarity Score", 'font': {'size': 14}},
gauge={
'axis': {'range': [0, 100], 'tickwidth': 1, 'tickcolor': "darkblue"},
'bar': {'color': "#06D6A0" if rag_score > 0.85 else "#FFD166"},
'steps': [
{'range': [0, 70], 'color': "rgba(255, 107, 107, 0.3)"},
{'range': [70, 85], 'color': "rgba(255, 209, 102, 0.3)"},
{'range': [85, 100], 'color': "rgba(6, 214, 160, 0.3)"}
],
'threshold': {
'line': {'color': "red", 'width': 4},
'thickness': 0.75,
'value': 85
}
}
))
fig.update_layout(
height=200,
margin=dict(l=30, r=30, t=50, b=20)
)
st.plotly_chart(fig, use_container_width=True)
# Pattern details based on ARF analysis
pattern_type = "cache_miss_storm"
if incident_data.get('database_load', 0) > 90:
pattern_type = "database_overload"
st.info(f"""
**Detected Pattern**: `{pattern_type}`
**Confidence**: {rag_score*100:.1f}%
**Auto-Heal Eligible**: {'βœ… Yes' if rag_score > 0.85 else '❌ Manual Review'}
**Similar Incidents**: {len(healing_intents[0].get('similar_incidents', [])) if healing_intents else 0}
""")
def create_healing_intent_visualizer(healing_intent: Dict[str, Any]):
"""
Visualize a HealingIntent object from ARF
"""
st.markdown("### πŸ’‘ ARF HealingIntent")
# Create columns for intent visualization
col1, col2 = st.columns([1, 2])
with col1:
# Confidence indicator
confidence = healing_intent.get('confidence', 0.85)
fig = go.Figure(go.Indicator(
mode="gauge+number",
value=confidence * 100,
domain={'x': [0, 1], 'y': [0, 1]},
title={'text': "Confidence"},
gauge={
'axis': {'range': [0, 100]},
'bar': {'color': "#06D6A0" if confidence > 0.85 else "#FFD166"},
'steps': [
{'range': [0, 70], 'color': "rgba(255, 107, 107, 0.3)"},
{'range': [70, 85], 'color': "rgba(255, 209, 102, 0.3)"},
{'range': [85, 100], 'color': "rgba(6, 214, 160, 0.3)"}
],
'threshold': {
'line': {'color': "red", 'width': 4},
'thickness': 0.75,
'value': 85
}
}
))
fig.update_layout(height=180)
st.plotly_chart(fig, use_container_width=True)
# Intent metadata
st.caption("Intent Metadata")
st.code(f"""
ID: {healing_intent.get('deterministic_id', 'N/A')}
Status: {healing_intent.get('status', 'created')}
Source: {healing_intent.get('source', 'oss_analysis')}
Created: {datetime.fromtimestamp(healing_intent.get('created_at', time.time())).strftime('%H:%M:%S')}
""")
with col2:
# Intent details
st.markdown("#### Action Details")
# Action card
action = healing_intent.get('action', 'scale_out')
component = healing_intent.get('component', 'redis_cache')
st.info(f"""
**Action**: `{action}`
**Component**: `{component}`
**Justification**: {healing_intent.get('justification', 'Based on historical pattern analysis')}
""")
# Parameters
params = healing_intent.get('parameters', {})
if params:
st.markdown("#### Parameters")
for key, value in params.items():
st.metric(label=key, value=str(value))
# Similar incidents
similar = healing_intent.get('similar_incidents', [])
if similar:
st.markdown(f"#### Similar Incidents ({len(similar)})")
for i, incident in enumerate(similar[:2]): # Show top 2
with st.expander(f"Similar Incident #{i+1}"):
st.json(incident)
def create_rag_similarity_panel(query: str, similar_incidents: List[Dict[str, Any]]):
"""
Display RAG similarity search results
"""
st.markdown("### πŸ” RAG Similarity Search")
if not similar_incidents:
st.info("No similar incidents found in memory")
return
# Create similarity results table
df_data = []
for i, incident in enumerate(similar_incidents):
df_data.append({
"Rank": i + 1,
"Component": incident.get('component', 'unknown'),
"Similarity": f"{incident.get('similarity_score', 0)*100:.1f}%",
"Resolution": incident.get('resolution', 'Unknown'),
"Success": "βœ…" if incident.get('success', False) else "❌",
"Actions": len(incident.get('actions_taken', []))
})
df = pd.DataFrame(df_data)
# Display as styled table
st.dataframe(
df,
use_container_width=True,
column_config={
"Rank": st.column_config.NumberColumn(width="small"),
"Similarity": st.column_config.ProgressColumn(
width="medium",
format="%f%%",
min_value=0,
max_value=100,
),
},
hide_index=True
)
# Similarity distribution chart
if len(similar_incidents) > 1:
fig = px.bar(
df,
x="Rank",
y=df["Similarity"].str.rstrip('%').astype(float),
color=df["Similarity"].str.rstrip('%').astype(float),
color_continuous_scale=["#FF6B6B", "#FFD166", "#06D6A0"],
title="Similarity Scores Distribution"
)
fig.update_layout(height=200, showlegend=False)
st.plotly_chart(fig, use_container_width=True)
def create_learning_engine_panel(learning_stats: Dict[str, Any]):
"""
Display ARF learning engine insights
"""
st.markdown("### 🧠 ARF Learning Engine")
cols = st.columns(2)
with cols[0]:
# Pattern detection stats
st.metric(
label="Patterns Detected",
value=learning_stats.get('patterns_detected', 6),
delta="+2 this week"
)
st.metric(
label="Success Rate",
value=f"{learning_stats.get('success_rate', '95.2%')}",
delta="+5.2%"
)
with cols[1]:
# Learning metrics
st.metric(
label="Auto-Heal Rate",
value=f"{learning_stats.get('auto_heal_rate', '78.6%')}",
delta="+12.4%"
)
st.metric(
label="Confidence Threshold",
value=f"{learning_stats.get('confidence_threshold', 0.85)}",
delta="Optimized"
)
# Detected patterns
patterns = learning_stats.get('detected_patterns', {})
if patterns:
st.markdown("#### Detected Patterns")
pattern_data = []
for pattern_name, pattern_info in patterns.items():
pattern_data.append({
"Pattern": pattern_name,
"Occurrences": pattern_info.get('occurrences', 0),
"Confidence": f"{pattern_info.get('confidence', 0)*100:.1f}%",
"Auto-Heal": "βœ…" if pattern_info.get('auto_heal', False) else "❌"
})
pattern_df = pd.DataFrame(pattern_data)
st.dataframe(pattern_df, use_container_width=True, hide_index=True)
def create_execution_mode_toggle(current_mode: str = "advisory"):
"""
Show OSS vs Enterprise execution mode differences
"""
st.markdown("### ⚑ ARF Execution Modes")
# Mode selector
modes = {
"advisory": {
"name": "OSS Advisory",
"description": "Analysis only, no execution",
"color": "#FF6B6B",
"features": [
"Incident analysis",
"RAG similarity search",
"HealingIntent creation",
"Pattern detection"
]
},
"approval": {
"name": "Enterprise (Approval)",
"description": "Human-in-the-loop execution",
"color": "#FFD166",
"features": [
"All OSS features",
"Human approval workflow",
"Audit trail",
"Compliance reporting"
]
},
"autonomous": {
"name": "Enterprise (Autonomous)",
"description": "AI-driven auto-healing",
"color": "#06D6A0",
"features": [
"All approval features",
"Auto-execution",
"Learning engine",
"Predictive analytics"
]
}
}
# Create mode selection
selected_mode = st.selectbox(
"Execution Mode",
options=list(modes.keys()),
format_func=lambda x: modes[x]["name"],
index=list(modes.keys()).index(current_mode) if current_mode in modes else 0
)
# Display mode details
mode = modes[selected_mode]
# Mode indicator
st.info(f"""
**Current Mode**: {mode['name']}
**Description**: {mode['description']}
""")
# Feature comparison
st.markdown("#### Features Available")
for feature in mode['features']:
st.markdown(f"βœ… {feature}")
# Mode differences
st.markdown("#### Mode Differences")
diff_data = {
"Feature": ["Execution", "Human Review", "Audit Trail", "Learning", "Compliance"],
"OSS Advisory": ["❌", "❌", "Basic", "❌", "❌"],
"Enterprise (Approval)": ["βœ…", "βœ…", "Full", "Basic", "βœ…"],
"Enterprise (Autonomous)": ["βœ…", "Optional", "Full", "Advanced", "βœ…"]
}
diff_df = pd.DataFrame(diff_data)
st.dataframe(diff_df, use_container_width=True, hide_index=True)
return selected_mode