AIdeaText commited on
Commit
5f4cc5b
·
verified ·
1 Parent(s): 4d1c5f5

Update modules/chatbot/chat_process.py

Browse files
Files changed (1) hide show
  1. 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 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.")
16
- self.client = anthropic.Anthropic(api_key=api_key)
17
  self.conversation_history = []
18
- self.semantic_context = None # <-- Añade esta línea para inicializar el atributo
19
 
20
  def set_semantic_context(self, text, metrics, graph_data):
21
- """Configura el contexto semántico para conversaciones especializadas"""
22
  self.semantic_context = {
23
- 'text_sample': text[:2000],
24
  'key_concepts': metrics.get('key_concepts', []),
25
- 'concept_centrality': metrics.get('concept_centrality', {}),
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 con contexto semántico si está disponible"""
35
  try:
36
- # Preparar mensaje con contexto si existe
37
  if self.semantic_context:
38
  system_prompt = f"""
39
- Eres un asistente especializado en análisis semántico. Datos del análisis actual:
40
- - Conceptos clave: {', '.join([c[0] for c in self.semantic_context['key_concepts'][:5]])}...
41
- - Centralidad: {len(self.semantic_context['concept_centrality'])} conceptos
42
- - Grafo: {self.semantic_context['graph_description']}
43
 
44
- Responde preguntas sobre este análisis específico.
 
 
 
 
45
  """
46
  else:
47
  system_prompt = "Eres un asistente útil. Responde preguntas generales."
48
-
49
- # Agregar mensaje a la historia
50
- self.conversation_history.append({"role": "user", "content": message})
51
-
52
- # Generar respuesta usando la API de Claude
53
- response = self.client.messages.create(
54
- model="claude-3-5-sonnet-20241022",
55
- messages=self.conversation_history,
56
- max_tokens=8000, # Añadimos este parámetro requerido
 
 
57
  temperature=0.7,
58
- )
59
-
60
- # Procesar la respuesta
61
- claude_response = response.content[0].text
62
- self.conversation_history.append({"role": "assistant", "content": claude_response})
 
 
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 f"Error: {str(e)}"
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."