1"""Helpers for creating Anthropic API clients.23The sync httpx client is cached so instances of ChatAnthropic share it. The async4client is not: its connections belong to the event loop that opened them, so it5must not be shared between models that may run in different event loops.67Logic is largely replicated from anthropic._base_client.8"""910from __future__ import annotations1112import asyncio13import os14from functools import lru_cache15from typing import Any1617import anthropic1819_NOT_GIVEN: Any = object()202122class _SyncHttpxClientWrapper(anthropic.DefaultHttpxClient):23 """Borrowed from anthropic._base_client."""2425 def __del__(self) -> None:26 try:27 if self.is_closed:28 return29 self.close()30 except Exception: # noqa: S11031 pass323334class _AsyncHttpxClientWrapper(anthropic.DefaultAsyncHttpxClient):35 """Borrowed from anthropic._base_client."""3637 def __del__(self) -> None:38 try:39 if self.is_closed:40 return41 # TODO(someday): support non asyncio runtimes here42 asyncio.get_running_loop().create_task(self.aclose())43 except Exception: # noqa: S11044 pass454647@lru_cache48def _get_default_httpx_client(49 *,50 base_url: str | None,51 timeout: Any = _NOT_GIVEN,52 anthropic_proxy: str | None = None,53) -> _SyncHttpxClientWrapper:54 kwargs: dict[str, Any] = {55 "base_url": base_url56 or os.environ.get("ANTHROPIC_BASE_URL")57 or "https://api.anthropic.com",58 }59 if timeout is not _NOT_GIVEN:60 kwargs["timeout"] = timeout61 if anthropic_proxy is not None:62 kwargs["proxy"] = anthropic_proxy63 return _SyncHttpxClientWrapper(**kwargs)646566def _get_default_async_httpx_client(67 *,68 base_url: str | None,69 timeout: Any = _NOT_GIVEN,70 anthropic_proxy: str | None = None,71) -> _AsyncHttpxClientWrapper:72 """Build a new async httpx client for one model.7374 Not cached, unlike the sync client: sharing one between models lets a model75 in a new event loop pick up a connection opened in an earlier, closed loop76 (`RuntimeError: Event loop is closed`). The SDK hides this today by retrying77 on a fresh connection, at the cost of a failed attempt and a backoff delay.78 """79 kwargs: dict[str, Any] = {80 "base_url": base_url81 or os.environ.get("ANTHROPIC_BASE_URL")82 or "https://api.anthropic.com",83 }84 if timeout is not _NOT_GIVEN:85 kwargs["timeout"] = timeout86 if anthropic_proxy is not None:87 kwargs["proxy"] = anthropic_proxy88 return _AsyncHttpxClientWrapper(**kwargs)
Findings
✓ No findings reported for this file.