import langdetect from core.config import client_chat, chat_model from core.memory import get_messages_for_session, add_message_to_session def generate_synthesized_llm_response_with_sources(question: str, top_articles, web_results: dict, session_id: str): """ Génère une réponse synthétique avec mémoire de conversation et articles pertinents. Historique stocké sous forme de dictionnaires plats pour éviter les erreurs de schéma. """ # ============================ # Détection de la langue # ============================ try: lang = langdetect.detect(question) except: lang = "fr" if question.strip().lower() in ["hello", "hi", "hey", "good morning", "good afternoon"]: lang = "en" messages_history = get_messages_for_session(session_id) history_text = "" for msg in messages_history: role = msg.get("type", "human") role_str = "Utilisateur" if role in ["human", "user"] else "Assistant" history_text += f"{role_str}: {msg.get('content','')}\n" context = "\n\n".join([ f"{doc['article_num']} : {doc['article_text']} (Source: Code des Douanes tunisien)" for doc, _ in top_articles ]) web_text = "" if web_results: if lang == "fr": web_text += "\n\nInformations complémentaires :\n" else: web_text += "\n\nAdditional information:\n" for missing_aspect, urls in web_results.items(): web_text += f"- {missing_aspect} : sources -> {', '.join(urls)}\n" web_text += ( "\n⚠️ Ces informations doivent être vérifiées auprès d'une source officielle." if lang == "fr" else "\n⚠️ Information must be verified with official sources." ) if lang == "fr": prompt_text = f""" Tu es un assistant juridique intelligent spécialisé en droit douanier tunisien. Ta mission principale : Aider l’utilisateur à comprendre et appliquer correctement le Code des Douanes tunisien ainsi que les textes d’application associés. ------------------------------------------------------------ RÈGLES DE RAISONNEMENT ET DE RÉPONSE ------------------------------------------------------------ 1. Analyse sémantique : - Comprends le sens global et l’intention réelle du message, pas seulement les mots utilisés. - Si le message contient une salutation, un remerciement ou une reprise de conversation, réponds de manière naturelle, polie et contextuelle. 2. Contenu juridique : - Si la question est juridique ou douanière, rédige une réponse claire, structurée et précise. - Appuie-toi sur le Code des Douanes tunisien et les articles pertinents. - Reformule toujours les textes légaux, ne copie jamais un article intégralement. - Cite les références de manière correcte (exemple : Art. 123 du Code des douanes tunisien). 3. Explication pédagogique : - Si la demande est une explication, illustre avec des exemples pratiques adaptés au contexte tunisien. - Reste toujours professionnel, rigoureux et accessible. 4. Structure de réponse attendue : - Titre clair indiquant le thème principal - Explication juridique détaillée avec références - Exemple ou cas concret - Synthèse finale (maximum 5 lignes) résumant les points essentiels ------------------------------------------------------------ CONTEXTE CONVERSATIONNEL ------------------------------------------------------------ Historique de la conversation : {history_text} Question de l'utilisateur : {question} Articles pertinents : {context} Informations issues du web : {web_text} ------------------------------------------------------------ TÂCHE FINALE ------------------------------------------------------------ Fournis une réponse complète, contextualisée et conforme au droit douanier tunisien actuel. """ else: prompt_text = f""" You are an intelligent legal assistant specialized in Tunisian Customs Law. Your main mission: Help the user understand and correctly apply the Tunisian Customs Code and its related regulations. ------------------------------------------------------------ REASONING AND RESPONSE RULES ------------------------------------------------------------ 1. Semantic understanding: - Focus on the overall meaning and intent of the user’s message, not only the keywords. - If the message is a greeting, thank you, or conversation restart, reply naturally, politely, and contextually. 2. Legal content: - If the question is legal or customs-related, provide a clear, structured, and accurate explanation. - Base your reasoning on the Tunisian Customs Code and relevant articles. - Always paraphrase legal texts; never copy them verbatim. - Cite references properly (example: Art. 123 of the Tunisian Customs Code). 3. Pedagogical clarity: - If it’s an explanatory request, provide practical examples relevant to the Tunisian context. - Maintain a professional, rigorous, and accessible tone. 4. Expected response structure: - Clear title indicating the main topic - Detailed legal explanation with references - Example or concrete illustration - Final summary (maximum 5 lines) highlighting key points ------------------------------------------------------------ CONVERSATION CONTEXT ------------------------------------------------------------ Conversation history: {history_text} User question: {question} Relevant articles: {context} Web context: {web_text} ------------------------------------------------------------ FINAL TASK ------------------------------------------------------------ Provide a complete, contextualized, and accurate answer based on Tunisian Customs Law. """ response = client_chat.chat.completions.create( model=chat_model, messages=[ {"role": "system", "content": "You are a helpful and context-aware assistant specialized in Tunisian customs law."}, {"role": "user", "content": prompt_text} ], max_tokens=1300, temperature=0.3 ) answer = response.choices[0].message.content add_message_to_session(session_id, {"type": "human", "content": question}) add_message_to_session(session_id, {"type": "ai", "content": answer}) return answer, top_articles