Public Access
fix: Résolution import RAG et correction HTTPResponse pour les pings
Build and Push Docker Image / build-and-push (push) Successful in 38s
Build and Push Docker Image / build-and-push (push) Successful in 38s
This commit is contained in:
1 parent
ffe820b00f
commit
2d7d93bc27
6 files changed
+3164
-59
No files matched your search
+11
-5
@@ -54,30 +54,35 @@ async def handle_chat_request(request, session):
|
||||
log_mode = "PAYANT 👑" if mode_payant else "GRATUIT 🆓"
|
||||
log_event("INFO", "SYSTEM", f"Requête reçue [{log_mode}]. Fichiers joints : {liste_fichiers_str}")
|
||||
|
||||
# NOUVEAU PROMPT : On demande à Qwen de deviner le thème RAG
|
||||
sec_prompt = f"""Tu es l'Orchestrateur système. Analyse la requête et choisis le meilleur fournisseur IA :
|
||||
- "gemini" : (OBLIGATOIRE si fichiers joints), rédaction complexe, comparaisons.
|
||||
- "openrouter_chat" : requêtes générales, texte rapide, traduction.
|
||||
- "openrouter_code" : programmation, Minecraft/KubeJS, scripts, mathématiques.
|
||||
- "openrouter_droit" : droit français, CGV, CGU, RGPD.
|
||||
- "local" : salutations basiques, questions simples.
|
||||
Renvoie STRICTEMENT un JSON : {{"intention": "Résumé...", "fournisseur": "gemini|openrouter_chat|openrouter_code|openrouter_droit|local"}}
|
||||
Tu dois aussi déterminer si la requête nécessite de lire la documentation interne (RAG). Thèmes : "minecraft", "droit", "serveur", "regles" ou "aucun".
|
||||
Renvoie STRICTEMENT un JSON : {{"intention": "Résumé...", "fournisseur": "gemini|openrouter_chat|openrouter_code|openrouter_droit|local", "theme_rag": "minecraft|droit|serveur|regles|aucun"}}
|
||||
Requête : {prompt}"""
|
||||
|
||||
try:
|
||||
texte_routeur, _, _, _ = interroger_local_ollama(sec_prompt, "qwen2.5-coder:3b")
|
||||
decision = nettoyer_decision_router(texte_routeur)
|
||||
except Exception:
|
||||
decision = {"intention": "Analyse de secours", "fournisseur": "openrouter_code" if "minecraft" in prompt.lower() else "openrouter_chat"}
|
||||
decision = {"intention": "Analyse de secours", "fournisseur": "openrouter_code" if "minecraft" in prompt.lower() else "openrouter_chat", "theme_rag": "aucun"}
|
||||
|
||||
intention = decision.get("intention", "Analyse")
|
||||
fournisseur = decision.get("fournisseur", "openrouter_chat").lower()
|
||||
thematique_rag = decision.get("theme_rag", "aucun").lower()
|
||||
|
||||
if file_names:
|
||||
fournisseur = "gemini"
|
||||
intention += " (Forcé Gemini via Sécurité Fichiers)"
|
||||
|
||||
thematique_rag = "minecraft" if "mine" in prompt.lower() or "kubejs" in prompt.lower() else ("droit" if "droit" in fournisseur else None)
|
||||
contexte_rag = rechercher_contexte_rag(prompt, thematique=thematique_rag)
|
||||
# Récupération dynamique du contexte RAG
|
||||
contexte_rag = ""
|
||||
if thematique_rag != "aucun":
|
||||
contexte_rag = rechercher_contexte_rag(prompt, thematique=thematique_rag)
|
||||
|
||||
urls = re.findall(r"https?://[^\s]+", prompt)
|
||||
mots_cles = ["cherche", "recherche", "sur internet", "sur le web", "sur le net", "trouve", "site"]
|
||||
@@ -86,9 +91,10 @@ async def handle_chat_request(request, session):
|
||||
|
||||
web_text = extraire_contenu_urls(list(set(urls))) if urls else ""
|
||||
|
||||
# Concaténation de tous les contextes
|
||||
full_prompt = prompt + ("\n" + "\n".join(file_summary) if file_summary else "")
|
||||
if contexte_rag:
|
||||
full_prompt += f"\n\n[Contexte Documentaire RAG :\n{contexte_rag}]"
|
||||
full_prompt += f"\n\n[Contexte Documentaire RAG (Base de connaissances interne) :\n{contexte_rag}]"
|
||||
if web_text:
|
||||
full_prompt += f"\n\n[Contexte web :\n{web_text}]"
|
||||
|
||||
|
||||
+55
-50
@@ -1,63 +1,68 @@
|
||||
import os
|
||||
import re
|
||||
from modules.logger import log_event
|
||||
|
||||
RAG_BASE_DIR = "rag_data"
|
||||
THEMATIQUES = ["minecraft", "droit", "serveur", "general"]
|
||||
# Définition du chemin racine sécurisé sur ton RAID
|
||||
RAG_BASE_DIR = "/DATA/AppData/MULTI-IA-AETHAS38/RAG"
|
||||
|
||||
def initialiser_structure_rag():
|
||||
"""Crée l'arborescence des dossiers RAG s'ils n'existent pas."""
|
||||
os.makedirs(RAG_BASE_DIR, exist_ok=True)
|
||||
for theme in THEMATIQUES:
|
||||
os.makedirs(os.path.join(RAG_BASE_DIR, theme), exist_ok=True)
|
||||
# Les thématiques générales pour organiser l'apprentissage
|
||||
THEMATIQUES_RAG = [
|
||||
"Minecraft_KubeJS",
|
||||
"Juridique_Loi_Francaise",
|
||||
"Serveur_Debian",
|
||||
"Bureautique_Excel",
|
||||
"Regles_Aethas38"
|
||||
]
|
||||
|
||||
def indexer_document(thematique: str, nom_fichier: str, contenu: str):
|
||||
"""Enregistre un document dans la thématique correspondante."""
|
||||
initialiser_structure_rag()
|
||||
if thematique not in THEMATIQUES:
|
||||
thematique = "general"
|
||||
chemin = os.path.join(RAG_BASE_DIR, thematique, nom_fichier)
|
||||
def initialiser_arborescence_rag():
|
||||
"""Crée les dossiers RAG physiques sur le disque s'ils n'existent pas."""
|
||||
try:
|
||||
with open(chemin, "w", encoding="utf-8") as f:
|
||||
f.write(contenu)
|
||||
log_event("INFO", "RAG", f"Document {nom_fichier} indexé dans {thematique}.")
|
||||
return True
|
||||
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"Échec d'indexation pour {nom_fichier} : {e}")
|
||||
return False
|
||||
log_event("ERROR", "RAG", f"Erreur lors de l'initialisation de l'arborescence : {e}")
|
||||
|
||||
def rechercher_contexte_rag(requete: str, thematique: str = None, top_k: int = 3) -> str:
|
||||
def extraire_contexte_rag(thematique):
|
||||
"""
|
||||
Recherche les passages les plus pertinents dans la base documentaire.
|
||||
Filtre par thématique si spécifiée, sinon cherche globalement.
|
||||
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.
|
||||
"""
|
||||
initialiser_structure_rag()
|
||||
dossiers_cibles = [os.path.join(RAG_BASE_DIR, thematique)] if thematique in THEMATIQUES else [os.path.join(RAG_BASE_DIR, t) for t in THEMATIQUES]
|
||||
contexte_global = ""
|
||||
chemin_theme = os.path.join(RAG_BASE_DIR, thematique)
|
||||
|
||||
mots_cles = set(re.findall(r'\w+', requete.lower()))
|
||||
resultats = []
|
||||
if not os.path.exists(chemin_theme):
|
||||
return contexte_global
|
||||
|
||||
try:
|
||||
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
|
||||
|
||||
for dossier in dossiers_cibles:
|
||||
if not os.path.exists(dossier):
|
||||
continue
|
||||
for fichier in os.listdir(dossier):
|
||||
chemin = os.path.join(dossier, fichier)
|
||||
if os.path.isfile(chemin):
|
||||
try:
|
||||
with open(chemin, "r", encoding="utf-8", errors="ignore") as f:
|
||||
contenu = f.read()
|
||||
paragraphes = contenu.split("\n\n")
|
||||
for p in paragraphes:
|
||||
texte_p = p.strip()
|
||||
if not texte_p:
|
||||
continue
|
||||
mots_p = set(re.findall(r'\w+', texte_p.lower()))
|
||||
score = len(mots_cles.intersection(mots_p))
|
||||
if score > 0:
|
||||
resultats.append((score, fichier, texte_p))
|
||||
except Exception as e:
|
||||
log_event("WARNING", "RAG", f"Erreur lecture {chemin} : {e}")
|
||||
def rechercher_contexte_rag(prompt, categorie="general"):
|
||||
"""
|
||||
Fonction appelée par le chat_handler pour récupérer le contexte.
|
||||
Pour l'instant, c'est un bouchon qui empêche le crash du serveur.
|
||||
"""
|
||||
try:
|
||||
# À terme, nous ferons le lien intelligent ici avec extraire_contexte_rag()
|
||||
# et une analyse sémantique. Pour l'instant on renvoie vide pour tester.
|
||||
return ""
|
||||
except Exception as e:
|
||||
log_event("ERROR", "RAG_MANAGER", f"Erreur lors de la recherche RAG : {e}")
|
||||
return ""
|
||||
|
||||
resultats.sort(key=lambda x: x[0], reverse=True)
|
||||
extraits = [f"[{res[1]}] {res[2]}" for res in resultats[:top_k]]
|
||||
return "\n---\n".join(extraits)
|
||||
# On s'assure que les dossiers existent dès l'import du module
|
||||
initialiser_arborescence_rag()
|
||||
Reference in new issue
Block a user