alemarino2025 commited on
Commit
b2ffe57
·
verified ·
1 Parent(s): e4eadfa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -66
app.py CHANGED
@@ -16,17 +16,6 @@ install("datasets")
16
  install ("ipywidgets")
17
 
18
 
19
- #!pip install -q openai==1.23.2 \
20
- # gcsfs>=2023.3.0 \
21
- # tiktoken==0.6.0 \
22
- # pypdf==4.0.1 \
23
- # langchain==0.1.9 \
24
- # langchain-community==0.0.32 \
25
- # chromadb==0.4.22 \
26
- # sentence-transformers==2.3.1 \
27
- # datasets
28
-
29
-
30
  ## Setup
31
  # Import the necessary Libraries
32
  import json
@@ -57,18 +46,6 @@ client = Groq(
57
  )
58
 
59
 
60
-
61
-
62
- #chat_completion = client.chat.completions.create(
63
- # messages=[
64
- # {
65
- # "role": "user",
66
- # "content": "Explain the importance of fast language models"
67
- # }
68
- #],
69
- # model="llama3-8b-8192",
70
- #)
71
-
72
  # Define the embedding model and the vectorstore
73
  embedding_model= SentenceTransformerEmbeddings(model_name="thenlper/gte-large")
74
 
@@ -123,22 +100,23 @@ Il contesto contiene riferimenti a parti specifiche di documenti pertinenti alla
123
  La fonte per il contesto inizierà con il token ###Pagina
124
 
125
  Quando crei le tue risposte:
126
- 1. Seleziona solo il contesto pertinente per rispondere alla domanda.
127
  2. Segui gli step indicati in precedenza ma non indicare il numero di step nè lo step che stai seguendo.
128
  3. Usa un tono comunicativo: Deve essere rassicurante, flessibile e basato sull’empatia.
129
- 4. Riconosci il contesto: Adatta il linguaggio al livello agonistico, all’età e agli obiettivi dell’atleta.
130
  5. Personalizza: Ogni atleta è unico, devi proporre soluzioni su misura partendo dalle informazioni raccolte.
131
  6. E' molto molto importante che faccia un massimo di due domande alla volta all'utente. Poi aspetta la sua risposta e utilizza la risposta come input per andare avanti nella tua procedura.
 
 
132
  Le domande dell'utente inizieranno con il token: ###Domanda.
133
  Se la domanda è irrilevante o se il contesto è vuoto - "Mi dispiace, questo è fuori dalla mia knowledge base"
134
 
135
-
136
-
137
-
138
  """
139
 
140
  # Define the user message template
 
141
  qna_user_message_template = """
 
142
  ###Context
143
  Here are some documents and their page number that are relevant to the question mentioned below.
144
  (context)
@@ -155,9 +133,6 @@ Here are some documents and their page number that are relevant to the question
155
  class TimeoutException(Exception):
156
  pass
157
 
158
- def alarm_handler(signum, frame):
159
- raise TimeoutException("Timed out!")
160
-
161
  # Define the function that will be called when the user submits its feedback (to be called in Gradio)
162
  def save_feedback(user_input:str, context_for_query: str, prediction:str) -> None:
163
  """
@@ -168,20 +143,14 @@ def save_feedback(user_input:str, context_for_query: str, prediction:str) -> Non
168
  f.write(json.dumps({"user_input": user_input,"retrieved_context": context_for_query,"model_response": prediction}))
169
  f.write("\n")
170
 
171
- # json_data = {
172
- # "user_input": user_input,
173
- # "retrieved_context": context_for_query,
174
- # "model_response": prediction
175
- # }
176
-
177
-
178
  # Initialize conversation history
 
179
  conversation_history = []
180
 
181
  def predict(user_input, timeout_seconds=1800): # 30 minutes = 1800 seconds
182
 
183
  filter = "/content/drive/My Drive/Colab Notebooks/medical/Conoscenze-unito.pdf"
184
- relevant_document_chunks = vectorstore.similarity_search(user_input, k=10)
185
  context_list = [d.page_content + "\ ###Page: " + str(d.metadata['page']) + "\n\n " for d in relevant_document_chunks]
186
  context_for_query = ".".join(context_list) + "this is all the context I have"
187
 
@@ -190,29 +159,22 @@ def predict(user_input, timeout_seconds=1800): # 30 minutes = 1800 seconds
190
  conversation_history.append({"role": "user", "content": user_input})
191
 
192
  # Prepare the prompt with conversation history
 
193
  current_prompt = [
194
  {'role': 'system','content': qna_system_message},
195
- {'role': 'user','content': qna_user_message_template.format(
196
- context=context_for_query,
197
- question=user_input
198
- )
199
- }
200
  ]
 
201
  current_prompt.extend(conversation_history)
202
 
203
- # Set signal handler
204
- #signal.signal(signal.SIGALRM, alarm_handler)
205
- #signal.alarm(timeout_seconds) # Produce SIGALRM in `timeout_seconds` seconds
206
-
207
  try:
208
  chat_completion = client.chat.completions.create(
209
  messages=current_prompt,
210
  model="deepseek-r1-distill-llama-70b", # Replace with your actual model name llama3-8b-8192 deepseek-r1-distill-llama-70b
211
  )
212
  bot_response = chat_completion.choices[0].message.content
 
213
  conversation_history.append({"role": "assistant", "content": bot_response})
214
- # signal.alarm(0) # Cancel the alarm
215
- #return bot_response
216
 
217
  except TimeoutException:
218
  print("The request timed out.")
@@ -224,28 +186,13 @@ def predict(user_input, timeout_seconds=1800): # 30 minutes = 1800 seconds
224
  # signal.alarm(0) # Cancel the alarm
225
  return "An error occurred during the conversation."
226
 
227
- #while True:
228
- # response = chat_with_bot_timeout(user_input)
229
- #print("Mat:", response)
230
-
231
- # user_input = input("You: ")
232
- # if user_input.lower() in ["quit", "exit"]:
233
- # break
234
-
235
  prediction = bot_response
236
 
237
  #prediction = bot_response.choices[0].message.content.strip()
238
 
239
  save_feedback(user_input, context_for_query, prediction)
240
 
241
- #except Exception as e:
242
- # prediction = str(e)
243
-
244
- # While the prediction is made, log boh the inputs and outputs to a local log file
245
- # while writing to the log file, ensure that the commit scheduler is locked to avoid parallel
246
- # access
247
-
248
- return prediction
249
 
250
  # Set-up the Gradio UI
251
  # Add text box.
 
16
  install ("ipywidgets")
17
 
18
 
 
 
 
 
 
 
 
 
 
 
 
19
  ## Setup
20
  # Import the necessary Libraries
21
  import json
 
46
  )
47
 
48
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  # Define the embedding model and the vectorstore
50
  embedding_model= SentenceTransformerEmbeddings(model_name="thenlper/gte-large")
51
 
 
100
  La fonte per il contesto inizierà con il token ###Pagina
101
 
102
  Quando crei le tue risposte:
103
+ 1. Per rispondere all'utente basati principalmente sul contesto fornito nell'input che inizia con il token ###Contesto e in aggiunta usa anche le tue conoscenze di psicologia clinica.
104
  2. Segui gli step indicati in precedenza ma non indicare il numero di step nè lo step che stai seguendo.
105
  3. Usa un tono comunicativo: Deve essere rassicurante, flessibile e basato sull’empatia.
106
+ 4. Adatta il linguaggio al livello agonistico, all’età e agli obiettivi dell’atleta.
107
  5. Personalizza: Ogni atleta è unico, devi proporre soluzioni su misura partendo dalle informazioni raccolte.
108
  6. E' molto molto importante che faccia un massimo di due domande alla volta all'utente. Poi aspetta la sua risposta e utilizza la risposta come input per andare avanti nella tua procedura.
109
+ 7. Per ogni domanda successiva progredisci nei sei step in modo che la conversazione non si dilunghi eccessivamente.
110
+
111
  Le domande dell'utente inizieranno con il token: ###Domanda.
112
  Se la domanda è irrilevante o se il contesto è vuoto - "Mi dispiace, questo è fuori dalla mia knowledge base"
113
 
 
 
 
114
  """
115
 
116
  # Define the user message template
117
+
118
  qna_user_message_template = """
119
+
120
  ###Context
121
  Here are some documents and their page number that are relevant to the question mentioned below.
122
  (context)
 
133
  class TimeoutException(Exception):
134
  pass
135
 
 
 
 
136
  # Define the function that will be called when the user submits its feedback (to be called in Gradio)
137
  def save_feedback(user_input:str, context_for_query: str, prediction:str) -> None:
138
  """
 
143
  f.write(json.dumps({"user_input": user_input,"retrieved_context": context_for_query,"model_response": prediction}))
144
  f.write("\n")
145
 
 
 
 
 
 
 
 
146
  # Initialize conversation history
147
+
148
  conversation_history = []
149
 
150
  def predict(user_input, timeout_seconds=1800): # 30 minutes = 1800 seconds
151
 
152
  filter = "/content/drive/My Drive/Colab Notebooks/medical/Conoscenze-unito.pdf"
153
+ relevant_document_chunks = vectorstore.similarity_search(user_input, k=5)
154
  context_list = [d.page_content + "\ ###Page: " + str(d.metadata['page']) + "\n\n " for d in relevant_document_chunks]
155
  context_for_query = ".".join(context_list) + "this is all the context I have"
156
 
 
159
  conversation_history.append({"role": "user", "content": user_input})
160
 
161
  # Prepare the prompt with conversation history
162
+
163
  current_prompt = [
164
  {'role': 'system','content': qna_system_message},
165
+ {'role': 'user','content': qna_user_message_template.format(context=context_for_query, question=user_input)}
 
 
 
 
166
  ]
167
+
168
  current_prompt.extend(conversation_history)
169
 
 
 
 
 
170
  try:
171
  chat_completion = client.chat.completions.create(
172
  messages=current_prompt,
173
  model="deepseek-r1-distill-llama-70b", # Replace with your actual model name llama3-8b-8192 deepseek-r1-distill-llama-70b
174
  )
175
  bot_response = chat_completion.choices[0].message.content
176
+
177
  conversation_history.append({"role": "assistant", "content": bot_response})
 
 
178
 
179
  except TimeoutException:
180
  print("The request timed out.")
 
186
  # signal.alarm(0) # Cancel the alarm
187
  return "An error occurred during the conversation."
188
 
 
 
 
 
 
 
 
 
189
  prediction = bot_response
190
 
191
  #prediction = bot_response.choices[0].message.content.strip()
192
 
193
  save_feedback(user_input, context_for_query, prediction)
194
 
195
+ return prediction, conversation_history
 
 
 
 
 
 
 
196
 
197
  # Set-up the Gradio UI
198
  # Add text box.