kadsai commited on
Commit
b2631f3
·
verified ·
1 Parent(s): c2b92e4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -16
app.py CHANGED
@@ -10,6 +10,11 @@ from langchain_chroma import Chroma
10
  from langchain.schema import HumanMessage, SystemMessage
11
  from tiktoken import encoding_for_model
12
 
 
 
 
 
 
13
  # Activation du logging HTTP pour OpenAI
14
  openai_logger = logging.getLogger("openai")
15
  openai_logger.setLevel(logging.DEBUG)
@@ -22,20 +27,21 @@ try:
22
  EXCELIS_MDP = os.getenv("EXCELIS_MDP")
23
  VECTORSTORE_BASE_DIR = "vectorstores"
24
  except Exception as e:
25
- print("Missing value of parameters",e)
26
  raise
 
27
  # --- Initialisation des modèles
28
  try:
29
  embedding_model = OpenAIEmbeddings(
30
- model="text-embedding-3-large",
31
- openai_api_key=OPENAI_API_KEY
32
- )
33
  except Exception as e:
34
- print("Can't init the modèle",e)
35
  raise
36
 
37
  # --- Initialisation de la base SQLite
38
- conn = sqlite3.connect("conversations.db")
39
  cursor = conn.cursor()
40
  cursor.execute('''
41
  CREATE TABLE IF NOT EXISTS conversations (
@@ -78,7 +84,7 @@ def respond(message, history, system_message, domain, model_name, max_tokens, te
78
  )
79
  else:
80
  system_message = system_message or "Tu es un assistant IA très compétent."
81
-
82
  collection = load_collection(domain)
83
 
84
  # Validation message
@@ -94,13 +100,12 @@ def respond(message, history, system_message, domain, model_name, max_tokens, te
94
  query_embedding = embedding_model.embed_query(message)
95
 
96
  # Recherche avec score dans Chroma
97
-
98
- #results_with_scores = collection.similarity_search_with_score(message, k=3)
99
  results_with_scores = collection.similarity_search_by_vector_with_relevance_scores(query_embedding, k=3)
100
 
101
  seuil = 0.75 # seuil de similarité à ajuster
102
  for doc, score in results_with_scores:
103
  print(f"SCORE: {score:.2f} - DOC: {doc.page_content[:80]}") # affiche le début du contenu
 
104
  # Filtrage des résultats selon le seuil
105
  filtered_results = [doc for doc, score in results_with_scores if score >= seuil]
106
  if not filtered_results:
@@ -143,7 +148,6 @@ def respond(message, history, system_message, domain, model_name, max_tokens, te
143
  except Exception as e:
144
  return [{"role": "assistant", "content": f"❌ Erreur : {e}"}]
145
 
146
-
147
  # --- Interface utilisateur Gradio
148
  with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {background-color: #b8c2d3;}") as app:
149
  with gr.Column(visible=True, elem_id="login-block") as login_block:
@@ -182,18 +186,14 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {background-color:
182
  temperature = gr.Slider(0.1, 2.0, value=0.7, label="🌡️ Température")
183
  top_p = gr.Slider(0.1, 1.0, value=0.95, label="🎯 Top-p")
184
 
185
- #chatbot = gr.Chatbot(label="💬 Chat", value=[], type="messages", elem_id="chat-display")
186
  chatbot = gr.Chatbot(label="💬 Chat", type="messages", elem_id="chat-display")
187
  message_input = gr.Textbox(label="✉️ Votre message", placeholder="Tapez votre question ici...")
188
  send_button = gr.Button("🚀 Envoyer", variant="primary")
189
 
190
  def chat_submit(msg, history, domain, model_name, max_tokens, temperature, top_p):
191
  if not msg or not msg.strip():
192
- # Message vide : ne rien envoyer, ne pas vider le champ, mais renvoyer historique inchangé
193
  return history, gr.update(value=msg)
194
- # Appel à respond pour obtenir nouvel historique
195
  new_history = respond(msg, history, "", domain, model_name, max_tokens, temperature, top_p)
196
- # Vide le champ message_input après envoi
197
  return new_history, gr.update(value="")
198
 
199
  send_button.click(
@@ -202,7 +202,6 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {background-color:
202
  outputs=[chatbot, message_input]
203
  )
204
 
205
-
206
  def login(username, password):
207
  if username == EXCELIS_USER and password == EXCELIS_MDP:
208
  return gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)
@@ -214,5 +213,41 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {background-color:
214
  outputs=[login_block, chatbot_block, error_box]
215
  )
216
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
  if __name__ == "__main__":
218
- app.launch()
 
 
 
 
10
  from langchain.schema import HumanMessage, SystemMessage
11
  from tiktoken import encoding_for_model
12
 
13
+ from fastapi import FastAPI, HTTPException
14
+ from pydantic import BaseModel
15
+ import uvicorn
16
+ import threading
17
+
18
  # Activation du logging HTTP pour OpenAI
19
  openai_logger = logging.getLogger("openai")
20
  openai_logger.setLevel(logging.DEBUG)
 
27
  EXCELIS_MDP = os.getenv("EXCELIS_MDP")
28
  VECTORSTORE_BASE_DIR = "vectorstores"
29
  except Exception as e:
30
+ print("Missing value of parameters", e)
31
  raise
32
+
33
  # --- Initialisation des modèles
34
  try:
35
  embedding_model = OpenAIEmbeddings(
36
+ model="text-embedding-3-large",
37
+ openai_api_key=OPENAI_API_KEY
38
+ )
39
  except Exception as e:
40
+ print("Can't init the modèle", e)
41
  raise
42
 
43
  # --- Initialisation de la base SQLite
44
+ conn = sqlite3.connect("conversations.db", check_same_thread=False)
45
  cursor = conn.cursor()
46
  cursor.execute('''
47
  CREATE TABLE IF NOT EXISTS conversations (
 
84
  )
85
  else:
86
  system_message = system_message or "Tu es un assistant IA très compétent."
87
+
88
  collection = load_collection(domain)
89
 
90
  # Validation message
 
100
  query_embedding = embedding_model.embed_query(message)
101
 
102
  # Recherche avec score dans Chroma
 
 
103
  results_with_scores = collection.similarity_search_by_vector_with_relevance_scores(query_embedding, k=3)
104
 
105
  seuil = 0.75 # seuil de similarité à ajuster
106
  for doc, score in results_with_scores:
107
  print(f"SCORE: {score:.2f} - DOC: {doc.page_content[:80]}") # affiche le début du contenu
108
+
109
  # Filtrage des résultats selon le seuil
110
  filtered_results = [doc for doc, score in results_with_scores if score >= seuil]
111
  if not filtered_results:
 
148
  except Exception as e:
149
  return [{"role": "assistant", "content": f"❌ Erreur : {e}"}]
150
 
 
151
  # --- Interface utilisateur Gradio
152
  with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {background-color: #b8c2d3;}") as app:
153
  with gr.Column(visible=True, elem_id="login-block") as login_block:
 
186
  temperature = gr.Slider(0.1, 2.0, value=0.7, label="🌡️ Température")
187
  top_p = gr.Slider(0.1, 1.0, value=0.95, label="🎯 Top-p")
188
 
 
189
  chatbot = gr.Chatbot(label="💬 Chat", type="messages", elem_id="chat-display")
190
  message_input = gr.Textbox(label="✉️ Votre message", placeholder="Tapez votre question ici...")
191
  send_button = gr.Button("🚀 Envoyer", variant="primary")
192
 
193
  def chat_submit(msg, history, domain, model_name, max_tokens, temperature, top_p):
194
  if not msg or not msg.strip():
 
195
  return history, gr.update(value=msg)
 
196
  new_history = respond(msg, history, "", domain, model_name, max_tokens, temperature, top_p)
 
197
  return new_history, gr.update(value="")
198
 
199
  send_button.click(
 
202
  outputs=[chatbot, message_input]
203
  )
204
 
 
205
  def login(username, password):
206
  if username == EXCELIS_USER and password == EXCELIS_MDP:
207
  return gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)
 
213
  outputs=[login_block, chatbot_block, error_box]
214
  )
215
 
216
+ # --- FastAPI app
217
+ app_fastapi = FastAPI()
218
+
219
+ class RequestData(BaseModel):
220
+ message: str
221
+ history: list = []
222
+ system_message: str = ""
223
+ domain: str = "corismoney"
224
+ model_name: str = "gpt-3.5-turbo"
225
+ max_tokens: int = 800
226
+ temperature: float = 0.7
227
+ top_p: float = 0.95
228
+
229
+ @app_fastapi.post("/api/respond")
230
+ async def api_respond(data: RequestData):
231
+ if not data.message.strip():
232
+ raise HTTPException(status_code=400, detail="Message vide")
233
+ history = data.history or []
234
+ response = respond(
235
+ message=data.message,
236
+ history=history,
237
+ system_message=data.system_message,
238
+ domain=data.domain,
239
+ model_name=data.model_name,
240
+ max_tokens=data.max_tokens,
241
+ temperature=data.temperature,
242
+ top_p=data.top_p
243
+ )
244
+ return {"history": response}
245
+
246
+ def start_gradio():
247
+ app.launch(server_name="0.0.0.0", server_port=7860, share=False)
248
+
249
  if __name__ == "__main__":
250
+ # Lancer Gradio dans un thread à part
251
+ threading.Thread(target=start_gradio, daemon=True).start()
252
+ # Lancer FastAPI avec uvicorn
253
+ uvicorn.run(app_fastapi, host="0.0.0.0", port=8000)