Update app.py
Browse files
app.py
CHANGED
|
@@ -1,278 +1,152 @@
|
|
| 1 |
-
# app.py
|
| 2 |
import os
|
| 3 |
import random
|
| 4 |
-
import
|
| 5 |
-
import
|
| 6 |
-
import io
|
| 7 |
-
from datetime import datetime
|
| 8 |
-
from typing import Tuple, Dict, Any, Optional
|
| 9 |
-
|
| 10 |
import gradio as gr
|
| 11 |
-
import
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
#
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
# Helper functions
|
| 48 |
-
# -------------------------
|
| 49 |
-
def now_ts() -> str:
|
| 50 |
-
return datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
|
| 51 |
-
|
| 52 |
-
def simulate_event(forced_anomaly: bool = False) -> Dict[str, Any]:
|
| 53 |
-
"""Create a synthetic telemetry event. If forced_anomaly=True, bump latency/error to trigger."""
|
| 54 |
-
component = random.choice(["api-service", "data-ingestor", "model-runner", "queue-worker"])
|
| 55 |
-
latency = round(random.gauss(150, 60), 2)
|
| 56 |
-
error_rate = round(random.random() * 0.2, 3)
|
| 57 |
-
if forced_anomaly:
|
| 58 |
-
# bump values to guarantee anomaly
|
| 59 |
-
latency = max(latency, LATENCY_THRESHOLD + random.uniform(20, 150))
|
| 60 |
-
error_rate = max(error_rate, ERROR_RATE_THRESHOLD + random.uniform(0.02, 0.2))
|
| 61 |
-
timestamp = now_ts()
|
| 62 |
-
return {
|
| 63 |
-
"timestamp": timestamp,
|
| 64 |
-
"component": component,
|
| 65 |
-
"latency": latency,
|
| 66 |
-
"error_rate": error_rate
|
| 67 |
-
}
|
| 68 |
-
|
| 69 |
-
def detect_anomaly(event: Dict[str, Any]) -> bool:
|
| 70 |
-
"""Detection rule (threshold-based for MVP)."""
|
| 71 |
-
return (event["latency"] > LATENCY_THRESHOLD) or (event["error_rate"] > ERROR_RATE_THRESHOLD)
|
| 72 |
-
|
| 73 |
-
def build_prompt_for_diagnosis(event: Dict[str, Any]) -> str:
|
| 74 |
-
"""Ask the LLM to return strict JSON with cause, confidence (0-1), and a safe one-line action."""
|
| 75 |
-
prompt = f"""
|
| 76 |
-
You are an experienced reliability engineer. Given the telemetry below, produce a JSON object only (no extra text)
|
| 77 |
-
with three fields:
|
| 78 |
-
- "cause": short plain-English reason for the anomaly (1-2 sentences).
|
| 79 |
-
- "confidence": a float between 0.0 and 1.0 indicating how confident you are in the cause.
|
| 80 |
-
- "action": a safe, specific, one-line remediation the system could attempt automatically (e.g., "restart service X", "retry job queue", "reload config from storage", "rollback model to version v1").
|
| 81 |
-
Telemetry:
|
| 82 |
-
- timestamp: {event['timestamp']}
|
| 83 |
-
- component: {event['component']}
|
| 84 |
-
- latency_ms: {event['latency']}
|
| 85 |
-
- error_rate: {event['error_rate']}
|
| 86 |
-
|
| 87 |
-
Return valid JSON only.
|
| 88 |
-
"""
|
| 89 |
-
return prompt
|
| 90 |
-
|
| 91 |
-
def call_hf_diagnosis(event: Dict[str, Any]) -> Tuple[Optional[Dict[str, Any]], str]:
|
| 92 |
-
"""Call HF inference API and parse JSON result robustly."""
|
| 93 |
-
prompt = build_prompt_for_diagnosis(event)
|
| 94 |
try:
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
# fallback to str
|
| 108 |
-
text = json.dumps(resp)
|
| 109 |
-
else:
|
| 110 |
-
text = str(resp)
|
| 111 |
-
|
| 112 |
-
# Extract JSON blob from the text (in-case model adds explanation)
|
| 113 |
-
# Find first "{" and last "}" to attempt JSON parse
|
| 114 |
-
start = text.find("{")
|
| 115 |
-
end = text.rfind("}")
|
| 116 |
-
if start != -1 and end != -1 and end > start:
|
| 117 |
-
json_str = text[start:end+1]
|
| 118 |
else:
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
parsed = json.loads(json_str)
|
| 122 |
-
# normalize keys/values
|
| 123 |
-
parsed["confidence"] = float(parsed.get("confidence", 0.0))
|
| 124 |
-
parsed["cause"] = str(parsed.get("cause", "")).strip()
|
| 125 |
-
parsed["action"] = str(parsed.get("action", "")).strip()
|
| 126 |
-
return parsed, text
|
| 127 |
except Exception as e:
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
fig, ax1 = plt.subplots(figsize=(8, 3.5))
|
| 149 |
-
ax2 = ax1.twinx()
|
| 150 |
-
|
| 151 |
-
# plotting last up to 50 points
|
| 152 |
-
tail = df.tail(50)
|
| 153 |
-
x = range(len(tail))
|
| 154 |
-
ax1.plot(x, tail["latency"], linewidth=1)
|
| 155 |
-
ax2.plot(x, tail["error_rate"], linewidth=1, linestyle="--")
|
| 156 |
-
|
| 157 |
-
ax1.set_xlabel("recent events")
|
| 158 |
-
ax1.set_ylabel("latency (ms)")
|
| 159 |
-
ax2.set_ylabel("error_rate")
|
| 160 |
-
|
| 161 |
-
plt.title("Telemetry trends (latency vs error_rate)")
|
| 162 |
-
plt.tight_layout()
|
| 163 |
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
plt.close(fig)
|
| 168 |
-
return buf
|
| 169 |
|
| 170 |
-
#
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
- simulate event (force anomaly every N runs)
|
| 177 |
-
- detect anomaly
|
| 178 |
-
- if anomaly: call HF for diagnosis -> parse JSON -> simulate healing (optional)
|
| 179 |
-
- append to events_log and return UI-friendly outputs
|
| 180 |
-
"""
|
| 181 |
-
run_counter["count"] += 1
|
| 182 |
-
forced = (run_counter["count"] % FORCE_EVERY_N == 0)
|
| 183 |
|
| 184 |
-
|
| 185 |
-
|
| 186 |
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
record["confidence"] = None
|
| 192 |
-
record["action"] = ""
|
| 193 |
-
record["healing_result"] = ""
|
| 194 |
|
| 195 |
-
if is_anomaly:
|
| 196 |
-
parsed, raw = call_hf_diagnosis(event)
|
| 197 |
-
record["analysis_raw"] = raw
|
| 198 |
-
if parsed is None:
|
| 199 |
-
record["cause"] = f"Diagnosis failed: {raw}"
|
| 200 |
-
record["confidence"] = 0.0
|
| 201 |
-
record["action"] = ""
|
| 202 |
-
record["healing_result"] = "No-action"
|
| 203 |
-
else:
|
| 204 |
-
record["cause"] = parsed.get("cause", "")
|
| 205 |
-
record["confidence"] = parsed.get("confidence", 0.0)
|
| 206 |
-
record["action"] = parsed.get("action", "")
|
| 207 |
-
# Decide whether to auto-execute: only auto if confidence > 0.5 and action is non-empty
|
| 208 |
-
if record["confidence"] >= 0.5 and record["action"]:
|
| 209 |
-
execution = simulate_execute_healing(record["action"])
|
| 210 |
-
record["healing_result"] = json.dumps(execution)
|
| 211 |
-
else:
|
| 212 |
-
record["healing_result"] = "deferred (low confidence or no action)"
|
| 213 |
else:
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
"timestamp":
|
| 220 |
-
"component":
|
| 221 |
-
"latency":
|
| 222 |
-
"error_rate":
|
| 223 |
-
"
|
| 224 |
-
"
|
| 225 |
-
"
|
| 226 |
-
|
| 227 |
-
"healing_result": record["healing_result"]
|
| 228 |
-
})
|
| 229 |
-
|
| 230 |
-
# prepare DataFrame for display
|
| 231 |
-
df = pd.DataFrame(events_log).fillna("-").tail(DISPLAY_TAIL)
|
| 232 |
-
|
| 233 |
-
# analytics plot
|
| 234 |
-
plot_buf = update_analytics_plot(pd.DataFrame(events_log).fillna(0))
|
| 235 |
|
| 236 |
-
|
| 237 |
-
|
|
|
|
| 238 |
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
with gr.Blocks(title="🧠 Agentic Reliability Framework MVP") as demo:
|
| 243 |
-
gr.Markdown("# 🧠 Agentic Reliability Framework MVP")
|
| 244 |
-
gr.Markdown(
|
| 245 |
-
"Real-time telemetry simulation → anomaly detection → HF-based diagnosis → simulated self-heal\n\n"
|
| 246 |
-
f"**Force anomaly every** `{FORCE_EVERY_N}` runs. Detection thresholds: latency>{LATENCY_THRESHOLD}ms or error_rate>{ERROR_RATE_THRESHOLD}."
|
| 247 |
)
|
| 248 |
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
plot_output = gr.Image(label="Telemetry Trends (latency / error_rate)")
|
| 257 |
-
|
| 258 |
-
# callbacks
|
| 259 |
-
run_btn.click(fn=process_event_and_return_outputs, inputs=None, outputs=[status, alerts, plot_output])
|
| 260 |
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
run_counter["count"] = 0
|
| 264 |
-
# return empty placeholders
|
| 265 |
-
return "Logs reset", pd.DataFrame([], columns=["timestamp", "component", "latency", "error_rate", "status", "cause", "confidence", "action", "healing_result"]), io.BytesIO()
|
| 266 |
|
| 267 |
-
|
| 268 |
|
| 269 |
-
gr.Markdown(
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
"- The model is prompted to return JSON only; we robustly parse the response but still handle parse errors.\n"
|
| 273 |
-
"- To test inference quickly, the system forces anomalies every N runs so you'll see diagnosis output frequently.\n"
|
| 274 |
-
)
|
| 275 |
|
|
|
|
| 276 |
if __name__ == "__main__":
|
| 277 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
| 278 |
-
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import random
|
| 3 |
+
import datetime
|
| 4 |
+
import numpy as np
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import gradio as gr
|
| 6 |
+
import requests
|
| 7 |
+
from sentence_transformers import SentenceTransformer
|
| 8 |
+
import faiss
|
| 9 |
+
|
| 10 |
+
# === Hugging Face Token (auto pulled from secrets) ===
|
| 11 |
+
HF_API_TOKEN = os.getenv("HF_API_TOKEN")
|
| 12 |
+
|
| 13 |
+
# === In-memory store for events ===
|
| 14 |
+
recent_events = []
|
| 15 |
+
|
| 16 |
+
# === Vector-based post-incident memory ===
|
| 17 |
+
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 18 |
+
dimension = 384 # embedding size
|
| 19 |
+
index = faiss.IndexFlatL2(dimension)
|
| 20 |
+
incident_texts = [] # metadata for recall
|
| 21 |
+
|
| 22 |
+
# === Helper: store + recall similar anomalies ===
|
| 23 |
+
def store_incident_vector(event, analysis):
|
| 24 |
+
"""Embed and store context of each anomaly."""
|
| 25 |
+
context = f"Component: {event['component']} | Latency: {event['latency']} | ErrorRate: {event['error_rate']} | Analysis: {analysis}"
|
| 26 |
+
embedding = embedding_model.encode(context)
|
| 27 |
+
index.add(np.array([embedding]).astype('float32'))
|
| 28 |
+
incident_texts.append(context)
|
| 29 |
+
|
| 30 |
+
def find_similar_incidents(event):
|
| 31 |
+
"""Return top-3 similar incidents (if exist)."""
|
| 32 |
+
if index.ntotal == 0:
|
| 33 |
+
return []
|
| 34 |
+
query = f"Component: {event['component']} | Latency: {event['latency']} | ErrorRate: {event['error_rate']}"
|
| 35 |
+
q_embed = embedding_model.encode(query)
|
| 36 |
+
D, I = index.search(np.array([q_embed]).astype('float32'), 3)
|
| 37 |
+
results = [incident_texts[i] for i in I[0] if i < len(incident_texts)]
|
| 38 |
+
return results
|
| 39 |
+
|
| 40 |
+
# === Hugging Face Inference API (for text analysis simulation) ===
|
| 41 |
+
def analyze_event_with_hf(event):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
try:
|
| 43 |
+
headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
|
| 44 |
+
payload = {
|
| 45 |
+
"inputs": f"Analyze system reliability for component {event['component']} with latency {event['latency']} and error rate {event['error_rate']}."
|
| 46 |
+
}
|
| 47 |
+
response = requests.post(
|
| 48 |
+
"https://api-inference.huggingface.co/models/distilbert-base-uncased",
|
| 49 |
+
headers=headers,
|
| 50 |
+
json=payload,
|
| 51 |
+
timeout=10
|
| 52 |
+
)
|
| 53 |
+
if response.status_code == 200:
|
| 54 |
+
return response.json()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
else:
|
| 56 |
+
return f"Error generating analysis: {response.text}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
except Exception as e:
|
| 58 |
+
return f"Error generating analysis: {str(e)}"
|
| 59 |
+
|
| 60 |
+
# === Forced anomaly toggle logic ===
|
| 61 |
+
run_counter = 0
|
| 62 |
+
def force_anomaly():
|
| 63 |
+
global run_counter
|
| 64 |
+
run_counter += 1
|
| 65 |
+
# Every 3rd run will be forced to trigger an anomaly
|
| 66 |
+
return run_counter % 3 == 0
|
| 67 |
+
|
| 68 |
+
# === Generate Telemetry Event ===
|
| 69 |
+
def simulate_event():
|
| 70 |
+
components = ["api-service", "data-ingestor", "model-runner", "queue-worker"]
|
| 71 |
+
event = {
|
| 72 |
+
"timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 73 |
+
"component": random.choice(components),
|
| 74 |
+
"latency": round(random.uniform(50, 350), 2),
|
| 75 |
+
"error_rate": round(random.uniform(0.01, 0.2), 3),
|
| 76 |
+
}
|
| 77 |
+
return event
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
+
# === Main processing logic ===
|
| 80 |
+
def process_event():
|
| 81 |
+
event = simulate_event()
|
|
|
|
|
|
|
| 82 |
|
| 83 |
+
# === Adaptive thresholding + forced anomaly ===
|
| 84 |
+
is_forced = force_anomaly()
|
| 85 |
+
if is_forced or event["latency"] > 150 or event["error_rate"] > 0.05:
|
| 86 |
+
status = "Anomaly"
|
| 87 |
+
analysis = analyze_event_with_hf(event)
|
| 88 |
+
store_incident_vector(event, str(analysis))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
+
# AI-driven "self-healing" simulation
|
| 91 |
+
healing_action = "Restarted container" if random.random() < 0.3 else "No actionable step detected."
|
| 92 |
|
| 93 |
+
# Check similarity with past incidents
|
| 94 |
+
similar = find_similar_incidents(event)
|
| 95 |
+
if similar:
|
| 96 |
+
healing_action += f" Found {len(similar)} similar incidents (e.g., {similar[0][:80]}...)."
|
|
|
|
|
|
|
|
|
|
| 97 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
else:
|
| 99 |
+
status = "Normal"
|
| 100 |
+
analysis = "-"
|
| 101 |
+
healing_action = "-"
|
| 102 |
+
|
| 103 |
+
event_record = {
|
| 104 |
+
"timestamp": event["timestamp"],
|
| 105 |
+
"component": event["component"],
|
| 106 |
+
"latency": event["latency"],
|
| 107 |
+
"error_rate": event["error_rate"],
|
| 108 |
+
"analysis": analysis,
|
| 109 |
+
"status": status,
|
| 110 |
+
"healing_action": healing_action
|
| 111 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
+
recent_events.append(event_record)
|
| 114 |
+
if len(recent_events) > 20:
|
| 115 |
+
recent_events.pop(0)
|
| 116 |
|
| 117 |
+
return (
|
| 118 |
+
f"✅ Event Processed ({status})",
|
| 119 |
+
gr.update(value=create_table(recent_events))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
)
|
| 121 |
|
| 122 |
+
# === Display helper for Gradio ===
|
| 123 |
+
def create_table(events):
|
| 124 |
+
if not events:
|
| 125 |
+
return "No events yet."
|
| 126 |
+
headers = list(events[0].keys())
|
| 127 |
+
table = "<table><tr>" + "".join(f"<th>{h}</th>" for h in headers) + "</tr>"
|
| 128 |
+
for e in events:
|
| 129 |
+
table += "<tr>" + "".join(f"<td>{e[h]}</td>" for h in headers) + "</tr>"
|
| 130 |
+
table += "</table>"
|
| 131 |
+
return table
|
| 132 |
+
|
| 133 |
+
# === Gradio UI ===
|
| 134 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 135 |
+
gr.Markdown("## 🧠 Agentic Reliability Framework MVP")
|
| 136 |
+
gr.Markdown("Adaptive anomaly detection + AI-driven self-healing + vector memory")
|
| 137 |
|
| 138 |
+
with gr.Row():
|
| 139 |
+
submit_btn = gr.Button("🚀 Submit Telemetry Event", variant="primary")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
|
| 141 |
+
detection_output = gr.Textbox(label="Detection Output", interactive=False)
|
| 142 |
+
recent_table = gr.HTML(label="Recent Events (Last 20)", value="No events yet.")
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
+
submit_btn.click(fn=process_event, outputs=[detection_output, recent_table])
|
| 145 |
|
| 146 |
+
gr.Markdown("---")
|
| 147 |
+
gr.Markdown("### Recent Events (Last 20)")
|
| 148 |
+
gr.Column([recent_table])
|
|
|
|
|
|
|
|
|
|
| 149 |
|
| 150 |
+
# === Launch app ===
|
| 151 |
if __name__ == "__main__":
|
| 152 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|