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

Update modules/chatbot/chat_process.py

Browse files
Files changed (1) hide show
  1. 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 Dict, Generator
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
- api_key = os.environ.get("ANTHROPIC_API_KEY")
14
- if not api_key:
15
- raise ValueError("No se encontró la clave API de Anthropic. Asegúrate de configurarla en las variables de entorno.")
16
- self.client = anthropic.Anthropic(api_key=api_key)
17
- self.conversation_history = []
18
-
19
- def process_chat_input(self, message: str, lang_code: str) -> Generator[str, None, None]:
20
- """Procesa el mensaje y genera una respuesta"""
21
- try:
22
- # Agregar mensaje a la historia
23
- self.conversation_history.append({"role": "user", "content": message})
24
-
25
- # Generar respuesta usando la API de Claude
26
- response = self.client.messages.create(
27
- model="claude-3-5-sonnet-20241022",
28
- messages=self.conversation_history,
29
- max_tokens=8000, # Añadimos este parámetro requerido
30
- temperature=0.7,
31
- )
32
-
33
- # Procesar la respuesta
34
- claude_response = response.content[0].text
35
- self.conversation_history.append({"role": "assistant", "content": claude_response})
36
-
37
- # Mantener un historial limitado
38
- if len(self.conversation_history) > 10:
39
- self.conversation_history = self.conversation_history[-10:]
40
-
41
- # Dividir la respuesta en palabras para streaming
42
- words = claude_response.split()
43
- for word in words:
44
- yield word + " "
45
-
46
- except Exception as e:
47
- logger.error(f"Error en process_chat_input: {str(e)}")
48
- yield f"Error: {str(e)}"
49
-
50
- def get_conversation_history(self) -> list:
51
- """Retorna el historial de la conversación"""
52
- return self.conversation_history
53
-
54
- def clear_history(self):
55
- """Limpia el historial de la conversación"""
56
- self.conversation_history = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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."