khadijaaao commited on
Commit
410ad2b
·
verified ·
1 Parent(s): 52eea35

Update streamlit_app.py.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py.py +25 -21
streamlit_app.py.py CHANGED
@@ -3,35 +3,48 @@ import os
3
  from llama_cpp import Llama
4
  from langchain_community.vectorstores import FAISS
5
  from langchain_community.embeddings import HuggingFaceEmbeddings
 
6
 
7
  # --- Configuration de la page Streamlit ---
8
- st.set_page_config(page_title="Wize, votre Coach RAG", layout="wide")
9
- st.title("🤖 Wize - Votre Coach Expert")
10
  st.write("Posez une question sur vos documents, et je vous répondrai en me basant sur leur contenu.")
11
 
12
  # --- Fonctions de chargement mises en cache ---
13
  # @st.cache_resource est CRUCIAL pour que Streamlit ne recharge pas les modèles à chaque interaction
 
14
  @st.cache_resource
15
- def load_llm(model_path):
16
- print("Chargement du modèle LLM...")
17
- return Llama(model_path=model_path, n_gpu_layers=-1, n_ctx=4096, verbose=False, chat_format="llama-3")
 
 
 
 
 
 
 
 
 
 
 
18
 
19
  @st.cache_resource
20
  def load_retriever(faiss_path, embeddings_path):
21
- print("Chargement du modèle d'embeddings et de FAISS...")
22
- embeddings_model = HuggingFaceEmbeddings(model_name=embeddings_path, model_kwargs={'device': 'cpu'}) # Utiliser le CPU sur les serveurs gratuits
23
- vectorstore = FAISS.load_local(faiss_path, embeddings_model, allow_dangerous_deserialization=True)
 
24
  return vectorstore.as_retriever(search_kwargs={"k": 5})
25
 
26
  # --- Chemins d'accès (relatifs) ---
27
  DOSSIER_PROJET = os.path.dirname(__file__)
28
- CHEMIN_MODELE_GGUF = os.path.join(DOSSIER_PROJET, "Meta-Llama-3-8B-Instruct.Q4_K_M.gguf") # Assurez-vous que le nom correspond
29
  CHEMIN_INDEX_FAISS = os.path.join(DOSSIER_PROJET, "faiss_index_wize")
30
  CHEMIN_MODELE_EMBEDDINGS = os.path.join(DOSSIER_PROJET, "embedding_model")
31
 
32
  # --- Chargement des modèles via Streamlit ---
33
  try:
34
- llm = load_llm(CHEMIN_MODELE_GGUF)
35
  retriever = load_retriever(CHEMIN_INDEX_FAISS, CHEMIN_MODELE_EMBEDDINGS)
36
  st.success("Les modèles sont chargés et prêts !")
37
  except Exception as e:
@@ -49,12 +62,10 @@ for message in st.session_state.messages:
49
 
50
  # --- Logique de Chat ---
51
  if prompt := st.chat_input("Posez votre question ici..."):
52
- # Ajouter le message de l'utilisateur à l'historique
53
  st.session_state.messages.append({"role": "user", "content": prompt})
54
  with st.chat_message("user"):
55
  st.markdown(prompt)
56
 
57
- # Générer la réponse de l'assistant
58
  with st.chat_message("assistant"):
59
  with st.spinner("Je réfléchis..."):
60
  # 1. Récupérer le contexte
@@ -62,19 +73,12 @@ if prompt := st.chat_input("Posez votre question ici..."):
62
  context = "\n".join([doc.page_content for doc in docs])
63
 
64
  # 2. Créer le prompt pour le LLM
65
- system_prompt = "Vous êtes Wize. Répondez à la question en vous basant uniquement sur le contexte fourni."
66
- full_prompt = f"""
67
- <|begin_of_text|><|start_header_id|>system<|end_header_id|>
68
- {system_prompt}
69
- Contexte : {context}<|eot_id|><|start_header_id|>user<|end_header_id|>
70
- Question : {prompt}<|eot_id|><|start_header_id|>assistant<|end_header_id|>
71
- """
72
 
73
  # 3. Générer la réponse
74
  response = llm(full_prompt, max_tokens=1500, stop=["<|eot_id|>"], echo=False)
75
  answer = response['choices'][0]['text'].strip()
76
-
77
  st.markdown(answer)
78
 
79
- # Ajouter la réponse de l'assistant à l'historique
80
  st.session_state.messages.append({"role": "assistant", "content": answer})
 
3
  from llama_cpp import Llama
4
  from langchain_community.vectorstores import FAISS
5
  from langchain_community.embeddings import HuggingFaceEmbeddings
6
+ from huggingface_hub import hf_hub_download
7
 
8
  # --- Configuration de la page Streamlit ---
9
+ st.set_page_config(page_title="Votre Coach RAG", layout="wide")
10
+ st.title("Votre Coach Expert")
11
  st.write("Posez une question sur vos documents, et je vous répondrai en me basant sur leur contenu.")
12
 
13
  # --- Fonctions de chargement mises en cache ---
14
  # @st.cache_resource est CRUCIAL pour que Streamlit ne recharge pas les modèles à chaque interaction
15
+
16
  @st.cache_resource
17
+ def load_llm():
18
+ # MODIFICATION : On télécharge le modèle depuis le Hub au lieu de le chercher localement.
19
+ # Cela contourne la limite de stockage de 1 Go du Space.
20
+ model_repo_id = "QuantFactory/Meta-Llama-3-8B-Instruct-GGUF"
21
+ model_filename = "Meta-Llama-3-8B-Instruct.Q4_K_M.gguf"
22
+
23
+ with st.spinner(f"Téléchargement du modèle '{model_filename}'... (Cette étape est longue et n'a lieu qu'une seule fois)"):
24
+ # Télécharge le fichier s'il n'est pas dans le cache et retourne son chemin
25
+ model_path = hf_hub_download(repo_id=model_repo_id, filename=model_filename)
26
+
27
+ with st.spinner("Chargement du modèle LLM en mémoire..."):
28
+ # ✅ MODIFICATION : n_gpu_layers=0 car nous utilisons le CPU gratuit.
29
+ llm = Llama(model_path=model_path, n_gpu_layers=0, n_ctx=4096, verbose=False, chat_format="llama-3")
30
+ return llm
31
 
32
  @st.cache_resource
33
  def load_retriever(faiss_path, embeddings_path):
34
+ with st.spinner("Chargement de la base de connaissances (FAISS)..."):
35
+ # MODIFICATION : On spécifie 'cpu' car nous n'avons pas de GPU.
36
+ embeddings_model = HuggingFaceEmbeddings(model_name=embeddings_path, model_kwargs={'device': 'cpu'})
37
+ vectorstore = FAISS.load_local(faiss_path, embeddings_model, allow_dangerous_deserialization=True)
38
  return vectorstore.as_retriever(search_kwargs={"k": 5})
39
 
40
  # --- Chemins d'accès (relatifs) ---
41
  DOSSIER_PROJET = os.path.dirname(__file__)
 
42
  CHEMIN_INDEX_FAISS = os.path.join(DOSSIER_PROJET, "faiss_index_wize")
43
  CHEMIN_MODELE_EMBEDDINGS = os.path.join(DOSSIER_PROJET, "embedding_model")
44
 
45
  # --- Chargement des modèles via Streamlit ---
46
  try:
47
+ llm = load_llm()
48
  retriever = load_retriever(CHEMIN_INDEX_FAISS, CHEMIN_MODELE_EMBEDDINGS)
49
  st.success("Les modèles sont chargés et prêts !")
50
  except Exception as e:
 
62
 
63
  # --- Logique de Chat ---
64
  if prompt := st.chat_input("Posez votre question ici..."):
 
65
  st.session_state.messages.append({"role": "user", "content": prompt})
66
  with st.chat_message("user"):
67
  st.markdown(prompt)
68
 
 
69
  with st.chat_message("assistant"):
70
  with st.spinner("Je réfléchis..."):
71
  # 1. Récupérer le contexte
 
73
  context = "\n".join([doc.page_content for doc in docs])
74
 
75
  # 2. Créer le prompt pour le LLM
76
+ system_prompt = "Vous êtes Un coach expert. Répondez à la question en vous basant uniquement sur le contexte fourni."
77
+ full_prompt = f"""<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n{system_prompt}\nContexte : {context}<|eot_id|><|start_header_id|>user<|end_header_id|>\nQuestion : {prompt}<|eot_id|><|start_header_id|>assistant<|end_header_id|>"""
 
 
 
 
 
78
 
79
  # 3. Générer la réponse
80
  response = llm(full_prompt, max_tokens=1500, stop=["<|eot_id|>"], echo=False)
81
  answer = response['choices'][0]['text'].strip()
 
82
  st.markdown(answer)
83
 
 
84
  st.session_state.messages.append({"role": "assistant", "content": answer})