Skip to content

Commit debf43d

Browse files
GWealeadk-bot
authored andcommitted
fix(models): handle Claude sampling settings on anthropic 1.x and 2.x
Since anthropic 1.0 removed temperature, top_p and top_k from messages.create(), every AnthropicLlm or Claude request that sets one of them fails with a TypeError, streaming or not. In addition, anthropic 2.0 switched both the direct API header and Vertex AI's request body to API version 2026-10-21, which rejects sampling parameters with HTTP 400 even when sent through extra_body. The adapter now omits sampling settings with a UserWarning when targeting API version 2026-10-21 or later (anthropic 2.x by default, unless an AsyncAnthropic client pins an earlier anthropic-version header such as 2023-06-01), and sends them through extra_body on earlier API versions so anthropic 0.78 through 1.x keep working without a TypeError. Co-authored-by: George Weale <gweale@google.com> PiperOrigin-RevId: 1029080642
1 parent 347dca6 commit debf43d

2 files changed

Lines changed: 505 additions & 29 deletions

File tree

‎src/google/adk/models/anthropic_llm.py‎

Lines changed: 93 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import asyncio
2020
import base64
2121
from collections.abc import Collection
22+
from collections.abc import Mapping
2223
import contextlib
2324
import copy
2425
import dataclasses
@@ -37,6 +38,7 @@
3738
from typing import TypeAlias
3839
import warnings
3940

41+
import anthropic
4042
from anthropic import AsyncAnthropic
4143
from anthropic import AsyncAnthropicVertex
4244
from anthropic import NOT_GIVEN
@@ -1381,6 +1383,51 @@ def _ensure_messages_end_with_user(
13811383
})
13821384

13831385

1386+
_SAMPLING_REMOVED_API_VERSION = "2026-10-21"
1387+
_API_VERSION_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
1388+
1389+
1390+
def _anthropic_sdk_major_version() -> int | None:
1391+
version = getattr(anthropic, "__version__", "")
1392+
if not isinstance(version, str):
1393+
return None
1394+
major, _, _ = version.partition(".")
1395+
return int(major) if major.isdigit() else None
1396+
1397+
1398+
def _extract_anthropic_version_header(
1399+
client: AsyncAnthropic,
1400+
) -> str | None:
1401+
"""Returns the client's effective anthropic-version header, if set."""
1402+
# _custom_headers holds caller overrides ahead of the SDK's lowercase default.
1403+
for attr in ("_custom_headers", "default_headers"):
1404+
headers = getattr(client, attr, None)
1405+
if not isinstance(headers, Mapping):
1406+
continue
1407+
found = False
1408+
api_version: str | None = None
1409+
for key, value in headers.items():
1410+
if isinstance(key, str) and key.lower() == "anthropic-version":
1411+
found = True
1412+
api_version = value.strip() if isinstance(value, str) else None
1413+
if found:
1414+
return api_version
1415+
return None
1416+
1417+
1418+
def _client_rejects_sampling(
1419+
client: AsyncAnthropic | AsyncAnthropicVertex | None,
1420+
) -> bool:
1421+
"""Returns whether the client targets API version 2026-10-21 or later."""
1422+
# Vertex sends anthropic_version in the body, not as an HTTP header.
1423+
if client is not None and not isinstance(client, AsyncAnthropicVertex):
1424+
api_version = _extract_anthropic_version_header(client)
1425+
if api_version is not None and _API_VERSION_DATE_RE.match(api_version):
1426+
return api_version >= _SAMPLING_REMOVED_API_VERSION
1427+
major = _anthropic_sdk_major_version()
1428+
return major is not None and major >= 2
1429+
1430+
13841431
class AnthropicLlm(BaseLlm):
13851432
"""Integration with Claude models via the Anthropic API.
13861433
@@ -1427,6 +1474,14 @@ def _resolve_model_name(self, model: str | None) -> str:
14271474
return match.group(1)
14281475
return model
14291476

1477+
def _resolved_anthropic_client(
1478+
self,
1479+
) -> AsyncAnthropic | AsyncAnthropicVertex | None:
1480+
cached_client = self.__dict__.get("_anthropic_client")
1481+
if cached_client is not None:
1482+
return cast(AsyncAnthropic | AsyncAnthropicVertex, cached_client)
1483+
return self.client
1484+
14301485
def _build_anthropic_kwargs(
14311486
self,
14321487
llm_request: LlmRequest,
@@ -1440,6 +1495,7 @@ def _build_anthropic_kwargs(
14401495
| NotGiven
14411496
),
14421497
*,
1498+
client: AsyncAnthropic | AsyncAnthropicVertex | None = None,
14431499
transient_message_indices: Collection[int] = (),
14441500
) -> dict[str, Any]:
14451501
system: str | NotGiven = NOT_GIVEN
@@ -1481,27 +1537,40 @@ def _build_anthropic_kwargs(
14811537
exclude_sampling = _thinking_is_enabled(thinking) or (effort is not None)
14821538

14831539
if llm_request.config:
1484-
# Models released after Claude Opus 4.6 do not support setting
1485-
# temperature, top_k, or top_p when thinking is enabled or effort is set.
1486-
if not exclude_sampling:
1487-
if llm_request.config.temperature is not None:
1488-
kwargs["temperature"] = llm_request.config.temperature
1489-
if llm_request.config.top_p is not None:
1490-
kwargs["top_p"] = llm_request.config.top_p
1491-
if llm_request.config.top_k is not None:
1492-
kwargs["top_k"] = int(llm_request.config.top_k)
1493-
else:
1494-
if (
1495-
llm_request.config.temperature is not None
1496-
or llm_request.config.top_p is not None
1497-
or llm_request.config.top_k is not None
1498-
):
1540+
has_sampling = (
1541+
llm_request.config.temperature is not None
1542+
or llm_request.config.top_p is not None
1543+
or llm_request.config.top_k is not None
1544+
)
1545+
if has_sampling:
1546+
if client is None:
1547+
client = self._resolved_anthropic_client()
1548+
# Models after Claude Opus 4.6 reject sampling params with thinking or
1549+
# effort enabled.
1550+
if exclude_sampling:
14991551
warnings.warn(
15001552
"Sampling parameters (temperature, top_p, top_k) are ignored "
15011553
"because thinking/effort is enabled.",
15021554
category=UserWarning,
15031555
stacklevel=3,
15041556
)
1557+
elif _client_rejects_sampling(client):
1558+
warnings.warn(
1559+
"Sampling parameters (temperature, top_p, top_k) are ignored "
1560+
"because Claude API version 2026-10-21 removed them.",
1561+
category=UserWarning,
1562+
stacklevel=3,
1563+
)
1564+
else:
1565+
# SDK 1.0 dropped these from create(); pre-2026-10-21 APIs take them.
1566+
sampling: dict[str, float | int] = {}
1567+
if llm_request.config.temperature is not None:
1568+
sampling["temperature"] = llm_request.config.temperature
1569+
if llm_request.config.top_p is not None:
1570+
sampling["top_p"] = llm_request.config.top_p
1571+
if llm_request.config.top_k is not None:
1572+
sampling["top_k"] = int(llm_request.config.top_k)
1573+
kwargs["extra_body"] = sampling
15051574

15061575
if llm_request.config.stop_sequences:
15071576
kwargs["stop_sequences"] = llm_request.config.stop_sequences
@@ -1591,13 +1660,16 @@ def _build_messages() -> (
15911660
else {}
15921661
)
15931662
if not stream:
1663+
extra_kwargs: dict[str, Any] = dict(transient_kwargs)
1664+
if client is not self._resolved_anthropic_client():
1665+
extra_kwargs["client"] = client
15941666
kwargs = self._build_anthropic_kwargs(
15951667
llm_request,
15961668
messages,
15971669
tools,
15981670
tool_choice,
15991671
thinking,
1600-
**transient_kwargs,
1672+
**extra_kwargs,
16011673
)
16021674
message = await client.messages.create(**kwargs)
16031675
response = message_to_generate_content_response(message)
@@ -1651,20 +1723,22 @@ async def _generate_content_streaming(
16511723
Partial LlmResponse objects as content arrives, followed by
16521724
a final aggregated LlmResponse with all content.
16531725
"""
1654-
transient_kwargs = (
1726+
client = await self._get_anthropic_client()
1727+
extra_kwargs: dict[str, Any] = (
16551728
{"transient_message_indices": transient_message_indices}
16561729
if transient_message_indices
16571730
else {}
16581731
)
1732+
if client is not self._resolved_anthropic_client():
1733+
extra_kwargs["client"] = client
16591734
kwargs = self._build_anthropic_kwargs(
16601735
llm_request,
16611736
messages,
16621737
tools,
16631738
tool_choice,
16641739
thinking,
1665-
**transient_kwargs,
1740+
**extra_kwargs,
16661741
)
1667-
client = await self._get_anthropic_client()
16681742
raw_stream = await client.messages.create(
16691743
stream=True,
16701744
**kwargs,

0 commit comments

Comments
 (0)