Public Access
106 lines
4.3 KiB
Python
106 lines
4.3 KiB
Python
import os
|
|
from datetime import datetime
|
|
from modules.logger import log_event
|
|
|
|
# Définition du chemin racine sécurisé sur ton RAID
|
|
RAG_BASE_DIR = "/DATA/AppData/MULTI-IA-AETHAS38/RAG"
|
|
|
|
# Les thématiques pour organiser l'apprentissage (Ajout de Général et Éducation)
|
|
THEMATIQUES_RAG = [
|
|
"Minecraft_KubeJS",
|
|
"Juridique_Loi_Francaise",
|
|
"Serveur_Debian",
|
|
"Bureautique_Excel",
|
|
"Regles_Aethas38",
|
|
"Education_Nationale",
|
|
"Connaissances_Generales"
|
|
]
|
|
|
|
def initialiser_arborescence_rag():
|
|
"""Crée les dossiers RAG physiques sur le disque s'ils n'existent pas."""
|
|
try:
|
|
if not os.path.exists(RAG_BASE_DIR):
|
|
os.makedirs(RAG_BASE_DIR)
|
|
log_event("INFO", "RAG", "Création du dossier racine RAG.")
|
|
|
|
for theme in THEMATIQUES_RAG:
|
|
chemin_theme = os.path.join(RAG_BASE_DIR, theme)
|
|
if not os.path.exists(chemin_theme):
|
|
os.makedirs(chemin_theme)
|
|
log_event("INFO", "RAG", f"Création du sous-dossier thématique : {theme}")
|
|
except Exception as e:
|
|
log_event("ERROR", "RAG", f"Erreur lors de l'initialisation de l'arborescence : {e}")
|
|
|
|
def extraire_contexte_rag(thematique):
|
|
"""
|
|
Lit tous les fichiers .txt ou .md d'une thématique donnée
|
|
et les concatène pour les injecter dans le prompt de l'IA.
|
|
"""
|
|
contexte_global = ""
|
|
chemin_theme = os.path.join(RAG_BASE_DIR, thematique)
|
|
|
|
# Si le thème est "aucun" ou introuvable, on tape dans les connaissances générales
|
|
if thematique == "aucun" or not os.path.exists(chemin_theme):
|
|
chemin_theme = os.path.join(RAG_BASE_DIR, "Connaissances_Generales")
|
|
|
|
try:
|
|
if os.path.exists(chemin_theme):
|
|
for fichier in os.listdir(chemin_theme):
|
|
if fichier.endswith(".txt") or fichier.endswith(".md"):
|
|
chemin_fichier = os.path.join(chemin_theme, fichier)
|
|
with open(chemin_fichier, 'r', encoding='utf-8') as f:
|
|
contexte_global += f"\n--- Extrait de {fichier} ---\n"
|
|
contexte_global += f.read() + "\n"
|
|
except Exception as e:
|
|
log_event("ERROR", "RAG", f"Erreur de lecture du contexte {thematique} : {e}")
|
|
|
|
return contexte_global
|
|
|
|
def rechercher_contexte_rag(prompt, categorie="general"):
|
|
"""
|
|
Récupère le contenu des fichiers de la thématique pour alimenter l'IA.
|
|
"""
|
|
try:
|
|
return extraire_contexte_rag(categorie)
|
|
except Exception as e:
|
|
log_event("ERROR", "RAG_MANAGER", f"Erreur lors de la recherche RAG : {e}")
|
|
return ""
|
|
|
|
def auto_apprendre_rag(prompt, reponse, thematique_simplifiee):
|
|
"""
|
|
Sauvegarde systématiquement TOUTES les réponses pour enrichir la base de connaissances.
|
|
"""
|
|
# Mapping élargi
|
|
mapping = {
|
|
"minecraft": "Minecraft_KubeJS",
|
|
"droit": "Juridique_Loi_Francaise",
|
|
"serveur": "Serveur_Debian",
|
|
"excel": "Bureautique_Excel",
|
|
"regles": "Regles_Aethas38",
|
|
"education_nationale": "Education_Nationale"
|
|
}
|
|
|
|
# Si le thème n'est pas dans le mapping (ex: "aucun", "physique", "cuisine"),
|
|
# on le force dans le dossier "Connaissances_Generales" au lieu de l'ignorer.
|
|
theme_reel = mapping.get(thematique_simplifiee.lower(), "Connaissances_Generales")
|
|
|
|
try:
|
|
chemin_theme = os.path.join(RAG_BASE_DIR, theme_reel)
|
|
os.makedirs(chemin_theme, exist_ok=True)
|
|
|
|
# On raccourcit le prompt pour créer un nom de fichier propre
|
|
sujet_court = "".join(c for c in prompt[:15] if c.isalnum() or c == " ").strip().replace(" ", "_")
|
|
nom_fichier = f"rag_{sujet_court}_{datetime.now().strftime('%H%M%S')}.md"
|
|
chemin_fichier = os.path.join(chemin_theme, nom_fichier)
|
|
|
|
contenu = f"## Question utilisateur\n{prompt}\n\n## Réponse de l'IA (Contexte validé)\n{reponse}\n"
|
|
|
|
with open(chemin_fichier, 'w', encoding='utf-8') as f:
|
|
f.write(contenu)
|
|
|
|
log_event("INFO", "RAG_MANAGER", f"Connaissance sauvegardée dans {theme_reel} ({nom_fichier}).")
|
|
except Exception as e:
|
|
log_event("ERROR", "RAG_MANAGER", f"Erreur lors de l'auto-apprentissage : {e}")
|
|
|
|
# On s'assure que les dossiers existent dès l'import du module
|
|
initialiser_arborescence_rag() |