Spaces:
Running
Running
Upload 12 files
Browse files
app.py
CHANGED
@@ -25,101 +25,76 @@ def is_greeting(text):
|
|
25 |
# Función para procesar mensajes (unifica la lógica de procesamiento)
|
26 |
def process_message(prompt, is_example=False):
|
27 |
"""Procesa un mensaje del usuario, ya sea directo o de un ejemplo"""
|
28 |
-
#
|
29 |
-
|
30 |
-
# Es una nueva conversación, generemos un título basado en el primer mensaje
|
31 |
-
temp_title = f'SesiónChat-{state.chat_id}'
|
32 |
-
past_chats[state.chat_id] = temp_title
|
33 |
-
|
34 |
-
# Generar título para el chat
|
35 |
-
generated_title = state.generate_chat_title(prompt)
|
36 |
-
|
37 |
-
# Actualizamos el título en past_chats
|
38 |
-
if generated_title:
|
39 |
-
state.chat_title = generated_title
|
40 |
-
past_chats[state.chat_id] = generated_title
|
41 |
-
else:
|
42 |
-
state.chat_title = temp_title
|
43 |
-
else:
|
44 |
-
# Ya existe esta conversación, usamos el título guardado
|
45 |
-
state.chat_title = past_chats[state.chat_id]
|
46 |
-
|
47 |
-
joblib.dump(past_chats, 'data/past_chats_list')
|
48 |
|
49 |
-
# Mostrar mensaje del usuario
|
50 |
with st.chat_message('user', avatar=USER_AVATAR_ICON):
|
51 |
st.markdown(prompt)
|
52 |
-
|
53 |
-
# Añadir mensaje del usuario al historial
|
54 |
state.add_message('user', prompt, USER_AVATAR_ICON)
|
55 |
|
56 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
if is_greeting(prompt):
|
58 |
-
|
59 |
-
enhanced_prompt = f"El usuario te ha saludado con '{prompt}'. Preséntate brevemente, explica qué es una PUV en 1-2 líneas, y haz 1-2 preguntas iniciales para comenzar a crear la PUV del usuario (como a quién se dirige su producto/servicio o qué ofrece). Sé amigable, breve y toma la iniciativa como el experto que eres."
|
60 |
elif is_example:
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
with st.chat_message(MODEL_ROLE, avatar=AI_AVATAR_ICON):
|
68 |
try:
|
69 |
-
# Configurar el placeholder y el indicador de escritura
|
70 |
message_placeholder = st.empty()
|
71 |
typing_indicator = st.empty()
|
72 |
typing_indicator.markdown("*Generando respuesta...*")
|
73 |
|
74 |
-
# Usar el nuevo método send_message
|
75 |
response = state.send_message(enhanced_prompt)
|
|
|
76 |
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
try:
|
81 |
-
for chunk in response:
|
82 |
-
if chunk.text: # Verificar que hay texto en el chunk
|
83 |
-
for ch in chunk.text:
|
84 |
-
full_response += ch
|
85 |
-
time.sleep(0.01)
|
86 |
-
# Mantener el indicador mientras se escribe
|
87 |
-
typing_indicator.markdown("*Generando respuesta...*")
|
88 |
-
message_placeholder.markdown(full_response + '▌')
|
89 |
-
except Exception as e:
|
90 |
-
st.error(f"Error en el streaming: {str(e)}")
|
91 |
-
return
|
92 |
-
|
93 |
-
# Limpiar el indicador de escritura al finalizar
|
94 |
-
typing_indicator.empty()
|
95 |
-
|
96 |
-
# Mostrar respuesta final
|
97 |
-
message_placeholder.markdown(full_response)
|
98 |
-
|
99 |
-
# Actualizar el historial
|
100 |
-
state.add_message(
|
101 |
-
role=MODEL_ROLE,
|
102 |
-
content=full_response,
|
103 |
-
avatar=AI_AVATAR_ICON
|
104 |
-
)
|
105 |
-
|
106 |
-
# Guardar el historial actualizado
|
107 |
state.save_chat_history()
|
108 |
|
109 |
except Exception as e:
|
110 |
st.error(f"Error: {str(e)}")
|
111 |
-
return
|
112 |
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
# state.save_chat_history() # Esta es la línea que causa el error
|
117 |
-
|
118 |
try:
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
123 |
|
124 |
# Función para cargar CSS personalizado
|
125 |
def load_css(file_path):
|
|
|
25 |
# Función para procesar mensajes (unifica la lógica de procesamiento)
|
26 |
def process_message(prompt, is_example=False):
|
27 |
"""Procesa un mensaje del usuario, ya sea directo o de un ejemplo"""
|
28 |
+
# Manejar el título del chat
|
29 |
+
handle_chat_title(prompt)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
|
31 |
+
# Mostrar y guardar mensaje del usuario
|
32 |
with st.chat_message('user', avatar=USER_AVATAR_ICON):
|
33 |
st.markdown(prompt)
|
|
|
|
|
34 |
state.add_message('user', prompt, USER_AVATAR_ICON)
|
35 |
|
36 |
+
# Obtener el prompt mejorado
|
37 |
+
enhanced_prompt = get_enhanced_prompt(prompt, is_example)
|
38 |
+
|
39 |
+
# Procesar respuesta del modelo
|
40 |
+
process_model_response(enhanced_prompt)
|
41 |
+
|
42 |
+
def handle_chat_title(prompt):
|
43 |
+
"""Maneja la lógica del título del chat"""
|
44 |
+
if state.chat_id not in past_chats:
|
45 |
+
temp_title = f'SesiónChat-{state.chat_id}'
|
46 |
+
generated_title = state.generate_chat_title(prompt)
|
47 |
+
state.chat_title = generated_title or temp_title
|
48 |
+
past_chats[state.chat_id] = state.chat_title
|
49 |
+
else:
|
50 |
+
state.chat_title = past_chats[state.chat_id]
|
51 |
+
joblib.dump(past_chats, 'data/past_chats_list')
|
52 |
+
|
53 |
+
def get_enhanced_prompt(prompt, is_example):
|
54 |
+
"""Genera el prompt mejorado según el tipo de mensaje"""
|
55 |
if is_greeting(prompt):
|
56 |
+
return f"El usuario te ha saludado con '{prompt}'. Preséntate brevemente, explica qué es una PUV en 1-2 líneas, y haz 1-2 preguntas iniciales para comenzar a crear la PUV del usuario (como a quién se dirige su producto/servicio o qué ofrece). Sé amigable, breve y toma la iniciativa como el experto que eres."
|
|
|
57 |
elif is_example:
|
58 |
+
return f"El usuario ha seleccionado un ejemplo: '{prompt}'. Responde de manera conversacional y sencilla, como si estuvieras hablando con un amigo. Evita tecnicismos innecesarios. Enfócate en dar información práctica que ayude al usuario a crear su PUV. Usa ejemplos concretos cuando sea posible. Termina tu respuesta con una pregunta que invite al usuario a compartir información sobre su negocio para poder ayudarle a crear su PUV personalizada."
|
59 |
+
return prompt
|
60 |
+
|
61 |
+
def process_model_response(enhanced_prompt):
|
62 |
+
"""Procesa la respuesta del modelo"""
|
|
|
63 |
with st.chat_message(MODEL_ROLE, avatar=AI_AVATAR_ICON):
|
64 |
try:
|
|
|
65 |
message_placeholder = st.empty()
|
66 |
typing_indicator = st.empty()
|
67 |
typing_indicator.markdown("*Generando respuesta...*")
|
68 |
|
|
|
69 |
response = state.send_message(enhanced_prompt)
|
70 |
+
full_response = stream_response(response, message_placeholder, typing_indicator)
|
71 |
|
72 |
+
# Actualizar historial
|
73 |
+
state.add_message(role=MODEL_ROLE, content=full_response, avatar=AI_AVATAR_ICON)
|
74 |
+
state.gemini_history = state.chat.history
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
75 |
state.save_chat_history()
|
76 |
|
77 |
except Exception as e:
|
78 |
st.error(f"Error: {str(e)}")
|
|
|
79 |
|
80 |
+
def stream_response(response, message_placeholder, typing_indicator):
|
81 |
+
"""Maneja el streaming de la respuesta"""
|
82 |
+
full_response = ''
|
|
|
|
|
83 |
try:
|
84 |
+
for chunk in response:
|
85 |
+
if chunk.text:
|
86 |
+
for ch in chunk.text:
|
87 |
+
full_response += ch
|
88 |
+
time.sleep(0.01)
|
89 |
+
typing_indicator.markdown("*Generando respuesta...*")
|
90 |
+
message_placeholder.markdown(full_response + '▌')
|
91 |
+
except Exception as e:
|
92 |
+
st.error(f"Error en el streaming: {str(e)}")
|
93 |
+
return ''
|
94 |
+
|
95 |
+
typing_indicator.empty()
|
96 |
+
message_placeholder.markdown(full_response)
|
97 |
+
return full_response
|
98 |
|
99 |
# Función para cargar CSS personalizado
|
100 |
def load_css(file_path):
|