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(bedrock): forward provider response headers on chat completions
Devin AI9c922f4aa4f6
diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.pyindex 99b1c1a2ab7..fe107d349c6 100644--- a/litellm/litellm_core_utils/streaming_handler.py+++ b/litellm/litellm_core_utils/streaming_handler.py@@ -164,7 +164,7 @@ class CustomStreamWrapper:custom_llm_provider: str | None = None,stream_options=None,make_call: Callable | None = None,- _response_headers: dict | None = None,+ _response_headers: dict | httpx.Headers | None = None,):self.model = modelself.make_call = make_calldiff --git a/litellm/llms/bedrock/chat/converse_handler.py b/litellm/llms/bedrock/chat/converse_handler.pyindex 25e544f4521..c9ea06d37dc 100644--- a/litellm/llms/bedrock/chat/converse_handler.py+++ b/litellm/llms/bedrock/chat/converse_handler.py@@ -33,7 +33,7 @@ def make_sync_call(json_mode: bool | None = False,fake_stream: bool = False,stream_chunk_size: int | None = None,-):+) -> tuple[Any, httpx.Headers]:if client is None:client = _get_httpx_client() # Create a new client if none provided@@ -74,7 +74,7 @@ def make_sync_call(additional_args={"complete_input_dict": data},)- return completion_stream+ return completion_stream, response.headersclass BedrockConverseLLM(BaseAWSLLM):@@ -132,7 +132,7 @@ class BedrockConverseLLM(BaseAWSLLM):},)- completion_stream: Final = await make_call(+ completion_stream, response_headers = await make_call(client=client,api_base=api_base,headers=dict(prepped.headers),@@ -149,6 +149,7 @@ class BedrockConverseLLM(BaseAWSLLM):model=model,custom_llm_provider="bedrock",logging_obj=logging_obj,+ _response_headers=response_headers,)return streaming_response@@ -225,7 +226,7 @@ class BedrockConverseLLM(BaseAWSLLM):except httpx.TimeoutException:raise BedrockError(status_code=408, message="Timeout error occurred.")- return litellm.AmazonConverseConfig()._transform_response(+ transformed_response: Final = litellm.AmazonConverseConfig()._transform_response(model=model,response=response,model_response=model_response,@@ -237,6 +238,8 @@ class BedrockConverseLLM(BaseAWSLLM):optional_params=optional_params,encoding=encoding,)+ transformed_response.set_provider_response_headers(response.headers)+ return transformed_responsedef completion(self,@@ -440,7 +443,7 @@ class BedrockConverseLLM(BaseAWSLLM):client = clientif stream is not None and stream is True:- completion_stream: Final = make_sync_call(+ completion_stream, response_headers = make_sync_call(client=(client if client is not None and isinstance(client, HTTPHandler) else None),api_base=proxy_endpoint_url,headers=prepped.headers,@@ -457,6 +460,7 @@ class BedrockConverseLLM(BaseAWSLLM):model=model,custom_llm_provider="bedrock",logging_obj=logging_obj,+ _response_headers=response_headers,)return streaming_response@@ -477,7 +481,7 @@ class BedrockConverseLLM(BaseAWSLLM):except httpx.TimeoutException:raise BedrockError(status_code=408, message="Timeout error occurred.")- return litellm.AmazonConverseConfig()._transform_response(+ sync_transformed_response: Final = litellm.AmazonConverseConfig()._transform_response(model=model,response=response,model_response=model_response,@@ -489,3 +493,5 @@ class BedrockConverseLLM(BaseAWSLLM):optional_params=optional_params,encoding=encoding,)+ sync_transformed_response.set_provider_response_headers(response.headers)+ return sync_transformed_responsediff --git a/litellm/llms/bedrock/chat/invoke_handler.py b/litellm/llms/bedrock/chat/invoke_handler.pyindex 8d2b3dae71b..21892af3aae 100644--- a/litellm/llms/bedrock/chat/invoke_handler.py+++ b/litellm/llms/bedrock/chat/invoke_handler.py@@ -163,7 +163,7 @@ async def make_call(json_mode: bool | None = False,bedrock_invoke_provider: litellm.BEDROCK_INVOKE_PROVIDERS_LITERAL | None = None,stream_chunk_size: int | None = None,-):+) -> tuple[Any, httpx.Headers]:try:if client is None:client = get_async_httpx_client(@@ -225,7 +225,7 @@ async def make_call(additional_args={"complete_input_dict": data},)- return completion_stream+ return completion_stream, response.headersexcept httpx.HTTPStatusError as err:error_code: Final = err.response.status_coderaise BedrockError(status_code=error_code, message=err.response.text)@@ -248,7 +248,7 @@ def make_sync_call(json_mode: bool | None = False,bedrock_invoke_provider: litellm.BEDROCK_INVOKE_PROVIDERS_LITERAL | None = None,stream_chunk_size: int | None = None,-):+) -> tuple[Any, httpx.Headers]:try:if client is None:client = _get_httpx_client(@@ -309,7 +309,7 @@ def make_sync_call(additional_args={"complete_input_dict": data},)- return completion_stream+ return completion_stream, response.headersexcept httpx.HTTPStatusError as err:error_code: Final = err.response.status_coderaise BedrockError(status_code=error_code, message=err.response.text)diff --git a/litellm/llms/bedrock/chat/invoke_transformations/base_invoke_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/base_invoke_transformation.pyindex 430d0a92b51..0b5855ccbd4 100644--- a/litellm/llms/bedrock/chat/invoke_transformations/base_invoke_transformation.py+++ b/litellm/llms/bedrock/chat/invoke_transformations/base_invoke_transformation.py@@ -1,7 +1,6 @@import copyimport jsonimport time-from functools import partialfrom typing import TYPE_CHECKING, Any, Final, cast, get_argsimport httpx@@ -444,24 +443,24 @@ class AmazonInvokeConfig(BaseConfig, BaseAWSLLM):json_mode: bool | None = None,signed_json_body: bytes | None = None,) -> CustomStreamWrapper:+ completion_stream, response_headers = await make_call(+ client=client,+ api_base=api_base,+ headers=headers,+ data=json.dumps(data),+ model=model,+ messages=messages,+ logging_obj=logging_obj,+ fake_stream=True if "ai21" in api_base else False,+ bedrock_invoke_provider=self.get_bedrock_invoke_provider(model),+ json_mode=json_mode,+ )streaming_response: Final = CustomStreamWrapper(- completion_stream=None,- make_call=partial(- make_call,- client=client,- api_base=api_base,- headers=headers,- data=json.dumps(data),- model=model,- messages=messages,- logging_obj=logging_obj,- fake_stream=True if "ai21" in api_base else False,- bedrock_invoke_provider=self.get_bedrock_invoke_provider(model),- json_mode=json_mode,- ),+ completion_stream=completion_stream,model=model,custom_llm_provider="bedrock",logging_obj=logging_obj,+ _response_headers=response_headers,)return streaming_response@@ -479,27 +478,28 @@ class AmazonInvokeConfig(BaseConfig, BaseAWSLLM):json_mode: bool | None = None,signed_json_body: bytes | None = None,) -> CustomStreamWrapper:- if client is None or isinstance(client, AsyncHTTPHandler):- client = _get_httpx_client(params={})+ sync_client: Final = (+ _get_httpx_client(params={}) if client is None or isinstance(client, AsyncHTTPHandler) else client+ )+ completion_stream, response_headers = make_sync_call(+ client=sync_client,+ api_base=api_base,+ headers=headers,+ data=json.dumps(data),+ signed_json_body=signed_json_body,+ model=model,+ messages=messages,+ logging_obj=logging_obj,+ fake_stream=True if "ai21" in api_base else False,+ bedrock_invoke_provider=self.get_bedrock_invoke_provider(model),+ json_mode=json_mode,+ )streaming_response: Final = CustomStreamWrapper(- completion_stream=None,- make_call=partial(- make_sync_call,- client=client,- api_base=api_base,- headers=headers,- data=json.dumps(data),- signed_json_body=signed_json_body,- model=model,- messages=messages,- logging_obj=logging_obj,- fake_stream=True if "ai21" in api_base else False,- bedrock_invoke_provider=self.get_bedrock_invoke_provider(model),- json_mode=json_mode,- ),+ completion_stream=completion_stream,model=model,custom_llm_provider="bedrock",logging_obj=logging_obj,+ _response_headers=response_headers,)return streaming_responsediff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.pyindex 721b9545ac1..36bcf58a243 100644--- a/litellm/llms/custom_httpx/llm_http_handler.py+++ b/litellm/llms/custom_httpx/llm_http_handler.py@@ -608,6 +608,7 @@ class BaseLLMHTTPHandler:model=model,custom_llm_provider=custom_llm_provider,logging_obj=logging_obj,+ _response_headers=headers,)if client is None or not isinstance(client, HTTPHandler):@@ -771,6 +772,7 @@ class BaseLLMHTTPHandler:model=model,custom_llm_provider=custom_llm_provider,logging_obj=logging_obj,+ _response_headers=_response_headers,)return streamwrapperdiff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex 220826ccbca..f49b5735f04 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -11,6 +11,7 @@ from typing import (get_args,)+import httpxfrom openai._models import BaseModel as OpenAIObjectfrom openai.types.audio.transcription_create_params import (FileTypes as FileTypes,@@ -49,7 +50,7 @@ from litellm.types.llms.base import ()from litellm.types.mcp import MCPServerCostInfo-from ..litellm_core_utils.core_helpers import map_finish_reason+from ..litellm_core_utils.core_helpers import map_finish_reason, process_response_headersfrom .agents import LiteLLMSendMessageResponsefrom .guardrails import GuardrailEventHooksfrom .llms.anthropic_messages.anthropic_response import AnthropicMessagesResponse@@ -1896,6 +1897,10 @@ class ModelResponseBase(OpenAIObject):_response_headers: dict | None = None+ def set_provider_response_headers(self, headers: httpx.Headers) -> None:+ """Surface a provider's raw response headers to the caller as `llm_provider-*` headers."""+ self._hidden_params["additional_headers"] = process_response_headers(headers)+def model_dump(self, **kwargs):"""Default to exclude_unset to avoid Pydantic serializer warnings for OpenAIObject-derived types."""if "exclude_unset" not in kwargs and "exclude_none" not in kwargs:diff --git a/tests/llm_translation/test_bedrock_moonshot.py b/tests/llm_translation/test_bedrock_moonshot.pyindex a9f4a86b3b6..c777305d562 100644--- a/tests/llm_translation/test_bedrock_moonshot.py+++ b/tests/llm_translation/test_bedrock_moonshot.py@@ -209,14 +209,12 @@ class TestBedrockMoonshotInvoke(BaseLLMChatTest):not exercised here — moonshot streaming delegates to the OpenAIparser and is covered by the OpenAI test suite.- Note: bedrock invoke streaming cannot be intercepted by patching- the caller-supplied client, because ``CustomStreamWrapper.fetch_sync_stream``- at streaming_handler.py invokes the stored ``make_call`` partial with- ``client=litellm.module_level_client``, which overrides any client the- caller passed. Patch ``make_sync_call`` at its import site in- ``base_invoke_transformation`` so we observe the exact kwargs the- partial was built with at stream-wrapper construction time.+ Patch ``make_sync_call`` at its import site in+ ``base_invoke_transformation`` so we observe the exact kwargs it is+ called with at stream-wrapper construction time."""+ import httpx+from litellm.utils import CustomStreamWrappercaptured: dict = {}@@ -225,7 +223,7 @@ class TestBedrockMoonshotInvoke(BaseLLMChatTest):captured.update(kwargs)# Return an empty iterator so the stream wrapper's iteration# doesn't try to parse real bytes.- return iter([])+ return iter([]), httpx.Headers()with patch("litellm.llms.bedrock.chat.invoke_transformations."@@ -246,11 +244,6 @@ class TestBedrockMoonshotInvoke(BaseLLMChatTest):aws_region_name="us-west-2",)assert isinstance(response, CustomStreamWrapper)- # Trigger fetch_sync_stream → make_call(...) → fake_make_sync_call.- try:- next(iter(response))- except StopIteration:- passassert captured, "make_sync_call was never invoked"assert captured["api_base"].endswith("/invoke-with-response-stream")diff --git a/tests/test_litellm/llms/bedrock/chat/test_invoke_handler.py b/tests/test_litellm/llms/bedrock/chat/test_invoke_handler.pyindex ee50b9db015..f211cdac475 100644--- a/tests/test_litellm/llms/bedrock/chat/test_invoke_handler.py+++ b/tests/test_litellm/llms/bedrock/chat/test_invoke_handler.py@@ -2,17 +2,20 @@ import osimport sysfrom unittest.mock import AsyncMock, MagicMock+import httpximport pytestsys.path.insert(0, os.path.abspath("../../../../..")) # Adds the parent directory to the system path+import litellmfrom litellm.llms.bedrock.chat.invoke_handler import (AWSEventStreamDecoder,make_call,make_sync_call,)+from litellm.llms.custom_httpx.http_handler import HTTPHandlerdef test_transform_thinking_blocks_with_redacted_content():@@ -293,3 +296,25 @@ def test_make_sync_call_honors_explicit_stream_chunk_size():response.iter_bytes.assert_called_once_with(chunk_size=2048)++def test_invoke_streaming_forwards_bedrock_response_headers():+ """Streaming callers need `x-amzn-requestid` to correlate a LiteLLM request with AWS support."""+ response = MagicMock()+ response.status_code = 200+ response.iter_bytes = MagicMock(return_value=iter([]))+ response.headers = httpx.Headers({"x-amzn-requestid": "req-789"})+ client = HTTPHandler()+ client.post = MagicMock(return_value=response)++ stream = litellm.completion(+ model="bedrock/invoke/anthropic.claude-haiku-4-5-20251001-v1:0",+ messages=[{"role": "user", "content": "hi"}],+ stream=True,+ client=client,+ aws_access_key_id="fake",+ aws_secret_access_key="fake",+ aws_region_name="us-east-1",+ )++ assert stream._hidden_params["additional_headers"]["llm_provider-x-amzn-requestid"] == "req-789"+diff --git a/tests/test_litellm/llms/chat/test_converse_handler.py b/tests/test_litellm/llms/chat/test_converse_handler.pyindex 2a3db5982ef..89ab29122d7 100644--- a/tests/test_litellm/llms/chat/test_converse_handler.py+++ b/tests/test_litellm/llms/chat/test_converse_handler.py@@ -1,7 +1,9 @@+import jsonimport osimport sysfrom unittest.mock import MagicMock+import httpximport pytestimport litellm@@ -202,6 +204,59 @@ def test_make_sync_call_honors_explicit_stream_chunk_size():response.iter_bytes.assert_called_once_with(chunk_size=2048)+def _converse_response_body() -> dict:+ return {+ "output": {"message": {"role": "assistant", "content": [{"text": "hi"}]}},+ "stopReason": "end_turn",+ "usage": {"inputTokens": 1, "outputTokens": 1, "totalTokens": 2},+ }+++def test_converse_completion_forwards_bedrock_response_headers():+ """Bedrock returns x-amzn-requestid on every converse call, which customers need to+ correlate proxy requests with AWS support cases, so it must reach the caller as+ llm_provider-x-amzn-requestid."""+ mock_response = MagicMock()+ mock_response.status_code = 200+ mock_response.json = MagicMock(return_value=_converse_response_body())+ mock_response.text = json.dumps(_converse_response_body())+ mock_response.headers = httpx.Headers({"x-amzn-requestid": "req-123"})+ client = HTTPHandler()+ client.post = MagicMock(return_value=mock_response)++ response = litellm.completion(+ model="bedrock/converse/anthropic.claude-haiku-4-5-20251001-v1:0",+ messages=[{"role": "user", "content": "hi"}],+ client=client,+ aws_access_key_id="fake",+ aws_secret_access_key="fake",+ aws_region_name="us-east-1",+ )++ assert response._hidden_params["additional_headers"]["llm_provider-x-amzn-requestid"] == "req-123"+++def test_converse_streaming_forwards_bedrock_response_headers():+ mock_response = MagicMock()+ mock_response.status_code = 200+ mock_response.iter_bytes = MagicMock(return_value=iter([]))+ mock_response.headers = httpx.Headers({"x-amzn-requestid": "req-456"})+ client = HTTPHandler()+ client.post = MagicMock(return_value=mock_response)++ response = litellm.completion(+ model="bedrock/converse/anthropic.claude-haiku-4-5-20251001-v1:0",+ messages=[{"role": "user", "content": "hi"}],+ stream=True,+ client=client,+ aws_access_key_id="fake",+ aws_secret_access_key="fake",+ aws_region_name="us-east-1",+ )++ assert response._hidden_params["additional_headers"]["llm_provider-x-amzn-requestid"] == "req-456"++def test_completion_plumbs_stream_chunk_size_through_converse():iter_bytes_spy = _stream_completion_with_spied_iter_bytes(model="bedrock/anthropic.claude-3-5-sonnet-20240620-v1:0"