libs/partners/anthropic/langchain_anthropic/_client_utils.py PYTHON 82 lines View on github.com → Search inside
1"""Helpers for creating Anthropic API clients.23This module allows for the caching of httpx clients to avoid creating new instances4for each instance of ChatAnthropic.56Logic is largely replicated from anthropic._base_client.7"""89from __future__ import annotations1011import asyncio12import os13from functools import lru_cache14from typing import Any1516import anthropic1718_NOT_GIVEN: Any = object()192021class _SyncHttpxClientWrapper(anthropic.DefaultHttpxClient):22    """Borrowed from anthropic._base_client."""2324    def __del__(self) -> None:25        try:26            if self.is_closed:27                return28            self.close()29        except Exception:  # noqa: S11030            pass313233class _AsyncHttpxClientWrapper(anthropic.DefaultAsyncHttpxClient):34    """Borrowed from anthropic._base_client."""3536    def __del__(self) -> None:37        try:38            if self.is_closed:39                return40            # TODO(someday): support non asyncio runtimes here41            asyncio.get_running_loop().create_task(self.aclose())42        except Exception:  # noqa: S11043            pass444546@lru_cache47def _get_default_httpx_client(48    *,49    base_url: str | None,50    timeout: Any = _NOT_GIVEN,51    anthropic_proxy: str | None = None,52) -> _SyncHttpxClientWrapper:53    kwargs: dict[str, Any] = {54        "base_url": base_url55        or os.environ.get("ANTHROPIC_BASE_URL")56        or "https://api.anthropic.com",57    }58    if timeout is not _NOT_GIVEN:59        kwargs["timeout"] = timeout60    if anthropic_proxy is not None:61        kwargs["proxy"] = anthropic_proxy62    return _SyncHttpxClientWrapper(**kwargs)636465@lru_cache66def _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    kwargs: dict[str, Any] = {73        "base_url": base_url74        or os.environ.get("ANTHROPIC_BASE_URL")75        or "https://api.anthropic.com",76    }77    if timeout is not _NOT_GIVEN:78        kwargs["timeout"] = timeout79    if anthropic_proxy is not None:80        kwargs["proxy"] = anthropic_proxy81    return _AsyncHttpxClientWrapper(**kwargs)

Code quality findings 2

Catch specific exceptions instead of Exception to avoid masking bugs
broad-except
except Exception: # noqa: S110
Catch specific exceptions instead of Exception to avoid masking bugs
broad-except
except Exception: # noqa: S110

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.