Skip to content

Commit d9b4e71

Browse files
IA2
1 parent 3e70420 commit d9b4e71

File tree

1 file changed

+87
-50
lines changed

1 file changed

+87
-50
lines changed

Diff for: app.py

+87-50
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,6 @@ def load_transportation_data(company_name):
175175

176176
def make_api_call(user_input, project_id, documents, retries=3, delay=2):
177177
try:
178-
#context_supabase = "\n".join([doc["content"] for doc in documents])
179178
context = []
180179
if any(keyword in user_input.lower() for keyword in ['seguridad', 'policia', 'emergencia', 'telefono']):
181180
with open("rag/policia.txt", "r") as file:
@@ -216,29 +215,46 @@ def make_api_call(user_input, project_id, documents, retries=3, delay=2):
216215
context_text = "\n\n".join(context)
217216

218217
for attempt in range(retries):
219-
completion = client.chat.completions.create(
220-
extra_headers={
221-
"HTTP-Referer": "<YOUR_SITE_URL>", # Optional. Site URL for rankings on openrouter.ai.
222-
"X-Title": "<YOUR_SITE_NAME>", # Optional. Site title for rankings on openrouter.ai.
223-
},
224-
extra_body={},
225-
model="deepseek/deepseek-chat:free",
226-
messages=[
227-
{
228-
"role": "system",
229-
"content": "Vos sos Deltix, el bot del humedal. Eres argentino y amable. Ingresando algunas de estas palabras el usuario puede obtener información útil: mareas: obtener el pronóstico de mareas, windguru: pronóstico meteorológico de windgurú, Colectivas: horarios de lanchas colectivas, memes: ver los memes más divertidos de la isla, clima/pronostico: información meteorológica actualizada, almaceneras: información sobre almacenes de la isla. Si hay información de contexto, intenta responder con esa información o guia al usuario para que ingrese las palabras clave"
218+
try:
219+
response_stream = client.chat.completions.create(
220+
extra_headers={
221+
"HTTP-Referer": "<YOUR_SITE_URL>", # Optional. Site URL for rankings on openrouter.ai.
222+
"X-Title": "<YOUR_SITE_NAME>", # Optional. Site title for rankings on openrouter.ai.
230223
},
231-
{
232-
"role": "user",
233-
"content": f"{user_input}\n\nMensajes anteriores:\n{previous_messages_content}\n\nContexto:\n{context_text}"
234-
}
235-
]
236-
)
237-
response_content = completion.choices[0].message.content
238-
if response_content.strip():
239-
return response_content
240-
time.sleep(delay)
241-
raise ValueError("Received empty response from OpenRouter API after multiple attempts")
224+
extra_body={},
225+
model="deepseek/deepseek-chat:free",
226+
messages=[
227+
{
228+
"role": "system",
229+
"content": "Vos sos Deltix, el bot del humedal. Eres argentino y amable. Ingresando algunas de estas palabras el usuario puede obtener información útil: mareas: obtener el pronóstico de mareas, windguru: pronóstico meteorológico de windgurú, Colectivas: horarios de lanchas colectivas, memes: ver los memes más divertidos de la isla, clima/pronostico: información meteorológica actualizada, almaceneras: información sobre almacenes de la isla. Si hay información de contexto, intenta responder con esa información o guia al usuario para que ingrese las palabras clave"
230+
},
231+
{
232+
"role": "user",
233+
"content": f"{user_input}\n\nMensajes anteriores:\n{previous_messages_content}\n\nContexto:\n{context_text}"
234+
}
235+
],
236+
stream=True # Enable streaming
237+
)
238+
239+
full_response = ""
240+
for chunk in response_stream:
241+
if chunk.choices and chunk.choices[0].delta and chunk.choices[0].delta.content:
242+
content = chunk.choices[0].delta.content
243+
full_response += content
244+
yield full_response # Yield incremental content
245+
246+
if not full_response.strip():
247+
if attempt == retries - 1:
248+
raise ValueError("Received empty response from OpenRouter API after multiple attempts")
249+
time.sleep(delay)
250+
else:
251+
# Store the final response
252+
return full_response
253+
except Exception as e:
254+
if attempt == retries - 1:
255+
raise e
256+
time.sleep(delay)
257+
242258
except Exception as e:
243259
raise e
244260

@@ -501,53 +517,74 @@ def colectivas():
501517
colectivas()
502518
elif st.session_state.get("colectivas_step"):
503519
if not handle_colectivas_input(user_input):
504-
# Create a placeholder for the "thinking" message
520+
# Create a placeholder for the streaming response
505521
with st.chat_message("assistant", avatar="bot_icon.png"):
506-
thinking_placeholder = st.empty()
507-
thinking_placeholder.write("deltix pensando...")
522+
message_placeholder = st.empty()
508523

509524
try:
510525
documents = []
511-
bot_reply = make_api_call(user_input, project_id, documents)
512-
# Replace with actual response
513-
thinking_placeholder.write(bot_reply)
514-
st.session_state.chat_messages.append({"role": "assistant", "content": bot_reply})
515-
store_chat_message(project_id, "assistant", bot_reply)
526+
full_response = ""
527+
528+
# Stream the response
529+
for streamed_response in make_api_call(user_input, project_id, documents):
530+
message_placeholder.markdown(streamed_response + "▌")
531+
full_response = streamed_response
532+
533+
# Display the final response without the cursor
534+
message_placeholder.markdown(full_response)
535+
536+
# Add to chat history and store in database
537+
st.session_state.chat_messages.append({"role": "assistant", "content": full_response})
538+
store_chat_message(project_id, "assistant", full_response)
516539
except Exception as e:
517540
error_msg = f"Error: {e}"
518-
thinking_placeholder.error(error_msg)
541+
message_placeholder.error(error_msg)
519542
st.session_state.chat_messages.append({"role": "assistant", "content": error_msg})
520543
elif contains_weather_keywords(user_input):
521-
# Create a placeholder for the "thinking" message
544+
# Create a placeholder for streaming response
522545
with st.chat_message("assistant", avatar="bot_icon.png"):
523-
thinking_placeholder = st.empty()
524-
thinking_placeholder.write("deltix pensando...")
546+
message_placeholder = st.empty()
525547

526548
try:
527549
documents = []
528-
bot_reply = make_api_call(user_input, project_id, documents)
529-
# Replace with actual response
530-
thinking_placeholder.write(bot_reply)
531-
st.session_state.chat_messages.append({"role": "assistant", "content": bot_reply})
532-
store_chat_message(project_id, "assistant", bot_reply)
550+
full_response = ""
551+
552+
# Stream the response
553+
for streamed_response in make_api_call(user_input, project_id, documents):
554+
message_placeholder.markdown(streamed_response + "▌")
555+
full_response = streamed_response
556+
557+
# Display the final response without the cursor
558+
message_placeholder.markdown(full_response)
559+
560+
# Add to chat history and store in database
561+
st.session_state.chat_messages.append({"role": "assistant", "content": full_response})
562+
store_chat_message(project_id, "assistant", full_response)
533563
except Exception as e:
534564
error_msg = f"Error: {e}"
535-
thinking_placeholder.error(error_msg)
565+
message_placeholder.error(error_msg)
536566
st.session_state.chat_messages.append({"role": "assistant", "content": error_msg})
537567
else:
538-
# Create a placeholder for the "thinking" message
568+
# Create a placeholder for streaming response
539569
with st.chat_message("assistant", avatar="bot_icon.png"):
540-
thinking_placeholder = st.empty()
541-
thinking_placeholder.write("deltix pensando...")
570+
message_placeholder = st.empty()
542571

543572
try:
544573
documents = []
545-
bot_reply = make_api_call(user_input, project_id, documents)
546-
# Replace with actual response
547-
thinking_placeholder.write(bot_reply)
548-
st.session_state.chat_messages.append({"role": "assistant", "content": bot_reply})
549-
store_chat_message(project_id, "assistant", bot_reply)
574+
full_response = ""
575+
576+
# Stream the response
577+
for streamed_response in make_api_call(user_input, project_id, documents):
578+
message_placeholder.markdown(streamed_response + "▌")
579+
full_response = streamed_response
580+
581+
# Display the final response without the cursor
582+
message_placeholder.markdown(full_response)
583+
584+
# Add to chat history and store in database
585+
st.session_state.chat_messages.append({"role": "assistant", "content": full_response})
586+
store_chat_message(project_id, "assistant", full_response)
550587
except Exception as e:
551588
error_msg = f"Error: {e}"
552-
thinking_placeholder.error(error_msg)
589+
message_placeholder.error(error_msg)
553590
st.session_state.chat_messages.append({"role": "assistant", "content": error_msg})

0 commit comments

Comments
 (0)