|
| 1 | +"""Adapt to the installed `anthropic` SDK major version. |
| 2 | +
|
| 3 | +`langchain-anthropic` supports `anthropic` 0.x and 1.x. Two differences between |
| 4 | +them reach this package, and each is resolved here by reading the answer off the |
| 5 | +installed SDK rather than off its version string: |
| 6 | +
|
| 7 | +- **Sampling parameters.** `anthropic>=1` dropped `temperature`, `top_p` and |
| 8 | + `top_k` from its message-creation methods, since current models do not use |
| 9 | + them. The API still honors them for older models, so they are relocated to |
| 10 | + `extra_body`, which the SDK merges into the request JSON as-is. The wire |
| 11 | + payload is identical on both majors. |
| 12 | +
|
| 13 | +- **Raw responses.** `.with_raw_response` on the async client returns |
| 14 | + `AsyncAPIResponse`, whose `parse()` is a coroutine; `anthropic<1` returned |
| 15 | + `LegacyAPIResponse` with a synchronous `parse()`. |
| 16 | +
|
| 17 | +`anthropic>=1` also moved its HTTP layer from `httpx` to |
| 18 | +[`httpx2`](https://github.com/pydantic/httpx2), but that does not surface here: |
| 19 | +this package hands the SDK only primitives (a `base_url` string, a float |
| 20 | +`timeout`, a `proxy` URL string) and subclasses `anthropic.DefaultHttpxClient`, |
| 21 | +which already points at the right library, so no `httpx` type crosses the |
| 22 | +boundary. Only the unit tests inject `httpx` objects, and they resolve the |
| 23 | +matching library themselves in `tests/unit_tests/_httpx_compat.py`. |
| 24 | +""" |
| 25 | + |
| 26 | +from __future__ import annotations |
| 27 | + |
| 28 | +import inspect |
| 29 | +import logging |
| 30 | +import re |
| 31 | +from collections.abc import Mapping |
| 32 | +from functools import lru_cache |
| 33 | +from typing import Any |
| 34 | + |
| 35 | +import anthropic |
| 36 | + |
| 37 | +logger = logging.getLogger(__name__) |
| 38 | + |
| 39 | +# Sampling parameters `anthropic>=1` no longer accepts as named arguments. |
| 40 | +_SAMPLING_PARAMS = ("temperature", "top_p", "top_k") |
| 41 | + |
| 42 | + |
| 43 | +def _sdk_major_version() -> int | None: |
| 44 | + """Major version of the installed `anthropic` SDK, or `None` if unreadable. |
| 45 | +
|
| 46 | + Tolerates tag-derived strings such as `v1.0.0`, which build tooling |
| 47 | + sometimes leaves unstripped, by reading the first integer run. |
| 48 | + """ |
| 49 | + match = re.match(r"\D*(\d+)", str(getattr(anthropic, "__version__", ""))) |
| 50 | + return int(match.group(1)) if match else None |
| 51 | + |
| 52 | + |
| 53 | +@lru_cache(maxsize=1) |
| 54 | +def _unsupported_sampling_params() -> frozenset[str]: |
| 55 | + """Sampling parameters the installed SDK's message methods no longer accept. |
| 56 | +
|
| 57 | + Derived from the signature of `Messages.create`, which `beta.messages` and |
| 58 | + the async resources track. No client is instantiated, so this is safe to |
| 59 | + call during payload construction without resolved credentials. |
| 60 | + """ |
| 61 | + try: |
| 62 | + from anthropic.resources.messages import Messages |
| 63 | + |
| 64 | + accepted = inspect.signature(Messages.create).parameters |
| 65 | + except (ImportError, AttributeError, TypeError, ValueError): |
| 66 | + # The SDK moved the resource or the signature is unreadable. Guess from |
| 67 | + # the major version rather than failing: a wrong guess costs a TypeError |
| 68 | + # on the first request, an exception here breaks every import. |
| 69 | + major = _sdk_major_version() |
| 70 | + logger.warning( |
| 71 | + "Could not introspect the anthropic SDK's `Messages.create` " |
| 72 | + "signature; falling back to its major version (%r) to decide " |
| 73 | + "whether `temperature`/`top_p`/`top_k` are still accepted.", |
| 74 | + major, |
| 75 | + ) |
| 76 | + if major is not None and major >= 1: |
| 77 | + return frozenset(_SAMPLING_PARAMS) |
| 78 | + return frozenset() |
| 79 | + |
| 80 | + return frozenset(p for p in _SAMPLING_PARAMS if p not in accepted) |
| 81 | + |
| 82 | + |
| 83 | +def _route_unsupported_sampling_params(payload: dict[str, Any]) -> dict[str, Any]: |
| 84 | + """Move sampling params the installed SDK rejects into `extra_body`. |
| 85 | +
|
| 86 | + A no-op on `anthropic<1`, where the message methods still accept them as |
| 87 | + named arguments. Values the caller already set in `extra_body` win, since |
| 88 | + that is the SDK's documented escape hatch and a deliberate choice. |
| 89 | +
|
| 90 | + Args: |
| 91 | + payload: Request payload, modified in place. |
| 92 | +
|
| 93 | + Returns: |
| 94 | + The same payload. |
| 95 | + """ |
| 96 | + unsupported = _unsupported_sampling_params() |
| 97 | + if not unsupported: |
| 98 | + return payload |
| 99 | + |
| 100 | + extra_body = payload.get("extra_body") |
| 101 | + if extra_body is not None and not isinstance(extra_body, Mapping): |
| 102 | + # A value the SDK would reject anyway. Leave the payload untouched |
| 103 | + # rather than relocating params into something that cannot hold them. |
| 104 | + return payload |
| 105 | + |
| 106 | + relocated = {k: payload.pop(k) for k in unsupported if k in payload} |
| 107 | + if not relocated: |
| 108 | + return payload |
| 109 | + |
| 110 | + payload["extra_body"] = {**relocated, **(extra_body or {})} |
| 111 | + return payload |
| 112 | + |
| 113 | + |
| 114 | +async def _aparse(raw_response: Any) -> Any: |
| 115 | + """Parse a raw SDK response from the async client. |
| 116 | +
|
| 117 | + `anthropic>=1` returns `AsyncAPIResponse`, whose `parse()` is a coroutine; |
| 118 | + `anthropic<1` returned `LegacyAPIResponse`, whose `parse()` was |
| 119 | + synchronous. |
| 120 | + """ |
| 121 | + parsed = raw_response.parse() |
| 122 | + if inspect.isawaitable(parsed): |
| 123 | + return await parsed |
| 124 | + return parsed |
0 commit comments