Spaces:
Running
Running
# modules/chatbot/sidebar_chat.py | |
import streamlit as st | |
from .chat_process import ChatProcessor | |
from ..database.chat_mongo_db import store_chat_history, get_chat_history | |
import logging | |
logger = logging.getLogger(__name__) | |
def display_sidebar_chat(lang_code: str, chatbot_t: dict): | |
""" | |
Muestra el chatbot en el sidebar con soporte para contexto semántico | |
""" | |
with st.sidebar: | |
# Estilos CSS para el chat | |
st.markdown(""" | |
<style> | |
/* Contenedor del chat con scroll */ | |
div[data-testid="stExpanderContent"] > div { | |
max-height: 60vh; | |
overflow-y: auto; | |
padding-right: 10px; | |
} | |
/* Input fijo en la parte inferior */ | |
div[data-testid="stHorizontalBlock"]:has(> div[data-testid="column"]) { | |
position: sticky; | |
bottom: 0; | |
background: white; | |
padding-top: 10px; | |
z-index: 100; | |
} | |
</style> | |
""", unsafe_allow_html=True) | |
# Inicializar el procesador de chat si no existe | |
if 'chat_processor' not in st.session_state: | |
st.session_state.chat_processor = ChatProcessor() | |
# Configurar contexto semántico si está activo | |
if st.session_state.get('semantic_agent_active', False): | |
semantic_data = st.session_state.get('semantic_agent_data') | |
if semantic_data: | |
st.session_state.chat_processor.set_semantic_context( | |
text=semantic_data['text'], | |
metrics=semantic_data['metrics'], | |
graph_data=semantic_data['graph_data'] | |
) | |
with st.expander("💬 Asistente Virtual", expanded=True): | |
try: | |
# Inicializar mensajes del chat | |
if 'sidebar_messages' not in st.session_state: | |
# Mensaje inicial según el modo (normal o semántico) | |
initial_message = ( | |
"¡Hola! Soy tu asistente de análisis semántico. ¿En qué puedo ayudarte?" | |
if st.session_state.get('semantic_agent_active', False) | |
else "¡Hola! ¿Cómo puedo ayudarte hoy?" | |
) | |
st.session_state.sidebar_messages = [ | |
{"role": "assistant", "content": initial_message} | |
] | |
# Mostrar historial del chat | |
chat_container = st.container() | |
with chat_container: | |
for message in st.session_state.sidebar_messages: | |
with st.chat_message(message["role"]): | |
st.markdown(message["content"]) | |
# Input del usuario | |
user_input = st.chat_input("Escribe tu mensaje...") | |
if user_input: | |
# Agregar mensaje del usuario | |
st.session_state.sidebar_messages.append( | |
{"role": "user", "content": user_input} | |
) | |
# Mostrar mensaje del usuario | |
with chat_container: | |
with st.chat_message("user"): | |
st.markdown(user_input) | |
# Mostrar respuesta del asistente | |
with st.chat_message("assistant"): | |
response_placeholder = st.empty() | |
full_response = "" | |
# Obtener respuesta del procesador | |
for chunk in st.session_state.chat_processor.process_chat_input( | |
user_input, | |
lang_code | |
): | |
full_response += chunk | |
response_placeholder.markdown(full_response + "▌") | |
response_placeholder.markdown(full_response) | |
# Guardar respuesta | |
st.session_state.sidebar_messages.append( | |
{"role": "assistant", "content": full_response} | |
) | |
# Guardar en base de datos | |
store_chat_history( | |
username=st.session_state.username, | |
messages=st.session_state.sidebar_messages, | |
chat_type='semantic' if st.session_state.get('semantic_agent_active') else 'general' | |
) | |
# Botón para limpiar el chat | |
if st.button("🔄 Limpiar conversación"): | |
st.session_state.sidebar_messages = [ | |
{"role": "assistant", "content": "¡Hola! ¿En qué puedo ayudarte?"} | |
] | |
st.rerun() | |
except Exception as e: | |
logger.error(f"Error en el chat: {str(e)}") | |
st.error("Ocurrió un error en el chat. Por favor, inténtalo de nuevo.") |