Spaces:
Running
Running
Update modules/chatbot/chat_process.py
Browse files- 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'
|
| 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 |
-
'
|
| 23 |
'key_concepts': metrics.get('key_concepts', []),
|
| 24 |
-
'
|
|
|
|
|
|
|
| 25 |
}
|
| 26 |
-
self.current_lang = lang_code
|
| 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
|
| 37 |
if not self.semantic_context:
|
| 38 |
-
return
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 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
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 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 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
|
| 66 |
-
'
|
| 67 |
-
|
|
|
|
|
|
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
|
| 75 |
-
'
|
| 76 |
-
|
|
|
|
|
|
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 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
|
| 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"
|
| 103 |
|
| 104 |
-
# Construir
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
|
|
|
| 112 |
|
| 113 |
-
# Llamar a
|
| 114 |
-
with
|
| 115 |
model="claude-3-sonnet-20240229",
|
| 116 |
max_tokens=4000,
|
| 117 |
temperature=0.7,
|
| 118 |
-
system=
|
| 119 |
-
messages=
|
| 120 |
) as stream:
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 129 |
-
yield
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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")
|