|
|
|
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. Aseg煤rate de configurarla 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 mensaje y genera una respuesta |
|
""" |
|
try: |
|
|
|
self.conversation_history.append(f"Human: {message}") |
|
full_message = "\n".join(self.conversation_history) |
|
|
|
|
|
response = self.client.completions.create( |
|
model="claude-2", |
|
prompt=f"{full_message}\n\nAssistant:", |
|
max_tokens_to_sample=300, |
|
temperature=0.7, |
|
stop_sequences=["Human:"] |
|
) |
|
|
|
|
|
claude_response = response.completion.strip() |
|
self.conversation_history.append(f"Assistant: {claude_response}") |
|
|
|
|
|
if len(self.conversation_history) > 10: |
|
self.conversation_history = self.conversation_history[-10:] |
|
|
|
|
|
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 = [] |