EATosin commited on
Commit
04ae0b4
·
verified ·
1 Parent(s): 435d673

Create rag_agent.py

Browse files
Files changed (1) hide show
  1. rag_agent.py +75 -0
rag_agent.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import google.generativeai as genai
3
+ from dotenv import load_dotenv
4
+
5
+ # --- CLOUD-READY KEY LOADING ---
6
+ # 1. Try to load from environment (Cloud/Hugging Face)
7
+ api_key = os.getenv("GEMINI_API_KEY")
8
+
9
+ # 2. If not found, try loading from local .env file (Local Dev)
10
+ if not api_key:
11
+ load_dotenv()
12
+ api_key = os.getenv("GEMINI_API_KEY")
13
+
14
+ if not api_key:
15
+ # If still missing, just warn (prevents crash on startup, fails later if called)
16
+ print("⚠️ Warning: GEMINI_API_KEY not found. Agent functionality will fail.")
17
+ else:
18
+ genai.configure(api_key=api_key)
19
+
20
+ # --- MODEL CONFIGURATION ---
21
+ print("📡 Connecting to Gemini 2.5 Flash...")
22
+ try:
23
+ # Try the latest model first
24
+ model = genai.GenerativeModel('gemini-2.5-flash')
25
+ except Exception as e:
26
+ print(f"⚠️ Model 2.5 not found, falling back to Pro. Error: {e}")
27
+ model = genai.GenerativeModel('gemini-pro')
28
+
29
+ class SentinelAgent:
30
+ def __init__(self):
31
+ # Simulated Vector DB (Log Store)
32
+ self.system_logs = {
33
+ "CPU_SPIKE": "Log 10:42am - Process 'minerd' started using 99% CPU. Unknown user 'xmr_bot'.",
34
+ "MEMORY_LEAK": "Log 10:45am - OutOfMemoryError: Java Heap Space. Service 'PaymentGateway' crashed.",
35
+ "NETWORK_LAG": "Log 10:50am - DDOS detected from IP Block 192.168.x.x. Latency increased to 5000ms."
36
+ }
37
+
38
+ def investigate(self, anomaly_value, z_score):
39
+ print("🤖 Sentinel Agent analyzing logs...")
40
+
41
+ # Simple heuristic retrieval
42
+ if anomaly_value > 100:
43
+ context = self.system_logs["CPU_SPIKE"]
44
+ elif anomaly_value > 80:
45
+ context = self.system_logs["MEMORY_LEAK"]
46
+ else:
47
+ context = self.system_logs["NETWORK_LAG"]
48
+
49
+ prompt = f"""
50
+ You are Sentinel, an Autonomous MLOps Agent.
51
+
52
+ **ALERT:** Anomaly Detected!
53
+ - Metric Value: {anomaly_value}
54
+ - Deviation: {z_score:.2f} sigma
55
+
56
+ **RETRIEVED LOGS:**
57
+ "{context}"
58
+
59
+ **TASK:**
60
+ Identify the root cause and recommend a fix. Short and technical.
61
+ """
62
+
63
+ try:
64
+ response = model.generate_content(prompt)
65
+ return response.text
66
+ except Exception as e:
67
+ return f"Agent Error: {str(e)}"
68
+
69
+ # --- Quick Test Block ---
70
+ if __name__ == "__main__":
71
+ agent = SentinelAgent()
72
+ print("🔥 Simulation: Testing Agent...")
73
+ report = agent.investigate(120, 4.5)
74
+ print("\n--- 📄 REPORT ---")
75
+ print(report)