Spaces:
Sleeping
Sleeping
File size: 9,232 Bytes
81a8d38 7f0d5fe 81a8d38 69e8487 81a8d38 a7b1b97 81a8d38 6fe4d90 81a8d38 c0f9e22 81a8d38 b2df223 81a8d38 b2df223 81a8d38 b2df223 81a8d38 aa222d4 81a8d38 b2df223 81a8d38 935a068 eb60dd1 3ffa756 81a8d38 935a068 81a8d38 935a068 81a8d38 5042d98 81a8d38 935a068 81a8d38 b3fdbe3 81a8d38 6af667c 81a8d38 b3fdbe3 81a8d38 5042d98 81a8d38 935a068 03bd66e 935a068 5042d98 81a8d38 6af667c 935a068 773642f | 1 2 3 4 5 6 7 8 9 10 11 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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 | # for the file processing
import json
import csv
# for embedding
from sentence_transformers import SentenceTransformer
import pandas as pd
import torch
import numpy as np
# for qDrant
from qdrant_client import QdrantClient, models
import os
from uuid import uuid4
# drive
#from google.colab import drive
# LLM
import openai
from openai import OpenAI
#from google.colab import userdata
# render markdown
import markdown
from IPython.display import display, HTML
# gradio
import gradio as gr
class LogAnalyzer:
def __init__(self, log_file_path, csv_file_path, qdrant_data_dir):
self.log_file_path = log_file_path
self.csv_file_path = csv_file_path
self.qdrant_data_dir = qdrant_data_dir
self.df_combined = None
self.embedder = None
self.client = None
self.open_router_client = None
self.results = {} # Dictionary to store queries and their results
def process_log_to_csv(self):
with open(self.log_file_path, 'r') as f:
log_content = f.read()
log_entries = log_content.strip().split('\n')
with open(self.csv_file_path, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
if log_entries:
first_entry = json.loads(log_entries[0])
headers = first_entry.keys()
writer.writerow(headers)
for entry in log_entries:
try:
log_data = json.loads(entry)
row_data = [log_data.get(header, '') for header in headers]
writer.writerow(row_data)
except json.JSONDecodeError:
print(f"Skipping invalid JSON entry: {entry}")
print(f"Log file converted to CSV: {self.csv_file_path}")
def create_log_embeddings(self):
df = pd.read_csv(self.csv_file_path)
df = df.drop_duplicates()
df["combined"] = (
"level: " + df.level.astype(str).str.strip()+"; tracId: " + df.traceId.astype(str).str.strip()
+"; msg: "+ df.astype(str).msg.str.strip()
)
self.df_combined = df.copy()
self.embedder = SentenceTransformer('all-mpnet-base-v2')
if torch.cuda.is_available():
print("GPU Found!")
self.embedder = self.embedder.to('cuda')
else:
print("Warning: No GPU found. Please add GPU to your notebook")
self.df_combined["embedding"] = self.df_combined.combined.apply(lambda x: self.embedder.encode(x))
def initialize_qdrant(self):
os.makedirs(self.qdrant_data_dir, exist_ok=True)
self.client = QdrantClient(path=self.qdrant_data_dir)
if self.df_combined is not None:
len_embedding = len(self.df_combined.embedding[0])
if not self.client.collection_exists("log_for_analysis"):
self.client.create_collection(
collection_name="log_for_analysis",
vectors_config=models.VectorParams(
size=len_embedding,
distance=models.Distance.COSINE
),
)
else:
print("self.df_combined is None.")
def upload_embeddings_to_qdrant(self):
if self.client is not None and self.df_combined is not None:
self.client.upload_points(
collection_name="log_for_analysis",
points=[
models.PointStruct(
id=str(uuid4()),
vector=np.array(row["embedding"]),
payload={
"metadata": {
key: row[key] for key in self.df_combined.columns if key != "embedding"
},
"content": row["combined"]
}
)
for _, row in self.df_combined.iterrows()
]
)
else:
print("Qdrant client not initialized")
def search_qdrant(self, query, n=15):
if self.client is not None and self.embedder is not None:
query_embedding = self.embedder.encode(query).tolist()
hits = self.client.query_points(
collection_name="log_for_analysis",
query=query_embedding,
limit=n,
with_payload=True
).points
results = []
for hit in hits:
results.append({
'content': hit.payload['content'],
'metadata': hit.payload['metadata']
})
return results
else:
print("Qdrant client not initialized")
return []
def setup_openrouter_client(self):
OPEN_ROUTER_API_KEY = os.getenv('OPEN_ROUTER_API_KEY_2')
self.open_router_client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=OPEN_ROUTER_API_KEY
)
def generate_answer(self, query):
if self.open_router_client is not None and self.client is not None and self.embedder is not None:
context = f"""
LOG ANALYSIS RESULTS:
{self.search_qdrant(query)}
"""
prompt = f"""
You are a log analyzer tool.
A user asked: "{query}"
Using the log analysis model gather info on logs relevant to the user query and summarize your thoughts.
context:
"{context}"
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
health of the system in one word - good or critical in the same line.
"""
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt}
]
response = self.open_router_client.chat.completions.create(
model="qwen/qwen3-8b:free",
messages=[
{
"role": "user",
"content": prompt,
},
],
)
generated_text = response.choices[0].message.content
self.results[query] = generated_text # Store the query and its result
return generated_text
else:
print("open router client not initialized")
return "Error: Log analysis components not fully initialized."
def get_results(self):
return self.results
def main_LogAnalyzer(log_file_path, queries):
csv_file_path = 'sample_log.csv'
qdrant_data_dir = 'qdrant_data_tech_103'
with open(log_file_path.name, 'r') as f_in, open(csv_file_path, 'w') as f_out:
f_out.write(f_in.read())
log_analyzer = LogAnalyzer(log_file_path.name, csv_file_path, qdrant_data_dir)
# Process log to CSV
log_analyzer.process_log_to_csv()
log_analyzer.create_log_embeddings()
log_analyzer.initialize_qdrant()
log_analyzer.upload_embeddings_to_qdrant()
log_analyzer.setup_openrouter_client()
for query in queries:
print(f"\nProcessing query: '{query}'")
log_analyzer.generate_answer(query)
return log_analyzer.get_results()
class Health:
def __init__(self):
self.health = "Good"
def HealthInspector(self,results,last_query):
# Get the answer for the last query
last_answer = results.get(last_query, "") # Use .get() for safe access
last_line = last_answer.strip().split('\n')[-1]
if "critical" in last_line.lower():
self.health = "Critical"
def render_markdown(md_text):
# Convert Markdown to HTML
html = markdown.markdown(md_text)
# Display the HTML
display(HTML(html))
def agent_LA(log_file):
# Perform a query
queries = [
"What are the most common errors in the logs?",
"Are there any performance issues or timeouts?",
"Which services are experiencing the most problems?",
"Are there any suspicious patterns or anomalies?",
"What are the critical issues that need immediate attention?",
"Is the Health of the system critical"
]
results = main_LogAnalyzer(log_file, queries)
# Format the results dictionary into a markdown string
markdown_out = ""
for query, answer in results.items():
markdown_out += f"## Query: {query}\n\n"
markdown_out += f"{answer}\n\n---\n\n" # Add separator between results
HP = Health()
HP.HealthInspector(results,queries[-1])
health_result = ""
if HP.health == "Critical":
health_result = "SYSTEM IN HIGH ALERT STATE"
else:
health_result = "SYSTEM IN GOOD HEALTH"
final_result = markdown_out + "\n ## HEALTH INSPECTOR \n\n " + health_result
return final_result
markdown_output = gr.Markdown()
demo = gr.Interface(
fn=agent_LA,
inputs=gr.File(label="Upload Log File", file_types=[".log", ".txt"]),
outputs=markdown_output,
title="Log Analyzer Agent"
)
demo.launch(share=True)
|