File size: 2,919 Bytes
9bbbea3
390251e
9bbbea3
bef9637
5f4cc5b
bef9637
 
 
 
 
de81808
5f4cc5b
 
 
bef9637
5f4cc5b
0d7cc9d
4713c81
5f4cc5b
4713c81
5f4cc5b
4713c81
5f4cc5b
4713c81
5f4cc5b
 
 
0d7cc9d
 
 
5f4cc5b
de81808
075d270
5f4cc5b
075d270
5f4cc5b
4713c81
 
5f4cc5b
 
 
4713c81
5f4cc5b
 
 
 
 
4713c81
 
0d7cc9d
5f4cc5b
 
 
 
 
 
 
 
 
 
 
075d270
5f4cc5b
 
 
 
 
 
 
27ec158
075d270
 
5f4cc5b
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
# 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."