Add Anthropic provider with total-time deadline

Calls stream through the SDK; DeadlineTransport checks the clock before each byte chunk (also pings) so a call ends within its limit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
torbenandClaude Sonnet 5.5 committed 2026-12-04 22:06:58 +01:00
1 parent 64ad1334ca
commit d759697aeb
3 files changed
+557

No files matched your search

+138
View File
@@ -0,0 +1,138 @@
"""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)
+57
View File
@@ -0,0 +1,57 @@
"""Total time limit for one HTTP call, enforced on the response stream."""
from collections.abc import Callable, Iterator
import httpx2
class DeadlineExceededError(Exception):
"""The total time of one call ran out."""
class _DeadlineStream(httpx2.SyncByteStream):
def __init__(
self,
inner: httpx2.SyncByteStream,
deadline: float,
clock: Callable[[], float],
) -> None:
self._inner = inner
self._deadline = deadline
self._clock = clock
def __iter__(self) -> Iterator[bytes]:
for chunk in self._inner:
if self._clock() >= self._deadline:
self.close()
raise DeadlineExceededError("total time of the call ran out")
yield chunk
def close(self) -> None:
self._inner.close()
class DeadlineTransport(httpx2.BaseTransport):
"""Wraps `inner`; one instance per call. The clock starts at construction.
The check runs before each byte chunk is passed on, so it also catches
keep-alive chunks the SDK swallows. `close()` leaves `inner` open.
"""
def __init__(
self, inner: httpx2.BaseTransport, seconds: float, clock: Callable[[], float]
) -> None:
self._inner = inner
self._clock = clock
self._deadline = clock() + seconds
def handle_request(self, request: httpx2.Request) -> httpx2.Response:
response = self._inner.handle_request(request)
if not isinstance(response.stream, httpx2.SyncByteStream):
raise TypeError("inner transport must return a synchronous byte stream")
return httpx2.Response(
status_code=response.status_code,
headers=response.headers,
stream=_DeadlineStream(response.stream, self._deadline, self._clock),
extensions=response.extensions,
)