Update modules/chatbot/chat_process.py
Browse files- modules/chatbot/chat_process.py +136 -128
modules/chatbot/chat_process.py
CHANGED
@@ -1,129 +1,137 @@
|
|
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 |
-
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 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
129 |
}.get(self.current_lang, "Processing error")
|
|
|
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 |
+
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 |
+
# Asegurar limpieza de caracteres especiales
|
124 |
+
def clean_generated_text(text):
|
125 |
+
return text.replace("\u2588", "").replace("▌", "").strip()
|
126 |
+
|
127 |
+
# Aplicar limpieza a la generación
|
128 |
+
for chunk in self.generate_response(user_input, lang_code):
|
129 |
+
yield clean_generated_text(chunk)
|
130 |
+
|
131 |
+
except Exception as e:
|
132 |
+
logger.error(f"Error en process_chat_input: {str(e)}", exc_info=True)
|
133 |
+
yield {
|
134 |
+
'en': "Error processing message. Please reload the analysis.",
|
135 |
+
'es': "Error al procesar mensaje. Recargue el análisis.",
|
136 |
+
'pt': "Erro ao processar mensagem. Recarregue a análise."
|
137 |
}.get(self.current_lang, "Processing error")
|