File size: 6,351 Bytes
f7b069f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
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