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
Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_fix_bedrock_adaptive_thinking_token_accounting
mateo-berri46a4eda19ece
diff --cc litellm/llms/bedrock/chat/converse_transformation.pyindex 8326d3e330c,cee89f42c2d..4dd3f802638--- a/litellm/llms/bedrock/chat/converse_transformation.py+++ b/litellm/llms/bedrock/chat/converse_transformation.py@@@ -2189,10 -2251,9 +2261,10 @@@ class AmazonConverseConfig(BaseConfig)chat_completion_message["tool_calls"] = filtered_tools## CALCULATING USAGE - bedrock returns usage in the headers- usage: Final = self._transform_usage(+ usage: Final = self.transform_usage(completion_response["usage"],reasoning_content=chat_completion_message.get("reasoning_content"),+ thinking_ran=reasoningContentBlocks is not None,)## HANDLE TOOL CALLSdiff --cc litellm/llms/bedrock/chat/invoke_handler.pyindex f0f377e6e91,86f7e9b0d9f..2a125e38a82--- a/litellm/llms/bedrock/chat/invoke_handler.py+++ b/litellm/llms/bedrock/chat/invoke_handler.py@@@ -560,12 -559,7 +560,12 @@@ class AWSEventStreamDecoderelif "stopReason" in chunk_data:finish_reason = map_finish_reason(chunk_data.get("stopReason", "stop"))elif "usage" in chunk_data:- usage = converse_config._transform_usage(- usage = converse_config.transform_usage(chunk_data.get("usage", {}))++ usage = converse_config.transform_usage(+ chunk_data.get("usage", {}),+ thinking_ran=self._thinking_ran,+ )+ if thinking_blocks:+ self._thinking_ran = Truemodel_response_provider_specific_fields: Final = {}if "trace" in chunk_data:diff --cc tests/test_litellm/llms/bedrock/chat/test_converse_transformation.pyindex 1f759b58cf7,298360789eb..a3be3ebcfc7--- a/tests/test_litellm/llms/bedrock/chat/test_converse_transformation.py+++ b/tests/test_litellm/llms/bedrock/chat/test_converse_transformation.py@@@ -5936,82 -6005,50 +6005,131 @@@ def test_adaptive_thinking_dropped_whenassert "thinking" not in optional_params+def test_converse_usage_reports_unknown_split_for_signature_only_thinking():+ config = AmazonConverseConfig()+- usage = config._transform_usage(++ usage = config.transform_usage(+ ConverseTokenUsageBlock(inputTokens=32, outputTokens=581, totalTokens=613),+ reasoning_content="",+ thinking_ran=True,+ )++ assert usage.completion_tokens == 581+ assert usage.completion_tokens_details is not None+ assert usage.completion_tokens_details.reasoning_tokens is None+ assert usage.completion_tokens_details.text_tokens is None+++def test_converse_usage_estimates_split_for_visible_thinking():+ config = AmazonConverseConfig()+- usage = config._transform_usage(++ usage = config.transform_usage(+ ConverseTokenUsageBlock(inputTokens=32, outputTokens=581, totalTokens=613),+ reasoning_content="Let me think about how many primes there are under thirty.",+ thinking_ran=True,+ )++ assert usage.completion_tokens_details is not None+ assert usage.completion_tokens_details.reasoning_tokens > 0+ assert (+ usage.completion_tokens_details.reasoning_tokens + usage.completion_tokens_details.text_tokens+ == usage.completion_tokens+ )+++def test_converse_usage_without_thinking_reports_all_output_as_text():+ config = AmazonConverseConfig()+- usage = config._transform_usage(ConverseTokenUsageBlock(inputTokens=32, outputTokens=171, totalTokens=203))++ usage = config.transform_usage(ConverseTokenUsageBlock(inputTokens=32, outputTokens=171, totalTokens=203))++ assert usage.completion_tokens_details is not None+ assert usage.completion_tokens_details.reasoning_tokens == 0+ assert usage.completion_tokens_details.text_tokens == 171+++def test_converse_transform_response_signature_only_thinking_reports_unknown_split():+ config = AmazonConverseConfig()+ raw_response = MagicMock(status_code=200)+ raw_response.text = json.dumps(+ {+ "output": {+ "message": {+ "role": "assistant",+ "content": [+ {"reasoningContent": {"reasoningText": {"text": "", "signature": "sig"}}},+ {"text": "10"},+ ],+ }+ },+ "stopReason": "end_turn",+ "usage": {"inputTokens": 32, "outputTokens": 581, "totalTokens": 613},+ }+ )+ raw_response.json.return_value = json.loads(raw_response.text)++ response = config._transform_response(+ model="bedrock/global.anthropic.claude-opus-4-8",+ response=raw_response,+ model_response=ModelResponse(),+ stream=False,+ logging_obj=None,+ optional_params={},+ api_key=None,+ data={},+ messages=[],+ encoding=None,+ )++ assert response.choices[0].message.reasoning_content == ""++ assert response.usage.completion_tokens_details.reasoning_tokens is None+ assert response.usage.completion_tokens_details.text_tokens is None+++++ def test_is_converse_usage_shape_distinguishes_camel_case_from_anthropic():+ config = AmazonConverseConfig()+ assert config.is_converse_usage_shape({"inputTokens": 1, "outputTokens": 2}) is True+ assert config.is_converse_usage_shape({"outputTokens": 2}) is True+ assert config.is_converse_usage_shape({"input_tokens": 1, "output_tokens": 2}) is False+ assert config.is_converse_usage_shape({}) is False+++ def test_usage_from_batch_output_completes_an_incomplete_block():+ """Batch output omits totalTokens and the cache counts the live API always sends."""+ usage = AmazonConverseConfig().usage_from_batch_output({"inputTokens": 2202, "outputTokens": 540})+ assert (usage.prompt_tokens, usage.completion_tokens, usage.total_tokens) == (2202, 540, 2742)+++ def test_usage_from_batch_output_inflates_input_by_cache_counts():+ usage = AmazonConverseConfig().usage_from_batch_output(+ {+ "inputTokens": 100,+ "outputTokens": 20,+ "totalTokens": 120,+ "cacheReadInputTokens": 800,+ "cacheWriteInputTokens": 200,+ }+ )+ assert usage.prompt_tokens == 1100+ assert usage.prompt_tokens_details.cached_tokens == 800+ assert usage.prompt_tokens_details.cache_creation_tokens == 200+++ def test_streaming_usage_chunk_is_transformed():+ """The streaming decoder's usage event feeds the same public transform."""+ from litellm.llms.bedrock.chat.invoke_handler import AWSEventStreamDecoder++ decoder = AWSEventStreamDecoder(model="us.amazon.nova-lite-v1:0")+ chunk = decoder.converse_chunk_parser({"usage": {"inputTokens": 11, "outputTokens": 4, "totalTokens": 15}})+ assert chunk.usage.prompt_tokens == 11+ assert chunk.usage.completion_tokens == 4+ assert chunk.usage.total_tokens == 15+++ def test_update_optional_params_with_thinking_tokens_bool_thinking_does_not_crash():+ config = AmazonConverseConfig()+ optional_params = {"thinking": True}+ config.update_optional_params_with_thinking_tokens(+ non_default_params={"thinking": True}, optional_params=optional_params+ )+ assert "maxTokens" not in optional_paramsdiff --cc tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.pyindex 51f757c9eaf,fef8c2d1349..0d4db2a0b11--- a/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py+++ b/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py@@@ -422,6 -419,6 +419,107 @@@ class TestLiteLLMCompletionResponsesCon]assert len(message_items) == 2, "Should have two message items"++ def test_signature_only_thinking_block_still_emits_reasoning_item(self):++ response = ModelResponse(++ id="test-id",++ created=1234567890,++ model="test-model",++ object="chat.completion",++ choices=[++ Choices(++ finish_reason="stop",++ index=0,++ message=Message(++ content="10",++ role="assistant",++ reasoning_content="",++ thinking_blocks=[++ {"type": "thinking", "thinking": "", "signature": "signature-payload"}++ ],++ ),++ )++ ],++ )++++ responses_api_response = LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(++ request_input="Test input",++ responses_api_request={},++ chat_completion_response=response,++ )++++ reasoning_items = [++ item for item in responses_api_response.output if item.type == "reasoning"++ ]++ assert len(reasoning_items) == 1, "Signature-only thinking should still surface a reasoning item"++ assert reasoning_items[0].content == []++ assert "signature-payload" in reasoning_items[0].encrypted_content++++ def test_redacted_thinking_block_preserved_as_encrypted_content(self):++ response = ModelResponse(++ id="test-id",++ created=1234567890,++ model="test-model",++ object="chat.completion",++ choices=[++ Choices(++ finish_reason="stop",++ index=0,++ message=Message(++ content="10",++ role="assistant",++ thinking_blocks=[{"type": "redacted_thinking", "data": "redacted-payload"}],++ ),++ )++ ],++ )++++ responses_api_response = LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(++ request_input="Test input",++ responses_api_request={},++ chat_completion_response=response,++ )++++ reasoning_items = [++ item for item in responses_api_response.output if item.type == "reasoning"++ ]++ assert len(reasoning_items) == 1++ assert "redacted-payload" in reasoning_items[0].encrypted_content++++ def test_visible_thinking_keeps_text_and_signature(self):++ response = ModelResponse(++ id="test-id",++ created=1234567890,++ model="test-model",++ object="chat.completion",++ choices=[++ Choices(++ finish_reason="stop",++ index=0,++ message=Message(++ content="10",++ role="assistant",++ reasoning_content="counting the primes",++ thinking_blocks=[++ {"type": "thinking", "thinking": "counting the primes", "signature": "sig"}++ ],++ ),++ )++ ],++ )++++ responses_api_response = LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(++ request_input="Test input",++ responses_api_request={},++ chat_completion_response=response,++ )++++ reasoning_items = [++ item for item in responses_api_response.output if item.type == "reasoning"++ ]++ assert len(reasoning_items) == 1++ assert reasoning_items[0].content[0].text == "counting the primes"++ assert "sig" in reasoning_items[0].encrypted_content++def test_transform_chat_completion_response_status_with_stop(self):"""Test that transforming a chat completion response with 'stop' finish_reason