Spaces:
Sleeping
Sleeping
Update modules/chatbot/chat_process.py
Browse files- modules/chatbot/chat_process.py +110 -63
modules/chatbot/chat_process.py
CHANGED
|
@@ -1,73 +1,120 @@
|
|
| 1 |
-
# modules/chatbot/
|
| 2 |
-
import
|
| 3 |
-
import
|
|
|
|
| 4 |
import logging
|
| 5 |
-
from typing import Generator
|
| 6 |
|
| 7 |
logger = logging.getLogger(__name__)
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
'text_sample': text[:2000], # Tomamos solo un fragmento
|
| 22 |
-
'key_concepts': metrics.get('key_concepts', []),
|
| 23 |
-
'graph_data': graph_data is not None
|
| 24 |
-
}
|
| 25 |
-
# Reiniciamos el historial para el nuevo contexto
|
| 26 |
-
self.conversation_history = []
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
- Sugerencias para mejorar el texto
|
| 47 |
-
- Explicaciones sobre el gráfico semántico
|
| 48 |
-
"""
|
| 49 |
-
else:
|
| 50 |
-
system_prompt = "Eres un asistente útil. Responde preguntas generales."
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
model="claude-3-sonnet-20240229",
|
| 61 |
-
max_tokens=4000,
|
| 62 |
-
temperature=0.7,
|
| 63 |
-
system=system_prompt,
|
| 64 |
-
messages=self.conversation_history
|
| 65 |
-
) as stream:
|
| 66 |
-
for text in stream.text_stream:
|
| 67 |
-
yield text
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# modules/chatbot/sidebar_chat.py
|
| 2 |
+
import streamlit as st
|
| 3 |
+
from .chat_process import ChatProcessor
|
| 4 |
+
from ..database.chat_mongo_db import store_chat_history, get_chat_history
|
| 5 |
import logging
|
|
|
|
| 6 |
|
| 7 |
logger = logging.getLogger(__name__)
|
| 8 |
|
| 9 |
+
def display_sidebar_chat(lang_code: str, chatbot_t: dict):
|
| 10 |
+
"""
|
| 11 |
+
Muestra el chatbot en el sidebar con soporte para contexto semántico
|
| 12 |
+
"""
|
| 13 |
+
with st.sidebar:
|
| 14 |
+
# Estilos CSS para el chat
|
| 15 |
+
st.markdown("""
|
| 16 |
+
<style>
|
| 17 |
+
/* Contenedor del chat con scroll */
|
| 18 |
+
div[data-testid="stExpanderContent"] > div {
|
| 19 |
+
max-height: 60vh;
|
| 20 |
+
overflow-y: auto;
|
| 21 |
+
padding-right: 10px;
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
/* Input fijo en la parte inferior */
|
| 25 |
+
div[data-testid="stHorizontalBlock"]:has(> div[data-testid="column"]) {
|
| 26 |
+
position: sticky;
|
| 27 |
+
bottom: 0;
|
| 28 |
+
background: white;
|
| 29 |
+
padding-top: 10px;
|
| 30 |
+
z-index: 100;
|
| 31 |
+
}
|
| 32 |
+
</style>
|
| 33 |
+
""", unsafe_allow_html=True)
|
| 34 |
|
| 35 |
+
# Inicializar el procesador de chat si no existe
|
| 36 |
+
if 'chat_processor' not in st.session_state:
|
| 37 |
+
st.session_state.chat_processor = ChatProcessor()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
+
# Configurar contexto semántico si está activo
|
| 40 |
+
if st.session_state.get('semantic_agent_active', False):
|
| 41 |
+
semantic_data = st.session_state.get('semantic_agent_data')
|
| 42 |
+
if semantic_data:
|
| 43 |
+
st.session_state.chat_processor.set_semantic_context(
|
| 44 |
+
text=semantic_data['text'],
|
| 45 |
+
metrics=semantic_data['metrics'],
|
| 46 |
+
graph_data=semantic_data['graph_data']
|
| 47 |
+
)
|
| 48 |
|
| 49 |
+
with st.expander("💬 Asistente Virtual", expanded=True):
|
| 50 |
+
try:
|
| 51 |
+
# Inicializar mensajes del chat
|
| 52 |
+
if 'sidebar_messages' not in st.session_state:
|
| 53 |
+
# Mensaje inicial según el modo (normal o semántico)
|
| 54 |
+
initial_message = (
|
| 55 |
+
"¡Hola! Soy tu asistente de análisis semántico. ¿En qué puedo ayudarte?"
|
| 56 |
+
if st.session_state.get('semantic_agent_active', False)
|
| 57 |
+
else "¡Hola! ¿Cómo puedo ayudarte hoy?"
|
| 58 |
+
)
|
| 59 |
+
st.session_state.sidebar_messages = [
|
| 60 |
+
{"role": "assistant", "content": initial_message}
|
| 61 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
+
# Mostrar historial del chat
|
| 64 |
+
chat_container = st.container()
|
| 65 |
+
with chat_container:
|
| 66 |
+
for message in st.session_state.sidebar_messages:
|
| 67 |
+
with st.chat_message(message["role"]):
|
| 68 |
+
st.markdown(message["content"])
|
| 69 |
|
| 70 |
+
# Input del usuario
|
| 71 |
+
user_input = st.chat_input("Escribe tu mensaje...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
+
if user_input:
|
| 74 |
+
# Agregar mensaje del usuario
|
| 75 |
+
st.session_state.sidebar_messages.append(
|
| 76 |
+
{"role": "user", "content": user_input}
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
# Mostrar mensaje del usuario
|
| 80 |
+
with chat_container:
|
| 81 |
+
with st.chat_message("user"):
|
| 82 |
+
st.markdown(user_input)
|
| 83 |
+
|
| 84 |
+
# Mostrar respuesta del asistente
|
| 85 |
+
with st.chat_message("assistant"):
|
| 86 |
+
response_placeholder = st.empty()
|
| 87 |
+
full_response = ""
|
| 88 |
+
|
| 89 |
+
# Obtener respuesta del procesador
|
| 90 |
+
for chunk in st.session_state.chat_processor.process_chat_input(
|
| 91 |
+
user_input,
|
| 92 |
+
lang_code
|
| 93 |
+
):
|
| 94 |
+
full_response += chunk
|
| 95 |
+
response_placeholder.markdown(full_response + "▌")
|
| 96 |
+
|
| 97 |
+
response_placeholder.markdown(full_response)
|
| 98 |
+
|
| 99 |
+
# Guardar respuesta
|
| 100 |
+
st.session_state.sidebar_messages.append(
|
| 101 |
+
{"role": "assistant", "content": full_response}
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
# Guardar en base de datos
|
| 105 |
+
store_chat_history(
|
| 106 |
+
username=st.session_state.username,
|
| 107 |
+
messages=st.session_state.sidebar_messages,
|
| 108 |
+
chat_type='semantic' if st.session_state.get('semantic_agent_active') else 'general'
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
# Botón para limpiar el chat
|
| 112 |
+
if st.button("🔄 Limpiar conversación"):
|
| 113 |
+
st.session_state.sidebar_messages = [
|
| 114 |
+
{"role": "assistant", "content": "¡Hola! ¿En qué puedo ayudarte?"}
|
| 115 |
+
]
|
| 116 |
+
st.rerun()
|
| 117 |
+
|
| 118 |
+
except Exception as e:
|
| 119 |
+
logger.error(f"Error en el chat: {str(e)}")
|
| 120 |
+
st.error("Ocurrió un error en el chat. Por favor, inténtalo de nuevo.")
|