Spaces:
Sleeping
Sleeping
Update modules/chatbot/chat_process.py
Browse files- modules/chatbot/chat_process.py +73 -56
modules/chatbot/chat_process.py
CHANGED
|
@@ -1,56 +1,73 @@
|
|
| 1 |
-
# modules/chatbot/chat_process.py
|
| 2 |
-
import os
|
| 3 |
-
import anthropic
|
| 4 |
-
import logging
|
| 5 |
-
from typing import
|
| 6 |
-
|
| 7 |
-
logger = logging.getLogger(__name__)
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
self.
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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."
|