Update chat.py
Browse files
chat.py
CHANGED
|
@@ -7,7 +7,7 @@ from sentence_transformers import SentenceTransformer
|
|
| 7 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 8 |
import re
|
| 9 |
import json
|
| 10 |
-
|
| 11 |
from auth import get_current_user
|
| 12 |
from database import get_db
|
| 13 |
from config import HF_TOKEN, MAX_TOKENS, EMBEDDING_MODEL
|
|
@@ -17,13 +17,14 @@ db=get_db()
|
|
| 17 |
conversation_history = {}
|
| 18 |
hf_client = InferenceClient(token=HF_TOKEN)
|
| 19 |
|
| 20 |
-
|
| 21 |
def save_bot_response(conversation_id, current_user, text, current_tokens=0, message_tokens=0):
|
|
|
|
| 22 |
if not conversation_id or not current_user:
|
| 23 |
-
print(" Impossible de sauvegarder la réponse")
|
| 24 |
return None
|
| 25 |
|
| 26 |
try:
|
|
|
|
| 27 |
message_id = db.messages.insert_one({
|
| 28 |
"conversation_id": conversation_id,
|
| 29 |
"user_id": str(current_user["_id"]),
|
|
@@ -32,6 +33,7 @@ def save_bot_response(conversation_id, current_user, text, current_tokens=0, mes
|
|
| 32 |
"timestamp": datetime.utcnow()
|
| 33 |
}).inserted_id
|
| 34 |
|
|
|
|
| 35 |
response_tokens = int(len(text.split()) * 1.3) if text else 0
|
| 36 |
total_tokens = current_tokens + message_tokens + response_tokens
|
| 37 |
|
|
@@ -44,13 +46,12 @@ def save_bot_response(conversation_id, current_user, text, current_tokens=0, mes
|
|
| 44 |
}}
|
| 45 |
)
|
| 46 |
|
| 47 |
-
print(f"Réponse du bot sauvegardée : {message_id}")
|
| 48 |
return message_id
|
| 49 |
except Exception as e:
|
| 50 |
-
print(f" Erreur: {str(e)}")
|
| 51 |
return None
|
| 52 |
|
| 53 |
-
|
| 54 |
try:
|
| 55 |
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 56 |
embedding_model = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL)
|
|
@@ -59,7 +60,7 @@ except Exception as e:
|
|
| 59 |
print(f"Erreur chargement embedding: {str(e)}")
|
| 60 |
embedding_model = None
|
| 61 |
|
| 62 |
-
#
|
| 63 |
def retrieve_relevant_context(query, embedding_model, mongo_collection, k=5):
|
| 64 |
query_embedding = embedding_model.embed_query(query)
|
| 65 |
|
|
@@ -111,6 +112,7 @@ async def chat(request: Request):
|
|
| 111 |
except HTTPException:
|
| 112 |
pass
|
| 113 |
|
|
|
|
| 114 |
if not skip_save and conversation_id and current_user:
|
| 115 |
db.messages.insert_one({
|
| 116 |
"conversation_id": conversation_id,
|
|
@@ -120,6 +122,7 @@ async def chat(request: Request):
|
|
| 120 |
"timestamp": datetime.utcnow()
|
| 121 |
})
|
| 122 |
|
|
|
|
| 123 |
current_tokens = 0
|
| 124 |
message_tokens = 0
|
| 125 |
if current_user and conversation_id:
|
|
@@ -133,6 +136,7 @@ async def chat(request: Request):
|
|
| 133 |
if current_tokens + message_tokens > MAX_TOKENS:
|
| 134 |
error_message = "⚠️ **Limite de taille de conversation atteinte**\n\nCette conversation est devenue trop longue. Pour continuer à discuter, veuillez créer une nouvelle conversation."
|
| 135 |
|
|
|
|
| 136 |
if conversation_id and current_user:
|
| 137 |
save_bot_response(conversation_id, current_user, error_message, current_tokens, message_tokens)
|
| 138 |
|
|
@@ -143,6 +147,7 @@ async def chat(request: Request):
|
|
| 143 |
"tokens_limit": MAX_TOKENS
|
| 144 |
}, status_code=403)
|
| 145 |
|
|
|
|
| 146 |
is_history_question = any(
|
| 147 |
phrase in user_message.lower()
|
| 148 |
for phrase in [
|
|
@@ -156,6 +161,7 @@ async def chat(request: Request):
|
|
| 156 |
or re.search(r"question pr[eé]c[eé]dente", user_message.lower()) \
|
| 157 |
or re.search(r"(toutes|liste|quelles|quoi).*questions", user_message.lower())
|
| 158 |
|
|
|
|
| 159 |
if conversation_id not in conversation_history:
|
| 160 |
conversation_history[conversation_id] = []
|
| 161 |
if current_user and conversation_id:
|
|
@@ -169,13 +175,16 @@ async def chat(request: Request):
|
|
| 169 |
else:
|
| 170 |
conversation_history[conversation_id].append(f"Réponse : {msg['text']}")
|
| 171 |
|
|
|
|
| 172 |
if is_history_question:
|
|
|
|
| 173 |
actual_questions = []
|
| 174 |
|
| 175 |
if conversation_id in conversation_history:
|
| 176 |
for msg in conversation_history[conversation_id]:
|
| 177 |
if msg.startswith("Question : "):
|
| 178 |
q_text = msg.replace("Question : ", "")
|
|
|
|
| 179 |
is_meta = any(phrase in q_text.lower() for phrase in [
|
| 180 |
"ma première question", "ma précédente question", "ma dernière question",
|
| 181 |
"ce que j'ai demandé", "j'ai dit quoi", "quelles questions",
|
|
@@ -188,20 +197,26 @@ async def chat(request: Request):
|
|
| 188 |
if not is_meta:
|
| 189 |
actual_questions.append(q_text)
|
| 190 |
|
|
|
|
| 191 |
history_response = ""
|
| 192 |
|
| 193 |
if not actual_questions:
|
| 194 |
history_response = "Vous n'avez pas encore posé de question dans cette conversation. C'est notre premier échange."
|
| 195 |
else:
|
|
|
|
| 196 |
|
|
|
|
| 197 |
if any(phrase in user_message.lower() for phrase in ["question précédente", "dernière question"]) and len(actual_questions) > 1:
|
|
|
|
| 198 |
prev_question = actual_questions[-1] if actual_questions else "Aucune question précédente trouvée."
|
| 199 |
history_response = f"**Votre question précédente était :**\n\n\"{prev_question}\""
|
| 200 |
|
|
|
|
| 201 |
elif any(phrase in user_message.lower() for phrase in ["première question", "1ère question", "1ere question"]):
|
| 202 |
first_question = actual_questions[0] if actual_questions else "Aucune première question trouvée."
|
| 203 |
history_response = f"**Votre première question était :**\n\n\"{first_question}\""
|
| 204 |
|
|
|
|
| 205 |
elif re.search(r"(\d+)[èeme]{1,3}", user_message.lower()):
|
| 206 |
match = re.search(r"(\d+)[èeme]{1,3}", user_message.lower())
|
| 207 |
if match:
|
|
@@ -212,32 +227,39 @@ async def chat(request: Request):
|
|
| 212 |
else:
|
| 213 |
history_response = f"Je ne trouve pas de question n°{question_num} dans notre conversation. Vous n'avez posé que {len(actual_questions)} question(s)."
|
| 214 |
|
|
|
|
| 215 |
else:
|
| 216 |
history_response = "**Voici les questions que vous avez posées dans cette conversation :**\n\n"
|
| 217 |
for i, question in enumerate(actual_questions, 1):
|
| 218 |
history_response += f"{i}. {question}\n"
|
| 219 |
|
|
|
|
| 220 |
if len(actual_questions) > 3:
|
| 221 |
history_response += f"\nVous avez posé {len(actual_questions)} questions dans cette conversation."
|
| 222 |
|
|
|
|
| 223 |
if conversation_id:
|
| 224 |
conversation_history[conversation_id].append(f"Réponse : {history_response}")
|
| 225 |
|
|
|
|
| 226 |
if conversation_id and current_user:
|
| 227 |
save_bot_response(conversation_id, current_user, history_response, current_tokens, message_tokens)
|
| 228 |
-
print(f"Réponse à la question d'historique sauvegardée pour conversation {conversation_id}")
|
| 229 |
|
| 230 |
return JSONResponse({"response": history_response})
|
| 231 |
|
|
|
|
| 232 |
if conversation_id:
|
| 233 |
conversation_history[conversation_id].append(f"Question : {user_message}")
|
| 234 |
|
|
|
|
| 235 |
context = None
|
| 236 |
if not is_history_question and embedding_model:
|
| 237 |
context = retrieve_relevant_context(user_message, embedding_model, db.connaissances, k=5)
|
| 238 |
if context and conversation_id:
|
| 239 |
conversation_history[conversation_id].append(f"Contexte : {context}")
|
| 240 |
|
|
|
|
| 241 |
system_prompt = (
|
| 242 |
"Tu es un chatbot spécialisé dans la santé mentale, et plus particulièrement la schizophrénie. "
|
| 243 |
"Tu réponds de façon fiable, claire et empathique, en t'appuyant uniquement sur des sources médicales et en français. "
|
|
@@ -252,6 +274,7 @@ async def chat(request: Request):
|
|
| 252 |
|
| 253 |
)
|
| 254 |
|
|
|
|
| 255 |
enriched_context = ""
|
| 256 |
|
| 257 |
if conversation_id in conversation_history:
|
|
@@ -298,11 +321,13 @@ async def chat(request: Request):
|
|
| 298 |
"Tu dois donner une réponse complète et bien structurée."
|
| 299 |
)
|
| 300 |
|
|
|
|
| 301 |
messages = [{"role": "system", "content": system_prompt}]
|
| 302 |
|
| 303 |
if conversation_id and len(conversation_history.get(conversation_id, [])) > 0:
|
| 304 |
history = conversation_history[conversation_id]
|
| 305 |
|
|
|
|
| 306 |
user_messages = []
|
| 307 |
bot_messages = []
|
| 308 |
|
|
@@ -315,94 +340,110 @@ async def chat(request: Request):
|
|
| 315 |
bot_text = history[i+1].replace("Réponse : ", "")
|
| 316 |
bot_messages.append(bot_text)
|
| 317 |
|
|
|
|
| 318 |
valid_pairs = min(len(user_messages), len(bot_messages))
|
| 319 |
|
| 320 |
for i in range(valid_pairs):
|
| 321 |
messages.append({"role": "user", "content": user_messages[i]})
|
| 322 |
messages.append({"role": "assistant", "content": bot_messages[i]})
|
| 323 |
|
|
|
|
| 324 |
messages.append({"role": "user", "content": user_message})
|
| 325 |
|
|
|
|
| 326 |
async def generate_stream():
|
| 327 |
try:
|
| 328 |
collected_response = ""
|
| 329 |
|
|
|
|
| 330 |
yield "data: {\"type\": \"start\"}\n\n"
|
| 331 |
|
|
|
|
| 332 |
completion_stream = hf_client.chat.completions.create(
|
| 333 |
model="mistralai/Mistral-7B-Instruct-v0.3",
|
| 334 |
messages=messages,
|
| 335 |
-
max_tokens=
|
| 336 |
temperature=0.7,
|
| 337 |
stream=True
|
| 338 |
)
|
| 339 |
chunk_buffer = ""
|
| 340 |
chunk_count = 0
|
| 341 |
-
MAX_CHUNKS_BEFORE_SEND =
|
|
|
|
| 342 |
for chunk in completion_stream:
|
| 343 |
if chunk.choices and chunk.choices[0].delta.content:
|
| 344 |
content = chunk.choices[0].delta.content
|
| 345 |
-
print(f"Token received: {content}")
|
| 346 |
collected_response += content
|
| 347 |
chunk_buffer += content
|
| 348 |
chunk_count += 1
|
| 349 |
|
| 350 |
-
# Envoyer
|
| 351 |
if chunk_count >= MAX_CHUNKS_BEFORE_SEND or '\n' in content:
|
| 352 |
-
print(f"Sending chunk: {chunk_buffer}") # Debug
|
| 353 |
yield f"data: {json.dumps({'content': chunk_buffer})}\n\n"
|
| 354 |
chunk_buffer = ""
|
| 355 |
chunk_count = 0
|
| 356 |
-
|
|
|
|
| 357 |
if chunk_buffer:
|
| 358 |
yield f"data: {json.dumps({'content': chunk_buffer})}\n\n"
|
| 359 |
-
|
|
|
|
| 360 |
if collected_response.endswith((".", "!", "?")) == False and len(collected_response) > 500:
|
| 361 |
suffix = "\n\n(Note: Ma réponse a été limitée par des contraintes de taille. N'hésitez pas à me demander de poursuivre si vous souhaitez plus d'informations.)"
|
| 362 |
collected_response += suffix
|
| 363 |
yield f"data: {json.dumps({'content': suffix})}\n\n"
|
| 364 |
|
|
|
|
| 365 |
if conversation_id:
|
| 366 |
conversation_history[conversation_id].append(f"Réponse : {collected_response}")
|
| 367 |
|
| 368 |
if len(conversation_history[conversation_id]) > 50:
|
| 369 |
conversation_history[conversation_id] = conversation_history[conversation_id][-50:]
|
| 370 |
|
|
|
|
| 371 |
if conversation_id and current_user:
|
| 372 |
save_bot_response(conversation_id, current_user, collected_response, current_tokens, message_tokens)
|
| 373 |
|
|
|
|
| 374 |
yield "data: {\"type\": \"end\"}\n\n"
|
| 375 |
|
| 376 |
except Exception as e:
|
|
|
|
| 377 |
error_message = str(e)
|
| 378 |
print(f"❌ Streaming error: {error_message}")
|
| 379 |
|
| 380 |
try:
|
|
|
|
| 381 |
fallback = hf_client.text_generation(
|
| 382 |
model="mistralai/Mistral-7B-Instruct-v0.3",
|
| 383 |
prompt=f"<s>[INST] {system_prompt}\n\nQuestion: {user_message} [/INST]",
|
| 384 |
-
|
| 385 |
temperature=0.7
|
| 386 |
)
|
| 387 |
yield f"data: {json.dumps({'content': fallback})}\n\n"
|
| 388 |
|
|
|
|
| 389 |
if conversation_id:
|
| 390 |
conversation_history[conversation_id].append(f"Réponse : {fallback}")
|
| 391 |
|
|
|
|
| 392 |
if conversation_id and current_user:
|
| 393 |
save_bot_response(conversation_id, current_user, fallback, current_tokens, message_tokens)
|
| 394 |
|
| 395 |
except Exception as fallback_error:
|
| 396 |
-
print(f" Erreur: {str(fallback_error)}")
|
| 397 |
-
error_response = "Je suis désolé, je rencontre actuellement des difficultés techniques"
|
| 398 |
yield f"data: {json.dumps({'content': error_response})}\n\n"
|
| 399 |
|
|
|
|
| 400 |
if conversation_id and current_user:
|
| 401 |
save_bot_response(conversation_id, current_user, error_response, current_tokens, message_tokens)
|
| 402 |
|
|
|
|
| 403 |
yield "data: {\"type\": \"end\"}\n\n"
|
| 404 |
|
|
|
|
| 405 |
return StreamingResponse(
|
| 406 |
generate_stream(),
|
| 407 |
media_type="text/event-stream"
|
| 408 |
-
)
|
|
|
|
| 7 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 8 |
import re
|
| 9 |
import json
|
| 10 |
+
|
| 11 |
from auth import get_current_user
|
| 12 |
from database import get_db
|
| 13 |
from config import HF_TOKEN, MAX_TOKENS, EMBEDDING_MODEL
|
|
|
|
| 17 |
conversation_history = {}
|
| 18 |
hf_client = InferenceClient(token=HF_TOKEN)
|
| 19 |
|
|
|
|
| 20 |
def save_bot_response(conversation_id, current_user, text, current_tokens=0, message_tokens=0):
|
| 21 |
+
"""Fonction utilitaire pour sauvegarder toutes les réponses du bot"""
|
| 22 |
if not conversation_id or not current_user:
|
| 23 |
+
print("⚠️ Impossible de sauvegarder la réponse - conversation_id ou current_user manquant")
|
| 24 |
return None
|
| 25 |
|
| 26 |
try:
|
| 27 |
+
# Sauvegarder le message
|
| 28 |
message_id = db.messages.insert_one({
|
| 29 |
"conversation_id": conversation_id,
|
| 30 |
"user_id": str(current_user["_id"]),
|
|
|
|
| 33 |
"timestamp": datetime.utcnow()
|
| 34 |
}).inserted_id
|
| 35 |
|
| 36 |
+
# Mettre à jour les métadonnées de la conversation
|
| 37 |
response_tokens = int(len(text.split()) * 1.3) if text else 0
|
| 38 |
total_tokens = current_tokens + message_tokens + response_tokens
|
| 39 |
|
|
|
|
| 46 |
}}
|
| 47 |
)
|
| 48 |
|
| 49 |
+
print(f"✅ Réponse du bot sauvegardée avec ID: {message_id}")
|
| 50 |
return message_id
|
| 51 |
except Exception as e:
|
| 52 |
+
print(f"❌ Erreur lors de la sauvegarde: {str(e)}")
|
| 53 |
return None
|
| 54 |
|
|
|
|
| 55 |
try:
|
| 56 |
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 57 |
embedding_model = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL)
|
|
|
|
| 60 |
print(f"Erreur chargement embedding: {str(e)}")
|
| 61 |
embedding_model = None
|
| 62 |
|
| 63 |
+
# Fonction de RAG (inchangée)
|
| 64 |
def retrieve_relevant_context(query, embedding_model, mongo_collection, k=5):
|
| 65 |
query_embedding = embedding_model.embed_query(query)
|
| 66 |
|
|
|
|
| 112 |
except HTTPException:
|
| 113 |
pass
|
| 114 |
|
| 115 |
+
# Sauvegarde du message utilisateur (si non anonyme)
|
| 116 |
if not skip_save and conversation_id and current_user:
|
| 117 |
db.messages.insert_one({
|
| 118 |
"conversation_id": conversation_id,
|
|
|
|
| 122 |
"timestamp": datetime.utcnow()
|
| 123 |
})
|
| 124 |
|
| 125 |
+
# Vérification des limites de tokens
|
| 126 |
current_tokens = 0
|
| 127 |
message_tokens = 0
|
| 128 |
if current_user and conversation_id:
|
|
|
|
| 136 |
if current_tokens + message_tokens > MAX_TOKENS:
|
| 137 |
error_message = "⚠️ **Limite de taille de conversation atteinte**\n\nCette conversation est devenue trop longue. Pour continuer à discuter, veuillez créer une nouvelle conversation."
|
| 138 |
|
| 139 |
+
# Sauvegarder ce message d'erreur dans la BD
|
| 140 |
if conversation_id and current_user:
|
| 141 |
save_bot_response(conversation_id, current_user, error_message, current_tokens, message_tokens)
|
| 142 |
|
|
|
|
| 147 |
"tokens_limit": MAX_TOKENS
|
| 148 |
}, status_code=403)
|
| 149 |
|
| 150 |
+
# Détection des questions sur l'historique
|
| 151 |
is_history_question = any(
|
| 152 |
phrase in user_message.lower()
|
| 153 |
for phrase in [
|
|
|
|
| 161 |
or re.search(r"question pr[eé]c[eé]dente", user_message.lower()) \
|
| 162 |
or re.search(r"(toutes|liste|quelles|quoi).*questions", user_message.lower())
|
| 163 |
|
| 164 |
+
# Initialisation de l'historique si nécessaire
|
| 165 |
if conversation_id not in conversation_history:
|
| 166 |
conversation_history[conversation_id] = []
|
| 167 |
if current_user and conversation_id:
|
|
|
|
| 175 |
else:
|
| 176 |
conversation_history[conversation_id].append(f"Réponse : {msg['text']}")
|
| 177 |
|
| 178 |
+
# Traitement spécial pour les questions sur l'historique
|
| 179 |
if is_history_question:
|
| 180 |
+
# Extraire les questions réelles (non meta)
|
| 181 |
actual_questions = []
|
| 182 |
|
| 183 |
if conversation_id in conversation_history:
|
| 184 |
for msg in conversation_history[conversation_id]:
|
| 185 |
if msg.startswith("Question : "):
|
| 186 |
q_text = msg.replace("Question : ", "")
|
| 187 |
+
# Vérifier si ce n'est pas une méta-question
|
| 188 |
is_meta = any(phrase in q_text.lower() for phrase in [
|
| 189 |
"ma première question", "ma précédente question", "ma dernière question",
|
| 190 |
"ce que j'ai demandé", "j'ai dit quoi", "quelles questions",
|
|
|
|
| 197 |
if not is_meta:
|
| 198 |
actual_questions.append(q_text)
|
| 199 |
|
| 200 |
+
# Préparer la réponse en fonction du type spécifique de question
|
| 201 |
history_response = ""
|
| 202 |
|
| 203 |
if not actual_questions:
|
| 204 |
history_response = "Vous n'avez pas encore posé de question dans cette conversation. C'est notre premier échange."
|
| 205 |
else:
|
| 206 |
+
# Rechercher des mots-clés spécifiques pour personnaliser la réponse
|
| 207 |
|
| 208 |
+
# Cas 1: Question précédente/dernière question
|
| 209 |
if any(phrase in user_message.lower() for phrase in ["question précédente", "dernière question"]) and len(actual_questions) > 1:
|
| 210 |
+
# La dernière question est l'avant-dernière du tableau (la dernière étant la question actuelle)
|
| 211 |
prev_question = actual_questions[-1] if actual_questions else "Aucune question précédente trouvée."
|
| 212 |
history_response = f"**Votre question précédente était :**\n\n\"{prev_question}\""
|
| 213 |
|
| 214 |
+
# Cas 2: Première question
|
| 215 |
elif any(phrase in user_message.lower() for phrase in ["première question", "1ère question", "1ere question"]):
|
| 216 |
first_question = actual_questions[0] if actual_questions else "Aucune première question trouvée."
|
| 217 |
history_response = f"**Votre première question était :**\n\n\"{first_question}\""
|
| 218 |
|
| 219 |
+
# Cas 3: Question numérotée spécifique (2ème, 3ème, etc.)
|
| 220 |
elif re.search(r"(\d+)[èeme]{1,3}", user_message.lower()):
|
| 221 |
match = re.search(r"(\d+)[èeme]{1,3}", user_message.lower())
|
| 222 |
if match:
|
|
|
|
| 227 |
else:
|
| 228 |
history_response = f"Je ne trouve pas de question n°{question_num} dans notre conversation. Vous n'avez posé que {len(actual_questions)} question(s)."
|
| 229 |
|
| 230 |
+
# Cas par défaut: Toutes les questions
|
| 231 |
else:
|
| 232 |
history_response = "**Voici les questions que vous avez posées dans cette conversation :**\n\n"
|
| 233 |
for i, question in enumerate(actual_questions, 1):
|
| 234 |
history_response += f"{i}. {question}\n"
|
| 235 |
|
| 236 |
+
# Ajouter des informations supplémentaires pour les longues listes
|
| 237 |
if len(actual_questions) > 3:
|
| 238 |
history_response += f"\nVous avez posé {len(actual_questions)} questions dans cette conversation."
|
| 239 |
|
| 240 |
+
# Ajouter l'historique en mémoire
|
| 241 |
if conversation_id:
|
| 242 |
conversation_history[conversation_id].append(f"Réponse : {history_response}")
|
| 243 |
|
| 244 |
+
# IMPORTANT: Sauvegarder la réponse dans la BD
|
| 245 |
if conversation_id and current_user:
|
| 246 |
save_bot_response(conversation_id, current_user, history_response, current_tokens, message_tokens)
|
| 247 |
+
print(f"✅ Réponse à la question d'historique sauvegardée pour conversation {conversation_id}")
|
| 248 |
|
| 249 |
return JSONResponse({"response": history_response})
|
| 250 |
|
| 251 |
+
# Ajout de la question actuelle à l'historique
|
| 252 |
if conversation_id:
|
| 253 |
conversation_history[conversation_id].append(f"Question : {user_message}")
|
| 254 |
|
| 255 |
+
# Récupération du contexte RAG
|
| 256 |
context = None
|
| 257 |
if not is_history_question and embedding_model:
|
| 258 |
context = retrieve_relevant_context(user_message, embedding_model, db.connaissances, k=5)
|
| 259 |
if context and conversation_id:
|
| 260 |
conversation_history[conversation_id].append(f"Contexte : {context}")
|
| 261 |
|
| 262 |
+
# Préparation du prompt système
|
| 263 |
system_prompt = (
|
| 264 |
"Tu es un chatbot spécialisé dans la santé mentale, et plus particulièrement la schizophrénie. "
|
| 265 |
"Tu réponds de façon fiable, claire et empathique, en t'appuyant uniquement sur des sources médicales et en français. "
|
|
|
|
| 274 |
|
| 275 |
)
|
| 276 |
|
| 277 |
+
# Enrichir l prompt avec l'historique et le contexte RAG
|
| 278 |
enriched_context = ""
|
| 279 |
|
| 280 |
if conversation_id in conversation_history:
|
|
|
|
| 321 |
"Tu dois donner une réponse complète et bien structurée."
|
| 322 |
)
|
| 323 |
|
| 324 |
+
# Préparation des messages pour le LLM
|
| 325 |
messages = [{"role": "system", "content": system_prompt}]
|
| 326 |
|
| 327 |
if conversation_id and len(conversation_history.get(conversation_id, [])) > 0:
|
| 328 |
history = conversation_history[conversation_id]
|
| 329 |
|
| 330 |
+
# Assurer l'alternance user/assistant
|
| 331 |
user_messages = []
|
| 332 |
bot_messages = []
|
| 333 |
|
|
|
|
| 340 |
bot_text = history[i+1].replace("Réponse : ", "")
|
| 341 |
bot_messages.append(bot_text)
|
| 342 |
|
| 343 |
+
# Construire des paires user/assistant
|
| 344 |
valid_pairs = min(len(user_messages), len(bot_messages))
|
| 345 |
|
| 346 |
for i in range(valid_pairs):
|
| 347 |
messages.append({"role": "user", "content": user_messages[i]})
|
| 348 |
messages.append({"role": "assistant", "content": bot_messages[i]})
|
| 349 |
|
| 350 |
+
# Ajouter le message actuel
|
| 351 |
messages.append({"role": "user", "content": user_message})
|
| 352 |
|
| 353 |
+
# Fonction génératrice pour le streaming
|
| 354 |
async def generate_stream():
|
| 355 |
try:
|
| 356 |
collected_response = ""
|
| 357 |
|
| 358 |
+
# Signal de début de stream
|
| 359 |
yield "data: {\"type\": \"start\"}\n\n"
|
| 360 |
|
| 361 |
+
# Appel à l'API Hugging Face avec streaming
|
| 362 |
completion_stream = hf_client.chat.completions.create(
|
| 363 |
model="mistralai/Mistral-7B-Instruct-v0.3",
|
| 364 |
messages=messages,
|
| 365 |
+
max_tokens=1024,
|
| 366 |
temperature=0.7,
|
| 367 |
stream=True
|
| 368 |
)
|
| 369 |
chunk_buffer = ""
|
| 370 |
chunk_count = 0
|
| 371 |
+
MAX_CHUNKS_BEFORE_SEND = 3 # Envoyer tous les 5 chunks reçus
|
| 372 |
+
# Traiter chaque chunk
|
| 373 |
for chunk in completion_stream:
|
| 374 |
if chunk.choices and chunk.choices[0].delta.content:
|
| 375 |
content = chunk.choices[0].delta.content
|
|
|
|
| 376 |
collected_response += content
|
| 377 |
chunk_buffer += content
|
| 378 |
chunk_count += 1
|
| 379 |
|
| 380 |
+
# Envoyer es chunks accumulés périodiquement
|
| 381 |
if chunk_count >= MAX_CHUNKS_BEFORE_SEND or '\n' in content:
|
|
|
|
| 382 |
yield f"data: {json.dumps({'content': chunk_buffer})}\n\n"
|
| 383 |
chunk_buffer = ""
|
| 384 |
chunk_count = 0
|
| 385 |
+
|
| 386 |
+
# Envoyer le reste du buffer
|
| 387 |
if chunk_buffer:
|
| 388 |
yield f"data: {json.dumps({'content': chunk_buffer})}\n\n"
|
| 389 |
+
|
| 390 |
+
# Ajouter une note si nécessaire
|
| 391 |
if collected_response.endswith((".", "!", "?")) == False and len(collected_response) > 500:
|
| 392 |
suffix = "\n\n(Note: Ma réponse a été limitée par des contraintes de taille. N'hésitez pas à me demander de poursuivre si vous souhaitez plus d'informations.)"
|
| 393 |
collected_response += suffix
|
| 394 |
yield f"data: {json.dumps({'content': suffix})}\n\n"
|
| 395 |
|
| 396 |
+
# Sauvegarder la réponse complète dans l'historique en mémoire
|
| 397 |
if conversation_id:
|
| 398 |
conversation_history[conversation_id].append(f"Réponse : {collected_response}")
|
| 399 |
|
| 400 |
if len(conversation_history[conversation_id]) > 50:
|
| 401 |
conversation_history[conversation_id] = conversation_history[conversation_id][-50:]
|
| 402 |
|
| 403 |
+
# Sauvegarder la réponse dans la BD (sans condition skip_save)
|
| 404 |
if conversation_id and current_user:
|
| 405 |
save_bot_response(conversation_id, current_user, collected_response, current_tokens, message_tokens)
|
| 406 |
|
| 407 |
+
# Signal de fin de stream
|
| 408 |
yield "data: {\"type\": \"end\"}\n\n"
|
| 409 |
|
| 410 |
except Exception as e:
|
| 411 |
+
# Gérer les erreurs de streaming
|
| 412 |
error_message = str(e)
|
| 413 |
print(f"❌ Streaming error: {error_message}")
|
| 414 |
|
| 415 |
try:
|
| 416 |
+
# Fallback en mode non-streaming
|
| 417 |
fallback = hf_client.text_generation(
|
| 418 |
model="mistralai/Mistral-7B-Instruct-v0.3",
|
| 419 |
prompt=f"<s>[INST] {system_prompt}\n\nQuestion: {user_message} [/INST]",
|
| 420 |
+
max_new_tokens=512,
|
| 421 |
temperature=0.7
|
| 422 |
)
|
| 423 |
yield f"data: {json.dumps({'content': fallback})}\n\n"
|
| 424 |
|
| 425 |
+
# Sauvegarder la réponse de fallback dans l'historique
|
| 426 |
if conversation_id:
|
| 427 |
conversation_history[conversation_id].append(f"Réponse : {fallback}")
|
| 428 |
|
| 429 |
+
# Sauvegarder la réponse fallback dans la BD
|
| 430 |
if conversation_id and current_user:
|
| 431 |
save_bot_response(conversation_id, current_user, fallback, current_tokens, message_tokens)
|
| 432 |
|
| 433 |
except Exception as fallback_error:
|
| 434 |
+
print(f"❌ Erreur de fallback: {str(fallback_error)}")
|
| 435 |
+
error_response = "Je suis désolé, je rencontre actuellement des difficultés techniques. Pourriez-vous reformuler votre question ou réessayer dans quelques instants?"
|
| 436 |
yield f"data: {json.dumps({'content': error_response})}\n\n"
|
| 437 |
|
| 438 |
+
# Sauvegarder aussi les messages d'erreur technique
|
| 439 |
if conversation_id and current_user:
|
| 440 |
save_bot_response(conversation_id, current_user, error_response, current_tokens, message_tokens)
|
| 441 |
|
| 442 |
+
# Signal de fin de stream
|
| 443 |
yield "data: {\"type\": \"end\"}\n\n"
|
| 444 |
|
| 445 |
+
# Retourner une réponse en streaming
|
| 446 |
return StreamingResponse(
|
| 447 |
generate_stream(),
|
| 448 |
media_type="text/event-stream"
|
| 449 |
+
)
|