Skip to content
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
7efd8ee
test(integration): Converse stream post_call guardrail relays frames …
yucheng-berri Oct 13, 2026
9ae91ef
fix(bedrock): stream Converse passthrough frames through post_call gu…
yucheng-berri Oct 13, 2026
cc04829
fix(bedrock): apply held Converse stream masks when the upstream ends…
yucheng-berri Oct 13, 2026
1cc5d08
fix(proxy): log a relayed passthrough stream's spend before its mid-s…
yucheng-berri Oct 13, 2026
46bbbab
fix(bedrock): close and report every way a relayed Converse stream en…
yucheng-berri Oct 13, 2026
fd24cf7
fix(bedrock): relay a Converse frame whose payload is not UTF-8 inste…
yucheng-berri Oct 13, 2026
fa77b66
test(integration): cover Converse stream relay failure, end-of-stream…
yucheng-berri Oct 13, 2026
fda904a
fix(bedrock): estimate prompt tokens for a passthrough stream cut bef…
yucheng-berri Oct 14, 2026
b347ab0
fix(bedrock): read tool result blocks without recursion in the passth…
yucheng-berri Oct 14, 2026
2b4194e
fix(passthrough): keep the spend flush running when the wait for it i…
yucheng-berri Oct 14, 2026
9088833
fix(bedrock): keep a converse-stream buffered when its guardrail rele…
yucheng-berri Oct 14, 2026
8f532fd
fix(bedrock): keep a converse-stream buffered when a post_call guardr…
yucheng-berri Oct 15, 2026
e82e15f
Merge remote-tracking branch 'origin/main' into litellm_converse_stre…
yucheng-berri Oct 16, 2026
c694684
fix(bedrock): mark Noma v2 relay scans like chat and stop reading Bed…
yucheng-berri Oct 16, 2026
fde82b3
fix(bedrock): send Noma the finished Converse reply's tool calls and …
yucheng-berri Oct 16, 2026
11bf918
fix(bedrock): give Noma the ended scan of a Converse reply that only …
yucheng-berri Oct 16, 2026
7191024
Merge remote-tracking branch 'origin/main' into litellm_converse_stre…
yucheng-berri Oct 16, 2026
8ab2027
test(bedrock): expect the ValidationException main now returns for a …
yucheng-berri Oct 16, 2026
1b6ba24
fix(bedrock): keep held masks when an earlier sampled guardrail ends …
yucheng-berri Oct 16, 2026
d0037cf
Merge remote-tracking branch 'origin/main' into litellm_converse_stre…
yucheng-berri Oct 16, 2026
a426ab4
fix(proxy): free the parallel slot when a caller leaves a Converse re…
yucheng-berri Oct 17, 2026
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
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,11 @@ async def process_output_streaming_response(
def get_streaming_scan_key(self, responses_so_far: Sequence[object]) -> StreamingScanKey | None:
return None

def needs_ended_stream_scan(self, guardrail: "CustomGuardrail", responses_so_far: Sequence[object]) -> bool:
"""Whether the end-of-stream round scans ``guardrail`` even when a sampled round already covered every
text, because this translation hands that guardrail marks only the ended round carries."""
return False

def released_stream_as_ended(self, responses_so_far: Sequence[object]) -> tuple[object, ...]:
"""The chunks a client left the stream with, closed the way this endpoint ends a stream, so the
end-of-stream scan also inspects tool calls the stream never finished"""
Expand Down
433 changes: 375 additions & 58 deletions litellm/llms/bedrock/passthrough/guardrail_translation/handler.py

Large diffs are not rendered by default.

65 changes: 63 additions & 2 deletions litellm/llms/bedrock/passthrough/transformation.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import json
from collections.abc import Callable, Mapping, Sequence
from collections.abc import Callable, Iterator, Mapping, Sequence
from functools import partial
from itertools import chain
from types import MappingProxyType
from typing import TYPE_CHECKING, Final, Optional, cast

import httpx
from httpx import Response
from pydantic import TypeAdapter

from litellm._logging import verbose_logger
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.llms.base_llm.passthrough.transformation import BasePassthroughConfig, PassthroughStreamCollector
from litellm.types.llms.openai import ChatCompletionSystemMessage, ChatCompletionUserMessage
from litellm.types.utils import ModelResponseStream

from ..base_aws_llm import BaseAWSLLM
Expand Down Expand Up @@ -91,14 +95,71 @@ def _translate_message(decoder: "AWSEventStreamDecoder", message: str) -> ModelR
return None


_JSON_OBJECT: Final = TypeAdapter(Mapping[str, object])
_JSON_OBJECTS: Final = TypeAdapter(tuple[Mapping[str, object], ...])


def _leaf_texts(block: Mapping[str, object]) -> Iterator[str]:
"""The prompt text a content block carries itself: its text or JSON, or a tool call's input."""
text: Final = block.get("text")
if isinstance(text, str):
yield text
if "json" in block:
yield json.dumps(block["json"], default=str)
if "toolUse" in block:
yield json.dumps(_JSON_OBJECT.validate_python(block["toolUse"]).get("input"), default=str)


def _block_texts(block: Mapping[str, object]) -> Iterator[str]:
"""The prompt text a request content block carries, including the blocks of a tool result's content, which
Bedrock does not nest further."""
yield from _leaf_texts(block)
if "toolResult" not in block:
return
tool_result: Final = _JSON_OBJECT.validate_python(block["toolResult"])
yield from chain.from_iterable(map(_leaf_texts, _JSON_OBJECTS.validate_python(tool_result.get("content", ()))))


def _content_text(content: object) -> str:
if isinstance(content, str):
return content
return "\n".join(chain.from_iterable(map(_block_texts, _JSON_OBJECTS.validate_python(content))))


def _chat_message(turn: Mapping[str, object]) -> ChatCompletionUserMessage:
return ChatCompletionUserMessage(role="user", content=_content_text(turn.get("content", "")))


def _count_prompt_tokens(model: str, request_body: object) -> int:
"""Estimate a Bedrock request's prompt tokens from its system prompt and turns, the way a chat completions
stream that ended before the provider reported usage is estimated."""
from litellm.litellm_core_utils.token_counter import token_counter

body: Final = _JSON_OBJECT.validate_python(request_body)
if "messages" not in body:
return 0
system: Final = body.get("system")
messages: Final = (
*((ChatCompletionSystemMessage(role="system", content=_content_text(system)),) if system else ()),
*map(_chat_message, _JSON_OBJECTS.validate_python(body["messages"])),
)
return token_counter(model=model, messages=messages)


def _build_logged_response(
chunks: Sequence[ModelResponseStream], litellm_logging_obj: "LiteLLMLoggingObj"
) -> Optional["CostResponseTypes"]:
from litellm.litellm_core_utils.streaming_chunk_builder_utils import stream_chunk_builder

if len(chunks) == 0:
return None
return stream_chunk_builder(chunks=list(chunks), logging_obj=litellm_logging_obj)
return stream_chunk_builder(
chunks=list(chunks),
logging_obj=litellm_logging_obj,
count_prompt_tokens=partial(
_count_prompt_tokens, litellm_logging_obj.model, litellm_logging_obj.model_call_details.get("input")
),
)


class BedrockEventStreamCollector:
Expand Down
111 changes: 108 additions & 3 deletions litellm/llms/pass_through/guardrail_translation/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,21 @@
to extract specific fields for guardrail processing.
"""

from collections.abc import Mapping
from collections.abc import AsyncIterable, AsyncIterator, Callable, Mapping, Sequence
from typing import TYPE_CHECKING, Final, Optional, Protocol, runtime_checkable

from litellm._logging import verbose_proxy_logger
from litellm.integrations.custom_guardrail import without_server_streaming_classification
from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
from litellm.llms.base_llm.guardrail_translation.base_translation import (
BaseTranslation,
StreamingScanKey,
StreamTransformSink,
)
from litellm.types.passthrough_endpoints.pass_through_endpoints import PassThroughGuardrailSettings
from litellm.types.utils import GenericGuardrailAPIInputs

if TYPE_CHECKING:
from litellm.integrations.custom_guardrail import CustomGuardrail
from litellm.integrations.custom_guardrail import CustomGuardrail, ModifyResponseException
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.proxy.utils import ProxyLogging
from litellm.types.proxy.auth.user_api_key_auth import UserAPIKeyAuth
Expand Down Expand Up @@ -225,6 +229,15 @@ def _get_provider_handlers() -> dict[str, type[BaseTranslation]]:
return _PROVIDER_HANDLERS


def _provider_handler(provider: object) -> type[BaseTranslation] | None:
return _get_provider_handlers().get(provider) if isinstance(provider, str) else None


def _owns_event_stream_item(handler_cls: type[BaseTranslation], item: object) -> bool:
owns: Final[Callable[[object], bool] | None] = getattr(handler_cls, "owns_event_stream_item", None)
return owns is not None and owns(item)


class LlmPassthroughRouteHandler(BaseTranslation):
"""
Dispatcher for allm_passthrough_route guardrail translation.
Expand Down Expand Up @@ -277,6 +290,98 @@ async def process_output_response(
request_data=request_data,
)

@staticmethod
def _event_stream_translation(items: Sequence[object], provider: object = None) -> BaseTranslation | None:
"""The provider handler for a relayed event stream: the one that owns its frames, else ``provider``'s."""
handlers: Final = _get_provider_handlers()
owner: Final = next(
(
handler_cls
for handler_cls in handlers.values()
if items and _owns_event_stream_item(handler_cls, items[0])
),
handlers.get(provider) if isinstance(provider, str) else None,
)
return owner() if owner is not None else None

async def process_output_streaming_response(
self,
responses_so_far: Sequence[object],
guardrail_to_apply: "CustomGuardrail",
litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None,
user_api_key_dict: Optional["UserAPIKeyAuth"] = None,
request_data: dict[str, object] | None = None, # mutable-ok: the request dict guardrails receive
stream_transform_sink: StreamTransformSink | None = None,
deliver_ended_stream_rewrites: bool = False,
) -> Sequence[object]:
translation: Final = self._event_stream_translation(
responses_so_far, (request_data or {}).get("custom_llm_provider")
)
if translation is not None:
await translation.process_output_streaming_response( # pyright: ignore[reportUnknownMemberType] # takes the untyped request dict
responses_so_far=list(responses_so_far),
guardrail_to_apply=guardrail_to_apply,
litellm_logging_obj=litellm_logging_obj,
user_api_key_dict=user_api_key_dict,
request_data=request_data,
stream_transform_sink=stream_transform_sink,
deliver_ended_stream_rewrites=deliver_ended_stream_rewrites,
)
return responses_so_far

def get_streaming_scan_key(self, responses_so_far: Sequence[object]) -> StreamingScanKey | None:
translation: Final = self._event_stream_translation(responses_so_far)
return translation.get_streaming_scan_key(responses_so_far) if translation is not None else None

def needs_ended_stream_scan(self, guardrail: "CustomGuardrail", responses_so_far: Sequence[object]) -> bool:
translation: Final = self._event_stream_translation(responses_so_far)
return translation is not None and translation.needs_ended_stream_scan(guardrail, responses_so_far)

def _check_streaming_has_ended(self, responses_so_far: Sequence[object]) -> bool:
has_ended: Final[Callable[[Sequence[object]], bool] | None] = getattr(
self._event_stream_translation(responses_so_far), "_check_streaming_has_ended", None
)
return has_ended is not None and has_ended(responses_so_far)

def build_block_sse_chunks(
self,
exc: "ModifyResponseException",
stream_started: bool = False,
responses_so_far: Sequence[object] | None = None,
) -> Sequence[bytes] | None:
translation: Final = self._event_stream_translation(
responses_so_far or (), exc.request_data.get("custom_llm_provider")
)
if translation is None:
return None
return translation.build_block_sse_chunks(exc, stream_started=stream_started, responses_so_far=responses_so_far)

@staticmethod
def event_stream_items(provider: object, chunks: AsyncIterable[bytes]) -> AsyncIterator[object] | None:
"""The upstream event stream cut into the items the provider's guardrail translation scans, or None when the
provider has no streaming guardrail translation."""
framer: Final[Callable[[AsyncIterable[bytes]], AsyncIterator[object]] | None] = getattr(
_provider_handler(provider), "event_stream_items", None
)
return framer(chunks) if framer is not None else None

@staticmethod
def encode_event_stream_item(provider: object, item: object) -> bytes:
encoder: Final[Callable[[object], bytes] | None] = getattr(
_provider_handler(provider), "encode_event_stream_item", None
)
if encoder is None:
raise TypeError(f"provider {provider!r} has no event-stream encoder")
return encoder(item)

@staticmethod
def event_stream_error_item(provider: object, message: str, status_code: int) -> bytes | None:
"""An in-stream error frame in the provider's event-stream format, or None when the format has none."""
builder: Final[Callable[[str, int], bytes] | None] = getattr(
_provider_handler(provider), "event_stream_error_item", None
)
return builder(message, status_code) if builder is not None else None

@staticmethod
def is_event_stream_response(provider: str | None, content_type: str) -> bool:
handler_cls: Final = _get_provider_handlers().get(provider or "")
Expand Down
10 changes: 9 additions & 1 deletion litellm/passthrough/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def __init__(
self._litellm_logging_obj = litellm_logging_obj
self._spend = _SpendCollection(provider_config, litellm_logging_obj)
self._flush_scheduled = False
self._background_tasks: set[asyncio.Task] = set() # mutable-ok: instance set for background task tracking
self._background_tasks: set[asyncio.Task[None]] = set() # mutable-ok: instance set for background task tracking
self._hidden_params: dict[str, object] = {} # mutable-ok: router attaches response headers here in place

@property
Expand Down Expand Up @@ -148,6 +148,14 @@ def _start_flush(self) -> None:
e,
)

async def wait_for_spend_flush(self) -> bool:
"""Wait until the spend-tracking flush scheduled when the stream ended or was closed has finished, and say
whether one was scheduled, which it is not when the stream returned nothing. Cancelling the wait leaves the
flush running."""
if self._background_tasks:
await asyncio.shield(asyncio.gather(*self._background_tasks, return_exceptions=True))
return self._flush_scheduled

def __aiter__(self) -> AsyncPassthroughStreamingResponse:
return self

Expand Down
Loading
Loading