The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(anthropic/bedrock): request summarized adaptive thinking for reasoning_effort and use provider thinking token counts
Devin AI20e92d1e68c1
diff --git a/litellm/llms/anthropic/chat/transformation.py b/litellm/llms/anthropic/chat/transformation.pyindex ef278c8f723..27caa9efc44 100644--- a/litellm/llms/anthropic/chat/transformation.py+++ b/litellm/llms/anthropic/chat/transformation.py@@ -1184,8 +1184,11 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):if reasoning_effort is None or reasoning_effort == "none":return Noneif AnthropicConfig._is_adaptive_thinking_model(model, custom_llm_provider):+ # without display, Anthropic defaults adaptive thinking to+ # display="omitted" and returns a blank thinking blockreturn AnthropicThinkingParam(type="adaptive",+ display="summarized",)elif reasoning_effort == "low":return AnthropicThinkingParam(@@ -2113,7 +2116,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):)@staticmethod- def _thinking_tokens_from_usage(usage_object: Mapping[str, object]) -> int | None:+ def thinking_tokens_from_usage(usage_object: Mapping[str, object]) -> int | None:details: Final = usage_object.get("output_tokens_details")if not isinstance(details, Mapping):return None@@ -2145,7 +2148,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):reported_thinking_tokens: Final = (iteration_thinking_tokensif iteration_thinking_tokens is not None- else self._thinking_tokens_from_usage(usage_object)+ else self.thinking_tokens_from_usage(usage_object))if reported_thinking_tokens is not None:capped_reported: Final = min(max(0, reported_thinking_tokens), completion_tokens)@@ -2168,7 +2171,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):def _sum_iteration_thinking_tokens(self, iterations: Sequence[object]) -> int | None:per_iteration: Final = tuple(- self._thinking_tokens_from_usage(iteration) if isinstance(iteration, Mapping) else None+ self.thinking_tokens_from_usage(iteration) if isinstance(iteration, Mapping) else Nonefor iteration in iterations)reported: Final = tuple(tokens for tokens in per_iteration if tokens is not None)diff --git a/litellm/llms/bedrock/chat/converse_transformation.py b/litellm/llms/bedrock/chat/converse_transformation.pyindex b437e25d24b..52366da8c35 100644--- a/litellm/llms/bedrock/chat/converse_transformation.py+++ b/litellm/llms/bedrock/chat/converse_transformation.py@@ -1617,6 +1617,8 @@ class AmazonConverseConfig(BaseConfig):}if additional_request_params:data["additionalModelRequestFields"] = additional_request_params+ if "thinking" in additional_request_params:+ data["additionalModelResponseFieldPaths"] = ["/usage/output_tokens_details"]if system_content_blocks:data["system"] = system_content_blocks@@ -1801,6 +1803,17 @@ class AmazonConverseConfig(BaseConfig):thinking_blocks_list.append(_redacted_block)return thinking_blocks_list+ @staticmethod+ def thinking_tokens_from_additional_fields(additional_fields: object) -> int | None:+ """Converse omits thinking tokens from its usage block; they only arrive under+ ``additionalModelResponseFields`` when ``/usage/output_tokens_details`` is requested."""+ if not isinstance(additional_fields, Mapping):+ return None+ usage: Final = additional_fields.get("usage")+ if not isinstance(usage, Mapping):+ return None+ return AnthropicConfig.thinking_tokens_from_usage(usage)+@staticmethoddef is_converse_usage_shape(usage_object: Mapping[str, object]) -> bool:"""Converse-family models report camelCase token counts, not Anthropic's snake_case."""@@ -1842,6 +1855,7 @@ class AmazonConverseConfig(BaseConfig):usage: ConverseTokenUsageBlock,reasoning_content: str | None = None,thinking_ran: bool = False,+ provider_reasoning_tokens: int | None = None,) -> Usage:input_tokens = usage["inputTokens"]output_tokens: Final = usage["outputTokens"]@@ -1862,9 +1876,14 @@ class AmazonConverseConfig(BaseConfig):cache_creation_tokens=cache_creation_input_tokens,text_tokens=raw_input_tokens,)- reasoning_tokens: Final = (+ estimated_reasoning_tokens: Final = (token_counter(text=reasoning_content, count_response_tokens=True) if reasoning_content else 0)+ reasoning_tokens: Final = (+ min(max(0, provider_reasoning_tokens), output_tokens)+ if provider_reasoning_tokens is not None+ else estimated_reasoning_tokens+ )completion_tokens_details: Final = (CompletionTokensDetailsWrapper(reasoning_tokens=reasoning_tokens,@@ -2272,6 +2291,9 @@ class AmazonConverseConfig(BaseConfig):completion_response["usage"],reasoning_content=chat_completion_message.get("reasoning_content"),thinking_ran=reasoningContentBlocks is not None,+ provider_reasoning_tokens=self.thinking_tokens_from_additional_fields(+ completion_response.get("additionalModelResponseFields")+ ),)## HANDLE TOOL CALLSdiff --git a/litellm/llms/bedrock/chat/invoke_handler.py b/litellm/llms/bedrock/chat/invoke_handler.pyindex ce89c6c23e2..3937b36aca0 100644--- a/litellm/llms/bedrock/chat/invoke_handler.py+++ b/litellm/llms/bedrock/chat/invoke_handler.py@@ -331,6 +331,7 @@ class AWSEventStreamDecoder:self.json_mode = json_modeself._current_tool_name: str | None = Noneself._thinking_ran = False+ self._provider_reasoning_tokens: int | None = Nonedef check_empty_tool_call_args(self) -> bool:"""@@ -559,10 +560,14 @@ class AWSEventStreamDecoder:tool_use = self._handle_converse_stop_event(content_block_index)elif "stopReason" in chunk_data:finish_reason = map_finish_reason(chunk_data.get("stopReason", "stop"))+ self._provider_reasoning_tokens = AmazonConverseConfig.thinking_tokens_from_additional_fields(+ chunk_data.get("additionalModelResponseFields")+ )elif "usage" in chunk_data:usage = converse_config.transform_usage(chunk_data.get("usage", {}),thinking_ran=self._thinking_ran,+ provider_reasoning_tokens=self._provider_reasoning_tokens,)if thinking_blocks:self._thinking_ran = Truediff --git a/litellm/types/llms/anthropic.py b/litellm/types/llms/anthropic.pyindex cc6eccbf3e0..d3b0f334163 100644--- a/litellm/types/llms/anthropic.py+++ b/litellm/types/llms/anthropic.py@@ -685,6 +685,7 @@ ANTHROPIC_API_ONLY_HEADERS: Final = { # fails if calling anthropic on vertex aiclass AnthropicThinkingParam(TypedDict, total=False):type: ReadOnly[Literal["enabled", "adaptive", "disabled"]]budget_tokens: int+ display: ReadOnly[Literal["summarized", "omitted"]]class ANTHROPIC_HOSTED_TOOLS(str, Enum):diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_reasoning_effort_translation.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_reasoning_effort_translation.pyindex f393a7b50b1..48a96d011d5 100644--- a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_reasoning_effort_translation.py+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_reasoning_effort_translation.py@@ -44,7 +44,7 @@ def test_reasoning_effort_maps_to_output_config_for_adaptive_model()assert "reasoning_effort" not in result- assert result.get("thinking") == {"type": "adaptive"}+ assert result.get("thinking") == {"type": "adaptive", "display": "summarized"}assert result.get("output_config") == {"effort": expected_effort}diff --git a/tests/test_litellm/llms/anthropic/test_anthropic_reasoning_effort.py b/tests/test_litellm/llms/anthropic/test_anthropic_reasoning_effort.pyindex ef74249ca8e..288817dff07 100644--- a/tests/test_litellm/llms/anthropic/test_anthropic_reasoning_effort.py+++ b/tests/test_litellm/llms/anthropic/test_anthropic_reasoning_effort.py@@ -5,6 +5,8 @@ Verifies that reasoning_effort=None returns None for all models,including Claude Opus 4.6."""+import pytest+from litellm.llms.anthropic.chat.transformation import AnthropicConfig@@ -35,6 +37,16 @@ class TestMapReasoningEffort:)assert result["type"] == "adaptive"+ @pytest.mark.parametrize("effort", ["low", "medium", "high"])+ def test_adaptive_mapping_requests_summarized_display(self, effort):+ """Regression LIT-5714: adaptive thinking without ``display`` makes Anthropic+ return a blank thinking block, so reasoning_effort callers always got+ ``reasoning_content: ""``."""+ result = AnthropicConfig._map_reasoning_effort(+ reasoning_effort=effort, model="claude-opus-4-6", custom_llm_provider="anthropic"+ )+ assert result["display"] == "summarized"+def test_other_model_low_returns_enabled_with_budget(self):result = AnthropicConfig._map_reasoning_effort(reasoning_effort="low", model="claude-4-sonnet-20250514", custom_llm_provider="anthropic"diff --git a/tests/test_litellm/llms/azure_ai/claude/test_azure_anthropic_messages_transformation.py b/tests/test_litellm/llms/azure_ai/claude/test_azure_anthropic_messages_transformation.pyindex 53a432427d3..326edde743d 100644--- a/tests/test_litellm/llms/azure_ai/claude/test_azure_anthropic_messages_transformation.py+++ b/tests/test_litellm/llms/azure_ai/claude/test_azure_anthropic_messages_transformation.py@@ -341,7 +341,7 @@ def test_messages_thinking_shape_follows_exact_azure_entry_flag(local_model_cost)result = transform()- assert result.get("thinking") == {"type": "adaptive"}+ assert result.get("thinking") == {"type": "adaptive", "display": "summarized"}assert result.get("output_config") == {"effort": "medium"}monkeypatch.setitem(diff --git a/tests/test_litellm/llms/bedrock/chat/test_converse_transformation.py b/tests/test_litellm/llms/bedrock/chat/test_converse_transformation.pyindex 604f3414775..b648b6322f7 100644--- a/tests/test_litellm/llms/bedrock/chat/test_converse_transformation.py+++ b/tests/test_litellm/llms/bedrock/chat/test_converse_transformation.py@@ -366,6 +366,96 @@ def test_output_config_effort_forwarded_into_additional_request_fields(model):assert additional.get("output_config") == {"effort": "high"}+def test_reasoning_effort_requests_summarized_display_converse():+ """Regression LIT-5714: adaptive thinking synthesized from reasoning_effort must+ request the summarized display, otherwise the provider returns a blank thinking+ block and reasoning_content is always empty."""+ config = AmazonConverseConfig()++ optional_params = config.map_openai_params(+ non_default_params={"reasoning_effort": "high"},+ optional_params={},+ model="bedrock/converse/us.anthropic.claude-opus-4-7",+ drop_params=False,+ )++ assert optional_params["thinking"]["type"] == "adaptive"+ assert optional_params["thinking"]["display"] == "summarized"+++def test_thinking_request_adds_output_tokens_details_response_path():+ """Regression LIT-5714: the Converse usage block has no thinking-token field, so+ thinking requests must ask for ``/usage/output_tokens_details`` via+ ``additionalModelResponseFieldPaths``."""+ config = AmazonConverseConfig()++ result = config._transform_request(+ model="bedrock/converse/us.anthropic.claude-opus-4-7",+ messages=[{"role": "user", "content": "hi"}],+ optional_params={+ "maxTokens": 256,+ "thinking": {"type": "adaptive", "display": "summarized"},+ "output_config": {"effort": "high"},+ },+ litellm_params={},+ headers={},+ )++ assert result["additionalModelResponseFieldPaths"] == ["/usage/output_tokens_details"]+++def test_request_without_thinking_omits_response_field_paths():+ config = AmazonConverseConfig()++ result = config._transform_request(+ model="bedrock/converse/us.anthropic.claude-opus-4-7",+ messages=[{"role": "user", "content": "hi"}],+ optional_params={"maxTokens": 256},+ litellm_params={},+ headers={},+ )++ assert "additionalModelResponseFieldPaths" not in result+++def test_transform_usage_prefers_provider_reasoning_tokens():+ """Regression LIT-5714: provider-reported thinking tokens must win over the+ token_counter estimate derived from visible reasoning text."""+ config = AmazonConverseConfig()++ usage = config.transform_usage(+ {"inputTokens": 40, "outputTokens": 3002, "totalTokens": 3042},+ reasoning_content="a short reasoning summary",+ thinking_ran=True,+ provider_reasoning_tokens=1033,+ )++ assert usage.completion_tokens_details.reasoning_tokens == 1033+ assert usage.completion_tokens_details.text_tokens == 3002 - 1033+++def test_transform_usage_falls_back_to_estimate_without_provider_tokens():+ config = AmazonConverseConfig()++ usage = config.transform_usage(+ {"inputTokens": 40, "outputTokens": 300, "totalTokens": 340},+ reasoning_content="a short reasoning summary",+ thinking_ran=True,+ )++ assert usage.completion_tokens_details.reasoning_tokens > 0+ assert usage.completion_tokens_details.reasoning_tokens < 300+++def test_thinking_tokens_parsed_from_additional_model_response_fields():+ parsed = AmazonConverseConfig.thinking_tokens_from_additional_fields(+ {"usage": {"output_tokens_details": {"thinking_tokens": 92}}}+ )+ assert parsed == 92+ assert AmazonConverseConfig.thinking_tokens_from_additional_fields(None) is None+ assert AmazonConverseConfig.thinking_tokens_from_additional_fields({"usage": {}}) is None++@pytest.mark.parametrize("model,effort,expected_effort",[diff --git a/tests/test_litellm/llms/bedrock/chat/test_invoke_handler.py b/tests/test_litellm/llms/bedrock/chat/test_invoke_handler.pyindex e2892a6ccee..2c5ff118c85 100644--- a/tests/test_litellm/llms/bedrock/chat/test_invoke_handler.py+++ b/tests/test_litellm/llms/bedrock/chat/test_invoke_handler.py@@ -206,6 +206,29 @@ def test_bedrock_converse_streaming_consistent_id():), "All chunk IDs must match the one captured from the messageStart event"+def test_converse_streaming_usage_uses_provider_thinking_tokens():+ """Regression LIT-5714: the messageStop event carries provider thinking tokens+ under ``additionalModelResponseFields``; the usage chunk must report them instead+ of a token_counter estimate."""+ chunks = [+ {+ "contentBlockIndex": 0,+ "delta": {"reasoningContent": {"text": "thinking about it"}},+ },+ {+ "stopReason": "end_turn",+ "additionalModelResponseFields": {"usage": {"output_tokens_details": {"thinking_tokens": 1033}}},+ },+ {"usage": {"inputTokens": 40, "outputTokens": 3002, "totalTokens": 3042}},+ ]++ decoder = AWSEventStreamDecoder(model="bedrock/anthropic.claude-opus-4-7")+ parsed = [decoder.converse_chunk_parser(chunk) for chunk in chunks]++ usage = parsed[-1].usage+ assert usage.completion_tokens_details.reasoning_tokens == 1033++@pytest.mark.asyncioasync def test_make_call_does_not_rechunk_stream_by_default():"""Re-chunking the event stream into fixed 1024-byte blocks holds smalldiff --git a/tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py b/tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.pyindex d3c28302bf9..1e09afd6919 100644--- a/tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py+++ b/tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py@@ -1387,7 +1387,7 @@ def test_bedrock_messages_maps_reasoning_effort_for_adaptive_model()assert "reasoning_effort" not in result- assert result.get("thinking") == {"type": "adaptive"}+ assert result.get("thinking") == {"type": "adaptive", "display": "summarized"}assert result.get("output_config") == {"effort": expected_effort}@@ -2935,7 +2935,7 @@ def test_bedrock_messages_thinking_shape_follows_exact_bedrock_entry_flag()result = transform()- assert result.get("thinking") == {"type": "adaptive"}+ assert result.get("thinking") == {"type": "adaptive", "display": "summarized"}assert result.get("output_config") == {"effort": "medium"}monkeypatch.setitem(litellm.model_cost[model], "supports_adaptive_thinking", False)diff --git a/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py b/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.pyindex ba2f20e2337..f19e169dc9e 100644--- a/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py+++ b/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py@@ -538,7 +538,7 @@ def test_messages_thinking_shape_follows_exact_vertex_entry_flag(local_model_cos)result = transform()- assert result.get("thinking") == {"type": "adaptive"}+ assert result.get("thinking") == {"type": "adaptive", "display": "summarized"}assert result.get("output_config") == {"effort": "medium"}monkeypatch.setitem(