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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# for the file processing
|
| 2 |
+
import json
|
| 3 |
+
import csv
|
| 4 |
+
|
| 5 |
+
# for embedding
|
| 6 |
+
!pip install sentence_transformers
|
| 7 |
+
from sentence_transformers import SentenceTransformer
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import torch
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
# for qDrant
|
| 13 |
+
!pip install qdrant_client
|
| 14 |
+
from qdrant_client import QdrantClient, models
|
| 15 |
+
import os
|
| 16 |
+
from uuid import uuid4
|
| 17 |
+
|
| 18 |
+
# drive
|
| 19 |
+
from google.colab import drive
|
| 20 |
+
|
| 21 |
+
# LLM
|
| 22 |
+
!pip install openai
|
| 23 |
+
import openai
|
| 24 |
+
from openai import OpenAI
|
| 25 |
+
from google.colab import userdata
|
| 26 |
+
|
| 27 |
+
# render markdown
|
| 28 |
+
import markdown
|
| 29 |
+
from IPython.display import display, HTML
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class LogAnalyzer:
|
| 34 |
+
def __init__(self, log_file_path, csv_file_path, qdrant_data_dir):
|
| 35 |
+
self.log_file_path = log_file_path
|
| 36 |
+
self.csv_file_path = csv_file_path
|
| 37 |
+
self.qdrant_data_dir = qdrant_data_dir
|
| 38 |
+
self.df_combined = None
|
| 39 |
+
self.embedder = None
|
| 40 |
+
self.client = None
|
| 41 |
+
self.open_router_client = None
|
| 42 |
+
self.results = {} # Dictionary to store queries and their results
|
| 43 |
+
|
| 44 |
+
def process_log_to_csv(self):
|
| 45 |
+
"""Reads a log file, converts it to CSV, and saves it."""
|
| 46 |
+
with open(self.log_file_path, 'r') as f:
|
| 47 |
+
log_content = f.read()
|
| 48 |
+
|
| 49 |
+
log_entries = log_content.strip().split('\n')
|
| 50 |
+
|
| 51 |
+
with open(self.csv_file_path, 'w', newline='') as csvfile:
|
| 52 |
+
writer = csv.writer(csvfile)
|
| 53 |
+
|
| 54 |
+
if log_entries:
|
| 55 |
+
first_entry = json.loads(log_entries[0])
|
| 56 |
+
headers = first_entry.keys()
|
| 57 |
+
writer.writerow(headers)
|
| 58 |
+
|
| 59 |
+
for entry in log_entries:
|
| 60 |
+
try:
|
| 61 |
+
log_data = json.loads(entry)
|
| 62 |
+
row_data = [log_data.get(header, '') for header in headers]
|
| 63 |
+
writer.writerow(row_data)
|
| 64 |
+
except json.JSONDecodeError:
|
| 65 |
+
print(f"Skipping invalid JSON entry: {entry}")
|
| 66 |
+
|
| 67 |
+
print(f"Log file converted to CSV: {self.csv_file_path}")
|
| 68 |
+
|
| 69 |
+
def create_log_embeddings(self):
|
| 70 |
+
"""Reads CSV, creates combined text, generates embeddings, and stores in instance."""
|
| 71 |
+
df = pd.read_csv(self.csv_file_path)
|
| 72 |
+
df = df.drop_duplicates()
|
| 73 |
+
|
| 74 |
+
df["combined"] = (
|
| 75 |
+
"level: " + df.level.astype(str).str.strip()+"; tracId: " + df.traceId.astype(str).str.strip()
|
| 76 |
+
+"; msg: "+ df.astype(str).msg.str.strip()
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
self.df_combined = df.copy()
|
| 80 |
+
|
| 81 |
+
self.embedder = SentenceTransformer('all-mpnet-base-v2')
|
| 82 |
+
if torch.cuda.is_available():
|
| 83 |
+
print("GPU Found!")
|
| 84 |
+
self.embedder = self.embedder.to('cuda')
|
| 85 |
+
else:
|
| 86 |
+
print("Warning: No GPU found. Please add GPU to your notebook")
|
| 87 |
+
|
| 88 |
+
self.df_combined["embedding"] = self.df_combined.combined.apply(lambda x: self.embedder.encode(x))
|
| 89 |
+
|
| 90 |
+
def initialize_qdrant(self):
|
| 91 |
+
"""Initializes Qdrant client and creates collection if it doesn't exist."""
|
| 92 |
+
drive.mount('/content/drive')
|
| 93 |
+
os.makedirs(self.qdrant_data_dir, exist_ok=True)
|
| 94 |
+
print("SWARNIM ", self.qdrant_data_dir)
|
| 95 |
+
self.client = QdrantClient(path=self.qdrant_data_dir)
|
| 96 |
+
|
| 97 |
+
if self.df_combined is not None:
|
| 98 |
+
len_embedding = len(self.df_combined.embedding[0])
|
| 99 |
+
if not self.client.collection_exists("log_for_analysis"):
|
| 100 |
+
self.client.create_collection(
|
| 101 |
+
collection_name="log_for_analysis",
|
| 102 |
+
vectors_config=models.VectorParams(
|
| 103 |
+
size=len_embedding,
|
| 104 |
+
distance=models.Distance.COSINE
|
| 105 |
+
),
|
| 106 |
+
)
|
| 107 |
+
else:
|
| 108 |
+
print("Embeddings not created yet. Run create_log_embeddings first.")
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def upload_embeddings_to_qdrant(self):
|
| 112 |
+
"""Uploads embeddings from dataframe to Qdrant collection."""
|
| 113 |
+
if self.client is not None and self.df_combined is not None:
|
| 114 |
+
self.client.upload_points(
|
| 115 |
+
collection_name="log_for_analysis",
|
| 116 |
+
points=[
|
| 117 |
+
models.PointStruct(
|
| 118 |
+
id=str(uuid4()),
|
| 119 |
+
vector=np.array(row["embedding"]),
|
| 120 |
+
payload={
|
| 121 |
+
"metadata": {
|
| 122 |
+
key: row[key] for key in self.df_combined.columns if key != "embedding"
|
| 123 |
+
},
|
| 124 |
+
"content": row["combined"]
|
| 125 |
+
}
|
| 126 |
+
)
|
| 127 |
+
for _, row in self.df_combined.iterrows()
|
| 128 |
+
]
|
| 129 |
+
)
|
| 130 |
+
else:
|
| 131 |
+
print("Qdrant client or embeddings not initialized. Run initialize_qdrant and create_log_embeddings first.")
|
| 132 |
+
|
| 133 |
+
def search_qdrant(self, query, n=15):
|
| 134 |
+
"""Searches Qdrant for similar log entries based on query."""
|
| 135 |
+
if self.client is not None and self.embedder is not None:
|
| 136 |
+
query_embedding = self.embedder.encode(query).tolist()
|
| 137 |
+
|
| 138 |
+
hits = self.client.query_points(
|
| 139 |
+
collection_name="log_for_analysis",
|
| 140 |
+
query=query_embedding,
|
| 141 |
+
limit=n,
|
| 142 |
+
with_payload=True
|
| 143 |
+
).points
|
| 144 |
+
|
| 145 |
+
results = []
|
| 146 |
+
for hit in hits:
|
| 147 |
+
results.append({
|
| 148 |
+
'content': hit.payload['content'],
|
| 149 |
+
'metadata': hit.payload['metadata']
|
| 150 |
+
})
|
| 151 |
+
|
| 152 |
+
return results
|
| 153 |
+
else:
|
| 154 |
+
print("Qdrant client or embedder not initialized. Run initialize_qdrant and create_log_embeddings first.")
|
| 155 |
+
return []
|
| 156 |
+
|
| 157 |
+
def setup_openrouter_client(self):
|
| 158 |
+
"""Sets up and returns the OpenRouter client."""
|
| 159 |
+
OPEN_ROUTER_API_KEY = userdata.get('OPEN_ROUTER_API_KEY_2')
|
| 160 |
+
self.open_router_client = OpenAI(
|
| 161 |
+
base_url="https://openrouter.ai/api/v1",
|
| 162 |
+
api_key=OPEN_ROUTER_API_KEY
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
def generate_answer(self, query):
|
| 166 |
+
"""Generates an answer to the query using LLM based on Qdrant search results and stores the result."""
|
| 167 |
+
if self.open_router_client is not None and self.client is not None and self.embedder is not None:
|
| 168 |
+
context = f"""
|
| 169 |
+
LOG ANALYSIS RESULTS:
|
| 170 |
+
{self.search_qdrant(query)}
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
prompt = f"""
|
| 174 |
+
You are a log analyzer tool.
|
| 175 |
+
|
| 176 |
+
A user asked: "{query}"
|
| 177 |
+
|
| 178 |
+
Using the log analysis model gather info on logs relevant to the user query and summarize your thoughts.
|
| 179 |
+
|
| 180 |
+
context:
|
| 181 |
+
"{context}"
|
| 182 |
+
|
| 183 |
+
Summarize the results in a organized manner with observations from logs, possible issues, suggested fix. Make sure the last line at the end is in the format overall_health: capturing the
|
| 184 |
+
health of the system in one word - good or critical in the same line.
|
| 185 |
+
"""
|
| 186 |
+
|
| 187 |
+
messages = [
|
| 188 |
+
{"role": "system", "content": "You are a helpful assistant."},
|
| 189 |
+
{"role": "user", "content": prompt}
|
| 190 |
+
]
|
| 191 |
+
|
| 192 |
+
response = self.open_router_client.chat.completions.create(
|
| 193 |
+
model="qwen/qwen3-8b:free",
|
| 194 |
+
messages=[
|
| 195 |
+
{
|
| 196 |
+
"role": "user",
|
| 197 |
+
"content": prompt,
|
| 198 |
+
},
|
| 199 |
+
],
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
generated_text = response.choices[0].message.content
|
| 203 |
+
self.results[query] = generated_text # Store the query and its result
|
| 204 |
+
return generated_text
|
| 205 |
+
else:
|
| 206 |
+
print("Clients or embedder not initialized. Run setup_openrouter_client, initialize_qdrant, and create_log_embeddings first.")
|
| 207 |
+
return "Error: Log analysis components not fully initialized."
|
| 208 |
+
|
| 209 |
+
def render_markdown(self, md_text):
|
| 210 |
+
"""Renders markdown text as HTML."""
|
| 211 |
+
html = markdown.markdown(md_text)
|
| 212 |
+
display(HTML(html))
|
| 213 |
+
|
| 214 |
+
def get_results(self):
|
| 215 |
+
"""Returns the dictionary of stored queries and their results."""
|
| 216 |
+
return self.results
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def main_LogAnalyzer(queries):
|
| 220 |
+
log_file_path = '/content/sample_data/sample.log'
|
| 221 |
+
csv_file_path = '/content/sample_data/sample_log.csv'
|
| 222 |
+
qdrant_data_dir = '/content/drive/MyDrive/Semantic_Search/qdrant_data'
|
| 223 |
+
|
| 224 |
+
log_analyzer = LogAnalyzer(log_file_path, csv_file_path, qdrant_data_dir)
|
| 225 |
+
|
| 226 |
+
# Process log to CSV
|
| 227 |
+
log_analyzer.process_log_to_csv()
|
| 228 |
+
log_analyzer.create_log_embeddings()
|
| 229 |
+
log_analyzer.initialize_qdrant()
|
| 230 |
+
log_analyzer.upload_embeddings_to_qdrant()
|
| 231 |
+
log_analyzer.setup_openrouter_client()
|
| 232 |
+
|
| 233 |
+
for query in queries:
|
| 234 |
+
print(f"\nProcessing query: '{query}'")
|
| 235 |
+
log_analyzer.generate_answer(query)
|
| 236 |
+
|
| 237 |
+
return log_analyzer.get_results()
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
class Health:
|
| 242 |
+
def __init__(self):
|
| 243 |
+
self.health = "Good"
|
| 244 |
+
|
| 245 |
+
def HealthInspector(self,results,last_query):
|
| 246 |
+
# Get the answer for the last query
|
| 247 |
+
last_answer = results.get(last_query, "") # Use .get() for safe access
|
| 248 |
+
last_line = last_answer.strip().split('\n')[-1]
|
| 249 |
+
if "critical" in last_line.lower():
|
| 250 |
+
self.health = "Critical"
|
| 251 |
+
|
| 252 |
+
def render_markdown(md_text):
|
| 253 |
+
# Convert Markdown to HTML
|
| 254 |
+
html = markdown.markdown(md_text)
|
| 255 |
+
# Display the HTML
|
| 256 |
+
display(HTML(html))
|
| 257 |
+
|
| 258 |
+
def agent_LA():
|
| 259 |
+
|
| 260 |
+
# Perform a query
|
| 261 |
+
queries = [
|
| 262 |
+
"What are the most common errors in the logs?",
|
| 263 |
+
"Are there any performance issues or timeouts?",
|
| 264 |
+
"Which services are experiencing the most problems?",
|
| 265 |
+
"Are there any suspicious patterns or anomalies?",
|
| 266 |
+
"What are the critical issues that need immediate attention?"
|
| 267 |
+
"Is the Health of the system critical"
|
| 268 |
+
]
|
| 269 |
+
|
| 270 |
+
results = main_LogAnalyzer(queries)
|
| 271 |
+
# Format the results dictionary into a markdown string
|
| 272 |
+
markdown_output = ""
|
| 273 |
+
for query, answer in results.items():
|
| 274 |
+
markdown_output += f"## Query: {query}\n\n"
|
| 275 |
+
markdown_output += f"{answer}\n\n---\n\n" # Add separator between results
|
| 276 |
+
|
| 277 |
+
render_markdown(markdown_output) # Pass the formatted string to render_markdown
|
| 278 |
+
|
| 279 |
+
HP = Health()
|
| 280 |
+
HP.HealthInspector(results,queries[-1])
|
| 281 |
+
if HP.health == "Critical":
|
| 282 |
+
print("ALERTTTTTTTTTTT")
|
| 283 |
+
else:
|
| 284 |
+
print("NO ALERTTTTTTTTTTT")
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
agent_LA()
|
| 288 |
+
|
| 289 |
+
|