File size: 10,940 Bytes
dc22afe
 
 
 
 
0da9d90
dc22afe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf0eecb
dc22afe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d9be73
f5693fd
dc22afe
 
 
 
f5693fd
 
dc22afe
 
 
 
 
 
 
 
 
f5693fd
dc22afe
 
 
 
 
 
 
f5693fd
dc22afe
 
 
e456ef9
dc22afe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0da9d90
 
 
 
 
 
 
 
dc22afe
0da9d90
dc22afe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3f3099
dc22afe
0a6fe39
 
1695b8d
c9721e9
55d77c9
f3f3099
a09febb
 
55d77c9
a09febb
 
 
 
 
 
 
 
 
a1f3271
a09febb
 
 
55d77c9
cb72503
9e91930
a09febb
 
 
 
 
9e91930
 
2ece9f2
c19c69b
 
0a6fe39
 
 
2ece9f2
 
 
 
 
 
 
 
b0613e4
0a6fe39
 
 
 
 
 
2ece9f2
0a6fe39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad4b5c8
 
 
 
 
f3f3099
060312a
 
 
 
 
 
 
 
 
 
 
ad4b5c8
0a6fe39
 
dc22afe
ad4b5c8
dc22afe
 
 
 
 
 
 
2d9be73
dc22afe
 
 
 
 
 
 
 
 
 
 
 
 
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import streamlit as st
import os
from chromadb import Client as ChromaClient
from chroma_storage import ChromaStorage
from retrieval import Retriever
from langchain_groq import ChatGroq

from generation import RAGGenerator
from langchain_community.vectorstores import Chroma
from langchain_huggingface import HuggingFaceEmbeddings
from constant import categorie
from dotenv import load_dotenv

import chromadb
from Reranker import Reranker 

chromadb.api.client.SharedSystemClient.clear_system_cache()
load_dotenv()
import os





CHROMA_DIR      = "src/chroma_db"
COLLECTION_NAME = "my_collection"

st.markdown("""
<style>
body {
    font-family: 'Segoe UI', Roboto, sans-serif;
}
.header {
    background-color: #4A90E2;
    color: white;
    padding: 10px;
    display: flex;
    align-items: center;
    box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}
.header img {
    height: 40px;
    margin-right: 10px;
}
.header h1 {
    margin: 0;
    font-size: 24px;
}
.chat-container {
    padding: 10px;
}
.bot-message, .user-message {
    display: flex;
    align-items: flex-start;
    margin: 8px 0;
}
.bot-message .bubble {
    margin-left: 10px;
    background-color: #f0f0f0;
    color: #000;
}
.user-message {
    justify-content: flex-end;
}
.user-message .bubble {
    margin-right: 10px;
    background-color: #4A90E2;
    color: #fff;
}
.bubble {
    border-radius: 8px;
    padding: 10px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    max-width: 70%;
}
.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
}
@media (max-width: 600px) {
    .header h1 {
        font-size: 18px;
    }
    .bubble {
        max-width: 90%;
    }
}
</style>
""", unsafe_allow_html=True)

# --- En-tΓͺte bleu avec logo et titre ---
st.markdown(f'''
<div class="header">
  <img src="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fmedia.licdn.com%2Fdms%2Fimage%2FD4D0BAQFNZTx4WjU6Kw%2Fcompany-logo_200_200%2F0%2F1706688195351%3Fe%3D2147483647%26v%3Dbeta%26t%3DCBoRbqESfYGI0cxj1-5IvCpkhBTRcXEbBqS6q7rA9l0&f=1&nofb=1&ipt=a3414940fc3b31a18d97ba116cc4b5a9bc4f88e8d72bf286c029be996d8d5b0e">
  <h1>car insurance assistant</h1>
</div>
''', unsafe_allow_html=True)


#if "categories" not in st.session_state:
 #   st.session_state.categories = categorie
if "messages" not in st.session_state:
    st.session_state.messages = []
if "step" not in st.session_state:
    st.session_state.step = 0
if "selected_category" not in st.session_state:
    st.session_state.selected_category = None


# --- Affichage du chat uniquement après sélection ---
#sel = st.session_state.selected_category



# Ajouter le message initial du bot Γ  l'Γ©tape 1
if st.session_state.step == 0:
    st.session_state.messages.append({
        "role": "assistant", 
        "content": "I am your assistant, Ominimo"
    })
  #  save_conversation_to_mongo(st.session_state.messages)
    st.session_state.step = 1
    st.rerun()



# ─────────────────────────────────────────────────────────────────────────────
# 2) INITIALISATION UNIQUE (cache via session_state)
# ─────────────────────────────────────────────────────────────────────────────
if "initialized" not in st.session_state:
    st.session_state.initialized = True
    retriever = Retriever(
        chroma_dir=CHROMA_DIR,
        collection_name=COLLECTION_NAME
       
    )
   
   
    llm = ChatGroq(
    model="meta-llama/llama-4-scout-17b-16e-instruct",  
    temperature=0,
    max_tokens=None,
    timeout=None,
    max_retries=2,

)
    generator = RAGGenerator()
    reranker = Reranker(model=llm)
    st.session_state.retriever   = retriever
    st.session_state.generator   = generator
    st.session_state.reranker    = reranker
   # st.session_state.categories  = categorie
   

# ─────────────────────────────────────────────────────────────────────────────
# 3) UI & Γ‰tat de chat
# ─────────────────────────────────────────────────────────────────────────────
query = st.chat_input("chat_query")
#if "last_rerank" in st.session_state:
   # st.code(f"Rerank result: {st.session_state.last_rerank}")

# Si l'utilisateur a saisi une requΓͺte
if query:
    # Si on est en phase de clarification
    if "qa_pairs" in st.session_state and "clarif_idx" in st.session_state:
        idx = st.session_state.clarif_idx
        st.session_state.messages.append({"role": "user", "content": query})
      #  save_conversation_to_mongo(st.session_state.messages)
        st.session_state.qa_pairs[idx]["response"] = query
        st.session_state.clarif_idx += 1
    else:
        # RequΓͺte initiale normale
        st.session_state.messages.append({"role": "user", "content": query})
      #  save_conversation_to_mongo(st.session_state.messages)
        try:
            # 1. RΓ©cupΓ©ration des documents initiaux
           # with st.spinner():
            docs = st.session_state.retriever.retrieve(query)
                

            passages = [(doc_tuple[0].page_content, doc_tuple[1]) for doc_tuple in docs]


           # st.code(passages)
            
            # 2. Reranking des documents pour amΓ©liorer la pertinence
            if docs:
                rerank_result = st.session_state.reranker.rerank(query, passages)
                
                # Affichage du rΓ©sultat brut pour debug
               # st.code(f"Rerank raw result: {rerank_result}")
                if rerank_result is not None:
                    st.session_state.last_rerank = rerank_result.model_dump()
                    
                    # Filtrage et rΓ©organisation des documents selon le reranking
                    if rerank_result.top_indexes:
                        reranked_docs = [docs[i] for i in rerank_result.top_indexes if i < len(docs)]
                        docs = reranked_docs
                    else:
                        st.session_state.messages.append({
                            "role": "assistant",
                            "content": rerank_result.message or "Aucun document pertinent trouvΓ©. Veuillez reformuler votre question."
                        })
                        

                # Si le reranker a Γ©chouΓ©
                # Si le reranker a Γ©chouΓ©
                else:
                    pass

                
                

                

            
                      



                    
            # 3. GΓ©nΓ©ration de la rΓ©ponse avec les documents reranked
            if docs:  # VΓ©rifier que nous avons des documents avant de continuer
                qa_pairs, solution, lang = st.session_state.generator.retrieve_qa(
                    query=query,
                    docs_scores=docs
                )
                st.session_state.qa_pairs = qa_pairs
                st.session_state.solution = solution
                st.session_state.lang = lang
            
                
            else:
                # Aucun document disponible
                st.session_state.messages.append({
                    "role": "assistant",
                    "content": "Aucun document pertinent trouvΓ© pour votre requΓͺte. Pouvez-vous la reformuler ?"
                })
                  
                
        except ValueError as e:
            st.session_state.messages.append({
                "role": "assistant",
                "content": str(e)
            })
         #   save_conversation_to_mongo(st.session_state.messages)
        except Exception as e:
            st.error(f"❌ Erreur : {e}")

# ───────────────────────────────────────────────
# Gestion des clarifications
# ───────────────────────────────────────────────
if "qa_pairs" in st.session_state:
    if "clarif_shown" not in st.session_state:
        questions_text = "\n".join([
            f"{i+1}. {pair['question']}" for i, pair in enumerate(st.session_state.qa_pairs)
        ])
        st.session_state.messages.append({
            "role": "assistant",
            "content": questions_text
        })
      #  save_conversation_to_mongo(st.session_state.messages)
        st.session_state.clarif_shown = True

    if "clarif_idx" not in st.session_state:
        st.session_state.clarif_idx = 0

    # Lorsque toutes les clarifications sont remplies, gΓ©nΓ©rer la rΓ©ponse finale
    if st.session_state.clarif_idx >= len(st.session_state.qa_pairs):
        final = st.session_state.generator.generate_answer(
            st.session_state.messages,
            st.session_state.solution,
            st.session_state.lang
        )

        if not final.strip() or "sorry" in final.lower():
            st.session_state.messages.append({
                "role": "assistant",
                "content": "I'm sorry, I cannot answer this request. It is beyond my capabilities or not related to car insurance."
            })
        else:
            st.session_state.messages.append({"role": "assistant", "content": final})    

    for key in ["qa_pairs", "solution", "lang", "clarif_idx", "clarif_shown"]:
        st.session_state.pop(key, None)

    
        for key in ["qa_pairs", "solution", "lang", "clarif_idx", "clarif_shown"]:
            st.session_state.pop(key, None)


st.markdown('<div class="chat-container">', unsafe_allow_html=True)
for msg in st.session_state.messages:
    if not msg.get("content"):
        continue
    if msg["role"] == "assistant":
        st.markdown(f'''
        <div class="bot-message">
          <img src="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fmedia.licdn.com%2Fdms%2Fimage%2FD4D0BAQFNZTx4WjU6Kw%2Fcompany-logo_200_200%2F0%2F1706688195351%3Fe%3D2147483647%26v%3Dbeta%26t%3DCBoRbqESfYGI0cxj1-5IvCpkhBTRcXEbBqS6q7rA9l0&f=1&nofb=1&ipt=a3414940fc3b31a18d97ba116cc4b5a9bc4f88e8d72bf286c029be996d8d5b0e" class="avatar">
          <div class="bubble">{msg["content"]}</div>
        </div>
        ''', unsafe_allow_html=True)
    else:
        st.markdown(f'''
        <div class="user-message">
          <div class="bubble">{msg["content"]}</div>
          <img src="https://img.icons8.com/ios-filled/50/4A90E2/user-male-circle.png" class="avatar">
        </div>
        ''', unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)