50 lines
1.7 KiB
Python
50 lines
1.7 KiB
Python
from typing import Any, Optional
|
|
|
|
from langchain_anthropic import ChatAnthropic
|
|
|
|
from .base_client import BaseLLMClient
|
|
from .validators import validate_model
|
|
|
|
|
|
class NormalizedChatAnthropic(ChatAnthropic):
|
|
"""ChatAnthropic with normalized content output.
|
|
|
|
Newer Claude models can return content as a list of content blocks.
|
|
This normalizes to a plain string for consistent downstream handling.
|
|
"""
|
|
|
|
def _normalize_content(self, response):
|
|
content = response.content
|
|
if isinstance(content, list):
|
|
texts = [
|
|
item.get("text", "") if isinstance(item, dict) and item.get("type") == "text"
|
|
else item if isinstance(item, str) else ""
|
|
for item in content
|
|
]
|
|
response.content = "\n".join(t for t in texts if t)
|
|
return response
|
|
|
|
def invoke(self, input, config=None, **kwargs):
|
|
return self._normalize_content(super().invoke(input, config, **kwargs))
|
|
|
|
|
|
class AnthropicClient(BaseLLMClient):
|
|
"""Client for Anthropic Claude models."""
|
|
|
|
def __init__(self, model: str, base_url: Optional[str] = None, **kwargs):
|
|
super().__init__(model, base_url, **kwargs)
|
|
|
|
def get_llm(self) -> Any:
|
|
"""Return configured ChatAnthropic instance."""
|
|
llm_kwargs = {"model": self.model}
|
|
|
|
for key in ("timeout", "max_retries", "api_key", "max_tokens", "callbacks", "http_client", "http_async_client"):
|
|
if key in self.kwargs:
|
|
llm_kwargs[key] = self.kwargs[key]
|
|
|
|
return NormalizedChatAnthropic(**llm_kwargs)
|
|
|
|
def validate_model(self) -> bool:
|
|
"""Validate model for Anthropic."""
|
|
return validate_model("anthropic", self.model)
|