# modules/chatbot/chatbot/chat_process.py import anthropic import os 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 Raises: ValueError: Si no se encuentra la clave API """ api_key = os.environ.get("ANTHROPIC_API_KEY") if not api_key: raise ValueError("No se encontró ANTHROPIC_API_KEY en las variables de entorno") self.client = anthropic.Anthropic(api_key=api_key) self.conversation_history = [] def process_chat_input(self, message: str, lang_code: str) -> Generator[str, None, None]: """ Procesa el input del chat y genera respuestas por chunks Args: message: Mensaje del usuario lang_code: Código del idioma para contexto Yields: str: Chunks de la respuesta """ try: # Agregar mensaje a la historia self.conversation_history.append(f"Human: {message}") # Construir el prompt con contexto del idioma system_prompt = f"You are an AI assistant for AIdeaText. Respond in {lang_code}." # Generar respuesta usando Claude API response = self.client.messages.create( model="claude-3-opus-20240229", max_tokens=300, temperature=0.7, system=system_prompt, messages=[ { "role": "user", "content": message } ], stream=True ) # Procesar la respuesta en streaming full_response = "" try: for chunk in response: if chunk.delta.text: # Verificar si hay texto en el chunk chunk_text = chunk.delta.text yield chunk_text full_response += chunk_text # Guardar la respuesta completa en el historial if full_response: self.conversation_history.append(f"Assistant: {full_response}") except Exception as e: logger.error(f"Error en streaming de respuesta: {str(e)}") yield f"Error en la comunicación: {str(e)}" 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 Returns: list: Lista de mensajes """ return self.conversation_history def clear_history(self): """ Limpia el historial de la conversación """ self.conversation_history = []