Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion litellm/litellm_core_utils/streaming_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ def __init__(
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 = model
self.make_call = make_call
Expand Down
18 changes: 12 additions & 6 deletions litellm/llms/bedrock/chat/converse_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -74,7 +74,7 @@ def make_sync_call(
additional_args={"complete_input_dict": data},
)

return completion_stream
return completion_stream, response.headers


class BedrockConverseLLM(BaseAWSLLM):
Expand Down Expand Up @@ -132,7 +132,7 @@ async def async_streaming(
},
)

completion_stream: Final = await make_call(
completion_stream, response_headers = await make_call(
client=client,
api_base=api_base,
headers=dict(prepped.headers),
Expand All @@ -149,6 +149,7 @@ async def async_streaming(
model=model,
custom_llm_provider="bedrock",
logging_obj=logging_obj,
_response_headers=response_headers,
)
return streaming_response

Expand Down Expand Up @@ -225,7 +226,7 @@ async def async_completion(
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,
Expand All @@ -237,6 +238,8 @@ async def async_completion(
optional_params=optional_params,
encoding=encoding,
)
transformed_response.set_provider_response_headers(response.headers)
return transformed_response

def completion(
self,
Expand Down Expand Up @@ -440,7 +443,7 @@ def completion(
client = client

if 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,
Expand All @@ -457,6 +460,7 @@ def completion(
model=model,
custom_llm_provider="bedrock",
logging_obj=logging_obj,
_response_headers=response_headers,
)

return streaming_response
Expand All @@ -477,7 +481,7 @@ def completion(
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,
Expand All @@ -489,3 +493,5 @@ def completion(
optional_params=optional_params,
encoding=encoding,
)
sync_transformed_response.set_provider_response_headers(response.headers)
return sync_transformed_response
8 changes: 4 additions & 4 deletions litellm/llms/bedrock/chat/invoke_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -225,7 +225,7 @@ async def make_call(
additional_args={"complete_input_dict": data},
)

return completion_stream
return completion_stream, response.headers
except httpx.HTTPStatusError as err:
error_code: Final = err.response.status_code
raise BedrockError(status_code=error_code, message=err.response.text)
Expand All @@ -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(
Expand Down Expand Up @@ -309,7 +309,7 @@ def make_sync_call(
additional_args={"complete_input_dict": data},
)

return completion_stream
return completion_stream, response.headers
except httpx.HTTPStatusError as err:
error_code: Final = err.response.status_code
raise BedrockError(status_code=error_code, message=err.response.text)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import copy
import json
import time
from functools import partial
from typing import TYPE_CHECKING, Any, Final, cast, get_args

import httpx
Expand Down Expand Up @@ -444,24 +443,24 @@ async def get_async_custom_stream_wrapper(
json_mode: bool | None = None,
signed_json_body: bytes | None = None,
) -> CustomStreamWrapper:
completion_stream, response_headers = await make_call(
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
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

Expand All @@ -479,27 +478,28 @@ def get_sync_custom_stream_wrapper(
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_response

Expand Down
2 changes: 2 additions & 0 deletions litellm/llms/custom_httpx/llm_http_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,7 @@ def completion(
model=model,
custom_llm_provider=custom_llm_provider,
logging_obj=logging_obj,
_response_headers=headers,
)

if client is None or not isinstance(client, HTTPHandler):
Expand Down Expand Up @@ -771,6 +772,7 @@ async def acompletion_stream_function(
model=model,
custom_llm_provider=custom_llm_provider,
logging_obj=logging_obj,
_response_headers=_response_headers,
)
return streamwrapper

Expand Down
7 changes: 6 additions & 1 deletion litellm/types/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
get_args,
)

import httpx
from openai._models import BaseModel as OpenAIObject
from openai.types.audio.transcription_create_params import (
FileTypes as FileTypes,
Expand Down Expand Up @@ -49,7 +50,7 @@
)
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_headers
from .agents import LiteLLMSendMessageResponse
from .guardrails import GuardrailEventHooks
from .llms.anthropic_messages.anthropic_response import AnthropicMessagesResponse
Expand Down Expand Up @@ -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)
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved

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:
Expand Down
16 changes: 2 additions & 14 deletions tests/llm_translation/test_bedrock_moonshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"""

from base_llm_unit_tests import BaseLLMChatTest
import httpx
import pytest
import sys
import os
Expand Down Expand Up @@ -208,14 +209,6 @@ def test_streaming(self):
endpoint with the messages body. Iteration of the stream itself is
not exercised here — moonshot streaming delegates to the OpenAI
parser 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.
"""
from litellm.utils import CustomStreamWrapper
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

Expand All @@ -225,7 +218,7 @@ def fake_make_sync_call(**kwargs):
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."
Expand All @@ -246,11 +239,6 @@ def fake_make_sync_call(**kwargs):
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:
pass

assert captured, "make_sync_call was never invoked"
assert captured["api_base"].endswith("/invoke-with-response-stream")
Expand Down
50 changes: 50 additions & 0 deletions tests/test_litellm/llms/bedrock/chat/test_invoke_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,20 @@
import sys
from unittest.mock import AsyncMock, MagicMock

import httpx
import pytest

sys.path.insert(
0, os.path.abspath("../../../../..")
) # Adds the parent directory to the system path

import litellm
from litellm.llms.bedrock.chat.invoke_handler import (
AWSEventStreamDecoder,
make_call,
make_sync_call,
)
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler


def test_transform_thinking_blocks_with_redacted_content():
Expand Down Expand Up @@ -293,3 +296,50 @@ 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():
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"


@pytest.mark.asyncio
async def test_async_invoke_streaming_forwards_bedrock_response_headers():
async def _no_bytes(chunk_size=None):
return
yield b""

response = MagicMock()
response.status_code = 200
response.aiter_bytes = _no_bytes
response.headers = httpx.Headers({"x-amzn-requestid": "req-987"})
client = AsyncHTTPHandler()
client.post = AsyncMock(return_value=response)

stream = await litellm.acompletion(
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-987"

Loading