Spaces:
Build error

pfe / app.py
amineelh's picture
Update app.py
65c0108 verified
Raw History Blame Contribute Delete
12.1 kB
import os
import logging
import streamlit as st
from datetime import datetime
from textwrap import dedent
from typing import Dict, Iterator, Optional
from pathlib import Path
import gradio as gr
# Load environment variables
from dotenv import load_dotenv
load_dotenv()
# Agno imports
from agno.agent import Agent
from agno.knowledge.pdf import PDFKnowledgeBase, PDFReader
from agno.models.groq import Groq
from agno.team import Team
from agno.vectordb.mongodb import MongoDb
from agno.embedder.huggingface import HuggingfaceCustomEmbedder
from agno.workflow import RunEvent, RunResponse
from transformers import AutoModel, AutoTokenizer
import torch
import numpy as np
# Configure logging
logging.basicConfig(level=logging.INFO)
# === Setup paths ===
cwd = Path(__file__).parent.resolve()
tmp = cwd.joinpath("tmp")
if not tmp.exists():
tmp.mkdir(exist_ok=True, parents=True)
# === API Keys & DB Configuration ===
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
db_url = os.getenv("MONGODB_URL")
# === Embedder Definition ===
class CustomDimensionEmbedder(HuggingfaceCustomEmbedder):
def __init__(self, model_name="sentence-transformers/all-mpnet-base-v2"):
self.model = AutoModel.from_pretrained(model_name)
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
self.model.eval()
def get_embedding(self, text):
tokens = self.tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512)
with torch.no_grad():
outputs = self.model(**tokens)
embeddings = outputs.last_hidden_state.mean(dim=1).squeeze().numpy()
if len(embeddings) < 1536:
padded_embeddings = np.zeros(1536)
padded_embeddings[:len(embeddings)] = embeddings
return padded_embeddings.tolist()
return embeddings[:1536].tolist()
embeddings = CustomDimensionEmbedder()
# # === Agent Instructions ===
# analysis_instructions = """
# Vous êtes un agent spécialisé dans l'analyse détaillée des descriptions d'incidents.
# Votre objectif est d'extraire les informations clés suivantes:
# 1. Type précis de l'incident (Infrastructure, Réseau, Sécurité, Applicatif)
# 2. Niveau de criticité (Critique, Élevé, Moyen, Faible)
# 3. Mots-clés principaux
# 4. Composants ou systèmes affectés
# 5. Impacts potentiels de l'incident
# Fournissez une analyse structurée et concise.
# """
mex_researcher_instructions = """
Vous êtes un agent spécialisé dans la recherche de solutions dans le manuel d'exploitation.
Votre mission est de:
"Recherchez toujours dans votre base de connaissances d'abord et utilisez-le si disponible."
1. Rechercher des solutions dans le manuel d'exploitation pour résoudre l'incident
2. Identifier les étapes et recommandations spécifiques selon le type d'incident
3. Extraire les informations pertinentes:
- Étapes à suivre pour résoudre l'incident
- Solutions proposées dans le manuel d'exploitation
4. Fournir un rapport détaillé avec des instructions et solutions
"""
# === Knowledge Base Setup ===
mex_knowledge_base = PDFKnowledgeBase(
path="./data/mex.pdf",
max_links=5,
vector_db=MongoDb(
collection_name="solutions_manuel",
db_url=db_url,
embedder=embeddings,
wait_until_index_ready=30,
wait_after_insert=60
),
reader=PDFReader(chunk=True)
)
# === Agent Setup ===
mex_researcher = Agent(
model=Groq(id="deepseek-r1-distill-llama-70b", api_key=GROQ_API_KEY),
name="mex_researcher",
role="chercheur manuel exploitation",
instructions=mex_researcher_instructions,
knowledge=mex_knowledge_base,
#knowledge_base.load(upsert=True),
add_references=True,
search_knowledge=True,
markdown=True
)
# analyzer = Agent(
# name="analyseur_description",
# role="analyseur de description d'incidents",
# model=Groq(id="deepseek-r1-distill-llama-70b", api_key=GROQ_API_KEY),
# instructions=analysis_instructions,
# add_references=True,
# markdown=True
# )
# === Team Setup ===
# team_instructions = """
# Vous êtes un gestionnaire de résolution d'incidents dirigeant une équipe d'agents spécialisés.
# 1. Demandez à l'agent d'analyse d'extraire les informations clés de l'incident.
# 2. Ensuite, demandez à l'agent de recherche de consulter le manuel d'exploitation pour identifier les solutions pertinentes.
# 3. Examinez les recommandations du manuel et leur adéquation au type d'incident.
# 4. Évaluez les étapes proposées selon les procédures établies.
# 5. Consolidez les informations pour élaborer un plan d'action clair.
# 6. Fournissez un rapport final avec analyses, solutions et étapes de résolution.
# """
# incident_team = Team(
# name="Incident Resolution Team",
# model=Groq(id="deepseek-r1-distill-llama-70b", api_key=GROQ_API_KEY),
# members=[analyzer, mex_researcher],
# instructions=team_instructions,
# markdown=True,
# debug_mode=True,
# add_datetime_to_instructions=True,
# mode="coordinate",
# )
# === Load Knowledge Base ===
@st.cache_resource
def load_knowledge_bases():
try:
print("Loading knowledge bases...")
mex_researcher.knowledge.load(recreate=False)
print("Knowledge bases loaded successfully")
return True
except Exception as e:
logging.error(f"Error loading knowledge bases: {e}")
return False
# === Authentication ===
def authenticate(username, password):
# Replace these with environment variables or a secure method to store credentials
valid_username = os.environ.get("USERNAME", "admin")
valid_password = os.environ.get("PASSWORD", "password")
return username == valid_username and password == valid_password
# Login form
if "authenticated" not in st.session_state:
st.session_state.authenticated = False
if not st.session_state.authenticated:
st.title("🔒 Authentification Requise")
username = st.text_input("Nom d'utilisateur")
password = st.text_input("Mot de passe", type="password")
if st.button("Se connecter"):
if authenticate(username, password):
st.session_state.authenticated = True
st.success("Authentification réussie!")
else:
st.error("Nom d'utilisateur ou mot de passe incorrect.")
st.stop()
# === Streamlit UI ===
st.title("🚨 Système de Résolution d'Incidents")
st.write("Assistant de résolution d'incidents avec analyse et recherche dans le manuel d'exploitation")
# === Sidebar Controls ===
with st.sidebar:
st.subheader("Types d'incidents:")
st.markdown("""
- Problèmes d'infrastructure
- Pannes réseau
- Incidents de sécurité
- Bugs applicatifs
- Problèmes de performance
""")
st.markdown("---")
# Settings
st.subheader("Paramètres")
stream = st.checkbox("Afficher le processus en temps réel", True)
# === Main UI ===
incident_description = st.text_area(
"Description de l'incident:",
placeholder="Décrivez l'incident en détail (ex: 'Serveur web principal inaccessible, applications client impactées')",
height=150
)
# Load knowledge bases
kb_loaded = load_knowledge_bases()
if not kb_loaded:
st.error("Erreur lors du chargement des bases de connaissances. Veuillez vérifier les logs.")
if incident_description:
if st.button("Soumettre l'analyse de l'incident"):
st.write(f"Analyse de l'incident en cours...")
# Process the incident
with st.spinner("🔍 Analyse de l'incident en cours..."):
result_container = st.empty()
full_result = ""
# Call the team and stream results
team_response_stream = mex_researcher.run(incident_description, stream=True)
for response_chunk in team_response_stream:
if hasattr(response_chunk, 'content') and response_chunk.content:
full_result += response_chunk.content
if stream:
result_container.markdown(full_result + "▌")
else:
st.write("Traitement en cours...")
# Display final result
result_container.markdown(full_result)
# Save report
filename = f"incident_{datetime.now():%Y%m%d%H%M%S}.md"
with open(tmp / filename, "w") as f:
f.write(full_result)
st.download_button(
label="Télécharger le rapport complet",
data=full_result,
file_name=filename,
mime="text/markdown"
)
# === Footer ===
st.markdown("---")
st.caption("""
**Fonctionnalités:**
- Analyse détaillée des incidents 🔍
- Recherche dans le manuel d'exploitation 📚
- Recommandations spécifiques au contexte ✅
- Rapport structuré des étapes de résolution 📋
- Export en format Markdown 📄
""")
# === Streamlit UI ===
# st.title("🚨 Système de Résolution d'Incidents")
# st.write("Assistant de résolution d'incidents avec analyse et recherche dans le manuel d'exploitation")
# === Sidebar Controls ===
# with st.sidebar:
# st.subheader("Types d'incidents:")
# st.markdown("""
# - Problèmes d'infrastructure
# - Pannes réseau
# - Incidents de sécurité
# - Bugs applicatifs
# - Problèmes de performance
# """)
# st.markdown("---")
# # Settings
# st.subheader("Paramètres")
# stream = st.checkbox("Afficher le processus en temps réel", True)
# # Stats
# if "incident_count" not in st.session_state:
# st.session_state.incident_count = 0
# st.caption(f"Incidents traités: {st.session_state.incident_count}")
# === Main UI ===
# incident_description = st.text_area(
# "Description de l'incident:",
# placeholder="Décrivez l'incident en détail (ex: 'Serveur web principal inaccessible, applications client impactées')",
# height=150
# )
# # Define the expander for process details
# expander = st.expander("Détails du processus", expanded=True)
# expander.write("Entrez une description de l'incident pour commencer l'analyse.")
# # Load knowledge bases
# kb_loaded = load_knowledge_bases()
# if not kb_loaded:
# st.error("Erreur lors du chargement des bases de connaissances. Veuillez vérifier les logs.")
# if incident_description:
# expander.write(f"Analyse de l'incident en cours...")
# Process the incident
# with st.spinner("🔍 Analyse de l'incident en cours..."):
# result_container = st.empty()
# full_result = ""
# # Call the team and stream results
# team_response_stream = incident_team.run(incident_description, stream=True)
# for response_chunk in team_response_stream:
# if hasattr(response_chunk, 'content') and response_chunk.content:
# full_result += response_chunk.content
# if stream:
# result_container.markdown(full_result + "▌")
# else:
# expander.write("Traitement en cours...")
# # Display final result
# result_container.markdown(full_result)
# # Update incident count
# st.session_state.incident_count += 1
# Save report
# filename = f"incident_{datetime.now():%Y%m%d%H%M%S}.md"
# with open(tmp / filename, "w") as f:
# f.write(full_result)
# st.download_button(
# label="Télécharger le rapport complet",
# data=full_result,
# file_name=filename,
# mime="text/markdown"
# )
# # === Footer ===
# st.markdown("---")
# st.caption("""
# **Fonctionnalités:**
# - Analyse détaillée des incidents 🔍
# - Recherche dans le manuel d'exploitation 📚
# - Recommandations spécifiques au contexte ✅
# - Rapport structuré des étapes de résolution 📋
# - Export en format Markdown 📄
# """)