AIdeaText commited on
Commit
fd4e7a7
·
verified ·
1 Parent(s): 44b566a

Update modules/chatbot/chat_process.py

Browse files
Files changed (1) hide show
  1. modules/chatbot/chat_process.py +110 -63
modules/chatbot/chat_process.py CHANGED
@@ -1,73 +1,120 @@
1
- # modules/chatbot/chat_process.py
2
- import os
3
- import anthropic
 
4
  import logging
5
- from typing import Generator
6
 
7
  logger = logging.getLogger(__name__)
8
 
9
- class ChatProcessor:
10
- def __init__(self):
11
- """Inicializa el procesador de chat con la API de Claude"""
12
- self.client = anthropic.Anthropic(
13
- api_key=os.environ.get("ANTHROPIC_API_KEY")
14
- )
15
- self.conversation_history = []
16
- self.semantic_context = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- def set_semantic_context(self, text, metrics, graph_data):
19
- """Configura el contexto semántico para el chat"""
20
- self.semantic_context = {
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
- def clear_semantic_context(self):
29
- """Limpia el contexto semántico"""
30
- self.semantic_context = None
31
- self.conversation_history = []
 
 
 
 
 
32
 
33
- def process_chat_input(self, message: str, lang_code: str) -> Generator[str, None, None]:
34
- """Procesa el mensaje del usuario y genera la respuesta"""
35
- try:
36
- # Construir el prompt del sistema según el contexto
37
- if self.semantic_context:
38
- system_prompt = f"""
39
- Eres un asistente especializado en análisis semántico de textos.
40
- El usuario ha analizado un texto con los siguientes conceptos clave:
41
- {', '.join([c[0] for c in self.semantic_context['key_concepts'][:5]])}
42
-
43
- Responde preguntas específicas sobre este análisis, incluyendo:
44
- - Interpretación de conceptos clave
45
- - Relaciones entre conceptos
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
- # Agregar mensaje al historial
53
- self.conversation_history.append({
54
- "role": "user",
55
- "content": message
56
- })
 
57
 
58
- # Llamar a la API de Claude
59
- with anthropic.Anthropic().messages.stream(
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
- # Actualizar historial (la API lo hace automáticamente)
70
-
71
- except Exception as e:
72
- logger.error(f"Error en process_chat_input: {str(e)}")
73
- yield "Lo siento, ocurrió un error al procesar tu mensaje. Por favor, inténtalo de nuevo."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.")