Spaces:
Running
Running
| # 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 | |
| self.current_lang = 'en' # Idioma por defecto | |
| def set_semantic_context(self, text, metrics, graph_data, lang_code='en'): | |
| """Configura el contexto semántico para el chat""" | |
| self.semantic_context = { | |
| 'text_sample': text[:2000], | |
| 'key_concepts': metrics.get('key_concepts', []), | |
| 'graph_data': graph_data is not None | |
| } | |
| self.current_lang = lang_code # Establece el idioma actual | |
| self.conversation_history = [] | |
| def clear_semantic_context(self): | |
| """Limpia el contexto semántico""" | |
| self.semantic_context = None | |
| self.conversation_history = [] | |
| self.current_lang = 'en' | |
| def _get_system_prompt(self): | |
| """Genera el prompt del sistema según el idioma y contexto""" | |
| if not self.semantic_context: | |
| return { | |
| 'en': "You are a helpful assistant. Answer general questions.", | |
| 'es': "Eres un asistente útil. Responde preguntas generales.", | |
| 'pt': "Você é um assistente útil. Responda a perguntas gerais.", | |
| 'fr': "Vous êtes un assistant utile. Répondez aux questions générales." | |
| }.get(self.current_lang, "You are a helpful assistant.") | |
| concepts = ', '.join([c[0] for c in self.semantic_context['key_concepts'][:5]]) | |
| prompts = { | |
| 'en': f"""You are an assistant specialized in semantic text analysis. | |
| The user has analyzed a text with these key concepts: {concepts} | |
| Answer specific questions about this analysis, including: | |
| - Interpretation of key concepts | |
| - Relationships between concepts | |
| - Suggestions to improve the text | |
| - Explanations about the semantic graph""", | |
| 'es': f"""Eres un asistente especializado en análisis semántico de textos. | |
| El usuario ha analizado un texto con estos conceptos clave: {concepts} | |
| 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""", | |
| 'pt': f"""Você é um assistente especializado em análise semântica de textos. | |
| O usuário analisou um texto com estes conceitos-chave: {concepts} | |
| Responda perguntas específicas sobre esta análise, incluindo: | |
| - Interpretação de conceitos-chave | |
| - Relações entre conceitos | |
| - Sugestões para melhorar o texto | |
| - Explicações sobre o gráfico semântico""", | |
| 'fr': f"""Vous êtes un assistant spécialisé dans l'analyse sémantique de textes. | |
| L'utilisateur a analysé un texte avec ces concepts clés: {concepts} | |
| Répondez aux questions spécifiques sur cette analyse, y compris: | |
| - Interprétation des concepts clés | |
| - Relations entre les concepts | |
| - Suggestions pour améliorer le texte | |
| - Explications sur le graphique sémantique""" | |
| } | |
| return prompts.get(self.current_lang, prompts['en']) | |
| def _get_error_response(self): | |
| """Devuelve mensaje de error en el idioma correcto""" | |
| return { | |
| 'en': "Sorry, an error occurred. Please try again.", | |
| 'es': "Lo siento, ocurrió un error. Por favor, inténtalo de nuevo.", | |
| 'pt': "Desculpe, ocorreu um erro. Por favor, tente novamente.", | |
| 'fr': "Désolé, une erreur s'est produite. Veuillez réessayer." | |
| }.get(self.current_lang, "Sorry, an error occurred.") | |
| def process_chat_input(self, message: str, lang_code: str) -> Generator[str, None, None]: | |
| """Procesa el mensaje del usuario y genera la respuesta""" | |
| try: | |
| # Actualizar idioma si es diferente | |
| if lang_code != self.current_lang: | |
| self.current_lang = lang_code | |
| logger.info(f"Language changed to: {lang_code}") | |
| # Construir prompt del sistema | |
| system_prompt = self._get_system_prompt() | |
| # 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 | |
| # Registrar conversación exitosa | |
| logger.info(f"Chat response generated for language: {self.current_lang}") | |
| except Exception as e: | |
| logger.error(f"Error in process_chat_input: {str(e)}", exc_info=True) | |
| yield self._get_error_response() |