Spaces:
Running
Running
Update modules/chatbot/chat_process.py
Browse files- modules/chatbot/chat_process.py +41 -51
modules/chatbot/chat_process.py
CHANGED
@@ -2,82 +2,72 @@
|
|
2 |
import os
|
3 |
import anthropic
|
4 |
import logging
|
5 |
-
from typing import
|
6 |
|
7 |
logger = logging.getLogger(__name__)
|
8 |
|
9 |
-
####################################################
|
10 |
class ChatProcessor:
|
11 |
def __init__(self):
|
12 |
"""Inicializa el procesador de chat con la API de Claude"""
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
self.client = anthropic.Anthropic(api_key=api_key)
|
17 |
self.conversation_history = []
|
18 |
-
self.semantic_context = None
|
19 |
|
20 |
def set_semantic_context(self, text, metrics, graph_data):
|
21 |
-
"""Configura el contexto semántico para
|
22 |
self.semantic_context = {
|
23 |
-
'text_sample': text[:2000],
|
24 |
'key_concepts': metrics.get('key_concepts', []),
|
25 |
-
'
|
26 |
-
'graph_description': "Available" if graph_data else "Not available"
|
27 |
}
|
28 |
-
|
|
|
|
|
29 |
def clear_semantic_context(self):
|
30 |
"""Limpia el contexto semántico"""
|
31 |
self.semantic_context = None
|
|
|
32 |
|
33 |
def process_chat_input(self, message: str, lang_code: str) -> Generator[str, None, None]:
|
34 |
-
"""Procesa el mensaje
|
35 |
try:
|
36 |
-
#
|
37 |
if self.semantic_context:
|
38 |
system_prompt = f"""
|
39 |
-
Eres un asistente especializado en análisis semántico
|
40 |
-
|
41 |
-
|
42 |
-
- Grafo: {self.semantic_context['graph_description']}
|
43 |
|
44 |
-
Responde preguntas sobre este análisis
|
|
|
|
|
|
|
|
|
45 |
"""
|
46 |
else:
|
47 |
system_prompt = "Eres un asistente útil. Responde preguntas generales."
|
48 |
-
|
49 |
-
# Agregar mensaje
|
50 |
-
self.conversation_history.append({
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
|
|
|
|
57 |
temperature=0.7,
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
|
|
|
|
63 |
|
64 |
-
# Mantener un historial limitado
|
65 |
-
if len(self.conversation_history) > 10:
|
66 |
-
self.conversation_history = self.conversation_history[-10:]
|
67 |
-
|
68 |
-
# Dividir la respuesta en palabras para streaming
|
69 |
-
words = claude_response.split()
|
70 |
-
for word in words:
|
71 |
-
yield word + " "
|
72 |
-
|
73 |
except Exception as e:
|
74 |
logger.error(f"Error en process_chat_input: {str(e)}")
|
75 |
-
yield
|
76 |
-
|
77 |
-
def get_conversation_history(self) -> list:
|
78 |
-
"""Retorna el historial de la conversación"""
|
79 |
-
return self.conversation_history
|
80 |
-
|
81 |
-
def clear_history(self):
|
82 |
-
"""Limpia el historial de la conversación"""
|
83 |
-
self.conversation_history = []
|
|
|
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."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|