petter2025 commited on
Commit
b0546d3
·
verified ·
1 Parent(s): 8e0e3e3

Update demo/orchestrator.py

Browse files
Files changed (1) hide show
  1. demo/orchestrator.py +57 -175
demo/orchestrator.py CHANGED
@@ -1,180 +1,62 @@
1
- """
2
- Enhanced demo orchestrator with real ARF integration patterns
3
- """
4
- import streamlit as st
5
- import time
6
- import json
7
- from datetime import datetime
8
- from typing import Dict, Any, List, Optional
9
 
10
- # Import mock ARF components
11
- from .scenarios import get_scenario_data
12
- from .mock_arf import (
13
- create_mock_healing_intent,
14
- run_rag_similarity_search,
15
- calculate_pattern_confidence,
16
- simulate_arf_analysis
17
- )
18
 
19
- def run_enhanced_incident_demo(scenario_name: str, execution_mode: str = "advisory"):
 
 
 
 
 
 
 
 
 
 
20
  """
21
- Run enhanced incident demo with ARF integration
 
 
 
22
  """
23
- # Get scenario data
24
- scenario = get_scenario_data(scenario_name)
25
- if not scenario:
26
- st.error(f"Scenario '{scenario_name}' not found")
27
- return
28
-
29
- # Display incident header
30
- st.markdown(f"### 🔥 {scenario['name']}")
31
- st.caption(scenario['description'])
32
-
33
- # Create columns for metrics and business impact
34
- col1, col2 = st.columns(2)
35
-
36
- with col1:
37
- st.markdown("#### 📊 Current Metrics")
38
- metrics = scenario.get('metrics', {})
39
-
40
- # Create metrics display
41
- metrics_cols = st.columns(2)
42
- for idx, (key, value) in enumerate(metrics.items()):
43
- with metrics_cols[idx % 2]:
44
- if isinstance(value, (int, float)):
45
- if key == "cache_hit_rate":
46
- st.metric(label=key.replace('_', ' ').title(),
47
- value=f"{value}%",
48
- delta="-65%" if value < 20 else None)
49
- elif key == "database_load":
50
- st.metric(label=key.replace('_', ' ').title(),
51
- value=f"{value}%",
52
- delta="+40%" if value > 80 else None)
53
- else:
54
- st.metric(label=key.replace('_', ' ').title(), value=str(value))
55
-
56
- with col2:
57
- st.markdown("#### 💰 Business Impact")
58
- impact = scenario.get('business_impact', {})
59
-
60
- if impact.get('revenue_loss_per_hour'):
61
- st.metric(
62
- label="Revenue Loss/Hour",
63
- value=f"${impact['revenue_loss_per_hour']:,.0f}",
64
- delta_color="inverse"
65
- )
66
-
67
- if impact.get('sla_violation'):
68
- st.error("⚠️ SLA Violation Detected")
69
-
70
- if impact.get('affected_users'):
71
- st.metric(
72
- label="Affected Users",
73
- value=f"{impact['affected_users']:,.0f}",
74
- delta_color="inverse"
75
  )
76
-
77
- # Run ARF analysis
78
- with st.spinner("🧠 ARF Analysis in progress..."):
79
- time.sleep(1.5)
80
-
81
- # Simulate ARF analysis pipeline
82
- arf_analysis = simulate_arf_analysis(scenario)
83
-
84
- # Run RAG similarity search
85
- similar_incidents = run_rag_similarity_search(scenario)
86
-
87
- # Calculate pattern confidence
88
- pattern_confidence = calculate_pattern_confidence(scenario, similar_incidents)
89
-
90
- # Create HealingIntent
91
- healing_intent = create_mock_healing_intent(
92
- scenario=scenario,
93
- similar_incidents=similar_incidents,
94
- confidence=pattern_confidence
95
- )
96
-
97
- # Display enhanced timeline with ARF integration
98
- from ..ui.components import create_arf_enhanced_timeline
99
- create_arf_enhanced_timeline(scenario, [healing_intent])
100
-
101
- # Show HealingIntent visualizer
102
- from ..ui.components import create_healing_intent_visualizer
103
- create_healing_intent_visualizer(healing_intent)
104
-
105
- # Show RAG similarity panel
106
- from ..ui.components import create_rag_similarity_panel
107
- create_rag_similarity_panel(
108
- query=f"{scenario['name']} - {scenario['description']}",
109
- similar_incidents=similar_incidents
110
- )
111
-
112
- # Show execution mode differences
113
- from ..ui.components import create_execution_mode_toggle
114
- selected_mode = create_execution_mode_toggle(execution_mode)
115
-
116
- # Action buttons based on mode
117
- st.markdown("---")
118
- st.markdown("### ⚡ Take Action")
119
-
120
- col1, col2, col3 = st.columns(3)
121
-
122
- with col1:
123
- if st.button("🆓 Run OSS Analysis", use_container_width=True):
124
- st.info("""
125
- **OSS Analysis Results:**
126
- - Incident identified: Cache miss storm
127
- - Recommended action: Scale Redis cluster
128
- - Confidence: 85%
129
- - Similar incidents found: 3
130
-
131
- *Note: OSS edition provides analysis only.*
132
- """)
133
-
134
- with col2:
135
- if st.button("🚀 Execute Enterprise Healing", use_container_width=True):
136
- if execution_mode == "advisory":
137
- st.warning("""
138
- **Enterprise Upgrade Required**
139
-
140
- To execute healing actions, upgrade to Enterprise Edition:
141
- - Autonomous healing capabilities
142
- - Approval workflows
143
- - Audit trails
144
- - Compliance reporting
145
-
146
- [Upgrade Now](https://arf.dev/enterprise)
147
- """)
148
- elif execution_mode == "approval":
149
- st.success("""
150
- **Healing Action Submitted for Approval**
151
-
152
- ✅ HealingIntent created
153
- 📋 Sent to approval workflow
154
- 👤 Awaiting human review
155
- 🕐 Estimated approval time: 2-5 minutes
156
- """)
157
- else: # autonomous
158
- st.success("""
159
- **Autonomous Healing Executed**
160
-
161
- ✅ Redis cluster scaled from 3 to 5 nodes
162
- ✅ Cache TTL adjusted to 300s
163
- ✅ Database connections optimized
164
- ⚡ Resolution time: 8.2 minutes
165
- 💰 Cost avoided: $7,225
166
- """)
167
-
168
- with col3:
169
- if st.button("🔐 Require Manual Approval", use_container_width=True):
170
- st.info("""
171
- **Approval Workflow Enabled**
172
-
173
- This incident will require manual approval before execution:
174
- 1. SRE team notified via PagerDuty
175
- 2. Approval required from team lead
176
- 3. Audit trail recorded
177
- 4. Compliance checks run
178
-
179
- *Enterprise feature: Human-in-the-loop safety*
180
- """)
 
1
+ # demo/orchestrator.py
2
+ from __future__ import annotations
 
 
 
 
 
 
3
 
4
+ import logging
5
+ from typing import Any, Dict, Optional
 
 
 
 
 
 
6
 
7
+ logger = logging.getLogger(__name__)
8
+
9
+ # --- Optional Streamlit import (SAFE) ---
10
+ try:
11
+ import streamlit as st # type: ignore
12
+ except Exception:
13
+ st = None
14
+ logger.info("Streamlit not available; running in non-Streamlit mode.")
15
+
16
+
17
+ class DemoOrchestrator:
18
  """
19
+ Orchestrates demo scenarios.
20
+
21
+ Streamlit is OPTIONAL and never required at import time.
22
+ This prevents Hugging Face Spaces from crashing.
23
  """
24
+
25
+ def __init__(self, enable_streamlit: bool = False):
26
+ self.enable_streamlit = enable_streamlit and st is not None
27
+
28
+ if enable_streamlit and st is None:
29
+ logger.warning(
30
+ "Streamlit requested but not installed. "
31
+ "Proceeding without Streamlit UI."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  )
33
+
34
+ def render_streamlit(self) -> None:
35
+ """
36
+ Render Streamlit UI if available.
37
+ Safe no-op otherwise.
38
+ """
39
+ if not self.enable_streamlit or st is None:
40
+ logger.debug("Streamlit UI disabled or unavailable.")
41
+ return
42
+
43
+ st.title("Agentic Reliability Framework Demo")
44
+ st.markdown("Interactive demo running inside Streamlit.")
45
+
46
+ def run_scenario(self, scenario: Dict[str, Any]) -> Dict[str, Any]:
47
+ """
48
+ Run a demo scenario without any UI dependency.
49
+ """
50
+ logger.info("Running scenario: %s", scenario.get("name", "unknown"))
51
+
52
+ result = {
53
+ "scenario": scenario.get("name"),
54
+ "status": "completed",
55
+ "output": scenario,
56
+ }
57
+
58
+ # Optional Streamlit visualization
59
+ if self.enable_streamlit and st is not None:
60
+ st.json(result)
61
+
62
+ return result