"""Provider for the Anthropic Messages API, one streamed call at a time.""" import socket import time from collections.abc import Callable import anthropic import httpx2 from anthropic.lib.streaming import MessageStream from chemenu.adapters.llm.config import ModelTarget from chemenu.adapters.llm.deadline import DeadlineExceededError, DeadlineTransport from chemenu.ports.llm import ( LlmRequest, LlmResponse, LlmTimeoutError, MissingApiKeyError, ProviderError, RefusedError, TruncatedError, Usage, ) _BASE_URL = "https://api.anthropic.com" _MAX_PAUSE_SECONDS = 120.0 _CONNECT_SECONDS = 5.0 def _default_transport() -> httpx2.HTTPTransport: """Shared transport with the limits and TCP keep-alive the SDK sets for its own. The SDK applies them only to a transport it builds; ours wraps one per call. Proxy variables from the environment do not apply to an explicit transport. """ options: list[tuple[int, int, int | bool]] = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True)] for name, value in (("TCP_KEEPIDLE", 60), ("TCP_KEEPINTVL", 60), ("TCP_KEEPCNT", 5)): option: int | None = getattr(socket, name, None) if option is not None: options.append((socket.IPPROTO_TCP, option, value)) return httpx2.HTTPTransport( limits=httpx2.Limits(max_connections=1000, max_keepalive_connections=100), socket_options=options, ) def _usage(raw: anthropic.types.Usage) -> Usage: return Usage( input_tokens=raw.input_tokens or 0, output_tokens=raw.output_tokens or 0, cache_read_tokens=raw.cache_read_input_tokens or 0, cache_write_tokens=raw.cache_creation_input_tokens or 0, ) def _snapshot_usage(stream: MessageStream) -> Usage | None: """Usage seen so far; a lower bound. None if the stream never started.""" try: snapshot = stream.current_message_snapshot except AssertionError, AttributeError: return None return _usage(snapshot.usage) class AnthropicProvider: """Implements `Provider`; a new SDK client per call, no per-call state kept.""" def __init__( self, api_key: str | None, transport: httpx2.BaseTransport | None = None, clock: Callable[[], float] = time.monotonic, ) -> None: self._api_key = api_key self._transport = transport if transport is not None else _default_transport() self._clock = clock def complete(self, request: LlmRequest, target: ModelTarget) -> LlmResponse: if not self._api_key: raise MissingApiKeyError("no API key for the Anthropic provider") schema = anthropic.transform_schema(request.output_model) client = anthropic.Anthropic( api_key=self._api_key, base_url=_BASE_URL, max_retries=0, timeout=anthropic.Timeout( min(_MAX_PAUSE_SECONDS, float(target.timeout_seconds)), connect=_CONNECT_SECONDS ), http_client=anthropic.DefaultHttpxClient( transport=DeadlineTransport(self._transport, target.timeout_seconds, self._clock) ), ) usage: Usage | None = None try: with ( client, client.messages.stream( model=target.model, max_tokens=target.max_tokens, messages=[{"role": "user", "content": request.prompt}], output_config={ "effort": target.effort, "format": { "type": "json_schema", "schema": schema, }, }, ) as stream, ): try: message = stream.get_final_message() except BaseException: usage = _snapshot_usage(stream) raise except ( DeadlineExceededError, anthropic.APITimeoutError, httpx2.TimeoutException, ) as exc: raise LlmTimeoutError(f"call timed out ({type(exc).__name__})", usage) from exc except anthropic.APIStatusError as exc: raise ProviderError( f"provider call failed ({type(exc).__name__}, HTTP {exc.status_code})", usage ) from exc except (anthropic.APIError, httpx2.HTTPError) as exc: raise ProviderError(f"provider call failed ({type(exc).__name__})", usage) from exc except (AssertionError, ValueError) as exc: raise ProviderError(f"malformed response stream ({type(exc).__name__})", usage) from exc usage = _usage(message.usage) stop = message.stop_reason if stop == "refusal": raise RefusedError("the model refused to answer", usage) if stop in ("max_tokens", "model_context_window_exceeded"): raise TruncatedError(f"the answer was cut off (stop reason {stop})", usage) if stop != "end_turn": raise ProviderError(f"unexpected stop reason: {stop}", usage) text = "".join(block.text for block in message.content if block.type == "text") return LlmResponse(text=text, model=message.model, usage=usage)