Spaces:
Running
Running
File size: 3,602 Bytes
9bbbea3 390251e 9bbbea3 bef9637 27ec158 bef9637 de81808 390251e 0d7cc9d 390251e bef9637 0d7cc9d 4713c81 0d7cc9d de81808 075d270 4713c81 075d270 4713c81 0d7cc9d 4713c81 0d7cc9d 4713c81 0d7cc9d 4713c81 0d7cc9d 4713c81 075d270 27ec158 075d270 164bc89 075d270 b0d7f21 075d270 27ec158 de81808 075d270 390251e de81808 6f432c7 de81808 390251e de81808 6f432c7 |
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 |
# modules/chatbot/chat_process.py
import os
import anthropic
import logging
from typing import Dict, Generator
logger = logging.getLogger(__name__)
####################################################
class ChatProcessor:
def __init__(self):
"""Inicializa el procesador de chat con la API de Claude"""
api_key = os.environ.get("ANTHROPIC_API_KEY")
if not api_key:
raise ValueError("No se encontró la clave API de Anthropic.")
self.client = anthropic.Anthropic(api_key=api_key)
self.conversation_history = []
self.semantic_context = None # <-- Añade esta línea para inicializar el atributo
def set_semantic_context(self, text, metrics, graph_data):
"""Configura el contexto semántico para conversaciones especializadas"""
self.semantic_context = {
'text_sample': text[:2000],
'key_concepts': metrics.get('key_concepts', []),
'concept_centrality': metrics.get('concept_centrality', {}),
'graph_description': "Available" if graph_data else "Not available"
}
def clear_semantic_context(self):
"""Limpia el contexto semántico"""
self.semantic_context = None
def process_chat_input(self, message: str, lang_code: str) -> Generator[str, None, None]:
"""Procesa el mensaje con contexto semántico si está disponible"""
try:
# Preparar mensaje con contexto si existe
if self.semantic_context:
system_prompt = f"""
Eres un asistente especializado en análisis semántico. Datos del análisis actual:
- Conceptos clave: {', '.join([c[0] for c in self.semantic_context['key_concepts'][:5]])}...
- Centralidad: {len(self.semantic_context['concept_centrality'])} conceptos
- Grafo: {self.semantic_context['graph_description']}
Responde preguntas sobre este análisis específico.
"""
else:
system_prompt = "Eres un asistente útil. Responde preguntas generales."
# Agregar mensaje a la historia
self.conversation_history.append({"role": "user", "content": message})
# Generar respuesta usando la API de Claude
response = self.client.messages.create(
model="claude-3-5-sonnet-20241022",
messages=self.conversation_history,
max_tokens=8000, # Añadimos este parámetro requerido
temperature=0.7,
)
# Procesar la respuesta
claude_response = response.content[0].text
self.conversation_history.append({"role": "assistant", "content": claude_response})
# Mantener un historial limitado
if len(self.conversation_history) > 10:
self.conversation_history = self.conversation_history[-10:]
# Dividir la respuesta en palabras para streaming
words = claude_response.split()
for word in words:
yield word + " "
except Exception as e:
logger.error(f"Error en process_chat_input: {str(e)}")
yield f"Error: {str(e)}"
def get_conversation_history(self) -> list:
"""Retorna el historial de la conversación"""
return self.conversation_history
def clear_history(self):
"""Limpia el historial de la conversación"""
self.conversation_history = [] |