rag_template / src /llms /anthropic.py
Guilherme Favaron
Major update: Add hybrid search, reranking, multiple LLMs, and UI improvements
1b447de
"""
Provider Anthropic (Claude 3 Opus, Sonnet, Haiku)
"""
from typing import Dict, Any
from .base import BaseLLM
class AnthropicLLM(BaseLLM):
"""Provider para Anthropic API (Claude)"""
def __init__(self, model_id: str, api_key: str, **kwargs):
"""
Inicializa provider Anthropic
Args:
model_id: ID do modelo (claude-3-opus, claude-3-sonnet, etc)
api_key: API key da Anthropic
**kwargs: Configurações adicionais
"""
super().__init__(model_id, **kwargs)
self.api_key = api_key
self.client = None
if api_key:
try:
import anthropic
self.client = anthropic.Anthropic(api_key=api_key)
except ImportError:
self.last_error = "Biblioteca 'anthropic' não instalada. Instale com: pip install anthropic"
except Exception as e:
self.last_error = f"Erro ao inicializar Anthropic client: {str(e)}"
def generate(
self,
prompt: str,
temperature: float = 0.3,
max_tokens: int = 512,
**kwargs
) -> str:
"""
Gera resposta usando Anthropic API
Args:
prompt: Texto do prompt
temperature: Temperatura de geração
max_tokens: Máximo de tokens
**kwargs: Parâmetros adicionais
Returns:
Texto gerado
"""
# Valida parâmetros
valid, error_msg = self.validate_parameters(temperature, max_tokens)
if not valid:
return f"Erro de validação: {error_msg}"
if not self.client:
return f"Erro: Cliente Anthropic não inicializado. {self.last_error}"
try:
message = self.client.messages.create(
model=self.model_id,
max_tokens=max_tokens,
temperature=temperature,
messages=[
{"role": "user", "content": prompt}
],
**kwargs
)
return message.content[0].text.strip()
except Exception as e:
error = f"Erro na geração Anthropic: {str(e)}"
self.last_error = error
return error
def is_available(self) -> bool:
"""
Verifica se o provider está disponível
Returns:
True se cliente foi inicializado
"""
return self.client is not None
def get_model_info(self) -> Dict[str, Any]:
"""
Retorna informações sobre o modelo
Returns:
Dicionário com informações
"""
return {
"provider": "Anthropic",
"model_id": self.model_id,
"available": self.is_available(),
"api_type": "Messages API",
"last_error": self.last_error if self.last_error else None
}