AIdeaText commited on
Commit
70d304b
·
verified ·
1 Parent(s): ce069d1

Update modules/chatbot/chat_process.py

Browse files
Files changed (1) hide show
  1. modules/chatbot/chat_process.py +80 -80
modules/chatbot/chat_process.py CHANGED
@@ -14,116 +14,116 @@ class ChatProcessor:
14
  )
15
  self.conversation_history = []
16
  self.semantic_context = None
17
- self.current_lang = 'en' # Idioma por defecto
18
 
19
  def set_semantic_context(self, text, metrics, graph_data, lang_code='en'):
20
- """Configura el contexto semántico para el chat"""
 
 
 
 
21
  self.semantic_context = {
22
- 'text_sample': text[:2000],
23
  'key_concepts': metrics.get('key_concepts', []),
24
- 'graph_data': graph_data is not None
 
 
25
  }
26
- self.current_lang = lang_code # Establece el idioma actual
27
  self.conversation_history = []
28
-
29
- def clear_semantic_context(self):
30
- """Limpia el contexto semántico"""
31
- self.semantic_context = None
32
- self.conversation_history = []
33
- self.current_lang = 'en'
34
 
35
  def _get_system_prompt(self):
36
- """Genera el prompt del sistema según el idioma y contexto"""
37
  if not self.semantic_context:
38
- return {
39
- 'en': "You are a helpful assistant. Answer general questions.",
40
- 'es': "Eres un asistente útil. Responde preguntas generales.",
41
- 'pt': "Você é um assistente útil. Responda a perguntas gerais.",
42
- 'fr': "Vous êtes un assistant utile. Répondez aux questions générales."
43
- }.get(self.current_lang, "You are a helpful assistant.")
44
-
45
- concepts = ', '.join([c[0] for c in self.semantic_context['key_concepts'][:5]])
46
 
47
  prompts = {
48
- 'en': f"""You are an assistant specialized in semantic text analysis.
49
- The user has analyzed a text with these key concepts: {concepts}
50
-
51
- Answer specific questions about this analysis, including:
52
- - Interpretation of key concepts
53
- - Relationships between concepts
54
- - Suggestions to improve the text
55
- - Explanations about the semantic graph""",
56
-
57
- 'es': f"""Eres un asistente especializado en análisis semántico de textos.
58
- El usuario ha analizado un texto con estos conceptos clave: {concepts}
59
 
60
- Responde preguntas específicas sobre este análisis, incluyendo:
61
- - Interpretación de conceptos clave
62
- - Relaciones entre conceptos
63
- - Sugerencias para mejorar el texto
64
- - Explicaciones sobre el gráfico semántico""",
65
 
66
- 'pt': f"""Você é um assistente especializado em análise semântica de textos.
67
- O usuário analisou um texto com estes conceitos-chave: {concepts}
 
 
68
 
69
- Responda perguntas específicas sobre esta análise, incluindo:
70
- - Interpretação de conceitos-chave
71
- - Relações entre conceitos
72
- - Sugestões para melhorar o texto
73
- - Explicações sobre o gráfico semântico""",
74
 
75
- 'fr': f"""Vous êtes un assistant spécialisé dans l'analyse sémantique de textes.
76
- L'utilisateur a analysé un texte avec ces concepts clés: {concepts}
 
 
77
 
78
- Répondez aux questions spécifiques sur cette analyse, y compris:
79
- - Interprétation des concepts clés
80
- - Relations entre les concepts
81
- - Suggestions pour améliorer le texte
82
- - Explications sur le graphique sémantique"""
83
  }
84
 
85
  return prompts.get(self.current_lang, prompts['en'])
86
 
87
- def _get_error_response(self):
88
- """Devuelve mensaje de error en el idioma correcto"""
89
- return {
90
- 'en': "Sorry, an error occurred. Please try again.",
91
- 'es': "Lo siento, ocurrió un error. Por favor, inténtalo de nuevo.",
92
- 'pt': "Desculpe, ocorreu um erro. Por favor, tente novamente.",
93
- 'fr': "Désolé, une erreur s'est produite. Veuillez réessayer."
94
- }.get(self.current_lang, "Sorry, an error occurred.")
95
-
96
  def process_chat_input(self, message: str, lang_code: str) -> Generator[str, None, None]:
97
- """Procesa el mensaje del usuario y genera la respuesta"""
98
  try:
 
 
 
 
99
  # Actualizar idioma si es diferente
100
  if lang_code != self.current_lang:
101
  self.current_lang = lang_code
102
- logger.info(f"Language changed to: {lang_code}")
103
 
104
- # Construir prompt del sistema
105
- system_prompt = self._get_system_prompt()
106
-
107
- # Agregar mensaje al historial
108
- self.conversation_history.append({
109
- "role": "user",
110
- "content": message
111
- })
 
112
 
113
- # Llamar a la API de Claude
114
- with anthropic.Anthropic().messages.stream(
115
  model="claude-3-sonnet-20240229",
116
  max_tokens=4000,
117
  temperature=0.7,
118
- system=system_prompt,
119
- messages=self.conversation_history
120
  ) as stream:
121
- for text in stream.text_stream:
122
- yield text
 
 
 
 
 
 
 
 
 
123
 
124
- # Registrar conversación exitosa
125
- logger.info(f"Chat response generated for language: {self.current_lang}")
126
-
127
  except Exception as e:
128
- logger.error(f"Error in process_chat_input: {str(e)}", exc_info=True)
129
- yield self._get_error_response()
 
 
 
 
 
14
  )
15
  self.conversation_history = []
16
  self.semantic_context = None
17
+ self.current_lang = 'en'
18
 
19
  def set_semantic_context(self, text, metrics, graph_data, lang_code='en'):
20
+ """Configura el contexto semántico completo para el chat"""
21
+ if not text or not metrics:
22
+ logger.error("Faltan datos esenciales para el contexto semántico")
23
+ raise ValueError("Texto y métricas son requeridos")
24
+
25
  self.semantic_context = {
26
+ 'full_text': text, # Texto completo del documento
27
  'key_concepts': metrics.get('key_concepts', []),
28
+ 'concept_centrality': metrics.get('concept_centrality', {}),
29
+ 'graph_available': graph_data is not None,
30
+ 'language': lang_code
31
  }
32
+ self.current_lang = lang_code
33
  self.conversation_history = []
34
+ logger.info("Contexto semántico configurado correctamente")
 
 
 
 
 
35
 
36
  def _get_system_prompt(self):
37
+ """Genera el prompt del sistema con todo el contexto necesario"""
38
  if not self.semantic_context:
39
+ return "You are a helpful assistant."
40
+
41
+ concepts = self.semantic_context['key_concepts']
42
+ top_concepts = ", ".join([f"{c[0]} ({c[1]:.2f})" for c in concepts[:5]])
 
 
 
 
43
 
44
  prompts = {
45
+ 'en': f"""You are a semantic analysis expert. The user analyzed a research article.
46
+ Full text available (abbreviated for context).
47
+ Key concepts: {top_concepts}
48
+ Graph available: {self.semantic_context['graph_available']}
 
 
 
 
 
 
 
49
 
50
+ Your tasks:
51
+ 1. Answer questions about concepts and their relationships
52
+ 2. Explain the semantic network structure
53
+ 3. Suggest text improvements
54
+ 4. Provide insights based on concept centrality""",
55
 
56
+ 'es': f"""Eres un experto en análisis semántico. El usuario analizó un artículo de investigación.
57
+ Texto completo disponible (abreviado para contexto).
58
+ Conceptos clave: {top_concepts}
59
+ Gráfico disponible: {self.semantic_context['graph_available']}
60
 
61
+ Tus tareas:
62
+ 1. Responder preguntas sobre conceptos y sus relaciones
63
+ 2. Explicar la estructura de la red semántica
64
+ 3. Sugerir mejoras al texto
65
+ 4. Proporcionar insights basados en centralidad de conceptos""",
66
 
67
+ 'pt': f"""Você é um especialista em análise semântica. O usuário analisou um artigo de pesquisa.
68
+ Texto completo disponível (abreviado para contexto).
69
+ Conceitos-chave: {top_concepts}
70
+ Gráfico disponível: {self.semantic_context['graph_available']}
71
 
72
+ Suas tarefas:
73
+ 1. Responder perguntas sobre conceitos e suas relações
74
+ 2. Explicar a estrutura da rede semântica
75
+ 3. Sugerir melhorias no texto
76
+ 4. Fornecer insights com base na centralidade dos conceitos"""
77
  }
78
 
79
  return prompts.get(self.current_lang, prompts['en'])
80
 
 
 
 
 
 
 
 
 
 
81
  def process_chat_input(self, message: str, lang_code: str) -> Generator[str, None, None]:
82
+ """Procesa el mensaje con todo el contexto disponible"""
83
  try:
84
+ if not self.semantic_context:
85
+ yield "Error: Contexto semántico no configurado. Recargue el análisis."
86
+ return
87
+
88
  # Actualizar idioma si es diferente
89
  if lang_code != self.current_lang:
90
  self.current_lang = lang_code
91
+ logger.info(f"Idioma cambiado a: {lang_code}")
92
 
93
+ # Construir historial de mensajes
94
+ messages = [
95
+ {
96
+ "role": "user",
97
+ "content": f"Documento analizado (extracto):\n{self.semantic_context['full_text'][:2000]}..."
98
+ },
99
+ *self.conversation_history,
100
+ {"role": "user", "content": message}
101
+ ]
102
 
103
+ # Llamar a Claude con streaming
104
+ with self.client.messages.stream(
105
  model="claude-3-sonnet-20240229",
106
  max_tokens=4000,
107
  temperature=0.7,
108
+ system=self._get_system_prompt(),
109
+ messages=messages
110
  ) as stream:
111
+ full_response = ""
112
+ for chunk in stream.text_stream:
113
+ full_response += chunk
114
+ yield chunk + "▌"
115
+
116
+ # Guardar respuesta en historial
117
+ self.conversation_history.extend([
118
+ {"role": "user", "content": message},
119
+ {"role": "assistant", "content": full_response}
120
+ ])
121
+ logger.info("Respuesta generada y guardada en historial")
122
 
 
 
 
123
  except Exception as e:
124
+ logger.error(f"Error en process_chat_input: {str(e)}", exc_info=True)
125
+ yield {
126
+ 'en': "Error processing message. Please reload the analysis.",
127
+ 'es': "Error al procesar mensaje. Recargue el análisis.",
128
+ 'pt': "Erro ao processar mensagem. Recarregue a análise."
129
+ }.get(self.current_lang, "Processing error")