LogAnalyzer / app.py
athottam's picture
Update app.py
b2df223 verified
Raw History Blame Contribute Delete
9.23 kB
# 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)