llm_ticket3/test_agent_ticket_analyser_mistral_large.py
2025-04-17 14:04:38 +02:00

149 lines
5.6 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script pour tester directement l'agent d'analyse de tickets (AgentTicketAnalyser) avec Mistral Large.
Permet d'évaluer rapidement l'analyse d'un ticket.
"""
import os
import sys
import argparse
import json
import glob
from typing import Dict, Any, List
from llm_classes.mistral_large import MistralLarge
from agents.mistral_large.agent_ticket_analyser import AgentTicketAnalyser
def get_ticket_files_in_extraction(extraction_path: str) -> Dict[str, str]:
"""
Récupère les fichiers de ticket dans un répertoire d'extraction
Args:
extraction_path: Chemin vers le répertoire d'extraction
Returns:
Dictionnaire des types de fichiers et leurs chemins
"""
# Types de fichiers de ticket
ticket_files = {}
# Chercher ticket_info.json
ticket_info_path = os.path.join(extraction_path, "ticket_info.json")
if os.path.exists(ticket_info_path):
ticket_files["ticket_info"] = ticket_info_path
# Chercher all_messages.json
all_messages_path = os.path.join(extraction_path, "all_messages.json")
if os.path.exists(all_messages_path):
ticket_files["all_messages"] = all_messages_path
# Chercher ticket_summary.json
ticket_summary_path = os.path.join(extraction_path, "ticket_summary.json")
if os.path.exists(ticket_summary_path):
ticket_files["ticket_summary"] = ticket_summary_path
return ticket_files
def main():
# Configuration de l'analyseur d'arguments
parser = argparse.ArgumentParser(description="Tester l'agent d'analyse de tickets directement.")
parser.add_argument("ticket_id", help="ID du ticket à analyser (ex: T1234)")
parser.add_argument("--ticket_file", help="Chemin spécifique vers un fichier JSON du ticket à analyser")
parser.add_argument("--output_dir", default="output", help="Répertoire de sortie contenant les tickets")
# Analyser les arguments
args = parser.parse_args()
# Construire le chemin vers le ticket
ticket_path = os.path.join(args.output_dir, f"ticket_{args.ticket_id}")
# Vérifier que le répertoire du ticket existe
if not os.path.exists(ticket_path):
print(f"ERREUR: Le ticket {args.ticket_id} n'existe pas dans {args.output_dir}")
return 1
# Rechercher la dernière extraction (la plus récente)
extractions = [d for d in os.listdir(ticket_path) if os.path.isdir(os.path.join(ticket_path, d)) and d.startswith(args.ticket_id)]
if not extractions:
print(f"ERREUR: Aucune extraction trouvée pour le ticket {args.ticket_id}")
return 1
# Trier par ordre décroissant pour avoir la plus récente en premier
extractions.sort(reverse=True)
latest_extraction = extractions[0]
extraction_path = os.path.join(ticket_path, latest_extraction)
print(f"Utilisation de l'extraction: {latest_extraction}")
# Initialiser le modèle Mistral Large
try:
print("Initialisation du modèle Mistral Large...")
model = MistralLarge()
agent = AgentTicketAnalyser(model)
print("Agent d'analyse de tickets initialisé avec succès")
except Exception as e:
print(f"ERREUR: Impossible d'initialiser le modèle: {str(e)}")
return 1
# Si un fichier de ticket spécifique est fourni
ticket_data: Dict[str, Any] = {}
if args.ticket_file:
if not os.path.exists(args.ticket_file):
print(f"ERREUR: Le fichier de ticket spécifié n'existe pas: {args.ticket_file}")
return 1
try:
with open(args.ticket_file, "r", encoding="utf-8") as f:
ticket_data = json.load(f)
print(f"Fichier de ticket chargé: {args.ticket_file}")
except json.JSONDecodeError:
print(f"ERREUR: Le fichier {args.ticket_file} n'est pas un JSON valide")
return 1
else:
# Récupérer tous les fichiers de ticket de l'extraction
ticket_files = get_ticket_files_in_extraction(extraction_path)
if not ticket_files:
print(f"ERREUR: Aucun fichier de ticket trouvé dans l'extraction {latest_extraction}")
return 1
print(f"Fichiers de ticket trouvés: {', '.join(ticket_files.keys())}")
# Privilégier ticket_info.json, puis all_messages.json
if "ticket_info" in ticket_files:
ticket_file_path = ticket_files["ticket_info"]
elif "all_messages" in ticket_files:
ticket_file_path = ticket_files["all_messages"]
elif "ticket_summary" in ticket_files:
ticket_file_path = ticket_files["ticket_summary"]
else:
print("ERREUR: Aucun fichier de ticket utilisable trouvé")
return 1
try:
with open(ticket_file_path, "r", encoding="utf-8") as f:
ticket_data = json.load(f)
print(f"Fichier de ticket chargé: {ticket_file_path}")
except json.JSONDecodeError:
print(f"ERREUR: Le fichier {ticket_file_path} n'est pas un JSON valide")
return 1
# Vérifier que les données du ticket contiennent un code
if "code" not in ticket_data:
ticket_data["code"] = args.ticket_id
print(f"Code de ticket ajouté: {args.ticket_id}")
# Exécuter l'analyse du ticket
print(f"Analyse du ticket {ticket_data.get('code', args.ticket_id)} en cours...")
result = agent.executer(ticket_data)
# Afficher le résultat
print("\nRésultat de l'analyse:")
print(result)
return 0
if __name__ == "__main__":
sys.exit(main())