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

139 lines
5.2 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
from typing import Dict, Any, Optional
from llm_classes.mistral_large import MistralLarge
from agents.mistral_large.agent_ticket_analyser import AgentTicketAnalyser
def get_ticket_report_file(ticket_id: str, output_dir: str) -> Optional[str]:
"""
Récupère le fichier de rapport du ticket dans le répertoire codeticket_rapports.
Args:
ticket_id: ID du ticket (ex: T1234)
output_dir: Répertoire de base contenant les tickets
Returns:
Chemin vers le fichier de rapport JSON, ou None si non trouvé
"""
# Construire le chemin vers le répertoire des rapports
ticket_path = os.path.join(output_dir, f"ticket_{ticket_id}")
# Chercher le répertoire d'extraction le plus récent
extractions = [d for d in os.listdir(ticket_path) if os.path.isdir(os.path.join(ticket_path, d)) and d.startswith(ticket_id)]
if not extractions:
return None
# Trier par ordre décroissant pour avoir la plus récente en premier
extractions.sort(reverse=True)
latest_extraction = extractions[0]
# Construire le chemin vers le répertoire des rapports
rapport_dir = os.path.join(ticket_path, latest_extraction, f"{ticket_id}_rapports")
rapport_file = os.path.join(rapport_dir, f"{ticket_id}_rapport.json")
if os.path.exists(rapport_file):
return rapport_file
return None
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:
# Chercher le fichier de rapport du ticket
rapport_file = get_ticket_report_file(args.ticket_id, args.output_dir)
if not rapport_file:
print(f"ERREUR: Aucun fichier de rapport trouvé pour le ticket {args.ticket_id}")
return 1
print(f"Fichier de rapport trouvé: {rapport_file}")
try:
with open(rapport_file, "r", encoding="utf-8") as f:
ticket_data = json.load(f)
print(f"Fichier de rapport chargé: {rapport_file}")
except json.JSONDecodeError:
print(f"ERREUR: Le fichier {rapport_file} 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())