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

+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,
)