Spaces:
Sleeping
Sleeping
| # modules/chatbot/chat_process.py | |
| import os | |
| import anthropic | |
| import logging | |
| from typing import Generator | |
| logger = logging.getLogger(__name__) | |
| class ChatProcessor: | |
| def __init__(self): | |
| """Inicializa el procesador de chat con la API de Claude""" | |
| self.client = anthropic.Anthropic( | |
| api_key=os.environ.get("ANTHROPIC_API_KEY") | |
| ) | |
| self.conversation_history = [] | |
| self.semantic_context = None | |
| def set_semantic_context(self, text, metrics, graph_data): | |
| """Configura el contexto semántico para el chat""" | |
| self.semantic_context = { | |
| 'text_sample': text[:2000], # Tomamos solo un fragmento | |
| 'key_concepts': metrics.get('key_concepts', []), | |
| 'graph_data': graph_data is not None | |
| } | |
| # Reiniciamos el historial para el nuevo contexto | |
| self.conversation_history = [] | |
| def clear_semantic_context(self): | |
| """Limpia el contexto semántico""" | |
| self.semantic_context = None | |
| self.conversation_history = [] | |
| def process_chat_input(self, message: str, lang_code: str) -> Generator[str, None, None]: | |
| """Procesa el mensaje del usuario y genera la respuesta""" | |
| try: | |
| # Construir el prompt del sistema según el contexto | |
| if self.semantic_context: | |
| system_prompt = f""" | |
| Eres un asistente especializado en análisis semántico de textos. | |
| El usuario ha analizado un texto con los siguientes conceptos clave: | |
| {', '.join([c[0] for c in self.semantic_context['key_concepts'][:5]])} | |
| Responde preguntas específicas sobre este análisis, incluyendo: | |
| - Interpretación de conceptos clave | |
| - Relaciones entre conceptos | |
| - Sugerencias para mejorar el texto | |
| - Explicaciones sobre el gráfico semántico | |
| """ | |
| else: | |
| system_prompt = "Eres un asistente útil. Responde preguntas generales." | |
| # Agregar mensaje al historial | |
| self.conversation_history.append({ | |
| "role": "user", | |
| "content": message | |
| }) | |
| # Llamar a la API de Claude | |
| with anthropic.Anthropic().messages.stream( | |
| model="claude-3-sonnet-20240229", | |
| max_tokens=4000, | |
| temperature=0.7, | |
| system=system_prompt, | |
| messages=self.conversation_history | |
| ) as stream: | |
| for text in stream.text_stream: | |
| yield text | |
| # Actualizar historial (la API lo hace automáticamente) | |
| except Exception as e: | |
| logger.error(f"Error en process_chat_input: {str(e)}") | |
| yield "Lo siento, ocurrió un error al procesar tu mensaje. Por favor, inténtalo de nuevo." |