Update app.py
Browse files
app.py
CHANGED
|
@@ -1,160 +1,117 @@
|
|
| 1 |
-
import
|
| 2 |
-
import random
|
| 3 |
import time
|
| 4 |
-
import
|
|
|
|
| 5 |
import numpy as np
|
| 6 |
-
import
|
| 7 |
-
import torch
|
| 8 |
-
from sentence_transformers import SentenceTransformer
|
| 9 |
import faiss
|
| 10 |
-
import
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
# Vector memory setup
|
| 26 |
-
embedder = SentenceTransformer("all-MiniLM-L6-v2")
|
| 27 |
-
embedding_dim = 384
|
| 28 |
-
index = faiss.IndexFlatL2(embedding_dim)
|
| 29 |
-
incident_memory = [] # stores {vector, metadata}
|
| 30 |
-
|
| 31 |
-
# Helper: create embeddings
|
| 32 |
-
def embed_text(text):
|
| 33 |
-
vector = embedder.encode([text], convert_to_numpy=True)
|
| 34 |
-
return vector
|
| 35 |
-
|
| 36 |
-
# ========================
|
| 37 |
-
# Core Functions
|
| 38 |
-
# ========================
|
| 39 |
-
def detect_anomaly(event):
|
| 40 |
-
"""Simple adaptive anomaly detection."""
|
| 41 |
-
# Random anomaly forcing for test verification
|
| 42 |
-
force_anomaly = random.random() < 0.25 # 25% of events become anomalies automatically
|
| 43 |
-
if force_anomaly or event["latency"] > 150 or event["error_rate"] > 0.05:
|
| 44 |
-
return "Anomaly"
|
| 45 |
-
return "Normal"
|
| 46 |
-
|
| 47 |
-
def analyze_with_hf_api(text):
|
| 48 |
-
"""Call Hugging Face Inference API safely."""
|
| 49 |
-
if not HF_API_TOKEN:
|
| 50 |
-
return "⚠️ No API token — running offline simulation."
|
| 51 |
-
headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
|
| 52 |
-
try:
|
| 53 |
-
response = requests.post(
|
| 54 |
-
HF_INFERENCE_ENDPOINT,
|
| 55 |
-
headers=headers,
|
| 56 |
-
json={"inputs": text},
|
| 57 |
-
timeout=5
|
| 58 |
-
)
|
| 59 |
-
if response.status_code == 200:
|
| 60 |
-
result = response.json()
|
| 61 |
-
if isinstance(result, list):
|
| 62 |
-
return result[0].get("label", "No label")
|
| 63 |
-
return str(result)
|
| 64 |
-
else:
|
| 65 |
-
return f"Error {response.status_code}: {response.text}"
|
| 66 |
-
except Exception as e:
|
| 67 |
-
return f"Error generating analysis: {e}"
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
actions = [
|
| 72 |
"Restarted container",
|
| 73 |
-
"Scaled up pods",
|
| 74 |
"Cleared queue backlog",
|
| 75 |
-
"
|
|
|
|
| 76 |
]
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
"metadata": text
|
| 89 |
-
})
|
| 90 |
-
return len(incident_memory)
|
| 91 |
-
|
| 92 |
-
def find_similar_events(event, top_k=3):
|
| 93 |
-
"""Find semantically similar past incidents."""
|
| 94 |
-
if len(incident_memory) < 3:
|
| 95 |
-
return "Not enough incidents stored yet."
|
| 96 |
-
text = f"Component: {event['component']} | Latency: {event['latency']} | ErrorRate: {event['error_rate']} | Analysis: {event['analysis']}"
|
| 97 |
-
query_vec = embed_text(text)
|
| 98 |
-
distances, indices = index.search(query_vec, top_k)
|
| 99 |
-
results = [incident_memory[i]["metadata"] for i in indices[0] if i < len(incident_memory)]
|
| 100 |
-
return f"Found {len(results)} similar incidents (e.g., {results[0][:100]}...)." if results else "No matches found."
|
| 101 |
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
|
|
|
| 107 |
def process_event(component, latency, error_rate):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
event = {
|
| 109 |
-
"timestamp":
|
| 110 |
"component": component,
|
| 111 |
-
"latency":
|
| 112 |
-
"error_rate":
|
|
|
|
|
|
|
|
|
|
| 113 |
}
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
|
| 119 |
-
#
|
| 120 |
-
|
| 121 |
-
|
| 122 |
|
| 123 |
-
|
| 124 |
-
if len(events) > 20:
|
| 125 |
-
events.pop(0)
|
| 126 |
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
# Gradio UI
|
| 132 |
-
# ========================
|
| 133 |
-
with gr.Blocks(title="Agentic Reliability Framework MVP") as demo:
|
| 134 |
-
gr.Markdown("## 🧠 Agentic Reliability Framework MVP\nAdaptive anomaly detection + AI-driven self-healing + vector memory")
|
| 135 |
|
| 136 |
with gr.Row():
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
value="api-service"
|
| 141 |
-
)
|
| 142 |
-
latency_input = gr.Number(label="Latency (ms)", value=random.uniform(50, 200))
|
| 143 |
-
error_input = gr.Number(label="Error Rate", value=random.uniform(0.01, 0.15))
|
| 144 |
-
|
| 145 |
-
submit_btn = gr.Button("🚀 Submit Telemetry Event")
|
| 146 |
|
|
|
|
| 147 |
output_text = gr.Textbox(label="Detection Output")
|
| 148 |
-
output_table = gr.Dataframe(headers=["timestamp", "component", "latency", "error_rate", "
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
outputs=[output_text, output_table]
|
| 154 |
-
)
|
| 155 |
-
|
| 156 |
-
# ========================
|
| 157 |
-
# Launch
|
| 158 |
-
# ========================
|
| 159 |
-
if __name__ == "__main__":
|
| 160 |
-
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 1 |
+
import gradio as gr
|
|
|
|
| 2 |
import time
|
| 3 |
+
import random
|
| 4 |
+
import requests
|
| 5 |
import numpy as np
|
| 6 |
+
import pandas as pd
|
|
|
|
|
|
|
| 7 |
import faiss
|
| 8 |
+
from sentence_transformers import SentenceTransformer
|
| 9 |
+
|
| 10 |
+
# --- CONFIG ---
|
| 11 |
+
HF_TOKEN = (open(".env", "r").read().strip() if ".env" else None) or ""
|
| 12 |
+
HF_TOKEN = HF_TOKEN.strip() if HF_TOKEN else ""
|
| 13 |
+
if not HF_TOKEN:
|
| 14 |
+
print("⚠️ No Hugging Face token found. Running in fallback mode (local inference).")
|
| 15 |
+
|
| 16 |
+
API_URL = "https://router.huggingface.co/hf-inference"
|
| 17 |
+
|
| 18 |
+
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 19 |
+
incident_embeddings = []
|
| 20 |
+
incident_texts = []
|
| 21 |
+
|
| 22 |
+
recent_events = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
# --- SIMULATION HELPERS ---
|
| 25 |
+
def simulate_healing_action(component: str) -> str:
|
| 26 |
actions = [
|
| 27 |
"Restarted container",
|
|
|
|
| 28 |
"Cleared queue backlog",
|
| 29 |
+
"Rebalanced load",
|
| 30 |
+
"No actionable step detected.",
|
| 31 |
]
|
| 32 |
+
return random.choice(actions)
|
| 33 |
+
|
| 34 |
+
def detect_anomaly(latency: float, error_rate: float) -> bool:
|
| 35 |
+
# Simple adaptive anomaly threshold
|
| 36 |
+
score = latency * error_rate
|
| 37 |
+
threshold = random.uniform(5, 25)
|
| 38 |
+
return score > threshold
|
| 39 |
+
|
| 40 |
+
def embed_incident(text: str):
|
| 41 |
+
emb = model.encode([text], normalize_embeddings=True)
|
| 42 |
+
return np.array(emb).astype("float32")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
+
def find_similar_incidents(new_text: str, top_k=3):
|
| 45 |
+
if not incident_embeddings:
|
| 46 |
+
return "Not enough incidents stored yet."
|
| 47 |
+
new_emb = embed_incident(new_text)
|
| 48 |
+
index = faiss.IndexFlatIP(len(new_emb[0]))
|
| 49 |
+
index.add(np.vstack(incident_embeddings))
|
| 50 |
+
scores, ids = index.search(new_emb, top_k)
|
| 51 |
+
similar = [
|
| 52 |
+
f"Component: {incident_texts[i]['component']} | Latency: {incident_texts[i]['latency']} | ErrorRate: {incident_texts[i]['error_rate']} | Analysis: {incident_texts[i]['analysis'][:60]}..."
|
| 53 |
+
for i in ids[0] if i < len(incident_texts)
|
| 54 |
+
]
|
| 55 |
+
return f"Found {len(similar)} similar incidents ({'; '.join(similar)})."
|
| 56 |
|
| 57 |
+
# --- MAIN PROCESS ---
|
| 58 |
def process_event(component, latency, error_rate):
|
| 59 |
+
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
|
| 60 |
+
anomaly = detect_anomaly(latency, error_rate)
|
| 61 |
+
|
| 62 |
+
# --- Analysis step ---
|
| 63 |
+
payload = {
|
| 64 |
+
"inputs": f"Component {component} showing latency {latency} and error rate {error_rate}.",
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
try:
|
| 68 |
+
headers = {"Authorization": f"Bearer {HF_TOKEN.strip()}"}
|
| 69 |
+
response = requests.post(f"{API_URL}/facebook/bart-large-mnli", headers=headers, json=payload)
|
| 70 |
+
if response.status_code == 200:
|
| 71 |
+
analysis = response.json().get("generated_text", "No analysis output.")
|
| 72 |
+
else:
|
| 73 |
+
analysis = f"Error {response.status_code}: {response.text}"
|
| 74 |
+
except Exception as e:
|
| 75 |
+
analysis = f"Error generating analysis: {str(e)}"
|
| 76 |
+
|
| 77 |
+
status = "Anomaly" if anomaly else "Normal"
|
| 78 |
+
healing_action = simulate_healing_action(component) if anomaly else "-"
|
| 79 |
+
similar_info = find_similar_incidents(analysis)
|
| 80 |
+
|
| 81 |
event = {
|
| 82 |
+
"timestamp": timestamp,
|
| 83 |
"component": component,
|
| 84 |
+
"latency": latency,
|
| 85 |
+
"error_rate": error_rate,
|
| 86 |
+
"status": status,
|
| 87 |
+
"analysis": analysis,
|
| 88 |
+
"healing_action": f"{healing_action} {similar_info}" if anomaly else f"- {similar_info}",
|
| 89 |
}
|
| 90 |
|
| 91 |
+
recent_events.append(event)
|
| 92 |
+
if len(recent_events) > 20:
|
| 93 |
+
recent_events.pop(0)
|
| 94 |
|
| 95 |
+
# --- Store vector memory ---
|
| 96 |
+
incident_embeddings.append(embed_incident(analysis))
|
| 97 |
+
incident_texts.append(event)
|
| 98 |
|
| 99 |
+
return f"✅ Event Processed", pd.DataFrame(recent_events)
|
|
|
|
|
|
|
| 100 |
|
| 101 |
+
# --- GRADIO UI ---
|
| 102 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 103 |
+
gr.Markdown("## 🧠 Agentic Reliability Framework MVP")
|
| 104 |
+
gr.Markdown("Adaptive anomaly detection + AI-driven self-healing + vector memory")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
with gr.Row():
|
| 107 |
+
component = gr.Textbox(label="Component", value="api-service")
|
| 108 |
+
latency = gr.Number(label="Latency (ms)", value=random.uniform(50, 200))
|
| 109 |
+
error_rate = gr.Number(label="Error Rate", value=random.uniform(0.01, 0.2))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
+
submit = gr.Button("🚀 Submit Telemetry Event")
|
| 112 |
output_text = gr.Textbox(label="Detection Output")
|
| 113 |
+
output_table = gr.Dataframe(headers=["timestamp", "component", "latency", "error_rate", "status", "analysis", "healing_action"], label="Recent Events (Last 20)")
|
| 114 |
+
|
| 115 |
+
submit.click(process_event, inputs=[component, latency, error_rate], outputs=[output_text, output_table])
|
| 116 |
+
|
| 117 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|