Create web_agent.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227from agno.agent import Agentfrom agno.knowledge.pdf import PDFKnowledgeBase, PDFReaderfrom agno.models.groq import Groqfrom agno.team import Teamfrom agno.vectordb.mongodb import MongoDbfrom agno.embedder.huggingface import HuggingfaceCustomEmbedderfrom transformers import AutoModel, AutoTokenizerimport torchfrom agno.knowledge.json import JSONKnowledgeBaseimport numpy as npimport osfrom dotenv import load_dotenv
# Load environment variablesload_dotenv()
# # Get the API key# GROQ_API_KEY = os.getenv("GROQ_API_KEY")# if not GROQ_API_KEY:# raise ValueError("API key not found. Please set the 'GROQ_API_KEY' environment variable.")
# # Debugging: Print the first few characters of the API key# print(f"Loaded API Key: {GROQ_API_KEY[:5]}...")GROQ_API_KEY =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
class CustomDimensionEmbedder(HuggingfaceCustomEmbedder): def __init__(self, model_name="sentence-transformers/all-mpnet-base-v2"): """ Initialize with a model that provides 1536-dimensional embeddings """ self.model = AutoModel.from_pretrained(model_name) self.tokenizer = AutoTokenizer.from_pretrained(model_name) self.model.eval() def get_embedding(self, text): """ Generate embeddings with consistent 1536 dimensions """ # Tokenize the input text tokens = self.tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512) # Generate embeddings with torch.no_grad(): outputs = self.model(**tokens) embeddings = outputs.last_hidden_state.mean(dim=1).squeeze().numpy() # Ensure 1536 dimensions by padding or truncating if len(embeddings) < 1536: # Pad with zeros padded_embeddings = np.zeros(1536) padded_embeddings[:len(embeddings)] = embeddings return padded_embeddings.tolist() # Convert to list for MongoDB else: # Truncate if longer return embeddings[:1536].tolist() # Convert to list for MongoDB
# MongoDB connection stringdb_url = "mongodb+srv://admin:admin@cluster0.0r52e.mongodb.net/agent?retryWrites=true&w=majority&appName=Cluster0"embeddings = CustomDimensionEmbedder()
# Simplified instructions for each agentanalysis_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 principaux4. Composants ou systèmes affectés5. Impacts potentiels de l'incidentFournissez 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:1. Rechercher des solutions dans le manuel d'exploitation pour résoudre l'incident2. Identifier les étapes et recommandations spécifiques selon le type d'incident3. Extraire les informations pertinentes: - Étapes à suivre pour résoudre l'incident - Solutions proposées dans le manuel d'exploitation4. Fournir un rapport détaillé avec des instructions et solutions"""
# historique_researcher_instructions = """# Vous êtes un agent spécialisé dans la recherche d'incidents historiques similaires.# Votre mission est de:# 1. Rechercher dans la base de données des incidents passés similaires# 2. Identifier les modèles et les stratégies de résolution précédentes# 3. Extraire les informations clés des incidents similaires# 4. Fournir un rapport détaillé des incidents historiquement proches# """
# Create knowledge basesmex_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, # Reduced wait time wait_after_insert=60 # Reduced wait time ), reader=PDFReader(chunk=True))
# analysis_knowledge_base = JSONKnowledgeBase(# path="data/cleaned_dataset.jsonl",# max_links=5,# vector_db=MongoDb(# collection_name="past_incidents",# db_url=db_url,# embedder=embeddings,# wait_until_index_ready=30, # Reduced wait time# wait_after_insert=60 # Reduced wait time# )# )
# Create agents with simpler configuration and smaller modelmex_researcher = Agent( model=Groq(id="llama-3.3-70b-versatile",api_key=GROQ_API_KEY), name="mex_researcher", role="chercheur manuel exploitation", instructions=mex_researcher_instructions, knowledge=mex_knowledge_base, add_references=True, search_knowledge=True, markdown=True)
# historique_agent = Agent(# name="past_incident_researcher",# role="chercheur des incidents passés",# model=Groq(id="llama-3.1-8b-instant"), # instructions=historique_researcher_instructions,# knowledge=analysis_knowledge_base,# add_references=True,# search_knowledge=True,# markdown=True# )
analyzer = Agent( name="analyseur_description", role="analyseur de description d'incidents", model=Groq(id="llama-3.3-70b-versatile",api_key=GROQ_API_KEY), instructions=analysis_instructions, add_references=True, markdown=True)
# Load knowledge bases with error handlingtry: print("Loading knowledge bases...") mex_researcher.knowledge.load(recreate=False) historique_agent.knowledge.load(recreate=False) print("Knowledge bases loaded successfully")except Exception as e: print(f"Error loading knowledge bases: {e}")
# Simplified team instructionsteam_instructions = """Vous êtes un gestionnaire de résolution d'incidents dirigeant une équipe d'agents spécialisés. "Tout d'abord, demandez à l'agent d'analyse d'extraire les informations clés de l'incident, notamment le type d'incident, le niveau de criticité, les mots-clés principaux, les composants ou systèmes affectés, ainsi que les impacts potentiels.", "Ensuite, demandez à l'agent de recherche de consulter le manuel d'exploitation pour identifier les solutions pertinentes et les étapes à suivre pour résoudre l'incident.", "Examinez les recommandations du manuel d'exploitation et assurez-vous qu'elles sont adaptées au type d'incident identifié.", "Évaluez les étapes proposées et vérifiez leur conformité avec les procédures établies.", "Consolidez les informations de l'agent d'analyse et du manuel d'exploitation pour élaborer un plan d'action détaillé.", "Assurez-vous que le plan d'action est clair, cohérent et adapté à la résolution de l'incident.", "Fournissez un rapport complet comprenant les analyses, les solutions proposées et les étapes à suivre pour résoudre l'incident." "Rappelez-vous : vous êtes le dernier gardien avant que les etapes de resolution d'incident soit generé." """
incident_team = Team( name="Incident Resolution Team", model=Groq(id="llama-3.3-70b-versatile",api_key=GROQ_API_KEY), members=[analyzer,mex_researcher], instructions=team_instructions, show_members_responses=True, markdown=True, show_tool_calls=True, debug_mode=True, add_datetime_to_instructions=True, mode="coordinate",)
def handle_incident(incident_description): """Function to process an incident with error handling""" try: print("Processing incident...") # First try without streaming to avoid potential streaming-related errors response = incident_team.print_response(message=incident_description, stream=True, stream_intermediate_steps=True,) print("\n=== TEAM RESPONSE ===") print(response) return response except Exception as e: print(f"Error during team processing: {e}") print("\nTrying individual agents instead...") try: # Try individual agents if team fails analysis = analyzer.print_response(message=incident_description) print("\n=== ANALYSIS ===") print(analysis) manual = mex_researcher.print_response(message=incident_description) print("\n=== MANUAL PROCEDURES ===") print(manual) return "Individual agent processing completed." except Exception as e2: print(f"Error during individual agent processing: {e2}") return "All processing attempts failed."
if __name__ == "__main__": # Test incident test_incident = """ comment resoudre ce type d'erreur :Tache CALL_CHECK_DATA_CALC_FLAG_AFTER_DNG KO """ # Process the incident with error handling handle_incident(test_incident)web_agent.pyAdded+227