1919import asyncio
2020import base64
2121from collections .abc import Collection
22+ from collections .abc import Mapping
2223import contextlib
2324import copy
2425import dataclasses
3738from typing import TypeAlias
3839import warnings
3940
41+ import anthropic
4042from anthropic import AsyncAnthropic
4143from anthropic import AsyncAnthropicVertex
4244from 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+
13841431class 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