Spaces:
Running
Running
File size: 5,625 Bytes
9bbbea3 390251e 9bbbea3 bef9637 5f4cc5b bef9637 de81808 5f4cc5b bef9637 5f4cc5b d1b4d8d 0d7cc9d d1b4d8d 5f4cc5b 4713c81 d1b4d8d 4713c81 5f4cc5b 4713c81 d1b4d8d 5f4cc5b 0d7cc9d 5f4cc5b d1b4d8d de81808 075d270 5f4cc5b 075d270 d1b4d8d 5f4cc5b d1b4d8d 5f4cc5b 075d270 5f4cc5b d1b4d8d 27ec158 075d270 d1b4d8d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
# 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() |