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)!: stream Converse passthrough frames through post_call guardrails instead of buffering (#46307)
yucheng-berrief1cb19351b1
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex 8d4730eb1bf..438b38f3f09 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -2933,11 +2933,14 @@ class Logging(LiteLLMLoggingBaseClass):if complete_streaming_response is not None:self.success_handler(result=complete_streaming_response)- async def async_flush_passthrough_collected_chunks(self, collector: "PassthroughStreamCollector"):+ async def async_flush_passthrough_collected_chunks(self, collector: "PassthroughStreamCollector") -> bool:+ """Log the response the collector built from the stream, and say whether there was one to log."""complete_streaming_response: Final = collector.build_logged_response(litellm_logging_obj=self)- if complete_streaming_response is not None:- await self.async_success_handler(result=complete_streaming_response)+ if complete_streaming_response is None:+ return False+ await self.async_success_handler(result=complete_streaming_response)+ return Truedef _restore_correlation_context(self) -> None:"""Restore trace_id/session_id contextvars to their pre-call value.diff --git a/litellm/llms/base_llm/guardrail_translation/base_translation.py b/litellm/llms/base_llm/guardrail_translation/base_translation.pyindex 88c4dbfdce6..ee2f6eb9f1a 100644--- a/litellm/llms/base_llm/guardrail_translation/base_translation.py+++ b/litellm/llms/base_llm/guardrail_translation/base_translation.py@@ -203,6 +203,11 @@ class BaseTranslation(ABC):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 theend-of-stream scan also inspects tool calls the stream never finished"""diff --git a/litellm/llms/bedrock/passthrough/guardrail_translation/handler.py b/litellm/llms/bedrock/passthrough/guardrail_translation/handler.pyindex 912936a8ecd..317b95f18f0 100644--- a/litellm/llms/bedrock/passthrough/guardrail_translation/handler.py+++ b/litellm/llms/bedrock/passthrough/guardrail_translation/handler.py@@ -1,10 +1,20 @@-from collections.abc import Mapping, Sequence+import copy+import json+import struct+from binascii import crc32+from collections.abc import AsyncGenerator, AsyncIterable, Mapping, Sequence+from dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, Final, Optional, Protocol, TypeAlias+from pydantic import TypeAdapter, ValidationErrorfrom typing_extensions import ReadOnly, TypedDictfrom litellm._logging import verbose_proxy_logger-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.llms.base_llm.guardrail_translation.utils import (effective_skip_system_message_for_guardrail,effective_skip_tool_message_for_guardrail,@@ -12,7 +22,7 @@ from litellm.llms.base_llm.guardrail_translation.utils import (from litellm.types.utils import GenericGuardrailAPIInputsif TYPE_CHECKING:- from litellm.integrations.custom_guardrail import CustomGuardrail+ from litellm.integrations.custom_guardrail import CustomGuardrail, ModifyResponseExceptionfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObjfrom litellm.llms.pass_through.guardrail_translation.handler import (PassThroughEndpointHandler,@@ -217,8 +227,6 @@ class _StreamFrame(TypedDict):def _unpack_uint32(buffer: bytes) -> int:- import struct-return struct.unpack("!I", buffer)[0]@@ -253,6 +261,307 @@ def _collect_stream_delta_text_holders(delta: object) -> list[_DeltaHolder]:return holders+def _delta_frame_texts(payload: Mapping[str, object]) -> tuple[tuple[_StreamGroupKey, str], ...]:+ """The guardrailable texts of one ``contentBlockDelta`` payload, each keyed by its content block and kind."""+ block_index: Final = payload.get("contentBlockIndex")+ # Group per content block: a guardrail edit that changes length must not move text between blocks.+ return tuple(+ ((block_index if isinstance(block_index, int) else None, group_key), container[key])+ for group_key, container, key in _collect_stream_delta_text_holders(payload.get("delta"))+ )+++@dataclass(frozen=True, slots=True)+class _StreamTextGroups:+ """Stream texts joined per group, keeping where each fragment came from so a rewrite can be split back."""++ groups: tuple[_StreamGroupKey, ...]+ members: Mapping[_StreamGroupKey, Sequence[tuple[int, int]]]+ fragments: Mapping[_StreamGroupKey, Sequence[str]]++ def texts(self) -> tuple[str, ...]:+ return tuple("".join(self.fragments[group]) for group in self.groups)+++def _group_stream_texts(frame_texts: Sequence[Sequence[tuple[_StreamGroupKey, str]]]) -> _StreamTextGroups:+ """Group the per-frame texts by key in first-seen order; ``groups`` keeps only the groups with any text."""+ order: Final[list[_StreamGroupKey]] = [] # mutable-ok: built in one pass over the frames+ members: Final[dict[_StreamGroupKey, list[tuple[int, int]]]] = {} # mutable-ok: built in one pass over the frames+ fragments: Final[dict[_StreamGroupKey, list[str]]] = {} # mutable-ok: built in one pass over the frames+ for frame_idx, texts in enumerate(frame_texts):+ for local_idx, (group_key, text) in enumerate(texts):+ if group_key not in members:+ members[group_key] = []+ fragments[group_key] = []+ order.append(group_key)+ members[group_key].append((frame_idx, local_idx))+ fragments[group_key].append(text)+ return _StreamTextGroups(+ groups=tuple(group for group in order if "".join(fragments[group])),+ members=members,+ fragments=fragments,+ )+++def _split_group_texts(groups: _StreamTextGroups, rewritten_texts: Sequence[str]) -> Mapping[tuple[int, int], str]:+ """Cut each group's rewritten text back into its fragments, sized like the original fragments."""+ split: Final[dict[tuple[int, int], str]] = {} # mutable-ok: built in one pass over the groups+ for group_key, rewritten in zip(groups.groups, rewritten_texts):+ members = groups.members[group_key]+ originals = groups.fragments[group_key]+ total_orig = sum(len(t) for t in originals) or 1+ pos = 0+ for k, member in enumerate(members):+ if k == len(members) - 1:+ split[member] = rewritten[pos:]+ else:+ end = pos + round(len(rewritten) * len(originals[k]) / total_orig)+ split[member] = rewritten[pos:end]+ pos = end+ return split+++def _event_stream_message(headers_bytes: bytes, payload: bytes) -> bytes:+ """One AWS event-stream message: prelude, prelude CRC, headers, payload and message CRC."""+ prelude: Final = struct.pack("!II", 12 + len(headers_bytes) + len(payload) + 4, len(headers_bytes))+ prelude_crc: Final = crc32(prelude) & 0xFFFFFFFF+ message: Final = prelude + struct.pack("!I", prelude_crc) + headers_bytes + payload+ return message + struct.pack("!I", crc32(message) & 0xFFFFFFFF)+++def _string_header(name: str, value: str) -> bytes:+ name_bytes: Final = name.encode()+ value_bytes: Final = value.encode()+ return bytes((len(name_bytes),)) + name_bytes + b"\x07" + struct.pack("!H", len(value_bytes)) + value_bytes+++def _string_headers(headers: Mapping[str, str]) -> bytes:+ return b"".join(_string_header(name, value) for name, value in headers.items())+++def _converse_event(event_type: str, payload: Mapping[str, object]) -> bytes:+ return _event_stream_message(+ _string_headers({":event-type": event_type, ":content-type": "application/json", ":message-type": "event"}),+ json.dumps(payload, separators=(",", ":")).encode(),+ )+++def _converse_exception(message: str, status_code: int) -> bytes:+ """An in-stream exception frame, which boto3 raises as ``EventStreamError`` carrying ``message``."""+ return _event_stream_message(+ _string_headers(+ {+ ":exception-type": "validationException" if status_code < 500 else "internalServerException",+ ":content-type": "application/json",+ ":message-type": "exception",+ }+ ),+ json.dumps({"message": message}, separators=(",", ":")).encode(),+ )+++@dataclass(slots=True)+class ConverseStreamFrame:+ """One frame of a Converse event stream as the proxy relays it.++ ``payload`` is the parsed JSON of an event frame; exception frames and bytes that do not decode keep it None and+ are relayed as received. ``ends_stream`` marks the empty item the framer adds once the upstream has ended, so an+ exception frame or a closed connection ends the stream as ``messageStop`` does. ``guardrailed_payload`` is set+ when a guardrail rewrote the frame's text."""++ raw: bytes+ event_type: str | None = None+ payload: Mapping[str, object] | None = None+ guardrailed_payload: Mapping[str, object] | None = None+ ends_stream: bool = False++ @property+ def block_index(self) -> int | None:+ index: Final = self.payload.get("contentBlockIndex") if self.payload is not None else None+ return index if isinstance(index, int) else None++ def scanned_texts(self) -> tuple[tuple[_StreamGroupKey, str], ...]:+ current: Final = self.guardrailed_payload if self.guardrailed_payload is not None else self.payload+ return _delta_frame_texts(current) if self.event_type == "contentBlockDelta" and current is not None else ()++ def received_texts(self) -> tuple[tuple[_StreamGroupKey, str], ...]:+ return (+ _delta_frame_texts(self.payload)+ if self.event_type == "contentBlockDelta" and self.payload is not None+ else ()+ )++ def encode(self) -> bytes:+ if self.guardrailed_payload is None:+ return self.raw+ headers_length: Final = _unpack_uint32(self.raw[4:8])+ return _event_stream_message(+ self.raw[12 : 12 + headers_length], json.dumps(self.guardrailed_payload, separators=(",", ":")).encode()+ )+++_JSON_OBJECT: Final = TypeAdapter(Mapping[str, object])+++def _decode_converse_frame(raw: bytes) -> ConverseStreamFrame:+ from botocore.eventstream import EventStreamBuffer, ParserError++ buffer: Final = EventStreamBuffer()+ buffer.add_data(raw)+ try:+ message: Final = next(iter(buffer))+ except (ParserError, StopIteration) as e:+ verbose_proxy_logger.debug(+ "BedrockPassthroughGuardrailHandler: could not decode event-stream frame, relaying it unmodified: %s", e+ )+ return ConverseStreamFrame(raw=raw)+ # botocore-stubs types EventStreamMessage.headers as int; at runtime it is the decoded header dict.+ headers: Final = _JSON_OBJECT.validate_python(message.headers)+ event_type: Final = headers.get(":event-type")+ if headers.get(":message-type") != "event" or not isinstance(event_type, str):+ return ConverseStreamFrame(raw=raw)+ try:+ payload: Final = _JSON_OBJECT.validate_python(json.loads(message.payload))+ except (json.JSONDecodeError, UnicodeDecodeError, ValidationError):+ return ConverseStreamFrame(raw=raw, event_type=event_type)+ return ConverseStreamFrame(raw=raw, event_type=event_type, payload=payload)+++async def _converse_stream_frames(chunks: AsyncIterable[bytes]) -> AsyncGenerator[ConverseStreamFrame, None]:+ """Cut the upstream bytes into frames as soon as each frame has fully arrived, then add an empty item that ends+ the stream once the upstream has ended.++ Bytes that cannot be framed (a length below the 16-byte minimum, or a stream that ends inside a frame) are relayed+ as received."""+ pending = b"" # rebind-ok: bytes received but not yet framed+ framing = True # rebind-ok: cleared once a frame length is unusable+ async for chunk in chunks:+ if not framing:+ yield ConverseStreamFrame(raw=chunk)+ continue+ pending += chunk+ while len(pending) >= 4:+ total_length = _unpack_uint32(pending[:4])+ if total_length < 16:+ framing = False+ break+ if len(pending) < total_length:+ break+ yield _decode_converse_frame(pending[:total_length])+ pending = pending[total_length:]+ if not framing and pending:+ yield ConverseStreamFrame(raw=pending)+ pending = b""+ if pending:+ yield ConverseStreamFrame(raw=pending)+ yield ConverseStreamFrame(raw=b"", ends_stream=True)+++def _converse_frames(items: Sequence[object]) -> tuple[ConverseStreamFrame, ...]:+ """The frames among ``items``, with the bytes an earlier guardrail's block message added read back into frames."""+ return tuple(+ item if isinstance(item, ConverseStreamFrame) else _decode_converse_frame(item)+ for item in items+ if isinstance(item, (ConverseStreamFrame, bytes))+ )+++def _reads_stream_marks(guardrail: "CustomGuardrail") -> bool:+ return getattr(guardrail, "reads_stream_marks", False) is True+++def _json_object_member(value: object, key: str) -> Mapping[str, object] | None:+ """``value[key]`` when both are JSON objects, else None."""+ try:+ return _JSON_OBJECT.validate_python(_JSON_OBJECT.validate_python(value).get(key))+ except ValidationError:+ return None+++def _reject_json_constant(name: str) -> object:+ raise ValueError(f"{name} is not JSON")+++def _finished_tool_input(text: str) -> object:+ """A tool call's streamed input as the JSON document Converse returns, or the text as received when it is not+ JSON (cut short, rewritten by a guardrail, or holding NaN or nesting too deep to send on)."""+ try:+ return json.loads(text, parse_constant=_reject_json_constant) if text else {}+ except (ValueError, RecursionError):+ return text+++def _finished_converse_content(+ frames: Sequence[ConverseStreamFrame], groups: _StreamTextGroups+) -> list[dict[str, object]]: # mutable-ok: the content of the finished response guardrails receive+ """The finished reply's text, reasoning and tool-call blocks, shaped as a non-streaming Converse response+ holds them."""+ texts: Final = dict(zip(groups.groups, groups.texts()))+ tool_starts: Final[dict[int | None, Mapping[str, object]]] = {} # mutable-ok: built in one pass over the frames+ keys: Final[dict[_StreamGroupKey, None]] = {} # mutable-ok: blocks in stream order, built in one pass+ for frame in frames:+ tool_use = (+ _json_object_member(_json_object_member(frame.payload, "start"), "toolUse")+ if frame.event_type == "contentBlockStart"+ else None+ )+ if tool_use is not None:+ tool_starts[frame.block_index] = tool_use+ keys[(frame.block_index, "tool")] = None+ keys.update((key, None) for key, _ in frame.scanned_texts())+ content: Final[list[dict[str, object]]] = [] # mutable-ok: built in one pass over the blocks+ for block_index, kind in keys:+ text = texts.get((block_index, kind), "")+ if kind == "tool":+ tool_start = tool_starts.get(block_index, {})+ named = {name: tool_start[name] for name in ("toolUseId", "name", "type") if name in tool_start}+ content.append({"toolUse": {**named, "input": _finished_tool_input(text)}})+ elif text and kind == "reasoning":+ content.append({"reasoningContent": {"reasoningText": {"text": text}}})+ elif text:+ content.append({"text": text})+ return content+++def _stream_marked_request_data(+ request_data: Mapping[str, object], frames: Sequence[ConverseStreamFrame], groups: _StreamTextGroups, ended: bool+) -> dict[str, object]: # mutable-ok: the request dict guardrails receive+ """``request_data`` with the marks chat completions gives a streamed answer: ``stream`` on every scan and, once+ the stream has ended, the finished ``response``."""+ if not ended:+ return {**request_data, "stream": True}+ stop_reason: Final = next(+ (+ frame.payload.get("stopReason")+ for frame in frames+ if frame.event_type == "messageStop" and frame.payload is not None+ ),+ None,+ )+ message: Final = {"role": "assistant", "content": _finished_converse_content(frames, groups)}+ response: Final = {"output": {"message": message}, **({"stopReason": stop_reason} if stop_reason else {})}+ return {**request_data, "stream": True, "response": response}+++def _write_back_stream_texts(+ frames: Sequence[ConverseStreamFrame], groups: _StreamTextGroups, rewritten_texts: Sequence[str]+) -> None:+ split: Final = _split_group_texts(groups, rewritten_texts)+ for frame_idx, frame in enumerate(frames):+ current = frame.guardrailed_payload if frame.guardrailed_payload is not None else frame.payload+ if frame.event_type != "contentBlockDelta" or current is None:+ continue+ rewritten = copy.deepcopy(current)+ changed = False+ for local_idx, (_, container, key) in enumerate(_collect_stream_delta_text_holders(rewritten.get("delta"))):+ new_text = split.get((frame_idx, local_idx))+ if new_text is not None and new_text != container[key]:+ container[key] = new_text+ changed = True+ if changed:+ frame.guardrailed_payload = rewritten++class BedrockPassthroughGuardrailHandler(BaseTranslation):@staticmethoddef is_event_stream_content_type(content_type: str) -> bool:@@ -273,10 +582,6 @@ class BedrockPassthroughGuardrailHandler(BaseTranslation):user_api_key_dict: "UserAPIKeyAuth",data: dict,) -> bytes:- import json as _json- import struct- from binascii import crc32 as esm_crc32-from botocore.eventstream import EventStreamBufferframes: Final[list[_StreamFrame]] = []@@ -304,16 +609,11 @@ class BedrockPassthroughGuardrailHandler(BaseTranslation):frames.append({"raw": frame_raw, "texts": []})continue- texts: list[tuple[_StreamGroupKey, str]] = []+ texts: Sequence[tuple[_StreamGroupKey, str]] = ()if event_type == "contentBlockDelta":try:- payload_dict: dict[str, object] = _json.loads(payload_bytes)- block_index = payload_dict.get("contentBlockIndex")- # Group per content block: a guardrail edit that changes length must not move text between blocks.- texts = [- ((block_index if isinstance(block_index, int) else None, group_key), container[key])- for group_key, container, key in _collect_stream_delta_text_holders(payload_dict.get("delta"))- ]+ payload_dict: dict[str, object] = json.loads(payload_bytes)+ texts = _delta_frame_texts(payload_dict)except Exception as e:verbose_proxy_logger.debug("BedrockPassthroughGuardrailHandler: could not parse "@@ -325,27 +625,15 @@ class BedrockPassthroughGuardrailHandler(BaseTranslation):trailing_bytes: Final = body_bytes[offset:]- group_order: Final[list[_StreamGroupKey]] = []- group_members: Final[dict[_StreamGroupKey, list[tuple[int, int]]]] = {}- group_texts: Final[dict[_StreamGroupKey, list[str]]] = {}- for frame_idx, frame in enumerate(frames):- for local_idx, (group_key, text) in enumerate(frame["texts"]):- if group_key not in group_members:- group_members[group_key] = []- group_texts[group_key] = []- group_order.append(group_key)- group_members[group_key].append((frame_idx, local_idx))- group_texts[group_key].append(text)-- active_groups: Final = [gk for gk in group_order if "".join(group_texts[gk])]- if not active_groups:+ groups: Final = _group_stream_texts([frame["texts"] for frame in frames])+ if not groups.groups:return body_bytessynthetic_response: Final[dict] = {"output": {"message": {"role": "assistant",- "content": [{"text": "".join(group_texts[gk])} for gk in active_groups],+ "content": [{"text": text} for text in groups.texts()],}},"stopReason": "end_turn",@@ -367,24 +655,11 @@ class BedrockPassthroughGuardrailHandler(BaseTranslation):try:processed_blocks: Final = processed["output"]["message"]["content"]- de_anonymized_texts: Final = [processed_blocks[i]["text"] for i in range(len(active_groups))]+ de_anonymized_texts: Final = [processed_blocks[i]["text"] for i in range(len(groups.groups))]except (KeyError, IndexError, TypeError):return body_bytes- new_text_map: Final[dict[tuple[int, int], str]] = {}- for group_key, de_anonymized_text in zip(active_groups, de_anonymized_texts):- members = group_members[group_key]- orig_texts = group_texts[group_key]- total_orig = sum(len(t) for t in orig_texts) or 1- de_anon_len = len(de_anonymized_text)- pos = 0- for k, member in enumerate(members):- if k == len(members) - 1:- new_text_map[member] = de_anonymized_text[pos:]- else:- end = pos + round(de_anon_len * len(orig_texts[k]) / total_orig)- new_text_map[member] = de_anonymized_text[pos:end]- pos = end+ new_text_map: Final = _split_group_texts(groups, de_anonymized_texts) # pyright: ignore[reportUnknownArgumentType] # the hook returns an untyped responseresult_parts: Final[list[bytes]] = []@@ -399,27 +674,19 @@ class BedrockPassthroughGuardrailHandler(BaseTranslation):headers_bytes = frame_raw[12 : 12 + orig_hdrs_len]try:- payload_dict = _json.loads(frame_raw[12 + orig_hdrs_len : orig_total - 4])+ payload_dict = json.loads(frame_raw[12 + orig_hdrs_len : orig_total - 4])for local_idx, (_, container, key) in enumerate(_collect_stream_delta_text_holders(payload_dict.get("delta"))):new_text = new_text_map.get((frame_idx, local_idx))if new_text is not None:container[key] = new_text- new_payload = _json.dumps(payload_dict, separators=(",", ":")).encode()+ new_payload = json.dumps(payload_dict, separators=(",", ":")).encode()except Exception:result_parts.append(frame_raw)continue- new_total = 12 + orig_hdrs_len + len(new_payload) + 4- prelude = struct.pack("!II", new_total, orig_hdrs_len)- prelude_crc_val = esm_crc32(prelude) & 0xFFFFFFFF- prelude_crc_b = struct.pack("!I", prelude_crc_val)- part_for_msg_crc = prelude_crc_b + headers_bytes + new_payload- msg_crc_val = esm_crc32(part_for_msg_crc, prelude_crc_val) & 0xFFFFFFFF- msg_crc_b = struct.pack("!I", msg_crc_val)-- result_parts.append(prelude + prelude_crc_b + headers_bytes + new_payload + msg_crc_b)+ result_parts.append(_event_stream_message(headers_bytes, new_payload))result_parts.append(trailing_bytes)return b"".join(result_parts)@@ -503,6 +770,20 @@ class BedrockPassthroughGuardrailHandler(BaseTranslation):if not texts:return response+ await self._scan_output_texts(+ texts, holders, guardrail_to_apply, litellm_logging_obj, user_api_key_dict, request_data+ )+ return response++ async def _scan_output_texts(+ self,+ texts: list[str],+ holders: list[_StringHolder],+ guardrail_to_apply: "CustomGuardrail",+ litellm_logging_obj: Optional["LiteLLMLoggingObj"],+ user_api_key_dict: Optional["UserAPIKeyAuth"],+ request_data: dict[str, object] | None, # mutable-ok: the request dict guardrails receive+ ) -> None:effective_request_data = request_data or {}if "litellm_metadata" not in effective_request_data and user_api_key_dict is not None:user_metadata: Final = self.transform_user_api_key_dict_to_metadata(user_api_key_dict)@@ -513,8 +794,8 @@ class BedrockPassthroughGuardrailHandler(BaseTranslation):}inputs: Final = GenericGuardrailAPIInputs(texts=texts)- model: Final = effective_request_data.get("model") if effective_request_data else None- if model:+ model: Final = effective_request_data.get("model")+ if isinstance(model, str) and model:inputs["model"] = modelguardrailed_inputs: Final = await guardrail_to_apply.apply_guardrail(@@ -528,4 +809,122 @@ class BedrockPassthroughGuardrailHandler(BaseTranslation):if guardrailed_texts:_write_back_texts(guardrailed_texts, holders)- return response+ 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]:+ """+ Scan the Converse frames relayed so far as the buffered path scans a whole response: one text per content+ block and kind. Once the stream has ended, guardrail rewrites are written back into the frames, which reach+ the caller only when the stream is held until moderated. A guardrail that sets ``reads_stream_marks`` gets+ a copy of the request marked as chat completions marks a streamed answer; the others get it unchanged.+ Such a guardrail also gets the ended scan of a reply with no text, such as a call to a tool that takes no+ input, with no texts to scan.+ """+ frames: Final = _converse_frames(responses_so_far)+ groups: Final = _group_stream_texts([frame.scanned_texts() for frame in frames])+ ended: Final = self._check_streaming_has_ended(frames)+ reads_marks: Final = _reads_stream_marks(guardrail_to_apply)+ if not groups.groups:+ if request_data is not None and reads_marks and ended and _finished_converse_content(frames, groups):+ await self._scan_output_texts(+ [],+ [],+ guardrail_to_apply,+ litellm_logging_obj,+ user_api_key_dict,+ _stream_marked_request_data(request_data, frames, groups, ended),+ )+ return responses_so_far+ content: Final = [{"text": text} for text in groups.texts()]+ await self.process_output_response( # pyright: ignore[reportUnknownMemberType] # takes the untyped request dict+ response={"output": {"message": {"role": "assistant", "content": content}}},+ guardrail_to_apply=guardrail_to_apply,+ litellm_logging_obj=litellm_logging_obj,+ user_api_key_dict=user_api_key_dict,+ request_data=(+ _stream_marked_request_data(request_data, frames, groups, ended)+ if request_data is not None and reads_marks+ else request_data+ ),+ )+ if ended:+ _write_back_stream_texts(frames, groups, [block["text"] for block in content])+ return responses_so_far++ def needs_ended_stream_scan(self, guardrail: "CustomGuardrail", responses_so_far: Sequence[object]) -> bool:+ return _reads_stream_marks(guardrail)++ def get_streaming_scan_key(self, responses_so_far: Sequence[object]) -> StreamingScanKey | None:+ frames: Final = _converse_frames(responses_so_far)+ return StreamingScanKey(+ texts=_group_stream_texts([frame.received_texts() for frame in frames]).texts(),+ stream_ended=self._check_streaming_has_ended(frames),+ )++ def _check_streaming_has_ended(self, responses_so_far: Sequence[object]) -> bool:+ return any(+ frame.event_type == "messageStop" or frame.ends_stream for frame in _converse_frames(responses_so_far)+ )++ def build_block_sse_chunks(+ self,+ exc: "ModifyResponseException",+ stream_started: bool = False,+ responses_so_far: Sequence[object] | None = None,+ ) -> Sequence[bytes]:+ """+ End the message with the guardrail's message as a new text block and ``stopReason`` ``guardrail_intervened``,+ closing any content block left open and starting the message when nothing was relayed yet.+ """+ frames: Final = _converse_frames(responses_so_far or ())+ started: Final = frozenset(+ index+ for index in (+ frame.block_index for frame in frames if frame.event_type in ("contentBlockStart", "contentBlockDelta")+ )+ if index is not None+ )+ stopped: Final = frozenset(+ index+ for index in (frame.block_index for frame in frames if frame.event_type == "contentBlockStop")+ if index is not None+ )+ block_index: Final = max(started | stopped, default=-1) + 1+ return (+ *(+ ()+ if any(frame.event_type == "messageStart" for frame in frames)+ else (_converse_event("messageStart", {"role": "assistant"}),)+ ),+ *(_converse_event("contentBlockStop", {"contentBlockIndex": index}) for index in sorted(started - stopped)),+ _converse_event("contentBlockDelta", {"contentBlockIndex": block_index, "delta": {"text": exc.message}}),+ _converse_event("contentBlockStop", {"contentBlockIndex": block_index}),+ _converse_event("messageStop", {"stopReason": "guardrail_intervened"}),+ )++ @staticmethod+ def owns_event_stream_item(item: object) -> bool:+ return isinstance(item, ConverseStreamFrame)++ @staticmethod+ def event_stream_items(chunks: AsyncIterable[bytes]) -> AsyncGenerator[ConverseStreamFrame, None]:+ return _converse_stream_frames(chunks)++ @staticmethod+ def encode_event_stream_item(item: object) -> bytes:+ if isinstance(item, ConverseStreamFrame):+ return item.encode()+ if isinstance(item, bytes):+ return item+ raise TypeError(f"cannot relay {type(item).__name__} on a Converse event stream")++ @staticmethod+ def event_stream_error_item(message: str, status_code: int) -> bytes:+ return _converse_exception(message, status_code)diff --git a/litellm/llms/bedrock/passthrough/transformation.py b/litellm/llms/bedrock/passthrough/transformation.pyindex 03e2ee6745c..fb0ecd5b825 100644--- a/litellm/llms/bedrock/passthrough/transformation.py+++ b/litellm/llms/bedrock/passthrough/transformation.py@@ -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 chainfrom types import MappingProxyTypefrom typing import TYPE_CHECKING, Final, Optional, castimport httpxfrom httpx import Response+from pydantic import TypeAdapterfrom litellm._logging import verbose_loggerfrom litellm.litellm_core_utils.litellm_logging import Loggingfrom litellm.llms.base_llm.passthrough.transformation import BasePassthroughConfig, PassthroughStreamCollector+from litellm.types.llms.openai import ChatCompletionSystemMessage, ChatCompletionUserMessagefrom litellm.types.utils import ModelResponseStreamfrom ..base_aws_llm import BaseAWSLLM@@ -91,6 +95,57 @@ def _translate_message(decoder: "AWSEventStreamDecoder", message: str) -> ModelRreturn 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"]:@@ -98,7 +153,13 @@ def _build_logged_response(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:diff --git a/litellm/llms/pass_through/guardrail_translation/handler.py b/litellm/llms/pass_through/guardrail_translation/handler.pyindex b0da53af8b3..d57175fa76e 100644--- a/litellm/llms/pass_through/guardrail_translation/handler.py+++ b/litellm/llms/pass_through/guardrail_translation/handler.py@@ -6,17 +6,21 @@ It uses the field targeting configuration from litellm_logging_objto extract specific fields for guardrail processing."""-from collections.abc import Mapping+from collections.abc import AsyncIterable, AsyncIterator, Callable, Mapping, Sequencefrom typing import TYPE_CHECKING, Final, Optional, Protocol, runtime_checkablefrom litellm._logging import verbose_proxy_loggerfrom 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 PassThroughGuardrailSettingsfrom litellm.types.utils import GenericGuardrailAPIInputsif TYPE_CHECKING:- from litellm.integrations.custom_guardrail import CustomGuardrail+ from litellm.integrations.custom_guardrail import CustomGuardrail, ModifyResponseExceptionfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObjfrom litellm.proxy.utils import ProxyLoggingfrom litellm.types.proxy.auth.user_api_key_auth import UserAPIKeyAuth@@ -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.@@ -277,6 +290,98 @@ class LlmPassthroughRouteHandler(BaseTranslation):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+@staticmethoddef is_event_stream_response(provider: str | None, content_type: str) -> bool:handler_cls: Final = _get_provider_handlers().get(provider or "")diff --git a/litellm/passthrough/main.py b/litellm/passthrough/main.pyindex 420f42c690c..744f9e1aa4c 100644--- a/litellm/passthrough/main.py+++ b/litellm/passthrough/main.py@@ -99,7 +99,8 @@ class AsyncPassthroughStreamingResponse(AsyncGenerator[bytes, bytes]):self._litellm_logging_obj = litellm_logging_objself._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[bool]] = set() # mutable-ok: instance set for background task tracking+ self._flush: asyncio.Task[bool] | None = Noneself._hidden_params: dict[str, object] = {} # mutable-ok: router attaches response headers here in place@property@@ -157,6 +158,7 @@ class AsyncPassthroughStreamingResponse(AsyncGenerator[bytes, bytes]):)self._background_tasks.add(task)+ self._flush = tasktask.add_done_callback(self._background_tasks.discard)except Exception as e: # noqa: BLE001 # Safe catch-all for verbose logging@@ -166,6 +168,16 @@ class AsyncPassthroughStreamingResponse(AsyncGenerator[bytes, bytes]):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 it logged the stream, which it does not when the stream returned nothing it could read. Cancelling the+ wait leaves the flush running."""+ flush: Final = self._flush+ if flush is None:+ return False+ outcome: Final = await asyncio.shield(asyncio.gather(flush, return_exceptions=True))+ return outcome[0] is True+def __aiter__(self) -> AsyncPassthroughStreamingResponse:return selfdiff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.pyindex 61c26cbd502..9020b89b766 100644--- a/litellm/proxy/common_request_processing.py+++ b/litellm/proxy/common_request_processing.py@@ -3,7 +3,7 @@ import contextlibimport jsonimport loggingimport math-from collections.abc import AsyncGenerator, Awaitable, Callable, Coroutine, Mapping, Sequence+from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Coroutine, Mapping, Sequencefrom datetime import datetimefrom functools import lru_cachefrom types import MappingProxyType@@ -138,6 +138,7 @@ from litellm.types.router_weights import validate_router_weights_LateResponseT = TypeVar("_LateResponseT", bound=Response)_LlmCallT = TypeVar("_LlmCallT")+_ChunkT: Final = TypeVar("_ChunkT")KNOWN_PROXY_ROUTES: Final = frozenset(route for member in LiteLLMRoutes for route in member.value if route.startswith("/")@@ -927,6 +928,21 @@ def _extract_error_from_sse_chunk(event_line: str | bytes) -> dict:return default_error+async def _close_upstream(upstream: object) -> None:+ aclose: Final[Callable[[], Awaitable[object]] | None] = getattr(upstream, "aclose", None)+ if aclose is not None:+ await aclose()+++async def _close_upstream_and_log_its_spend(upstream: object) -> bool:+ """Close the upstream and wait until the spend it collected has been logged. False when it had none to log."""+ await _close_upstream(upstream)+ wait_for_spend_flush: Final[Callable[[], Awaitable[object]] | None] = getattr(+ upstream, "wait_for_spend_flush", None+ )+ return wait_for_spend_flush is not None and await wait_for_spend_flush() is True++class _UpstreamClosingStreamingResponse(StreamingResponse):"""StreamingResponse that always closes its body iterator and the wrappedupstream generator.@@ -973,7 +989,7 @@ class _UpstreamClosingStreamingResponse(StreamingResponse):class _ClientDisconnectedBeforeFirstChunk(Exception):- """Client went away during create_response's first-chunk buffering window.+ """Client went away while the first chunk of a streamed response was being buffered.The upstream LLM stream has already been closed by the time this is raised."""@@ -997,24 +1013,24 @@ async def _wait_for_http_disconnect(request: Request) -> None:async def _buffer_first_chunk_honoring_disconnect(- generator: AsyncGenerator[str, None],+ generator: AsyncGenerator[_ChunkT, None],request: Request | None,-) -> str:+) -> _ChunkT:"""Fetch the first streamed chunk, cancelling the upstream LLM call if theclient disconnects before it arrives.- create_response buffers the first chunk to detect error-only streams before- handing the StreamingResponse to Starlette, which only begins listening for- client disconnects once it is serving that response. A disconnect during a- long time-to-first-token would otherwise leave the upstream call running- until the request timeout (LIT-3568). Cancelling the fetch propagates into- async_streaming_data_generator, whose finally block records the 499 and- closes the upstream stream.+ create_response and the guarded passthrough relay buffer the first chunk+ before handing the StreamingResponse to Starlette, which only begins+ listening for client disconnects once it is serving that response. A+ disconnect during a long time-to-first-token would otherwise leave the+ upstream call running until the request timeout (LIT-3568). Cancelling the+ fetch propagates into the generator, whose cleanup closes the upstream+ stream. A cancellation of the caller stops the fetch the same way."""if request is None:return await generator.__anext__()- chunk_task: Final[asyncio.Task[str]] = asyncio.ensure_future(generator.__anext__())+ chunk_task: Final[asyncio.Task[_ChunkT]] = asyncio.ensure_future(generator.__anext__())disconnect_task: Final[asyncio.Task[None]] = asyncio.ensure_future(_wait_for_http_disconnect(request))try:await asyncio.wait({chunk_task, disconnect_task}, return_when=asyncio.FIRST_COMPLETED)@@ -1023,6 +1039,9 @@ async def _buffer_first_chunk_honoring_disconnect(# Take the cancellation path whenever a disconnect was observed, even if# the first chunk landed in the same scheduler turn.disconnect_observed: Final = disconnect_task.done()+ except BaseException:+ await _cancel_first_chunk_fetch(chunk_task, generator)+ raisefinally:disconnect_task.cancel()try:@@ -1033,6 +1052,14 @@ async def _buffer_first_chunk_honoring_disconnect(if not disconnect_observed and chunk_task.done() and not chunk_task.cancelled():return chunk_task.result()+ await _cancel_first_chunk_fetch(chunk_task, generator)+ verbose_proxy_logger.info("client disconnected before the first streamed chunk, upstream LLM request cancelled")+ raise _ClientDisconnectedBeforeFirstChunk()+++async def _cancel_first_chunk_fetch(+ chunk_task: asyncio.Task[_ChunkT], generator: AsyncGenerator[_ChunkT, None]+) -> None:chunk_task.cancel()with anyio.CancelScope(shield=True):try:@@ -1042,9 +1069,25 @@ async def _buffer_first_chunk_honoring_disconnect(try:await generator.aclose()except BaseException as exc: # noqa: BLE001- verbose_proxy_logger.debug("create_response: error closing generator on disconnect: %s", exc)- verbose_proxy_logger.info("create_response: client disconnected before first chunk, upstream LLM request cancelled")- raise _ClientDisconnectedBeforeFirstChunk()+ verbose_proxy_logger.debug(+ "error closing the streamed response's generator before its first chunk: %s", exc+ )+++def _client_disconnected_response(headers: Mapping[str, str] | None) -> JSONResponse:+ """The 499 returned once the client left before the first streamed chunk, which the client never reads."""+ return JSONResponse(+ status_code=LITELLM_HTTP_STATUS_CLIENT_DISCONNECTED,+ content={+ "error": {+ "message": _CLIENT_DISCONNECT_DETAIL,+ "type": "client_disconnect",+ "param": None,+ "code": str(LITELLM_HTTP_STATUS_CLIENT_DISCONNECTED),+ }+ },+ headers=headers,+ )def sse_error_payload(exc: BaseException) -> tuple[int, Mapping[str, object]]:@@ -1174,18 +1217,7 @@ async def create_response(except _ClientDisconnectedBeforeFirstChunk:# Client vanished during the time-to-first-token wait; the upstream# stream is already closed. Return a 499 the (now-gone) client never reads.- return JSONResponse(- status_code=LITELLM_HTTP_STATUS_CLIENT_DISCONNECTED,- content={- "error": {- "message": _CLIENT_DISCONNECT_DETAIL,- "type": "client_disconnect",- "param": None,- "code": str(LITELLM_HTTP_STATUS_CLIENT_DISCONNECTED),- }- },- headers=headers,- )+ return _client_disconnected_response(headers)except StopAsyncIteration:# Generator was empty. Default statusasync def empty_gen() -> AsyncGenerator[str, None]:@@ -2954,6 +2986,19 @@ class ProxyBaseLLMRequestProcessing:self._has_post_call_guardrails_for_passthrough()and self._passthrough_endpoint_has_stream_guardrail_handler()):+ relayed_guardrails: Final = self._passthrough_stream_guardrails(+ self.data # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType] # self.data is the untyped request dict+ )+ if relayed_guardrails is not None:+ return await self._relay_guarded_passthrough_event_stream(+ request=request,+ request_data=self.data, # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType] # self.data is the untyped request dict+ generator=generator, # pyright: ignore[reportUnknownArgumentType] # raw upstream byte stream+ guardrails=relayed_guardrails,+ proxy_logging_obj=proxy_logging_obj,+ user_api_key_dict=user_api_key_dict,+ headers=streaming_headers, # pyright: ignore[reportUnknownArgumentType] # merged upstream headers+ )body_bytes: Final = b"".join([chunk async for chunk in generator])modified_bytes: Final = await self._handle_event_stream_allm_passthrough_route(body_bytes=body_bytes,@@ -3473,6 +3518,175 @@ class ProxyBaseLLMRequestProcessing:self.data.get("endpoint"),)+ @staticmethod+ def _passthrough_stream_guardrails(+ request_data: dict[str, object], # mutable-ok: model-level guardrails merge into a copy of it+ ) -> tuple[tuple[CustomGuardrail, bool], ...] | None:+ """+ The post_call guardrails to run on a passthrough event stream relayed frame by frame, each with whether it+ holds the stream until moderated by default, or None when the stream must be buffered whole instead.++ A guardrail relays when ``post_call_success_hook`` would scan it through ``apply_guardrail``. One that runs+ its own ``async_post_call_success_hook``, masks responses with ``mask_response_content``, releases a held+ stream as each scan passes, runs with ``run_in_parallel`` after the sequential guardrails, or is a step of a+ post_call policy pipeline still needs the whole response, so its stream stays buffered.+ """+ from litellm.proxy.proxy_server import llm_router+ from litellm.proxy.utils import pipeline_managed_guardrail_names++ if pipeline_managed_guardrail_names(request_data, "post_call"):+ return None+ guardrail_data: Final = check_and_merge_model_level_guardrails( # pyright: ignore[reportUnknownVariableType] # returns the untyped request dict+ data=request_data, llm_router=llm_router+ )+ relayed: Final[list[tuple[CustomGuardrail, bool]]] = [] # mutable-ok: built once per request+ for cb in litellm.callbacks:+ if not isinstance(cb, CustomGuardrail):+ continue+ if (+ cb.should_run_guardrail( # pyright: ignore[reportUnknownMemberType] # takes the untyped request dict+ data=guardrail_data, event_type=GuardrailEventHooks.post_call+ )+ is not True+ ):+ continue+ leaf_attrs = type(cb).__dict__+ holds_until_moderated = "async_post_call_streaming_iterator_hook" in leaf_attrs+ if (+ "apply_guardrail" not in leaf_attrs+ or cb.use_native_lifecycle_hooks+ or cb.mask_response_content+ or cb.run_in_parallel+ or ProxyBaseLLMRequestProcessing._releases_held_stream_on_scan(cb, holds_until_moderated)+ ):+ return None+ relayed.append((cb, holds_until_moderated))+ return tuple(relayed)++ @staticmethod+ def _releases_held_stream_on_scan(guardrail: CustomGuardrail, holds_until_moderated: bool) -> bool:+ """+ Whether the unified guardrail holds this guardrail's stream and releases each window once its scan passes+ (``streaming_buffer_release_on_scan``). Those windows go out as received, without the scan's masks.+ """+ from litellm.proxy.utils import unified_guardrail++ def flag(name: str, default: bool) -> bool:+ return bool(unified_guardrail.resolve_streaming_flag(guardrail, name, default))++ return (+ flag("streaming_buffer_until_moderated", holds_until_moderated)+ and flag("streaming_buffer_release_on_scan", False)+ and not flag("streaming_end_of_stream_only", False)+ )++ async def _relay_guarded_passthrough_event_stream(+ self,+ request: Request | None,+ request_data: dict[str, object], # mutable-ok: the request dict the hooks mutate+ generator: AsyncIterator[bytes],+ guardrails: Sequence[tuple[CustomGuardrail, bool]],+ proxy_logging_obj: ProxyLogging,+ user_api_key_dict: UserAPIKeyAuth,+ headers: Mapping[str, str],+ ) -> StreamingResponse | JSONResponse:+ """+ Relay a passthrough event stream as it arrives while post_call guardrails scan it, the way /v1/messages+ streams are guarded. A failure before the first frame raises, so the caller gets an HTTP error as on the+ buffered path; after it, the failure ends the stream with the provider's in-stream exception frame. A+ client that leaves before the first frame stops the upstream read and gets the 499 chat completions returns.+ """+ from litellm.llms.pass_through.guardrail_translation.handler import (+ LlmPassthroughRouteHandler,+ )++ provider: Final = request_data.get("custom_llm_provider")+ items: Final = LlmPassthroughRouteHandler.event_stream_items(provider, generator)+ if items is None:+ raise TypeError(f"provider {provider!r} has no event-stream framer")+ guarded: Final = proxy_logging_obj.async_post_call_event_stream_iterator_hook(+ response=items,+ user_api_key_dict=user_api_key_dict,+ request_data=request_data,+ guardrails=guardrails,+ )++ async def relay() -> AsyncGenerator[bytes, None]:+ delivered = False # rebind-ok: set once the first frame reached the caller+ try:+ async for item in guarded:+ frame = LlmPassthroughRouteHandler.encode_event_stream_item(provider, item)+ if frame:+ yield frame+ delivered = True+ except Exception as e:+ if not delivered:+ raise+ verbose_proxy_logger.exception("allm_passthrough_route: guarded event stream failed mid-stream: %s", e)+ # The failure hook rewrites the request's logging object, so the stream's spend is logged first.+ await _close_upstream_and_log_its_spend(generator)+ transformed: Final = await proxy_logging_obj.post_call_failure_hook( # pyright: ignore[reportUnknownMemberType] # takes the untyped request dict+ user_api_key_dict=user_api_key_dict,+ original_exception=e,+ request_data=request_data,+ )+ failure: Final = transformed if transformed is not None else e+ message: Final = (+ serialize_http_exception_detail(failure.detail)[0]+ if isinstance(failure, HTTPException)+ else redact_internal_details_from_client_message(getattr(failure, "message", str(failure)))+ )+ error_item: Final = LlmPassthroughRouteHandler.event_stream_error_item(+ provider, message, error_status_code(failure, status.HTTP_500_INTERNAL_SERVER_ERROR)+ )+ if error_item is None:+ raise+ yield error_item+ finally:+ try:+ await guarded.aclose()+ finally:+ await _close_upstream(generator)++ relayed: Final = relay()+ read_ahead: Final[list[bytes]] = [] # mutable-ok: the first frame, read before the response starts+ try:+ read_ahead.append(await _buffer_first_chunk_honoring_disconnect(relayed, request))+ except _ClientDisconnectedBeforeFirstChunk:+ with anyio.CancelScope(shield=True):+ if not await _close_upstream_and_log_its_spend(generator):+ # No spend row settles a stream that returned nothing it could log, so release what the request+ # holds, as chat completions does.+ from litellm.proxy.spend_tracking.budget_reservation import (+ release_budget_reservation_on_cancel, # pyright: ignore[reportUnknownVariableType] # takes the untyped reservation dict+ )++ await release_budget_reservation_on_cancel(getattr(user_api_key_dict, "budget_reservation", None))+ await proxy_logging_obj.arelease_max_parallel_requests_on_disconnect(user_api_key_dict)+ return _client_disconnected_response(+ {k: v for k, v in headers.items() if k.lower() not in ("content-length", "content-type")}+ )+ except StopAsyncIteration:+ pass+ except BaseException:+ with anyio.CancelScope(shield=True):+ await _close_upstream_and_log_its_spend(generator)+ raise++ async def body() -> AsyncGenerator[bytes, None]:+ async with contextlib.aclosing(relayed) as rest:+ for frame in read_ahead:+ yield frame+ async for frame in rest:+ yield frame++ return _UpstreamClosingStreamingResponse(+ content=body(), # pyright: ignore[reportArgumentType] # bytes body, as on the unguarded relay+ media_type=self._passthrough_event_stream_media_type(),+ headers={k: v for k, v in headers.items() if k.lower() != "content-length"},+ upstream_generator=relayed, # pyright: ignore[reportArgumentType] # closing it closes the guardrails and the upstream+ )+def _passthrough_event_stream_media_type(self) -> str | None:"""Content-type for a passthrough event-stream response, resolved from thediff --git a/litellm/proxy/guardrails/guardrail_hooks/noma/noma_v2.py b/litellm/proxy/guardrails/guardrail_hooks/noma/noma_v2.pyindex 360752d201a..718401b6e68 100644--- a/litellm/proxy/guardrails/guardrail_hooks/noma/noma_v2.py+++ b/litellm/proxy/guardrails/guardrail_hooks/noma/noma_v2.py@@ -4,12 +4,13 @@## +-------------------------------------------------------------++import asyncioimport enumimport jsonimport osfrom collections.abc import Callable, Mappingfrom datetime import datetime-from typing import TYPE_CHECKING, Any, Final, Literal, Optional, TypeAlias, cast+from typing import TYPE_CHECKING, Any, ClassVar, Final, Literal, Optional, TypeAlias, castfrom urllib.parse import urlparsefrom litellm._logging import verbose_proxy_logger@@ -56,6 +57,11 @@ class _Action(str, enum.Enum):class NomaV2Guardrail(CustomGuardrail):+ reads_stream_marks: ClassVar[bool] = True+ """Noma keeps one record per streamed reply when every scan carries ``stream`` and only the last one carries the+ finished ``response``, as chat completions sends them, so provider streams relayed on the passthrough route mark+ this guardrail's scans that way."""+def __init__(self,api_key: str | None = None,@@ -361,6 +367,10 @@ class NomaV2Guardrail(CustomGuardrail):response_json if isinstance(response_json, dict) else getattr(e, "detail", blocked_detail))raise+ except asyncio.CancelledError:+ # The caller left before Noma answered, so there is no verdict to record.+ guardrail_status = "not_run" # rebind-ok: the status the finally block records+ raiseexcept Exception as e:guardrail_status = "guardrail_failed_to_respond"guardrail_json_response = str(e)diff --git a/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py b/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.pyindex a7f813d953e..3ad9d1a2c42 100644--- a/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py+++ b/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py@@ -82,6 +82,9 @@ class _EndpointTranslation(Protocol):@propertydef get_streaming_scan_key(self) -> "Callable[[Sequence[object]], StreamingScanKey | None]": ...+ @property+ def needs_ended_stream_scan(self) -> "Callable[[CustomGuardrail, Sequence[object]], bool]": ...+@propertydef released_stream_as_ended(self) -> "Callable[[Sequence[object]], tuple[object, ...]]": ...@@ -153,6 +156,21 @@ def _is_redundant_scan(scan_key: "StreamingScanKey | None", last_scan_key: "Strereturn scan_key == last_scan_key or scan_key.has_nothing_to_scan+def _owes_ended_scan(+ endpoint_translation: _EndpointTranslation,+ guardrail: CustomGuardrail,+ responses_so_far: Sequence[object],+ last_scan_key: "StreamingScanKey | None",+) -> bool:+ """Whether the end-of-stream round still runs after a sampled round covered every text before the stream ended,+ because the translation hands ``guardrail`` marks only an ended round carries."""+ return (+ last_scan_key is not None+ and not last_scan_key.stream_ended+ and endpoint_translation.needs_ended_stream_scan(guardrail, responses_so_far)+ )++class _StreamTerminated(Exception):"""Internal signal that the incremental transform stream has already emittedits terminal chunks (block message or in-stream error) and must stop."""@@ -1233,6 +1251,13 @@ class UnifiedLLMGuardrails(CustomLogger):if call_type is None:call_type = infer_call_type(call_type=None, completion_response=item)+ # Provider passthrough routes (e.g. /bedrock/.../converse-stream) map to no call type, and their+ # frames carry none; the logging object names the passthrough, as on the non-streaming path.+ if call_type is None:+ logging_call_type = getattr(typed_request_data.get("litellm_logging_obj"), "call_type", None)+ if logging_call_type == CallTypes.allm_passthrough_route.value:+ call_type = logging_call_type+# If call type not supported, just pass through all chunksif call_type is None or CallTypes(call_type) not in mappings:yield item@@ -1383,7 +1408,9 @@ class UnifiedLLMGuardrails(CustomLogger):)end_scan_key: Final = endpoint_translation.get_streaming_scan_key(responses_so_far)verdict_settled = True- if _is_redundant_scan(end_scan_key, last_scan_key):+ if _is_redundant_scan(end_scan_key, last_scan_key) and not _owes_ended_scan(+ endpoint_translation, guardrail_to_apply, responses_so_far, last_scan_key+ ):verbose_proxy_logger.debug("Skipping end-of-stream scan for guardrail %s: the last sampled round already scanned it all",guardrail_to_apply.guardrail_name,diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex e34093a7caf..29749afb429 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -4167,6 +4167,49 @@ class ProxyLogging:await ProxyLogging._record_served_stream_output(request_data, served_chunks)ProxyLogging.fire_deferred_stream_logging(request_data)+ async def async_post_call_event_stream_iterator_hook(+ self,+ response: AsyncIterable[object],+ user_api_key_dict: UserAPIKeyAuth,+ request_data: dict[str, object], # mutable-ok: same request-payload shape the hooks mutate+ guardrails: Sequence[tuple[CustomGuardrail, bool]],+ ) -> AsyncGenerator[object, None]:+ """+ Run post_call guardrails over a provider event stream the proxy relays as it arrives, such as a Bedrock+ Converse stream on the passthrough route. Each guardrail scans the stream through the unified guardrail, as+ on /v1/messages; its flag says whether it holds the stream until moderated by default.+ """+ from litellm.proxy.proxy_server import llm_router++ merged_request_data: Final[dict[str, object]] = check_and_merge_model_level_guardrails( # pyright: ignore[reportUnknownVariableType] # returns the untyped request dict # mutable-ok: same request-payload shape the hooks mutate+ data=request_data, llm_router=llm_router+ )+ current_response: AsyncIterable[object] = response # rebind-ok: each guardrail wraps the previous layer+ guarded_layers: Final[list[AsyncGenerator[object, None]]] = [] # mutable-ok: closed on disconnect+ for guardrail, holds_until_moderated in guardrails:+ if guarded_layers:+ current_response = ProxyLogging._released_copies(current_response)+ guarded_layers.append(current_response)+ current_response = self._wrap_streaming_iterator_with_enrichment(+ guardrail,+ current_response,+ partial(+ unified_guardrail.async_post_call_streaming_iterator_hook, # pyright: ignore[reportUnknownMemberType] # takes the untyped request dict+ user_api_key_dict=user_api_key_dict,+ request_data=merged_request_data,+ guardrail_to_apply=guardrail,+ buffer_until_moderated_default=holds_until_moderated,+ ),+ request_data=merged_request_data,+ )+ guarded_layers.append(current_response)+ try:+ async for item in current_response:+ yield item+ except (GeneratorExit, asyncio.CancelledError):+ await ProxyLogging._close_guarded_layers(guarded_layers)+ raise+async def _pipeline_gated_stream(self,response: "AsyncGenerator[object, None]",@@ -4351,6 +4394,13 @@ class ProxyLogging:event_type=GuardrailEventHooks.post_call,)+ @staticmethod+ async def _released_copies(items: AsyncIterable[object]) -> AsyncGenerator[object, None]:+ """Each item a guardrail layer released, copied for the next layer, so a rewrite the earlier layer writes+ back once its stream ends never reaches items the next layer is still holding."""+ async for item in items:+ yield copy.copy(item)+@staticmethodasync def _close_guarded_layers(layers: Sequence[AsyncGenerator[object, None]]) -> None:for layer in reversed(layers):diff --git a/tests/integration/_support/wire.py b/tests/integration/_support/wire.pyindex e5ce909ab18..df6036ff8d7 100644--- a/tests/integration/_support/wire.py+++ b/tests/integration/_support/wire.py@@ -59,6 +59,7 @@ class Reply:content_type: str = "application/json"chunks: tuple[bytes, ...] | None = Noneabort_after: int | None = None+ gate_before_first: threading.Event | None = Nonegate_after_first: threading.Event | None = Nonepause_between_chunks: float = 0heartbeat: bytes | None = None@@ -166,6 +167,12 @@ def wire_server(for index, chunk in enumerate(reply.chunks):if reply.abort_after == index:break+ if (+ index == 0+ and reply.gate_before_first is not None+ and not _await_release(reply.gate_before_first, closing)+ ):+ breakself.write_chunk(chunk)if (index == 0diff --git a/tests/integration/observability/test_bedrock_converse_stream_post_call_guardrail.py b/tests/integration/observability/test_bedrock_converse_stream_post_call_guardrail.pynew file mode 100644index 00000000000..c55bd181ecb--- /dev/null+++ b/tests/integration/observability/test_bedrock_converse_stream_post_call_guardrail.py@@ -0,0 +1,1015 @@+"""A post_call guardrail on the Bedrock Converse streaming passthrough streams frame by frame (LIT-9515).++The caller is boto3 ``ConverseStream`` (or raw HTTP) against ``/bedrock/model/<model>/converse-stream``. A+guardrail that scans responses through ``apply_guardrail`` runs on the stream the way it runs on+``/v1/chat/completions``, ``/v1/messages`` and ``/v1/responses``: frames reach the caller as the upstream sends+them, every fifth frame and the end of the stream are scanned, and a block ends the stream with an AWS+exception frame. ``streaming_buffer_until_moderated: true`` still holds the stream and applies masks per content+block, and a caller leaving before the first held frame stops the proxy reading the upstream. Noma v2 scans carry+``stream`` and, on the last one, the finished ``response``, as chat completions sends them; other guardrails see the+request as before."""++from __future__ import annotations++import json+import os+import threading+import uuid+from collections.abc import Iterator, Mapping, Sequence+from concurrent.futures import ThreadPoolExecutor+from dataclasses import dataclass+from functools import partial+from pathlib import Path+from typing import Final++import boto3+import httpx+import pytest+import yaml+from botocore.config import Config+from botocore.eventstream import EventStreamBuffer+from botocore.exceptions import ClientError, EventStreamError+from integration._support.budget import case_timeout_seconds, import_seconds+from integration._support.client import Gateway, JsonValue, Scenario, eventually+from integration._support.database import read_rows+from integration._support.process import owned_proxy_process+from integration._support.upstream import aws_event_stream_frame+from integration._support.wire import Reply, Request, Wire, wire_server++MODEL_ID: Final = "anthropic.claude-sonnet-5-v1:0"+ROUTER_MODEL: Final = "converse-relay"+EVENT_STREAM: Final = "application/vnd.amazon.eventstream"+SAMPLED: Final = "relay-sampled"+BUFFERED: Final = "relay-buffered"+CODE: Final = "relay-code"+FAILING: Final = "relay-failing"+FAILING_HELD: Final = "relay-failing-held"+END_ONLY: Final = "relay-end-only"+OUTAGE: Final = "relay-outage"+STACKED: Final = "relay-stacked"+RELEASE_ON_SCAN: Final = "relay-release-on-scan"+REPLACING: Final = "relay-replacing"+REPLACING_THEN_HELD: Final = "relay-replacing-then-held"+PARALLEL: Final = "relay-parallel"+PARALLEL_FIRST: Final = "relay-parallel-first"+HELD_END_ONLY: Final = "relay-held-end-only"+NOMA: Final = "relay-noma"+ALICE: Final = "relay-alice"+NOMA_THEN_ALICE: Final = "relay-noma-then-alice"+CODE_BLOCK_REASON: Final = "code says no"+BLOCK_REASON: Final = "Violated guardrail policy"+MASKED_WORD: Final = "Paris"+MASK: Final = "[CITY]"+BLOCKED_WORD: Final = "FORBIDDEN"+REPLACED_WORD: Final = "CLASSIFIED"+REPLACEMENT: Final = "That answer was withheld"+++def event_frame(event_type: str, payload: Mapping[str, JsonValue]) -> bytes:+ return aws_event_stream_frame(+ {":event-type": event_type, ":content-type": "application/json", ":message-type": "event"},+ json.dumps(payload, separators=(",", ":")).encode(),+ )+++def converse_frames(*blocks: Sequence[str]) -> tuple[bytes, ...]:+ """A Converse stream with one text content block per entry of ``blocks``, one delta frame per string."""+ return (+ event_frame("messageStart", {"role": "assistant"}),+ *(+ frame+ for index, deltas in enumerate(blocks)+ for frame in (+ *(event_frame("contentBlockDelta", {"contentBlockIndex": index, "delta": {"text": t}}) for t in deltas),+ event_frame("contentBlockStop", {"contentBlockIndex": index}),+ )+ ),+ event_frame("messageStop", {"stopReason": "end_turn"}),+ event_frame("metadata", {"usage": {"inputTokens": 9, "outputTokens": 4, "totalTokens": 13}, "metrics": {}}),+ )+++@dataclass(frozen=True, slots=True)+class Frame:+ message_type: str+ kind: str+ payload: Mapping[str, JsonValue]+++def decode(raw: bytes) -> tuple[Frame, ...]:+ buffer: Final = EventStreamBuffer()+ buffer.add_data(raw)+ return tuple(+ Frame(+ str(message.headers[":message-type"]),+ str(message.headers.get(":event-type") or message.headers.get(":exception-type")),+ json.loads(message.payload),+ )+ for message in buffer+ )+++def block_texts(frames: Sequence[Frame]) -> dict[int, str]:+ texts: Final[dict[int, str]] = {}+ for frame in frames:+ if frame.kind != "contentBlockDelta":+ continue+ index = frame.payload["contentBlockIndex"]+ delta = frame.payload["delta"]+ assert isinstance(index, int) and isinstance(delta, dict), frame+ texts[index] = texts.get(index, "") + str(delta["text"])+ return texts+++def verdict(request: Request) -> Reply:+ texts: Final = [str(text) for text in json.loads(request.body)["texts"]]+ if any(BLOCKED_WORD in text for text in texts):+ return Reply(body=json.dumps({"action": "BLOCKED", "blocked_reason": BLOCK_REASON}).encode())+ if any(MASKED_WORD in text for text in texts):+ masked: Final = [text.replace(MASKED_WORD, MASK) for text in texts]+ return Reply(body=json.dumps({"action": "GUARDRAIL_INTERVENED", "texts": masked}).encode())+ return Reply(body=json.dumps({"action": "NONE"}).encode())+++def parallel_verdict(request: Request) -> Reply:+ """A block-only check that rejects ``MASKED_WORD`` it sees unmasked."""+ texts: Final = [str(text) for text in json.loads(request.body)["texts"]]+ if any(MASKED_WORD in text for text in texts):+ return Reply(body=json.dumps({"action": "BLOCKED", "blocked_reason": BLOCK_REASON}).encode())+ return Reply(body=json.dumps({"action": "NONE"}).encode())+++def bedrock_texts(request: Request) -> tuple[str, ...]:+ return tuple(str(item["text"]["text"]) for item in json.loads(request.body)["content"])+++def bedrock_verdict(request: Request) -> Reply:+ """ApplyGuardrail anonymizing ``MASKED_WORD``, as a Bedrock sensitive-information policy does."""+ texts: Final = bedrock_texts(request)+ if not any(MASKED_WORD in text for text in texts):+ return Reply(body=json.dumps({"action": "NONE", "outputs": [], "assessments": []}).encode())+ pii: Final = {"match": MASKED_WORD, "type": "ADDRESS", "action": "ANONYMIZED"}+ return Reply(+ body=json.dumps(+ {+ "action": "GUARDRAIL_INTERVENED",+ "outputs": [{"text": text.replace(MASKED_WORD, MASK)} for text in texts],+ "assessments": [{"sensitiveInformationPolicy": {"piiEntities": [pii]}}],+ }+ ).encode()+ )+++def bedrock_replacing_verdict(request: Request) -> Reply:+ """ApplyGuardrail blocking ``REPLACED_WORD`` with its blocked message, as a Bedrock word policy does."""+ if not any(REPLACED_WORD in text for text in bedrock_texts(request)):+ return Reply(body=json.dumps({"action": "NONE", "outputs": [], "assessments": []}).encode())+ word: Final = {"match": REPLACED_WORD, "action": "BLOCKED"}+ return Reply(+ body=json.dumps(+ {+ "action": "GUARDRAIL_INTERVENED",+ "outputs": [{"text": REPLACEMENT}],+ "assessments": [{"wordPolicy": {"customWords": [word]}}],+ }+ ).encode()+ )+++@dataclass(frozen=True, slots=True)+class Rig:+ gateway: Gateway+ scenario: Scenario+ provider: Wire+ sink: Wire+ scripts: dict[str, Reply]+ keys: Mapping[str, str]+ outage: threading.Event++ def scans(self, guardrail: str, marker: str) -> tuple[tuple[str, ...], ...]:+ return tuple(+ tuple(json.loads(request.body)["texts"])+ for request in self.sink.drain()+ if request.target.startswith(f"/{guardrail}/") and marker.encode() in request.body+ )++ def bedrock_scans(self, guardrail: str, marker: str) -> tuple[tuple[str, ...], ...]:+ return tuple(+ bedrock_texts(request)+ for request in self.sink.drain()+ if request.target.startswith(f"/{guardrail}/") and marker.encode() in request.body+ )++ def forwarded_request_data(self, marker: str) -> dict[str, tuple[Mapping[str, JsonValue], ...]]:+ """The ``request_data`` each response scan forwarded to Noma v2 and Alice, by guardrail, in scan order."""+ forwarded: Final[dict[str, list[Mapping[str, JsonValue]]]] = {NOMA: [], ALICE: []}+ for request in self.sink.drain():+ guardrail = request.target.split("/")[1]+ if guardrail in forwarded and marker.encode() in request.body:+ body = json.loads(request.body)+ if body["input_type"] == "response":+ forwarded[guardrail].append(body["request_data"])+ return {guardrail: tuple(scans) for guardrail, scans in forwarded.items()}++ def converse_stream(self, guardrail: str, marker: str) -> StreamOutcome:+ client: Final = boto3.client(+ "bedrock-runtime",+ region_name="us-east-1",+ endpoint_url=str(self.gateway.client.base_url).rstrip("/") + "/bedrock",+ aws_access_key_id="AKIASYNTHETICRELAY",+ aws_secret_access_key="synthetic-relay-secret",+ config=Config(read_timeout=case_timeout_seconds(), retries={"max_attempts": 1}),+ )+ key: Final = self.keys[guardrail]++ def authenticate(request: object, **_: object) -> None:+ getattr(request, "headers")["x-litellm-api-key"] = key++ client.meta.events.register("before-send.bedrock-runtime.*", authenticate)+ try:+ response: Final = client.converse_stream(+ modelId=ROUTER_MODEL, messages=[{"role": "user", "content": [{"text": marker}]}]+ )+ except ClientError as error:+ return StreamOutcome((), None, None, str(error))+ events: Final[list[str]] = []+ try:+ for event in response["stream"]:+ events.extend(event)+ except EventStreamError as error:+ return StreamOutcome(+ tuple(events), error.response["Error"]["Code"], error.response["Error"]["Message"], None+ )+ return StreamOutcome(tuple(events), None, None, None)+++@dataclass(frozen=True, slots=True)+class StreamOutcome:+ events: tuple[str, ...]+ error_code: str | None+ error_message: str | None+ rejected_before_stream: str | None+++def _guardrail(name: str, sink: Wire, **settings: JsonValue) -> dict[str, JsonValue]:+ return {+ "guardrail_name": name,+ "litellm_params": {+ "guardrail": "generic_guardrail_api",+ "mode": "post_call",+ "default_on": False,+ "api_base": f"{sink.url}/{name}",+ "api_key": "synthetic-guardrail-key",+ **settings,+ },+ }++[email protected](scope="module")+def rig(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Rig]:+ scripts: Final[dict[str, Reply]] = {}+ outage: Final = threading.Event()++ def provider(request: Request) -> Reply:+ assert request.target in (f"/model/{MODEL_ID}/converse-stream", f"/model/{MODEL_ID}/converse"), request.target+ marker: Final = json.loads(request.body)["messages"][0]["content"][0]["text"]+ return scripts[marker]++ def vendor(request: Request) -> Reply:+ failing: Final = request.target.startswith((f"/{FAILING}/", f"/{FAILING_HELD}/"))+ if failing or (outage.is_set() and request.target.startswith(f"/{OUTAGE}/")):+ return Reply(status=503, body=b'{"error":"guardrail vendor unavailable"}')+ if request.target.startswith(f"/{RELEASE_ON_SCAN}/"):+ return bedrock_verdict(request)+ if request.target.startswith(f"/{REPLACING}/"):+ return bedrock_replacing_verdict(request)+ if request.target.startswith(f"/{PARALLEL}/"):+ return parallel_verdict(request)+ if request.target.startswith(f"/{NOMA}/"):+ return Reply(body=json.dumps({"action": "NONE"}).encode())+ if request.target.startswith(f"/{ALICE}/"):+ return Reply(body=json.dumps({"verdict": "ALLOW"}).encode())+ return verdict(request)++ with httpx.Client(base_url=os.environ["INTEGRATION_PROXY_URL"], timeout=30, trust_env=False) as root_client:+ root: Final = Gateway(+ root_client,+ os.environ.get("INTEGRATION_MASTER_KEY", "sk-integration-master"),+ os.environ["INTEGRATION_UPSTREAM_URL"],+ )+ directory: Final = tmp_path_factory.mktemp("converse-stream-relay")+ with wire_server(provider) as upstream, wire_server(vendor) as sink:+ config: Final = yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text())+ config["guardrails"] = [+ _guardrail(PARALLEL, sink, run_in_parallel=True),+ _guardrail(SAMPLED, sink),+ {+ "guardrail_name": REPLACING,+ "litellm_params": {+ "guardrail": "bedrock",+ "mode": "post_call",+ "default_on": False,+ "guardrailIdentifier": "relay-replacing",+ "guardrailVersion": "1",+ "aws_access_key_id": "AKIASYNTHETICGUARD",+ "aws_secret_access_key": "synthetic-guardrail-secret",+ "aws_region_name": "us-east-1",+ "aws_bedrock_runtime_endpoint": f"{sink.url}/{REPLACING}",+ "disable_exception_on_block": True,+ "streaming_buffer_until_moderated": False,+ },+ },+ _guardrail(BUFFERED, sink, streaming_buffer_until_moderated=True),+ _guardrail(FAILING, sink),+ _guardrail(FAILING_HELD, sink, streaming_buffer_until_moderated=True),+ _guardrail(END_ONLY, sink, streaming_end_of_stream_only=True),+ _guardrail(+ HELD_END_ONLY, sink, streaming_buffer_until_moderated=True, streaming_end_of_stream_only=True+ ),+ {+ "guardrail_name": NOMA,+ "litellm_params": {+ "guardrail": "noma_v2",+ "mode": "post_call",+ "default_on": False,+ "api_base": f"{sink.url}/{NOMA}",+ "api_key": "synthetic-noma-key",+ },+ },+ {+ "guardrail_name": ALICE,+ "litellm_params": {+ "guardrail": "alice",+ "mode": "post_call",+ "default_on": False,+ "api_base": f"{sink.url}/{ALICE}",+ "api_key": "synthetic-alice-key",+ },+ },+ _guardrail(OUTAGE, sink),+ {+ "guardrail_name": RELEASE_ON_SCAN,+ "litellm_params": {+ "guardrail": "bedrock",+ "mode": "post_call",+ "default_on": False,+ "guardrailIdentifier": "relay-release-on-scan",+ "guardrailVersion": "1",+ "aws_access_key_id": "AKIASYNTHETICGUARD",+ "aws_secret_access_key": "synthetic-guardrail-secret",+ "aws_region_name": "us-east-1",+ "aws_bedrock_runtime_endpoint": f"{sink.url}/{RELEASE_ON_SCAN}",+ "streaming_buffer_release_on_scan": True,+ },+ },+ {+ "guardrail_name": CODE,+ "litellm_params": {+ "guardrail": "custom_code",+ "mode": "post_call",+ "default_on": False,+ "custom_code": (+ "def apply_guardrail(inputs, request_data, input_type):\n"+ " for text in inputs['texts']:\n"+ f" if '{BLOCKED_WORD}' in text:\n"+ f" return block('{CODE_BLOCK_REASON}')\n"+ " return allow()\n"+ ),+ },+ },+ ]+ config["model_list"] = [+ {+ "model_name": ROUTER_MODEL,+ "litellm_params": {+ "model": f"bedrock/{MODEL_ID}",+ "api_base": upstream.url,+ "aws_access_key_id": "AKIASYNTHETICRELAY",+ "aws_secret_access_key": "synthetic-relay-secret",+ "aws_region_name": "us-east-1",+ },+ }+ ]+ config_path: Final = directory / "converse-stream-relay.yaml"+ config_path.write_text(yaml.safe_dump(config))+ with owned_proxy_process(root, directory, {}, config=config_path, workers=2) as owned:+ with owned.gateway.scenario() as scenario:+ single: Final = (+ SAMPLED,+ BUFFERED,+ CODE,+ FAILING,+ FAILING_HELD,+ END_ONLY,+ OUTAGE,+ RELEASE_ON_SCAN,+ NOMA,+ )+ yield Rig(+ owned.gateway,+ scenario,+ upstream,+ sink,+ scripts,+ {+ **{name: scenario.key(guardrails=[name]) for name in single},+ STACKED: scenario.key(guardrails=[SAMPLED, BUFFERED]),+ REPLACING_THEN_HELD: scenario.key(guardrails=[REPLACING, BUFFERED]),+ PARALLEL_FIRST: scenario.key(guardrails=[PARALLEL, BUFFERED]),+ NOMA_THEN_ALICE: scenario.key(guardrails=[NOMA, ALICE]),+ },+ outage,+ )+++def _stream_path() -> str:+ return f"/bedrock/model/{ROUTER_MODEL}/converse-stream"+++def _stream_body(marker: str) -> dict[str, JsonValue]:+ return {"messages": [{"role": "user", "content": [{"text": marker}]}]}+++def _stream(rig: Rig, guardrail: str, marker: str) -> tuple[int, str, bytes]:+ status, content_type, body, _ = _stream_with_call_id(rig, guardrail, marker)+ return status, content_type, body+++def _stream_with_call_id(rig: Rig, guardrail: str, marker: str) -> tuple[int, str, bytes, str]:+ with rig.gateway.client.stream(+ "POST",+ _stream_path(),+ json=_stream_body(marker),+ headers={"Authorization": f"Bearer {rig.keys[guardrail]}"},+ timeout=case_timeout_seconds(),+ ) as response:+ return (+ response.status_code,+ response.headers.get("content-type", ""),+ response.read(),+ response.headers.get("x-litellm-call-id", ""),+ )+++def _spend_rows(call_id: str) -> list[dict[str, JsonValue]]:+ return read_rows(+ 'SELECT status, api_base, prompt_tokens FROM "LiteLLM_SpendLogs" WHERE litellm_call_id=%s OR request_id=%s '+ "OR metadata->>'litellm_call_id'=%s ORDER BY status",+ (call_id, call_id, call_id),+ )+++def _spend_rows_for_key_alias(alias: str) -> list[dict[str, JsonValue]]:+ return read_rows(+ "SELECT status, prompt_tokens FROM \"LiteLLM_SpendLogs\" WHERE metadata->>'user_api_key_alias'=%s",+ (alias,),+ )+++def _stream_releasing_upstream(+ rig: Rig, marker: str, first_chunk_length: int, gate: threading.Event+) -> tuple[int, bool, bytes]:+ """Stream ``marker`` through the sampled guardrail and release the upstream held after its first transport chunk+ once that chunk has reached the caller; report whether the upstream was still held at that point."""+ release_held_upstream: Final = threading.Timer(import_seconds(), gate.set)+ release_held_upstream.start()+ try:+ with rig.gateway.client.stream(+ "POST",+ _stream_path(),+ json=_stream_body(marker),+ headers={"Authorization": f"Bearer {rig.keys[SAMPLED]}"},+ timeout=case_timeout_seconds(),+ ) as response:+ chunks: Final = response.iter_raw()+ received: Final = bytearray()+ for chunk in chunks:+ received.extend(chunk)+ if len(received) >= first_chunk_length:+ break+ upstream_still_held: Final = not gate.is_set()+ gate.set()+ received.extend(b"".join(chunks))+ return response.status_code, upstream_still_held, bytes(received)+ finally:+ release_held_upstream.cancel()+ gate.set()+++def test_first_frames_reach_the_caller_while_the_upstream_is_still_streaming(rig: Rig) -> None:+ gate: Final = threading.Event()+ marker: Final = f"relay-{uuid.uuid4().hex}"+ frames: Final = converse_frames((f"Hello {marker} ", "world"))+ first_transport_chunk: Final = frames[0] + frames[1]+ rig.scripts[marker] = Reply(+ content_type=EVENT_STREAM, chunks=(first_transport_chunk, *frames[2:]), gate_after_first=gate+ )+ status, upstream_still_held, received = _stream_releasing_upstream(rig, marker, len(first_transport_chunk), gate)+ assert status == 200, received+ assert upstream_still_held, "the first frames reached the caller only after the upstream finished its stream"+ assert received == b"".join(frames), decode(received)+ assert rig.scans(SAMPLED, marker) == ((f"Hello {marker} world",),)+++def test_block_mid_stream_reaches_boto3_as_an_event_stream_exception(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ rig.scripts[marker] = Reply(+ content_type=EVENT_STREAM, chunks=converse_frames((f"The secret {marker} is ", BLOCKED_WORD, "."))+ )+ outcome: Final = rig.converse_stream(SAMPLED, marker)+ assert outcome.rejected_before_stream is None, outcome+ assert outcome.events[:2] == ("messageStart", "contentBlockDelta"), outcome+ assert "messageStop" not in outcome.events, outcome+ assert (outcome.error_code, outcome.error_message) == ("validationException", BLOCK_REASON), outcome+++def test_block_raised_mid_stream_logs_the_relayed_spend_and_the_failure(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ rig.scripts[marker] = Reply(+ content_type=EVENT_STREAM,+ chunks=converse_frames((f"The secret {marker} is ", BLOCKED_WORD, *(f" word{index}" for index in range(30)))),+ pause_between_chunks=0.05,+ )+ status, content_type, body, call_id = _stream_with_call_id(rig, CODE, marker)+ assert (status, content_type) == (200, EVENT_STREAM), body+ frames: Final = decode(body)+ assert frames[0].kind == "messageStart", frames+ assert frames[-1].message_type == "exception" and frames[-1].kind == "validationException", frames+ assert CODE_BLOCK_REASON in str(frames[-1].payload["message"]), frames+ assert call_id, "the relayed stream carries no x-litellm-call-id"+ rows: Final = eventually(lambda: _spend_rows(call_id), lambda rows: len(rows) >= 2, seconds=70)+ assert [row["status"] for row in rows] == ["failure", "success"], rows+ assert rows[1]["api_base"], rows+ assert isinstance(rows[1]["prompt_tokens"], int) and rows[1]["prompt_tokens"] > 0, rows+++def test_clean_stream_reaches_boto3_unchanged(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ rig.scripts[marker] = Reply(content_type=EVENT_STREAM, chunks=converse_frames((f"Fine {marker} ", "answer")))+ outcome: Final = rig.converse_stream(SAMPLED, marker)+ assert outcome == StreamOutcome(+ (+ "messageStart",+ "contentBlockDelta",+ "contentBlockDelta",+ "contentBlockStop",+ "messageStop",+ "metadata",+ ),+ None,+ None,+ None,+ ), outcome+ assert rig.scans(SAMPLED, marker) == ((f"Fine {marker} answer",),)+++def test_sampled_stream_forwards_frames_as_sent_without_applying_masks_like_chat(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ frames: Final = converse_frames((f"{MASKED_WORD} {marker} ", "is the capital"))+ rig.scripts[marker] = Reply(content_type=EVENT_STREAM, chunks=frames)+ status, content_type, body = _stream(rig, SAMPLED, marker)+ assert (status, content_type) == (200, EVENT_STREAM), body+ assert body == b"".join(frames), decode(body)+ assert rig.scans(SAMPLED, marker) == ((f"{MASKED_WORD} {marker} is the capital",),)+++def test_a_frame_whose_payload_is_not_utf8_is_relayed_as_sent_and_the_rest_still_scanned(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ clean: Final = converse_frames((f"Before {marker} ", "after"))+ garbled: Final = aws_event_stream_frame(+ {":event-type": "contentBlockDelta", ":content-type": "application/json", ":message-type": "event"},+ b'{"contentBlockIndex":0,"delta":{"text":"\xff"}}',+ )+ frames: Final = (*clean[:2], garbled, *clean[2:])+ rig.scripts[marker] = Reply(content_type=EVENT_STREAM, chunks=frames)+ status, content_type, body = _stream(rig, SAMPLED, marker)+ assert (status, content_type) == (200, EVENT_STREAM), body+ assert body == b"".join(frames), body[-300:]+ assert set(rig.scans(SAMPLED, marker)) == {(f"Before {marker} after",)}+++def test_buffered_stream_applies_masks_per_content_block(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ rig.scripts[marker] = Reply(+ content_type=EVENT_STREAM,+ chunks=converse_frames((f"{marker} {MASKED_WORD[:3]}", f"{MASKED_WORD[3:]} is big"), ("I like ", MASKED_WORD)),+ )+ status, content_type, body = _stream(rig, BUFFERED, marker)+ assert (status, content_type) == (200, EVENT_STREAM), body+ frames: Final = decode(body)+ assert [frame.kind for frame in frames] == [+ "messageStart",+ "contentBlockDelta",+ "contentBlockDelta",+ "contentBlockStop",+ "contentBlockDelta",+ "contentBlockDelta",+ "contentBlockStop",+ "messageStop",+ "metadata",+ ], frames+ assert block_texts(frames) == {0: f"{marker} {MASK} is big", 1: f"I like {MASK}"}, frames+ assert rig.scans(BUFFERED, marker) == ((f"{marker} {MASKED_WORD} is big", f"I like {MASKED_WORD}"),)+++def test_buffered_stream_ending_in_an_upstream_exception_still_applies_masks(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ upstream_error: Final = aws_event_stream_frame(+ {+ ":exception-type": "modelStreamErrorException",+ ":content-type": "application/json",+ ":message-type": "exception",+ },+ json.dumps({"message": "Model stream error"}).encode(),+ )+ rig.scripts[marker] = Reply(+ content_type=EVENT_STREAM, chunks=(*converse_frames((f"{marker} ", MASKED_WORD))[:3], upstream_error)+ )+ status, content_type, body = _stream(rig, BUFFERED, marker)+ assert (status, content_type) == (200, EVENT_STREAM), body+ frames: Final = decode(body)+ assert block_texts(frames) == {0: f"{marker} {MASK}"}, frames+ assert frames[-1] == Frame("exception", "modelStreamErrorException", {"message": "Model stream error"}), frames+++def test_buffered_stream_block_returns_an_error_before_any_frame(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ rig.scripts[marker] = Reply(+ content_type=EVENT_STREAM, chunks=converse_frames((f"The secret {marker} is ", BLOCKED_WORD))+ )+ outcome: Final = rig.converse_stream(BUFFERED, marker)+ assert outcome.events == () and outcome.rejected_before_stream is not None, outcome+ assert outcome.rejected_before_stream.endswith(+ f"(ValidationException) when calling the ConverseStream operation: {BLOCK_REASON}"+ ), outcome+++def _spend_statuses(call_id: str, at_least: int) -> list[JsonValue]:+ rows: Final = eventually(lambda: _spend_rows(call_id), lambda rows: len(rows) >= at_least, seconds=70)+ return [row["status"] for row in rows]+++def _exception(frames: Sequence[Frame]) -> tuple[str, str] | None:+ last: Final = frames[-1] if frames else None+ if last is None or last.message_type != "exception":+ return None+ return last.kind, str(last.payload.get("message"))+++def test_upstream_closing_mid_stream_ends_the_relayed_stream_with_an_exception_frame(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ gate: Final = threading.Event()+ frames: Final = converse_frames((f"Cut {marker} ", "short", " here"))+ first_transport_chunk: Final = frames[0] + frames[1]+ rig.scripts[marker] = Reply(+ content_type=EVENT_STREAM, chunks=(first_transport_chunk, *frames[2:]), gate_after_first=gate, abort_after=1+ )+ status, upstream_still_held, body = _stream_releasing_upstream(rig, marker, len(first_transport_chunk), gate)+ assert status == 200, body+ assert upstream_still_held, "the first frames reached the caller only after the upstream closed"+ assert body.startswith(first_transport_chunk), decode(body)+ relayed: Final = decode(body)+ exception: Final = _exception(relayed)+ assert exception is not None and exception[0] == "internalServerException", relayed+++def test_guardrail_vendor_failing_mid_stream_fails_closed_with_an_exception_frame(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ frames: Final = converse_frames((f"Scan {marker} ", "one", " two", " three", " four", " five"))+ rig.scripts[marker] = Reply(content_type=EVENT_STREAM, chunks=frames)+ status, content_type, body = _stream(rig, FAILING, marker)+ assert (status, content_type) == (200, EVENT_STREAM), body+ assert body.startswith(b"".join(frames[:4])), decode(body)+ relayed: Final = decode(body)+ assert "messageStop" not in [frame.kind for frame in relayed], relayed+ exception: Final = _exception(relayed)+ assert exception is not None and exception[0] == "internalServerException", relayed+++def test_held_stream_with_the_guardrail_vendor_failing_returns_an_error_before_any_frame(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ rig.scripts[marker] = Reply(content_type=EVENT_STREAM, chunks=converse_frames((f"Held {marker} ", "text")))+ status, content_type, body = _stream(rig, FAILING_HELD, marker)+ assert status == 500 and content_type.startswith("application/json"), (status, content_type, body)+++def test_end_of_stream_only_relays_every_content_frame_then_blocks(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ frames: Final = converse_frames((f"Late {marker} ", "one", " two", " three", " four", f" {BLOCKED_WORD}"))+ rig.scripts[marker] = Reply(content_type=EVENT_STREAM, chunks=frames)+ status, content_type, body = _stream(rig, END_ONLY, marker)+ assert (status, content_type) == (200, EVENT_STREAM), body+ content_frames: Final = b"".join(frames[:-2])+ assert body.startswith(content_frames), decode(body)+ assert decode(body[len(content_frames) :]) == (+ Frame("exception", "validationException", {"message": BLOCK_REASON}),+ ), decode(body)+ assert rig.scans(END_ONLY, marker) == ((f"Late {marker} one two three four {BLOCKED_WORD}",),)+++def test_end_of_stream_only_scans_a_clean_stream_once_and_relays_it_unchanged(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ frames: Final = converse_frames((f"Fine {marker} ", "one", " two", " three", " four", " five"))+ rig.scripts[marker] = Reply(content_type=EVENT_STREAM, chunks=frames)+ status, _, body = _stream(rig, END_ONLY, marker)+ assert status == 200 and body == b"".join(frames), decode(body)+ assert rig.scans(END_ONLY, marker) == ((f"Fine {marker} one two three four five",),)+++def test_held_stream_released_on_scan_stays_buffered_and_applies_masks(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ rig.scripts[marker] = Reply(+ content_type=EVENT_STREAM,+ chunks=converse_frames((f"{marker} ", MASKED_WORD, " is", " the", " capital", " of", " France")),+ )+ status, content_type, body = _stream(rig, RELEASE_ON_SCAN, marker)+ assert (status, content_type) == (200, EVENT_STREAM), body+ assert block_texts(decode(body)) == {0: f"{marker} {MASK} is the capital of France"}, decode(body)+ assert rig.bedrock_scans(RELEASE_ON_SCAN, marker) == ((f"{marker} {MASKED_WORD} is the capital of France",),)+++def test_sampled_and_held_guardrails_on_one_key_hold_the_stream_and_mask_it(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ rig.scripts[marker] = Reply(+ content_type=EVENT_STREAM, chunks=converse_frames((f"{MASKED_WORD} {marker} ", "is", " the", " capital"))+ )+ status, content_type, body = _stream(rig, STACKED, marker)+ assert (status, content_type) == (200, EVENT_STREAM), body+ assert block_texts(decode(body)) == {0: f"{MASK} {marker} is the capital"}, decode(body)+ scanned_by: Final = {+ request.target.split("/")[1] for request in rig.sink.drain() if marker.encode() in request.body+ }+ assert scanned_by == {SAMPLED, BUFFERED}, scanned_by+++def test_held_guardrail_still_masks_after_a_sampled_guardrail_replaces_the_rest_of_the_answer(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ rig.scripts[marker] = Reply(+ content_type=EVENT_STREAM, chunks=converse_frames((f"{MASKED_WORD} {marker} ", "is", f" {REPLACED_WORD}"))+ )+ status, content_type, body = _stream(rig, REPLACING_THEN_HELD, marker)+ assert (status, content_type) == (200, EVENT_STREAM), body+ frames: Final = decode(body)+ assert block_texts(frames) == {0: f"{MASK} {marker} is {REPLACED_WORD}", 1: REPLACEMENT}, frames+ assert frames[-1] == Frame("event", "messageStop", {"stopReason": "guardrail_intervened"}), frames+++def test_parallel_guardrail_listed_before_a_masker_still_scans_the_masked_text(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ rig.scripts[marker] = Reply(+ content_type=EVENT_STREAM, chunks=converse_frames((f"{MASKED_WORD} {marker} ", "is the capital"))+ )+ status, content_type, body = _stream(rig, PARALLEL_FIRST, marker)+ assert (status, content_type) == (200, EVENT_STREAM), body+ assert block_texts(decode(body)) == {0: f"{MASK} {marker} is the capital"}, decode(body)+ assert rig.scans(PARALLEL, marker) == ((f"{MASK} {marker} is the capital",),)+++def test_client_disconnect_stops_the_proxy_reading_the_upstream(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ frames: Final = converse_frames((f"Long {marker} ", *(f" word{index}" for index in range(60))))+ rig.scripts[marker] = Reply(content_type=EVENT_STREAM, chunks=frames, pause_between_chunks=0.1)+ while not rig.provider.disconnected.empty():+ rig.provider.disconnected.get_nowait()+ with rig.gateway.client.stream(+ "POST",+ _stream_path(),+ json=_stream_body(marker),+ headers={"Authorization": f"Bearer {rig.keys[SAMPLED]}"},+ timeout=case_timeout_seconds(),+ ) as response:+ assert response.status_code == 200+ received: Final = bytearray()+ for chunk in response.iter_raw():+ received.extend(chunk)+ if len(received) >= len(b"".join(frames[:3])):+ break+ target: Final = f"/model/{MODEL_ID}/converse-stream"+ closed: Final = eventually(+ lambda: rig.provider.disconnected.qsize(), lambda count: count > 0, seconds=4, return_last_on_timeout=True+ )+ assert closed, "the proxy kept reading the upstream after the caller went away"+ assert rig.provider.disconnected.get_nowait() == target+++def test_client_disconnect_logs_prompt_tokens_the_upstream_never_reported(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ frames: Final = converse_frames((f"Long {marker} ", *(f" word{index}" for index in range(60))))+ rig.scripts[marker] = Reply(content_type=EVENT_STREAM, chunks=frames, pause_between_chunks=0.1)+ with rig.gateway.client.stream(+ "POST",+ _stream_path(),+ json=_stream_body(marker),+ headers={"Authorization": f"Bearer {rig.keys[SAMPLED]}"},+ timeout=case_timeout_seconds(),+ ) as response:+ assert response.status_code == 200+ call_id: Final = response.headers.get("x-litellm-call-id", "")+ received: Final = bytearray()+ for chunk in response.iter_raw():+ received.extend(chunk)+ if len(received) >= len(b"".join(frames[:3])):+ break+ assert call_id, "the relayed stream carries no x-litellm-call-id"+ rows: Final = eventually(lambda: _spend_rows(call_id), lambda rows: len(rows) >= 1, seconds=70)+ assert [row["status"] for row in rows] == ["success"], rows+ assert isinstance(rows[0]["prompt_tokens"], int) and rows[0]["prompt_tokens"] > 0, rows+++def test_client_leaving_a_held_stream_before_its_first_frame_stops_the_proxy_reading_the_upstream(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ frames: Final = converse_frames((f"Held {marker} ", *(f" word{index}" for index in range(80))))+ rig.scripts[marker] = Reply(content_type=EVENT_STREAM, chunks=frames, pause_between_chunks=0.1)+ alias: Final = f"held-{marker}"+ key: Final = rig.scenario.key(guardrails=[HELD_END_ONLY], key_alias=alias)+ while not rig.provider.disconnected.empty():+ rig.provider.disconnected.get_nowait()+ with pytest.raises(httpx.ReadTimeout):+ rig.gateway.client.post(+ _stream_path(),+ json=_stream_body(marker),+ headers={"Authorization": f"Bearer {key}"},+ timeout=httpx.Timeout(case_timeout_seconds(), read=1.5),+ )+ closed: Final = eventually(+ lambda: rig.provider.disconnected.qsize(), lambda count: count > 0, seconds=3, return_last_on_timeout=True+ )+ assert closed, "the proxy kept reading the upstream after the caller left a held stream"+ assert rig.provider.disconnected.get_nowait() == f"/model/{MODEL_ID}/converse-stream"+ rows: Final = eventually(lambda: _spend_rows_for_key_alias(alias), lambda rows: len(rows) >= 1, seconds=70)+ assert [row["status"] for row in rows] == ["success"], rows+ assert isinstance(rows[0]["prompt_tokens"], int) and rows[0]["prompt_tokens"] > 0, rows+++def _follow_up_status_after_leaving_a_held_stream(rig: Rig, marker: str) -> int:+ """Leave a held stream of ``marker`` before its first frame on a key with one parallel slot, then report the status+ of the next request on that key once the slot is free, or the last status seen when it never frees."""+ key: Final = rig.scenario.key(guardrails=[HELD_END_ONLY], max_parallel_requests=1)+ follow_up: Final = f"relay-{uuid.uuid4().hex}"+ rig.scripts[follow_up] = Reply(content_type=EVENT_STREAM, chunks=converse_frames((f"Next {follow_up} ", " done")))++ def follow_up_status() -> int:+ return rig.gateway.client.post(+ _stream_path(),+ json=_stream_body(follow_up),+ headers={"Authorization": f"Bearer {key}"},+ timeout=case_timeout_seconds(),+ ).status_code++ with pytest.raises(httpx.ReadTimeout):+ rig.gateway.client.post(+ _stream_path(),+ json=_stream_body(marker),+ headers={"Authorization": f"Bearer {key}"},+ timeout=httpx.Timeout(case_timeout_seconds(), read=1.5),+ )+ return eventually(follow_up_status, lambda status: status == 200, seconds=5, return_last_on_timeout=True)+++def test_client_leaving_a_held_stream_before_bedrock_sends_a_byte_frees_its_parallel_request_slot(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ first_byte: Final = threading.Event()+ rig.scripts[marker] = Reply(+ content_type=EVENT_STREAM, chunks=converse_frames((f"Held {marker} ", " done")), gate_before_first=first_byte+ )+ try:+ status: Final = _follow_up_status_after_leaving_a_held_stream(rig, marker)+ finally:+ first_byte.set()+ assert status == 200, "the request that left before Bedrock answered still holds the key's only parallel slot"+++def test_client_leaving_a_held_stream_after_part_of_the_first_frame_frees_its_parallel_request_slot(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ frames: Final = converse_frames((f"Held {marker} ", " done"))+ rest_of_stream: Final = threading.Event()+ rig.scripts[marker] = Reply(+ content_type=EVENT_STREAM,+ chunks=(frames[0][:12], frames[0][12:], *frames[1:]),+ gate_after_first=rest_of_stream,+ )+ try:+ status: Final = _follow_up_status_after_leaving_a_held_stream(rig, marker)+ finally:+ rest_of_stream.set()+ assert status == 200, "the request that left with part of Bedrock's first frame still holds the key's only slot"+++ "word_count", [12, 9], ids=["a-sampled-scan-sees-the-end", "the-last-sampled-scan-runs-before-the-end"]+)+def test_noma_scans_carry_stream_and_only_the_last_carries_the_finished_response(rig: Rig, word_count: int) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ words: Final = (f"Noma {marker} ", *(f" word{index}" for index in range(word_count - 1)))+ rig.scripts[marker] = Reply(content_type=EVENT_STREAM, chunks=converse_frames(words))+ status, _, body = _stream(rig, NOMA, marker)+ assert status == 200 and _exception(decode(body)) is None, decode(body)+ scans: Final = rig.forwarded_request_data(marker)[NOMA]+ assert len(scans) >= 2, scans+ assert [scan.get("stream") for scan in scans] == [True] * len(scans), scans+ assert [scan.get("response") is not None for scan in scans] == [False] * (len(scans) - 1) + [True], scans+ assert scans[-1]["response"] == {+ "output": {"message": {"role": "assistant", "content": [{"text": "".join(words)}]}},+ "stopReason": "end_turn",+ }, scans[-1]+++def test_noma_gets_one_scan_of_a_reply_that_only_calls_a_tool_without_input(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ tool_use: Final = {"toolUseId": "tooluse_relay", "name": "get_time", "type": "tool_use"}+ rig.scripts[marker] = Reply(+ content_type=EVENT_STREAM,+ chunks=(+ event_frame("messageStart", {"role": "assistant"}),+ event_frame("contentBlockStart", {"contentBlockIndex": 0, "start": {"toolUse": tool_use}}),+ event_frame("contentBlockDelta", {"contentBlockIndex": 0, "delta": {"toolUse": {"input": ""}}}),+ event_frame("contentBlockStop", {"contentBlockIndex": 0}),+ event_frame("messageStop", {"stopReason": "tool_use"}),+ event_frame("metadata", {"usage": {"inputTokens": 9, "outputTokens": 4, "totalTokens": 13}, "metrics": {}}),+ ),+ )+ status, _, body = _stream(rig, NOMA, marker)+ assert status == 200 and _exception(decode(body)) is None, decode(body)+ finished: Final = {+ "output": {"message": {"role": "assistant", "content": [{"toolUse": {**tool_use, "input": {}}}]}},+ "stopReason": "tool_use",+ }+ scans: Final = rig.forwarded_request_data(marker)[NOMA]+ assert [(scan.get("stream"), scan.get("response")) for scan in scans] == [(True, finished)], scans+++def test_guardrails_after_noma_see_the_streamed_request_unchanged(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ words: Final = (f"Alice {marker} ", *(f" word{index}" for index in range(11)))+ rig.scripts[marker] = Reply(content_type=EVENT_STREAM, chunks=converse_frames(words))+ status, _, body = _stream(rig, NOMA_THEN_ALICE, marker)+ assert status == 200 and _exception(decode(body)) is None, decode(body)+ scans: Final = rig.forwarded_request_data(marker)[ALICE]+ assert len(scans) >= 2, scans+ assert [(scan.get("stream"), scan.get("response")) for scan in scans] == [(None, None)] * len(scans), scans+++def test_non_streaming_converse_block_is_unchanged(rig: Rig) -> None:+ marker: Final = f"relay-{uuid.uuid4().hex}"+ reply: Final = {+ "output": {"message": {"role": "assistant", "content": [{"text": f"The secret {marker} is {BLOCKED_WORD}"}]}},+ "stopReason": "end_turn",+ "usage": {"inputTokens": 9, "outputTokens": 4, "totalTokens": 13},+ "metrics": {"latencyMs": 10},+ }+ rig.scripts[marker] = Reply(body=json.dumps(reply).encode())+ response: Final = rig.gateway.client.post(+ f"/bedrock/model/{ROUTER_MODEL}/converse",+ json=_stream_body(marker),+ headers={"Authorization": f"Bearer {rig.keys[SAMPLED]}"},+ timeout=case_timeout_seconds(),+ )+ assert response.status_code == 400, response.text+ assert BLOCK_REASON in response.text, response.text+++def test_concurrent_streams_each_get_their_own_verdict_and_spend_rows(rig: Rig) -> None:+ markers: Final = [f"relay-{uuid.uuid4().hex}" for _ in range(16)]+ blocked: Final = frozenset(markers[::2])+ for marker in markers:+ words = (f"Burst {marker} ", "one", " two", BLOCKED_WORD if marker in blocked else " three", " four", " five")+ rig.scripts[marker] = Reply(content_type=EVENT_STREAM, chunks=converse_frames(words), pause_between_chunks=0.02)+ with ThreadPoolExecutor(max_workers=len(markers)) as pool:+ outcomes: Final = dict(zip(markers, pool.map(partial(_stream_with_call_id, rig, SAMPLED), markers)))+ for marker, (status, _, body, call_id) in outcomes.items():+ assert status == 200 and call_id, (marker, status, body)+ frames = decode(body)+ if marker in blocked:+ assert _exception(frames) == ("validationException", BLOCK_REASON), (marker, frames)+ else:+ assert _exception(frames) is None and frames[-1].kind == "metadata", (marker, frames)+ for marker, (_, _, _, call_id) in outcomes.items():+ expected = ["failure", "success"] if marker in blocked else ["success"]+ assert _spend_statuses(call_id, len(expected)) == expected, marker+++def test_guardrail_vendor_outage_during_a_burst_fails_closed_then_recovers(rig: Rig) -> None:+ def burst(count: int) -> list[tuple[str, tuple[int, str, bytes, str]]]:+ markers = [f"relay-{uuid.uuid4().hex}" for _ in range(count)]+ for marker in markers:+ rig.scripts[marker] = Reply(+ content_type=EVENT_STREAM,+ chunks=converse_frames((f"Outage {marker} ", "one", " two", " three", " four")),+ )+ with ThreadPoolExecutor(max_workers=count) as pool:+ return list(zip(markers, pool.map(partial(_stream_with_call_id, rig, OUTAGE), markers)))++ rig.outage.set()+ try:+ during: Final = burst(8)+ finally:+ rig.outage.clear()+ after: Final = burst(8)+ for marker, (status, _, body, _) in during:+ exception = _exception(decode(body))+ assert status == 200 and exception is not None and exception[0] == "internalServerException", (marker, body)+ for marker, (status, _, body, _) in after:+ assert status == 200 and _exception(decode(body)) is None, (marker, body)+ assert body == b"".join(rig.scripts[marker].chunks or ()), (marker, decode(body))+ for marker, (_, _, _, call_id) in (*during, *after):+ assert _spend_statuses(call_id, 1).count("success") == 1, markerdiff --git a/tests/unit/llms/bedrock/passthrough/guardrail_translation/test_handler.py b/tests/unit/llms/bedrock/passthrough/guardrail_translation/test_handler.pyindex 57768b41943..1bf85b89232 100644--- a/tests/unit/llms/bedrock/passthrough/guardrail_translation/test_handler.py+++ b/tests/unit/llms/bedrock/passthrough/guardrail_translation/test_handler.py@@ -10,17 +10,20 @@ Validates that:"""import copy+import jsonfrom datetime import datetimefrom typing import Literalfrom unittest.mock import AsyncMock, MagicMockimport pytest+import respximport litellmfrom litellm.caching.caching import DualCachefrom litellm.integrations.custom_guardrail import CustomGuardrailfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObjfrom litellm.proxy._types import UserAPIKeyAuth+from litellm.proxy.guardrails.guardrail_hooks.noma import NomaV2Guardrailfrom litellm.proxy.utils import ProxyLoggingfrom litellm.types.guardrails import GuardrailEventHooksfrom litellm.types.utils import GenericGuardrailAPIInputs@@ -803,11 +806,17 @@ class TestBedrockPassthroughGuardrailHandlerOutput:def _build_event_stream_frame(event_type: str, payload: dict) -> bytes:import json++ return _build_frame(+ {":event-type": event_type, ":content-type": "application/json", ":message-type": "event"},+ json.dumps(payload, separators=(",", ":")).encode(),+ )+++def _build_frame(headers: dict[str, str], payload_bytes: bytes) -> bytes:import structfrom binascii import crc32 as esm_crc32- payload_bytes = json.dumps(payload, separators=(",", ":")).encode()-def _encode_str_header(name: str, value: str) -> bytes:name_b = name.encode()value_b = value.encode()@@ -815,11 +824,7 @@ def _build_event_stream_frame(event_type: str, payload: dict) -> bytes:struct.pack("!B", len(name_b)) + name_b + struct.pack("!B", 7) + struct.pack("!H", len(value_b)) + value_b)- headers_bytes = (- _encode_str_header(":event-type", event_type)- + _encode_str_header(":content-type", "application/json")- + _encode_str_header(":message-type", "event")- )+ headers_bytes = b"".join(_encode_str_header(name, value) for name, value in headers.items())headers_length = len(headers_bytes)total_length = 12 + headers_length + len(payload_bytes) + 4@@ -1342,3 +1347,657 @@ class TestDeAnonymizeConverseStream:hook_spy.assert_not_called()assert result is stream_bytes+++def _decoded_frames(raw: bytes) -> list[tuple[str, str, dict]]:+ import json+ from botocore.eventstream import EventStreamBuffer++ buf = EventStreamBuffer()+ buf.add_data(raw)+ return [+ (+ str(msg.headers[":message-type"]),+ str(msg.headers.get(":event-type") or msg.headers.get(":exception-type")),+ json.loads(msg.payload),+ )+ for msg in buf+ ]+++async def _chunks(*chunks: bytes):+ for chunk in chunks:+ yield chunk+++async def _relay_through_post_call_guardrail(+ chunks: tuple[bytes, ...],+ guardrail: CustomGuardrail,+ monkeypatch: pytest.MonkeyPatch,+ holds_until_moderated: bool = False,+ received: list[bytes] | None = None,+ outer: tuple[CustomGuardrail, bool] | None = None,+) -> bytes:+ layers = [(guardrail, holds_until_moderated), *([outer] if outer is not None else [])]+ monkeypatch.setattr(litellm, "callbacks", [layer for layer, _ in layers])+ logging_obj = LiteLLMLoggingObj(+ model="claude",+ messages=[],+ stream=True,+ call_type="allm_passthrough_route",+ start_time=datetime(2026, 1, 1),+ litellm_call_id="test-call",+ function_id="test-function",+ )+ relayed = ProxyLogging(user_api_key_cache=DualCache()).async_post_call_event_stream_iterator_hook(+ response=BedrockPassthroughGuardrailHandler.event_stream_items(_chunks(*chunks)),+ user_api_key_dict=UserAPIKeyAuth(api_key="test-key"),+ request_data={+ "model": "claude",+ "custom_llm_provider": "bedrock",+ "endpoint": "model/claude/converse-stream",+ "litellm_logging_obj": logging_obj,+ },+ guardrails=layers,+ )+ frames = [] if received is None else received+ async for item in relayed:+ frame = BedrockPassthroughGuardrailHandler.encode_event_stream_item(item)+ if frame:+ frames.append(frame)+ return b"".join(frames)+++def _card_stream() -> tuple[bytes, ...]:+ return (+ _build_event_stream_frame("messageStart", {"role": "assistant"}),+ _build_event_stream_frame("contentBlockDelta", {"contentBlockIndex": 0, "delta": {"text": "Card: 4111 1111 "}}),+ _build_event_stream_frame("contentBlockDelta", {"contentBlockIndex": 0, "delta": {"text": "1111 1111."}}),+ _build_event_stream_frame("contentBlockStop", {"contentBlockIndex": 0}),+ _build_event_stream_frame("contentBlockDelta", {"contentBlockIndex": 1, "delta": {"text": "Thanks!"}}),+ _build_event_stream_frame("contentBlockStop", {"contentBlockIndex": 1}),+ _build_event_stream_frame("messageStop", {"stopReason": "end_turn"}),+ )+++class _RaisingGuardrail(CustomGuardrail):+ def __init__(self, raised: Exception, on_text: str) -> None:+ super().__init__(guardrail_name="raiser", event_hook=GuardrailEventHooks.post_call, default_on=True)+ self.raised = raised+ self.on_text = on_text++ async def apply_guardrail(+ self,+ inputs: GenericGuardrailAPIInputs,+ request_data: dict,+ input_type: Literal["request", "response"],+ logging_obj: LiteLLMLoggingObj | None = None,+ ) -> GenericGuardrailAPIInputs:+ if any(self.on_text in text for text in inputs.get("texts", [])):+ raise self.raised+ return inputs+++class _RecordingGuardrail(CustomGuardrail):+ def __init__(self) -> None:+ super().__init__(guardrail_name="recorder", event_hook=GuardrailEventHooks.post_call, default_on=True)+ self.received_texts: list[list[str]] = []++ async def apply_guardrail(+ self,+ inputs: GenericGuardrailAPIInputs,+ request_data: dict,+ input_type: Literal["request", "response"],+ logging_obj: LiteLLMLoggingObj | None = None,+ ) -> GenericGuardrailAPIInputs:+ self.received_texts.append(list(inputs.get("texts", [])))+ return inputs+++class _RequestMarksRecordingGuardrail(CustomGuardrail):+ def __init__(self) -> None:+ super().__init__(guardrail_name="marks", event_hook=GuardrailEventHooks.post_call, default_on=True)+ self.received_marks: list[tuple[object, object]] = []++ async def apply_guardrail(+ self,+ inputs: GenericGuardrailAPIInputs,+ request_data: dict,+ input_type: Literal["request", "response"],+ logging_obj: LiteLLMLoggingObj | None = None,+ ) -> GenericGuardrailAPIInputs:+ self.received_marks.append((request_data.get("stream"), request_data.get("response")))+ return inputs+++def _two_scan_stream() -> tuple[bytes, ...]:+ return (+ _build_event_stream_frame("messageStart", {"role": "assistant"}),+ *(+ _build_event_stream_frame("contentBlockDelta", {"contentBlockIndex": 0, "delta": {"text": text}})+ for text in ("Your ", "order ", "ships ", "on ", "Monday.")+ ),+ _build_event_stream_frame("contentBlockStop", {"contentBlockIndex": 0}),+ _build_event_stream_frame("contentBlockDelta", {"contentBlockIndex": 1, "delta": {"text": "Thanks!"}}),+ _build_event_stream_frame("contentBlockStop", {"contentBlockIndex": 1}),+ _build_event_stream_frame("messageStop", {"stopReason": "end_turn"}),+ )+++_NOMA_API_BASE = "https://noma.example.test"+++def _noma_guardrail(monkeypatch: pytest.MonkeyPatch) -> NomaV2Guardrail:+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ monkeypatch.setattr(litellm, "in_memory_llm_clients_cache", None)+ return NomaV2Guardrail(+ api_key="test-key",+ api_base=_NOMA_API_BASE,+ guardrail_name="noma",+ event_hook="post_call",+ default_on=True,+ )+++class TestConverseStreamFrames:+ @pytest.mark.asyncio+ async def test_frames_are_cut_at_their_boundaries_whatever_the_transport_chunks(self):+ stream = b"".join(_card_stream())+ transport = tuple(stream[i : i + 7] for i in range(0, len(stream), 7))++ frames = [frame async for frame in BedrockPassthroughGuardrailHandler.event_stream_items(_chunks(*transport))]++ assert [frame.raw for frame in frames] == [*_card_stream(), b""]+ assert [frame.event_type for frame in frames] == [+ "messageStart",+ "contentBlockDelta",+ "contentBlockDelta",+ "contentBlockStop",+ "contentBlockDelta",+ "contentBlockStop",+ "messageStop",+ None,+ ]+ assert [frame.ends_stream for frame in frames] == [False] * 7 + [True]++ @pytest.mark.asyncio+ async def test_bytes_that_cannot_be_framed_are_relayed_as_received(self):+ frame = _build_event_stream_frame("messageStart", {"role": "assistant"})+ garbage = b"\x00\x00\x00\x05abcdefgh"++ frames = [+ frame+ async for frame in BedrockPassthroughGuardrailHandler.event_stream_items(_chunks(frame + garbage, b"tail"))+ ]++ assert [item.raw for item in frames] == [frame, garbage, b"tail", b""]+ assert [item.payload for item in frames[1:]] == [None, None, None]++ @pytest.mark.asyncio+ async def test_a_stream_ending_inside_a_frame_relays_the_partial_frame(self):+ complete, partial = _card_stream()[:2]++ frames = [+ frame+ async for frame in BedrockPassthroughGuardrailHandler.event_stream_items(_chunks(complete + partial[:-3]))+ ]++ assert [frame.raw for frame in frames] == [complete, partial[:-3], b""]++ @pytest.mark.asyncio+ async def test_a_delta_ending_in_half_a_surrogate_pair_is_still_decoded(self):+ delta = {"contentBlockIndex": 0, "delta": {"text": "abc\ud83d"}}++ frames = [+ frame+ async for frame in BedrockPassthroughGuardrailHandler.event_stream_items(+ _chunks(_build_event_stream_frame("contentBlockDelta", delta))+ )+ ]++ assert frames[0].payload == delta++ @pytest.mark.asyncio+ async def test_a_payload_that_is_not_utf8_is_relayed_as_received(self):+ frame = _build_frame(+ {":event-type": "contentBlockDelta", ":content-type": "application/json", ":message-type": "event"},+ b'{"contentBlockIndex":0,"delta":{"text":"\xff"}}',+ )++ frames = [frame async for frame in BedrockPassthroughGuardrailHandler.event_stream_items(_chunks(frame))]++ assert [(item.raw, item.event_type, item.payload) for item in frames] == [+ (frame, "contentBlockDelta", None),+ (b"", None, None),+ ]+++def _tool_use_start_frame(index: int, tool_use_id: str, name: str) -> bytes:+ tool_use = {"toolUseId": tool_use_id, "name": name, "type": "tool_use"}+ return _build_event_stream_frame("contentBlockStart", {"contentBlockIndex": index, "start": {"toolUse": tool_use}})+++def _tool_call_stream(tool_input: str) -> tuple[bytes, ...]:+ return (+ _build_event_stream_frame("messageStart", {"role": "assistant"}),+ _build_event_stream_frame("contentBlockDelta", {"contentBlockIndex": 0, "delta": {"text": "Checking."}}),+ _build_event_stream_frame("contentBlockStop", {"contentBlockIndex": 0}),+ _tool_use_start_frame(1, "tooluse_1", "lookup_order"),+ _build_event_stream_frame(+ "contentBlockDelta", {"contentBlockIndex": 1, "delta": {"toolUse": {"input": tool_input}}}+ ),+ _build_event_stream_frame("contentBlockStop", {"contentBlockIndex": 1}),+ _build_event_stream_frame("messageStop", {"stopReason": "max_tokens"}),+ )+++def _tool_without_input_stream() -> tuple[bytes, ...]:+ return (+ _build_event_stream_frame("messageStart", {"role": "assistant"}),+ _tool_use_start_frame(0, "tooluse_1", "get_time"),+ _build_event_stream_frame("contentBlockDelta", {"contentBlockIndex": 0, "delta": {"toolUse": {"input": ""}}}),+ _build_event_stream_frame("contentBlockStop", {"contentBlockIndex": 0}),+ _build_event_stream_frame("messageStop", {"stopReason": "tool_use"}),+ )+++class TestConverseStreamGuardrailRelay:+ @pytest.mark.asyncio+ async def test_sampled_stream_relays_frames_as_received_and_scans_one_text_per_block(self, monkeypatch):+ guardrail = _CardMaskingGuardrail()++ relayed = await _relay_through_post_call_guardrail(_card_stream(), guardrail, monkeypatch)++ assert relayed == b"".join(_card_stream())+ assert guardrail.received_texts == [[f"Card: {_TEST_CARD}.", "Thanks!"]]++ @pytest.mark.asyncio+ async def test_each_sampled_round_scans_the_text_the_caller_received(self, monkeypatch):+ guardrail = _CardMaskingGuardrail()+ stream = (+ _build_event_stream_frame("messageStart", {"role": "assistant"}),+ *(+ _build_event_stream_frame("contentBlockDelta", {"contentBlockIndex": 0, "delta": {"text": text}})+ for text in ("Card: 4111 1111 ", "1111 1111.", " More", " text", " here")+ ),+ _build_event_stream_frame("contentBlockStop", {"contentBlockIndex": 0}),+ _build_event_stream_frame("messageStop", {"stopReason": "end_turn"}),+ )++ relayed = await _relay_through_post_call_guardrail(stream, guardrail, monkeypatch)++ assert relayed == b"".join(stream)+ assert guardrail.received_texts == [+ [f"Card: {_TEST_CARD}. More text"],+ [f"Card: {_TEST_CARD}. More text here"],+ ]++ @pytest.mark.asyncio+ async def test_stream_held_until_moderated_applies_masks_per_block(self, monkeypatch):+ guardrail = _CardMaskingGuardrail()++ relayed = await _relay_through_post_call_guardrail(+ _card_stream(), guardrail, monkeypatch, holds_until_moderated=True+ )++ frames = _decoded_frames(relayed)+ assert [kind for _, kind, _ in frames] == [+ "messageStart",+ "contentBlockDelta",+ "contentBlockDelta",+ "contentBlockStop",+ "contentBlockDelta",+ "contentBlockStop",+ "messageStop",+ ]+ assert TestDeAnonymizeConverseStream._deltas_by_block(relayed, "text") == {0: "Card: ****.", 1: "Thanks!"}+ assert relayed.endswith(b"".join(_card_stream()[3:]))++ @pytest.mark.parametrize(+ "ending",+ [+ pytest.param(+ BedrockPassthroughGuardrailHandler.event_stream_error_item("Model stream error", 500),+ id="exception-frame",+ ),+ pytest.param(+ _build_frame(+ {":message-type": "error", ":error-code": "InternalFailure", ":error-message": "boom"}, b""+ ),+ id="error-frame",+ ),+ pytest.param(b"", id="upstream-closed-without-messageStop"),+ ],+ )+ @pytest.mark.asyncio+ async def test_held_stream_that_ends_without_messageStop_still_applies_masks(self, monkeypatch, ending: bytes):+ stream = (*_card_stream()[:3], ending)++ relayed = await _relay_through_post_call_guardrail(+ stream, _CardMaskingGuardrail(), monkeypatch, holds_until_moderated=True+ )++ assert TestDeAnonymizeConverseStream._deltas_by_block(relayed, "text") == {0: "Card: ****."}+ assert relayed.endswith(ending)++ @pytest.mark.asyncio+ async def test_a_sampled_guardrail_rewriting_at_the_end_never_reaches_frames_a_later_guardrail_holds(+ self, monkeypatch+ ):+ stream = (+ _build_event_stream_frame("messageStart", {"role": "assistant"}),+ *(+ _build_event_stream_frame("contentBlockDelta", {"contentBlockIndex": 0, "delta": {"text": text}})+ for text in ("Card: 4111", " 1111", " 1111", " 1111", " now.")+ ),+ _build_event_stream_frame("contentBlockStop", {"contentBlockIndex": 0}),+ _build_event_stream_frame("messageStop", {"stopReason": "end_turn"}),+ )+ held = _RecordingGuardrail()++ relayed = await _relay_through_post_call_guardrail(+ stream, _CardMaskingGuardrail(), monkeypatch, outer=(held, True)+ )++ assert relayed == b"".join(stream)+ assert held.received_texts[-1] == [f"Card: {_TEST_CARD} now."]++ @pytest.mark.parametrize("filler_frames", range(8))+ @pytest.mark.asyncio+ async def test_a_held_guardrail_still_masks_after_a_sampled_guardrail_ends_the_stream_with_its_message(+ self, monkeypatch, filler_frames: int+ ):+ from litellm.exceptions import ModifyResponseException++ sampled = _RaisingGuardrail(+ ModifyResponseException(message="Sorry, I can't share that.", model="claude", request_data={}),+ "FORBIDDEN",+ )+ stream = (+ *_card_stream()[:3],+ *(+ _build_event_stream_frame("contentBlockDelta", {"contentBlockIndex": 0, "delta": {"text": " ok"}})+ for _ in range(filler_frames)+ ),+ _build_event_stream_frame("contentBlockDelta", {"contentBlockIndex": 0, "delta": {"text": " FORBIDDEN"}}),+ _build_event_stream_frame("contentBlockStop", {"contentBlockIndex": 0}),+ _build_event_stream_frame("messageStop", {"stopReason": "end_turn"}),+ )++ relayed = await _relay_through_post_call_guardrail(+ stream, sampled, monkeypatch, outer=(_CardMaskingGuardrail(), True)+ )++ texts = TestDeAnonymizeConverseStream._deltas_by_block(relayed, "text")+ assert texts[0].startswith("Card: ****."), texts+ assert texts[max(texts)] == "Sorry, I can't share that.", texts+ assert _decoded_frames(relayed)[-1] == ("event", "messageStop", {"stopReason": "guardrail_intervened"})++ @pytest.mark.asyncio+ async def test_noma_scans_carry_stream_and_only_the_last_one_the_finished_answer(+ self, monkeypatch, respx_mock: respx.MockRouter+ ):+ route = respx_mock.post(f"{_NOMA_API_BASE}/litellm/guardrail").respond(json={"action": "NONE"})++ await _relay_through_post_call_guardrail(_two_scan_stream(), _noma_guardrail(monkeypatch), monkeypatch)++ sent = [json.loads(call.request.content)["request_data"] for call in route.calls]+ answer = [{"text": "Your order ships on Monday."}, {"text": "Thanks!"}]+ finished = {"output": {"message": {"role": "assistant", "content": answer}}, "stopReason": "end_turn"}+ assert [(scan.get("stream"), scan.get("response")) for scan in sent] == [(True, None), (True, finished)]++ @pytest.mark.asyncio+ async def test_noma_gets_the_finished_answer_when_the_last_sampled_scan_already_covered_it(+ self, monkeypatch, respx_mock: respx.MockRouter+ ):+ route = respx_mock.post(f"{_NOMA_API_BASE}/litellm/guardrail").respond(json={"action": "NONE"})+ later = _RequestMarksRecordingGuardrail()+ stream = (+ _build_event_stream_frame("messageStart", {"role": "assistant"}),+ *(+ _build_event_stream_frame("contentBlockDelta", {"contentBlockIndex": 0, "delta": {"text": text}})+ for text in ("Your ", "order ", "ships ", "Monday.")+ ),+ _build_event_stream_frame("contentBlockStop", {"contentBlockIndex": 0}),+ _build_event_stream_frame("messageStop", {"stopReason": "end_turn"}),+ )++ await _relay_through_post_call_guardrail(+ stream, _noma_guardrail(monkeypatch), monkeypatch, outer=(later, False)+ )++ sent = [json.loads(call.request.content)["request_data"] for call in route.calls]+ finished = {+ "output": {"message": {"role": "assistant", "content": [{"text": "Your order ships Monday."}]}},+ "stopReason": "end_turn",+ }+ assert [(scan.get("stream"), scan.get("response")) for scan in sent] == [(True, None), (True, finished)]+ assert later.received_marks == [(None, None)]++ @pytest.mark.asyncio+ async def test_noma_gets_the_finished_answer_with_its_reasoning_and_tool_calls_as_converse_blocks(+ self, monkeypatch, respx_mock: respx.MockRouter+ ):+ route = respx_mock.post(f"{_NOMA_API_BASE}/litellm/guardrail").respond(json={"action": "NONE"})+ stream = (+ _build_event_stream_frame("messageStart", {"role": "assistant"}),+ _build_event_stream_frame(+ "contentBlockDelta", {"contentBlockIndex": 0, "delta": {"reasoningContent": {"text": "Look it up."}}}+ ),+ _build_event_stream_frame("contentBlockStop", {"contentBlockIndex": 0}),+ _build_event_stream_frame("contentBlockDelta", {"contentBlockIndex": 1, "delta": {"text": "Checking."}}),+ _build_event_stream_frame("contentBlockStop", {"contentBlockIndex": 1}),+ _tool_use_start_frame(2, "tooluse_1", "lookup_order"),+ *(+ _build_event_stream_frame(+ "contentBlockDelta", {"contentBlockIndex": 2, "delta": {"toolUse": {"input": fragment}}}+ )+ for fragment in ('{"order_', 'id": "A1"}')+ ),+ _build_event_stream_frame("contentBlockStop", {"contentBlockIndex": 2}),+ _tool_use_start_frame(3, "tooluse_2", "list_orders"),+ _build_event_stream_frame("contentBlockStop", {"contentBlockIndex": 3}),+ _build_event_stream_frame("messageStop", {"stopReason": "tool_use"}),+ )++ await _relay_through_post_call_guardrail(stream, _noma_guardrail(monkeypatch), monkeypatch)++ finished = json.loads(route.calls[-1].request.content)["request_data"]["response"]+ assert finished == {+ "output": {+ "message": {+ "role": "assistant",+ "content": [+ {"reasoningContent": {"reasoningText": {"text": "Look it up."}}},+ {"text": "Checking."},+ {+ "toolUse": {+ "toolUseId": "tooluse_1",+ "name": "lookup_order",+ "type": "tool_use",+ "input": {"order_id": "A1"},+ }+ },+ {"toolUse": {"toolUseId": "tooluse_2", "name": "list_orders", "type": "tool_use", "input": {}}},+ ],+ }+ },+ "stopReason": "tool_use",+ }++ @pytest.mark.parametrize(+ "tool_input",+ [+ pytest.param('{"order_id": "A', id="cut-short"),+ pytest.param('{"order_id": NaN}', id="nan"),+ pytest.param("[" * 10_000, id="nested-too-deep"),+ ],+ )+ @pytest.mark.asyncio+ async def test_noma_gets_a_tool_input_that_is_not_json_as_streamed(+ self, monkeypatch, respx_mock: respx.MockRouter, tool_input: str+ ):+ route = respx_mock.post(f"{_NOMA_API_BASE}/litellm/guardrail").respond(json={"action": "NONE"})++ relayed = await _relay_through_post_call_guardrail(+ _tool_call_stream(tool_input), _noma_guardrail(monkeypatch), monkeypatch+ )++ assert relayed == b"".join(_tool_call_stream(tool_input))+ finished = json.loads(route.calls[-1].request.content)["request_data"]["response"]+ assert finished["output"]["message"]["content"][1]["toolUse"]["input"] == tool_input++ @pytest.mark.parametrize("held", [False, True], ids=["sampled", "held"])+ @pytest.mark.asyncio+ async def test_noma_alone_gets_one_ended_scan_of_a_reply_that_only_calls_a_tool_without_input(+ self, monkeypatch, respx_mock: respx.MockRouter, held: bool+ ):+ route = respx_mock.post(f"{_NOMA_API_BASE}/litellm/guardrail").respond(json={"action": "NONE"})+ later = _RecordingGuardrail()++ relayed = await _relay_through_post_call_guardrail(+ _tool_without_input_stream(),+ _noma_guardrail(monkeypatch),+ monkeypatch,+ holds_until_moderated=held,+ outer=(later, False),+ )++ assert relayed == b"".join(_tool_without_input_stream())+ scans = [json.loads(call.request.content) for call in route.calls]+ tool_call = {"toolUse": {"toolUseId": "tooluse_1", "name": "get_time", "type": "tool_use", "input": {}}}+ finished = {"output": {"message": {"role": "assistant", "content": [tool_call]}}, "stopReason": "tool_use"}+ assert [+ (+ scan["input_type"],+ scan["inputs"]["texts"],+ scan["request_data"]["stream"],+ scan["request_data"]["response"],+ )+ for scan in scans+ ] == [("response", [], True, finished)]+ assert later.received_texts == []++ @pytest.mark.asyncio+ async def test_noma_gets_no_scan_of_a_reply_with_no_text_and_no_tool_call(+ self, monkeypatch, respx_mock: respx.MockRouter+ ):+ route = respx_mock.post(f"{_NOMA_API_BASE}/litellm/guardrail").respond(json={"action": "NONE"})+ stream = (+ _build_event_stream_frame("messageStart", {"role": "assistant"}),+ _build_event_stream_frame("messageStop", {"stopReason": "end_turn"}),+ )++ relayed = await _relay_through_post_call_guardrail(stream, _noma_guardrail(monkeypatch), monkeypatch)++ assert relayed == b"".join(stream)+ assert route.calls.call_count == 0++ @pytest.mark.asyncio+ async def test_noma_gets_no_scan_of_a_tool_call_without_input_before_the_reply_ends(+ self, monkeypatch, respx_mock: respx.MockRouter+ ):+ route = respx_mock.post(f"{_NOMA_API_BASE}/litellm/guardrail").respond(json={"action": "NONE"})+ frames = [+ frame+ async for frame in BedrockPassthroughGuardrailHandler.event_stream_items(+ _chunks(*_tool_without_input_stream())+ )+ ]++ await BedrockPassthroughGuardrailHandler().process_output_streaming_response(+ frames[:4],+ _noma_guardrail(monkeypatch),+ request_data={"model": "claude", "endpoint": "model/claude/converse-stream"},+ )++ assert route.calls.call_count == 0++ @pytest.mark.asyncio+ async def test_guardrails_scanning_after_noma_see_the_request_without_its_stream_marks(+ self, monkeypatch, respx_mock: respx.MockRouter+ ):+ respx_mock.post(f"{_NOMA_API_BASE}/litellm/guardrail").respond(json={"action": "NONE"})+ later = _RequestMarksRecordingGuardrail()++ await _relay_through_post_call_guardrail(+ _two_scan_stream(), _noma_guardrail(monkeypatch), monkeypatch, outer=(later, False)+ )++ assert later.received_marks == [(None, None), (None, None)]++ @pytest.mark.asyncio+ async def test_block_after_frames_were_relayed_raises_for_the_relay_to_report(self, monkeypatch):+ from fastapi import HTTPException++ block = HTTPException(status_code=400, detail="Violated guardrail policy")+ relayed: list[bytes] = []++ with pytest.raises(HTTPException) as raised:+ await _relay_through_post_call_guardrail(+ _card_stream(), _RaisingGuardrail(block, "Thanks"), monkeypatch, received=relayed+ )++ assert raised.value is block+ assert relayed == list(_card_stream()[:4])++ @pytest.mark.asyncio+ async def test_guardrail_message_ends_the_message_after_closing_the_open_block(self, monkeypatch):+ from litellm.exceptions import ModifyResponseException++ guardrail = _RaisingGuardrail(+ ModifyResponseException(message="Sorry, I can't share that.", model="claude", request_data={}),+ "1111 1111.",+ )+ stream = (+ _build_event_stream_frame("messageStart", {"role": "assistant"}),+ *(+ _build_event_stream_frame("contentBlockDelta", {"contentBlockIndex": 0, "delta": {"text": text}})+ for text in ("Card: ", "4111 1111 ", "1111 1111.", " Done")+ ),+ _build_event_stream_frame("contentBlockStop", {"contentBlockIndex": 0}),+ _build_event_stream_frame("messageStop", {"stopReason": "end_turn"}),+ )++ relayed = await _relay_through_post_call_guardrail(stream, guardrail, monkeypatch)++ assert relayed.startswith(b"".join(stream[:4]))+ assert _decoded_frames(relayed)[4:] == [+ ("event", "contentBlockStop", {"contentBlockIndex": 0}),+ ("event", "contentBlockDelta", {"contentBlockIndex": 1, "delta": {"text": "Sorry, I can't share that."}}),+ ("event", "contentBlockStop", {"contentBlockIndex": 1}),+ ("event", "messageStop", {"stopReason": "guardrail_intervened"}),+ ]++ @pytest.mark.asyncio+ async def test_guardrail_message_on_a_held_stream_is_a_whole_message(self, monkeypatch):+ from litellm.exceptions import ModifyResponseException++ guardrail = _RaisingGuardrail(+ ModifyResponseException(+ message="Sorry, I can't share that.",+ model="claude",+ request_data={"custom_llm_provider": "bedrock"},+ ),+ "Card",+ )++ relayed = await _relay_through_post_call_guardrail(+ _card_stream(), guardrail, monkeypatch, holds_until_moderated=True+ )++ assert _decoded_frames(relayed) == [+ ("event", "messageStart", {"role": "assistant"}),+ ("event", "contentBlockDelta", {"contentBlockIndex": 0, "delta": {"text": "Sorry, I can't share that."}}),+ ("event", "contentBlockStop", {"contentBlockIndex": 0}),+ ("event", "messageStop", {"stopReason": "guardrail_intervened"}),+ ]++ @pytest.mark.parametrize(+ ("status_code", "exception_type"),+ [(400, "validationException"), (503, "internalServerException")],+ )+ def test_stream_error_frame_type_follows_the_status(self, status_code: int, exception_type: str):+ item = BedrockPassthroughGuardrailHandler.event_stream_error_item("scan failed", status_code)++ assert _decoded_frames(item) == [("exception", exception_type, {"message": "scan failed"})]diff --git a/tests/unit/llms/bedrock/passthrough/test_bedrock_passthrough_transformation.py b/tests/unit/llms/bedrock/passthrough/test_bedrock_passthrough_transformation.pyindex 936528f93e7..84d3160e609 100644--- a/tests/unit/llms/bedrock/passthrough/test_bedrock_passthrough_transformation.py+++ b/tests/unit/llms/bedrock/passthrough/test_bedrock_passthrough_transformation.py@@ -691,6 +691,58 @@ def test_converse_stream_collector_keeps_usage_without_retaining_the_stream():)+def test_converse_stream_cut_before_usage_estimates_prompt_tokens_from_the_request():+ logging_obj: Final = _converse_stream_logging_obj()+ logging_obj.model_call_details["input"] = {+ "system": [{"text": "You are a terse assistant."}],+ "messages": [+ {"role": "user", "content": [{"text": "Write a story about a lighthouse keeper."}]},+ {+ "role": "assistant",+ "content": [{"toolUse": {"toolUseId": "t1", "name": "lookup", "input": {"query": "harbor log"}}}],+ },+ {+ "role": "user",+ "content": [+ {+ "toolResult": {+ "toolUseId": "t1",+ "content": [{"text": "calm water"}, {"json": {"wind": "steady"}}],+ }+ }+ ],+ },+ ],+ }+ cut: Final = _converse_stream_collector()+ _feed(cut, _event_frame("messageStart", {"role": "assistant"}) + _text_block(0, ["Once ", "upon"]))+ response: Final = cut.build_logged_response(logging_obj)+ assert isinstance(response, ModelResponse)+ expected_messages: Final = [+ {"role": "system", "content": "You are a terse assistant."},+ {"role": "user", "content": "Write a story about a lighthouse keeper."},+ {"role": "user", "content": '{"query": "harbor log"}'},+ {"role": "user", "content": 'calm water\n{"wind": "steady"}'},+ ]+ assert response.usage.prompt_tokens == litellm.token_counter(model=logging_obj.model, messages=expected_messages)+ assert response.usage.prompt_tokens > 0++ for request_without_turns in ("not a Converse request", {"prompt": "a model-native invoke body"}):+ logging_obj.model_call_details["input"] = request_without_turns+ unestimated = cut.build_logged_response(logging_obj)+ assert isinstance(unestimated, ModelResponse)+ assert (unestimated.usage.prompt_tokens, unestimated.usage.completion_tokens) == (+ 0,+ response.usage.completion_tokens,+ ), request_without_turns++ full: Final = _converse_stream_collector()+ _feed(full, _converse_text_stream(["Once ", "upon"]))+ full_response: Final = full.build_logged_response(logging_obj)+ assert isinstance(full_response, ModelResponse)+ assert full_response.usage.prompt_tokens == 25++class _CaptureAsyncSuccessCallback(CustomLogger):def __init__(self) -> None:super().__init__()@@ -734,6 +786,32 @@ async def test_bedrock_stream_passthrough_logs_cost_and_standard_metadata(endpoiassert standard_logging_object["model"] == f"bedrock/{CONVERSE_MODEL}"+async def test_bedrock_stream_flush_says_whether_it_logged_the_stream() -> None:+ stream: Final = _converse_text_stream(["Converse response"])+ part_of_the_first_frame: Final = _stream_collector(CONVERSE_STREAM_ENDPOINT)+ _feed(part_of_the_first_frame, stream[:12])+ whole_stream: Final = _stream_collector(CONVERSE_STREAM_ENDPOINT)+ _feed(whole_stream, stream)+ nothing_logged: Final = _CaptureAsyncSuccessCallback()+ logged: Final = _CaptureAsyncSuccessCallback()++ assert (+ await _stream_logging_obj(CONVERSE_STREAM_ENDPOINT, [nothing_logged]).async_flush_passthrough_collected_chunks(+ collector=part_of_the_first_frame+ )+ is False+ )+ assert nothing_logged.kwargs is None+ assert (+ await _stream_logging_obj(CONVERSE_STREAM_ENDPOINT, [logged]).async_flush_passthrough_collected_chunks(+ collector=whole_stream+ )+ is True+ )+ assert logged.kwargs is not None++def test_converse_stream_collector_keeps_tool_calls_between_text_runs():stream = (_event_frame("messageStart", {"role": "assistant"})diff --git a/tests/unit/llms/pass_through/guardrail_translation/test_handler.py b/tests/unit/llms/pass_through/guardrail_translation/test_handler.pyindex 82ad7702052..9b5bfe5534f 100644--- a/tests/unit/llms/pass_through/guardrail_translation/test_handler.py+++ b/tests/unit/llms/pass_through/guardrail_translation/test_handler.py@@ -50,3 +50,69 @@ def test_full_payload_guardrail_text_scans_caller_value_but_not_the_marker(marke)assert SERVER_STREAMING_CLASSIFICATION_KEY not in json.loads(marker_text), marker_text+++def _converse_frame(event_type: str, payload: dict) -> bytes:+ import struct+ from binascii import crc32++ headers = b"".join(+ bytes((len(name),)) + name + b"\x07" + struct.pack("!H", len(value)) + value+ for name, value in (+ (b":event-type", event_type.encode()),+ (b":content-type", b"application/json"),+ (b":message-type", b"event"),+ )+ )+ body = json.dumps(payload).encode()+ prelude = struct.pack("!II", 16 + len(headers) + len(body), len(headers))+ message = prelude + struct.pack("!I", crc32(prelude)) + headers + body+ return message + struct.pack("!I", crc32(message))+++async def _frames(*raw: bytes) -> list[object]:+ from litellm.llms.bedrock.passthrough.guardrail_translation.handler import BedrockPassthroughGuardrailHandler++ async def chunks():+ for chunk in raw:+ yield chunk++ return [frame async for frame in BedrockPassthroughGuardrailHandler.event_stream_items(chunks())]+++async def test_passthrough_route_scans_converse_frames_with_the_bedrock_translation():+ from litellm.llms.pass_through.guardrail_translation.handler import LlmPassthroughRouteHandler++ frames: Final = await _frames(+ _converse_frame("contentBlockDelta", {"contentBlockIndex": 0, "delta": {"text": "Hello "}}),+ _converse_frame("contentBlockDelta", {"contentBlockIndex": 0, "delta": {"text": "world"}}),+ _converse_frame("messageStop", {"stopReason": "end_turn"}),+ )++ scan_key: Final = LlmPassthroughRouteHandler().get_streaming_scan_key(frames)++ assert scan_key is not None and (scan_key.texts, scan_key.stream_ended) == (("Hello world",), True)+ assert LlmPassthroughRouteHandler()._check_streaming_has_ended(frames) is True+ assert LlmPassthroughRouteHandler()._check_streaming_has_ended(frames[:2]) is False+++def test_passthrough_route_has_no_stream_translation_for_items_no_provider_owns():+ from litellm.llms.pass_through.guardrail_translation.handler import LlmPassthroughRouteHandler++ assert LlmPassthroughRouteHandler().get_streaming_scan_key([b"raw", {"chunk": 1}]) is None+ assert LlmPassthroughRouteHandler()._check_streaming_has_ended([b"raw"]) is False++[email protected](("provider", "ends_message"), [("bedrock", True), ("vertex_ai", False)])+def test_passthrough_route_block_before_any_frame_uses_the_request_provider(provider: str, ends_message: bool):+ from litellm.exceptions import ModifyResponseException+ from litellm.llms.pass_through.guardrail_translation.handler import LlmPassthroughRouteHandler++ chunks: Final = LlmPassthroughRouteHandler().build_block_sse_chunks(+ ModifyResponseException(message="blocked", model="m", request_data={"custom_llm_provider": provider}),+ stream_started=False,+ responses_so_far=[],+ )++ assert (chunks is not None) is ends_messagediff --git a/tests/unit/passthrough/test_streaming_interrupt_spend_tracking.py b/tests/unit/passthrough/test_streaming_interrupt_spend_tracking.pyindex 922643f9834..4819688f14e 100644--- a/tests/unit/passthrough/test_streaming_interrupt_spend_tracking.py+++ b/tests/unit/passthrough/test_streaming_interrupt_spend_tracking.py@@ -128,6 +128,119 @@ async def test_asyncpassthroughstreamingresponse_flushes_on_client_disconnect():assert _spend_payload(mock_logging_obj.async_flush_passthrough_collected_chunks) == chunks[0]+async def test_asyncpassthroughstreamingresponse_wait_for_spend_flush_returns_once_the_flush_has_finished():+ from litellm.passthrough.main import AsyncPassthroughStreamingResponse++ mock_response = _make_streaming_response([b"chunk-1", b"chunk-2"])++ async def response_coro():+ return mock_response++ flushed: List[bytes] = []++ async def flush(collector: _RecordingCollector) -> bool:+ await asyncio.sleep(0)+ await asyncio.sleep(0)+ flushed.append(collector.build_logged_response(litellm_logging_obj=MagicMock()))+ return True++ mock_logging_obj = MagicMock()+ mock_logging_obj.async_flush_passthrough_collected_chunks = flush+ gen = AsyncPassthroughStreamingResponse(+ response=response_coro(),+ litellm_logging_obj=mock_logging_obj,+ provider_config=_provider_config(_RecordingCollector()),+ )++ await gen.__anext__()+ await gen.aclose()++ assert await gen.wait_for_spend_flush() is True+ assert flushed == [b"chunk-1"]+++async def test_asyncpassthroughstreamingresponse_says_it_logged_no_spend_when_the_flush_had_nothing_to_log():+ from litellm.passthrough.main import AsyncPassthroughStreamingResponse++ async def response_coro():+ return _make_streaming_response([b"part-of-a-frame", b"rest-of-the-frame"])++ mock_logging_obj = MagicMock()+ mock_logging_obj.async_flush_passthrough_collected_chunks = AsyncMock(return_value=False)+ gen = AsyncPassthroughStreamingResponse(+ response=response_coro(),+ litellm_logging_obj=mock_logging_obj,+ provider_config=_provider_config(_RecordingCollector()),+ )++ await gen.__anext__()+ await gen.aclose()++ assert await gen.wait_for_spend_flush() is False+ mock_logging_obj.async_flush_passthrough_collected_chunks.assert_awaited_once()+++async def test_asyncpassthroughstreamingresponse_closed_before_any_chunk_says_it_logged_no_spend():+ from litellm.passthrough.main import AsyncPassthroughStreamingResponse++ async def response_coro():+ return _make_streaming_response([b"chunk-1"])++ mock_logging_obj = _make_logging_obj()+ gen = AsyncPassthroughStreamingResponse(+ response=response_coro(),+ litellm_logging_obj=mock_logging_obj,+ provider_config=_provider_config(_RecordingCollector()),+ )++ await gen+ await gen.aclose()++ assert await gen.wait_for_spend_flush() is False+ mock_logging_obj.async_flush_passthrough_collected_chunks.assert_not_called()+++async def test_asyncpassthroughstreamingresponse_spend_flush_survives_a_cancelled_wait():+ from litellm.passthrough.main import AsyncPassthroughStreamingResponse++ mock_response = _make_streaming_response([b"chunk-1", b"chunk-2"])++ async def response_coro():+ return mock_response++ release = asyncio.Event()+ flushed: List[bytes] = []++ async def flush(collector: _RecordingCollector) -> None:+ await release.wait()+ flushed.append(collector.build_logged_response(litellm_logging_obj=MagicMock()))++ mock_logging_obj = MagicMock()+ mock_logging_obj.async_flush_passthrough_collected_chunks = flush+ gen = AsyncPassthroughStreamingResponse(+ response=response_coro(),+ litellm_logging_obj=mock_logging_obj,+ provider_config=_provider_config(_RecordingCollector()),+ )++ await gen.__anext__()+ await gen.aclose()+ waiter = asyncio.create_task(gen.wait_for_spend_flush())+ await asyncio.sleep(0)+ await asyncio.sleep(0)+ waiter.cancel()+ with pytest.raises(asyncio.CancelledError):+ await waiter+ release.set()+ await gen.wait_for_spend_flush()++ assert flushed == [b"chunk-1"]++@pytest.mark.asyncioasync def test_asyncpassthroughstreamingresponse_does_not_flush_on_4xx():from litellm.passthrough.main import AsyncPassthroughStreamingResponsediff --git a/tests/unit/proxy/guardrails/guardrail_hooks/test_noma_v2.py b/tests/unit/proxy/guardrails/guardrail_hooks/test_noma_v2.pyindex 180cdbe5bb5..b145b990539 100644--- a/tests/unit/proxy/guardrails/guardrail_hooks/test_noma_v2.py+++ b/tests/unit/proxy/guardrails/guardrail_hooks/test_noma_v2.py@@ -1,3 +1,4 @@+import asyncioimport osfrom unittest.mock import AsyncMock, MagicMock, patch@@ -534,6 +535,33 @@ class TestNomaV2ActionBehavior:assert result == inputs+ @pytest.mark.asyncio+ async def test_a_scan_cancelled_before_noma_answers_is_recorded_as_not_run(self, noma_v2_guardrail):+ scan_sent = asyncio.Event()++ async def noma_never_answers(payload):+ scan_sent.set()+ await asyncio.Event().wait()++ request_data = {"metadata": {}}+ with patch.object(noma_v2_guardrail, "_call_noma_scan", noma_never_answers):+ scan = asyncio.ensure_future(+ noma_v2_guardrail.apply_guardrail(+ inputs={"texts": ["hello"]},+ request_data=request_data,+ input_type="response",+ )+ )+ await scan_sent.wait()+ scan.cancel()+ with pytest.raises(asyncio.CancelledError):+ await scan++ assert [+ record["guardrail_status"]+ for record in request_data["metadata"]["standard_logging_guardrail_information"]+ ] == ["not_run"]+@pytest.mark.asyncioasync def test_fail_closed_on_technical_scan_failure_when_block_failures_true(self):guardrail = NomaV2Guardrail(diff --git a/tests/unit/proxy/test_common_request_processing.py b/tests/unit/proxy/test_common_request_processing.pyindex c3556bbaeb7..37cc67af143 100644--- a/tests/unit/proxy/test_common_request_processing.py+++ b/tests/unit/proxy/test_common_request_processing.py@@ -4623,6 +4623,32 @@ class TestStreamCloseOnDisconnect:timeout=5,)+ async def test_cancelling_the_first_chunk_wait_stops_the_upstream_read(self):+ reads: list[int] = []+ closed = asyncio.Event()++ async def slow_upstream():+ try:+ while True:+ reads.append(len(reads))+ await asyncio.sleep(0.01)+ yield "data: never\n\n"+ finally:+ closed.set()++ waiting = asyncio.ensure_future(+ _buffer_first_chunk_honoring_disconnect(slow_upstream(), request=self._request_that_stays_connected())+ )+ await asyncio.sleep(0.05)+ waiting.cancel()+ with pytest.raises(asyncio.CancelledError):+ await waiting+ reads_at_cancel = len(reads)+ await asyncio.sleep(0.05)++ assert closed.is_set()+ assert len(reads) == reads_at_cancel+async def test_buffer_first_chunk_raises_sentinel_and_closes_on_disconnect(self):closed = asyncio.Event()@@ -6032,7 +6058,7 @@ class TestAllmPassthroughStreamingProviderGate:}return ProxyBaseLLMRequestProcessing(data=data)- async def _run(self, processing_obj, monkeypatch, chunks, stream=None):+ async def _run(self, processing_obj, monkeypatch, chunks, stream=None, proxy_logging_obj=None, request=None):import litellm.proxy.common_request_processing as crpfrom litellm.proxy._types import UserAPIKeyAuth as RealUserAPIKeyAuth@@ -6050,14 +6076,14 @@ class TestAllmPassthroughStreamingProviderGate:monkeypatch.setattr(crp, "route_request", fake_route_request)- proxy_logging_obj = MagicMock(spec=ProxyLogging)+ proxy_logging_obj = proxy_logging_obj if proxy_logging_obj is not None else MagicMock(spec=ProxyLogging)proxy_logging_obj.during_call_hook = AsyncMock(return_value=None)proxy_logging_obj.update_request_status = AsyncMock(return_value=None)proxy_logging_obj.post_call_response_headers_hook = AsyncMock(return_value=None)proxy_logging_obj.post_call_success_hook = AsyncMock()return await processing_obj.base_process_llm_request(- request=MagicMock(spec=Request, headers={}),+ request=request if request is not None else MagicMock(spec=Request, headers={}),fastapi_response=Response(),user_api_key_dict=RealUserAPIKeyAuth(api_key="sk-test"),route_type="allm_passthrough_route",@@ -6123,15 +6149,138 @@ class TestAllmPassthroughStreamingProviderGate:streamed = [chunk async for chunk in result.body_iterator]assert streamed == chunks- @pytest.mark.asyncio- async def test_bedrock_converse_stream_is_buffered_through_handler(- self, monkeypatch- ):- processing_obj = self._build_processing_obj(- "bedrock", "model/us.amazon.nova-lite-v1:0/converse-stream"+ @staticmethod+ def _converse_frame(event_type: str, payload: dict) -> bytes:+ import struct+ from binascii import crc32++ headers = b"".join(+ bytes((len(name),)) + name + b"\x07" + struct.pack("!H", len(value)) + value+ for name, value in (+ (b":event-type", event_type.encode()),+ (b":content-type", b"application/json"),+ (b":message-type", b"event"),+ ))- chunks = [b"raw-1", b"raw-2"]+ body = json.dumps(payload).encode()+ prelude = struct.pack("!II", 16 + len(headers) + len(body), len(headers))+ message = prelude + struct.pack("!I", crc32(prelude)) + headers + body+ return message + struct.pack("!I", crc32(message))++ def _converse_stream(self) -> list[bytes]:+ return [+ self._converse_frame("messageStart", {"role": "assistant"}),+ self._converse_frame("contentBlockDelta", {"contentBlockIndex": 0, "delta": {"text": "Hello"}}),+ self._converse_frame("contentBlockStop", {"contentBlockIndex": 0}),+ self._converse_frame("messageStop", {"stopReason": "end_turn"}),+ ]++ @staticmethod+ def _apply_guardrail(**kwargs):+ from litellm.integrations.custom_guardrail import CustomGuardrail++ class _ApplyGuardrail(CustomGuardrail):+ async def apply_guardrail(self, inputs, request_data, input_type, logging_obj=None):+ return inputs++ return _ApplyGuardrail(guardrail_name="scan", event_hook="post_call", default_on=True, **kwargs)++ @staticmethod+ def _success_hook_guardrail():+ from litellm.integrations.custom_guardrail import CustomGuardrail++ class _SuccessHookGuardrail(CustomGuardrail):+ async def async_post_call_success_hook(self, data, user_api_key_dict, response):+ return response++ return _SuccessHookGuardrail(guardrail_name="whole", event_hook="post_call", default_on=True)++ @staticmethod+ def _native_hooks_guardrail():+ from litellm.integrations.custom_guardrail import CustomGuardrail++ class _NativeHooksGuardrail(CustomGuardrail):+ use_native_lifecycle_hooks = True++ async def apply_guardrail(self, inputs, request_data, input_type, logging_obj=None):+ return inputs++ return _NativeHooksGuardrail(guardrail_name="native", event_hook="post_call", default_on=True)++ @classmethod+ def _release_on_scan_guardrail(cls):+ guardrail = cls._apply_guardrail()+ guardrail.streaming_buffer_until_moderated = True+ guardrail.streaming_buffer_release_on_scan = True+ return guardrail++ @classmethod+ def _parallel_guardrail(cls):+ return cls._apply_guardrail(run_in_parallel=True)++ @staticmethod+ def _holding_release_on_scan_guardrail():+ from litellm.integrations.custom_guardrail import CustomGuardrail++ class _HoldingGuardrail(CustomGuardrail):+ async def apply_guardrail(self, inputs, request_data, input_type, logging_obj=None):+ return inputs++ async def async_post_call_streaming_iterator_hook(self, user_api_key_dict, response, request_data):+ async for item in response:+ yield item+ guardrail = _HoldingGuardrail(guardrail_name="held", event_hook="post_call", default_on=True)+ guardrail.streaming_buffer_release_on_scan = True+ return guardrail++ @staticmethod+ def _recording_upstream(frames: list[bytes], events: list[str]):+ class _Upstream:+ def __init__(self) -> None:+ self._frames = iter(frames)++ def __aiter__(self):+ return self++ async def __anext__(self) -> bytes:+ frame = next(self._frames, None)+ if frame is None:+ raise StopAsyncIteration+ return frame++ async def aclose(self) -> None:+ events.append("upstream closed")++ async def wait_for_spend_flush(self) -> bool:+ events.append("spend logged")+ return True++ return _Upstream()++ async def _run_converse_stream(+ self,+ monkeypatch,+ guardrail,+ chunks,+ event_stream_hook=None,+ stream=None,+ failure_hook=None,+ read_body=True,+ request=None,+ ):+ processing_obj = self._build_processing_obj("bedrock", "model/us.amazon.nova-lite-v1:0/converse-stream")+ monkeypatch.setattr(litellm, "callbacks", [guardrail])+ recorded: dict = {}++ async def relay_frames(response, user_api_key_dict, request_data, guardrails):+ recorded["guardrails"] = list(guardrails)+ async for item in response:+ yield item++ self._proxy_logging_obj = MagicMock(spec=ProxyLogging)+ self._proxy_logging_obj.async_post_call_event_stream_iterator_hook = event_stream_hook or relay_frames+ self._proxy_logging_obj.post_call_failure_hook = AsyncMock(return_value=None, side_effect=failure_hook)with patch.object(ProxyBaseLLMRequestProcessing,"_has_post_call_guardrails",@@ -6145,13 +6294,346 @@ class TestAllmPassthroughStreamingProviderGate:"BedrockPassthroughGuardrailHandler.de_anonymize_event_stream",new=AsyncMock(return_value=b"modified-body"),) as mock_handler:- result = await self._run(processing_obj, monkeypatch, chunks)+ result = await self._run(+ processing_obj,+ monkeypatch,+ chunks,+ stream=stream,+ proxy_logging_obj=self._proxy_logging_obj,+ request=request,+ )+ body = (+ b"".join([chunk async for chunk in result.body_iterator])+ if isinstance(result, StreamingResponse) and read_body+ else None+ if isinstance(result, StreamingResponse)+ else result.body+ )+ return result, body, mock_handler, recorded++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "guardrail_factory",+ [+ "_success_hook_guardrail",+ "_native_hooks_guardrail",+ "_mask_response_guardrail",+ "_release_on_scan_guardrail",+ "_holding_release_on_scan_guardrail",+ "_parallel_guardrail",+ ],+ )+ async def test_bedrock_converse_stream_is_buffered_for_a_guardrail_that_needs_the_whole_response(+ self, monkeypatch, guardrail_factory+ ):+ guardrail = (+ self._apply_guardrail(mask_response_content=True)+ if guardrail_factory == "_mask_response_guardrail"+ else getattr(self, guardrail_factory)()+ )++ result, body, mock_handler, recorded = await self._run_converse_stream(+ monkeypatch, guardrail, [b"raw-1", b"raw-2"]+ )assert isinstance(result, Response)assert not isinstance(result, StreamingResponse)- assert result.body == b"modified-body"+ assert body == b"modified-body"assert result.headers["content-type"] == "application/vnd.amazon.eventstream"mock_handler.assert_awaited_once()+ assert recorded == {}++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "streaming_flags",+ [+ {},+ {"streaming_buffer_release_on_scan": True},+ {+ "streaming_buffer_until_moderated": True,+ "streaming_buffer_release_on_scan": True,+ "streaming_end_of_stream_only": True,+ },+ ],+ ids=["sampled", "release-on-scan-while-sampled", "release-on-scan-at-end-of-stream-only"],+ )+ async def test_bedrock_converse_stream_relays_frames_for_an_apply_guardrail_guardrail(+ self, monkeypatch, streaming_flags+ ):+ guardrail = self._apply_guardrail()+ for name, value in streaming_flags.items():+ setattr(guardrail, name, value)+ stream = b"".join(self._converse_stream())++ result, body, mock_handler, recorded = await self._run_converse_stream(+ monkeypatch, guardrail, [stream[:20], stream[20:]]+ )++ assert isinstance(result, _UpstreamClosingStreamingResponse)+ assert result.headers["content-type"] == "application/vnd.amazon.eventstream"+ assert body == stream+ assert recorded == {"guardrails": [(guardrail, False)]}+ mock_handler.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_bedrock_converse_stream_failure_after_the_first_frame_ends_with_an_exception_frame(+ self, monkeypatch+ ):+ from botocore.eventstream import EventStreamBuffer++ from litellm.exceptions import GuardrailRaisedException++ async def block_after_first_frame(response, user_api_key_dict, request_data, guardrails):+ async for item in response:+ yield item+ raise GuardrailRaisedException(+ guardrail_name="scan", message="Violated guardrail policy", should_wrap_with_default_message=False+ )++ frames = self._converse_stream()+ result, body, _, _ = await self._run_converse_stream(+ monkeypatch, self._apply_guardrail(), frames, event_stream_hook=block_after_first_frame+ )++ assert isinstance(result, _UpstreamClosingStreamingResponse)+ assert body.startswith(frames[0])+ buffer = EventStreamBuffer()+ buffer.add_data(body[len(frames[0]) :])+ messages = list(buffer)+ assert [(m.headers[":message-type"], m.headers[":exception-type"]) for m in messages] == [+ ("exception", "validationException")+ ]+ assert json.loads(messages[0].payload) == {"message": "Violated guardrail policy"}+ self._proxy_logging_obj.post_call_failure_hook.assert_awaited_once()++ @pytest.mark.asyncio+ async def test_bedrock_converse_stream_failure_after_the_first_frame_logs_the_upstream_spend_first(+ self, monkeypatch+ ):+ from litellm.exceptions import GuardrailRaisedException++ events: list[str] = []+ frames = self._converse_stream()++ async def block_after_first_frame(response, user_api_key_dict, request_data, guardrails):+ async for item in response:+ yield item+ raise GuardrailRaisedException(+ guardrail_name="scan", message="Violated guardrail policy", should_wrap_with_default_message=False+ )++ async def failure_hook(**kwargs):+ events.append("failure hook")++ result, _, _, _ = await self._run_converse_stream(+ monkeypatch,+ self._apply_guardrail(),+ frames,+ event_stream_hook=block_after_first_frame,+ stream=self._recording_upstream(frames, events),+ failure_hook=failure_hook,+ )++ assert isinstance(result, _UpstreamClosingStreamingResponse)+ assert events[:3] == ["upstream closed", "spend logged", "failure hook"]++ @pytest.mark.asyncio+ async def test_bedrock_converse_stream_block_raised_after_the_first_frame_runs_the_failure_hook(self, monkeypatch):+ from botocore.eventstream import EventStreamBuffer++ async def block_after_first_frame(response, user_api_key_dict, request_data, guardrails):+ async for item in response:+ yield item+ raise HTTPException(status_code=400, detail="Violated guardrail policy")++ frames = self._converse_stream()+ result, body, _, _ = await self._run_converse_stream(+ monkeypatch, self._apply_guardrail(), frames, event_stream_hook=block_after_first_frame+ )++ assert body.startswith(frames[0])+ buffer = EventStreamBuffer()+ buffer.add_data(body[len(frames[0]) :])+ messages = list(buffer)+ assert [(m.headers[":message-type"], m.headers[":exception-type"]) for m in messages] == [+ ("exception", "validationException")+ ]+ assert json.loads(messages[0].payload) == {"message": "Violated guardrail policy"}+ self._proxy_logging_obj.post_call_failure_hook.assert_awaited_once()+ assert self._proxy_logging_obj.post_call_failure_hook.await_args.kwargs["original_exception"].status_code == 400++ @pytest.mark.asyncio+ async def test_bedrock_converse_stream_failing_after_an_empty_upstream_raises(self, monkeypatch):+ async def fail_at_the_end(response, user_api_key_dict, request_data, guardrails):+ async for item in response:+ yield item+ raise HTTPException(status_code=503, detail="guardrail unavailable")++ with pytest.raises(HTTPException) as raised:+ await self._run_converse_stream(monkeypatch, self._apply_guardrail(), [], event_stream_hook=fail_at_the_end)++ assert raised.value.status_code == 503++ @pytest.mark.asyncio+ async def test_bedrock_converse_stream_closed_before_its_body_starts_closes_the_guardrails_and_the_upstream(+ self, monkeypatch+ ):+ events: list[str] = []+ frames = self._converse_stream()++ async def scan(response, user_api_key_dict, request_data, guardrails):+ try:+ async for item in response:+ yield item+ finally:+ events.append("guardrails closed")++ result, _, _, _ = await self._run_converse_stream(+ monkeypatch,+ self._apply_guardrail(),+ frames,+ event_stream_hook=scan,+ stream=self._recording_upstream(frames, events),+ read_body=False,+ )+ await result.upstream_generator.aclose()++ assert events == ["guardrails closed", "upstream closed"]++ @pytest.mark.asyncio+ async def test_bedrock_converse_stream_client_leaving_a_held_stream_before_its_first_frame_gets_a_499(+ self, monkeypatch+ ):+ events: list[str] = []+ frames = self._converse_stream()+ first_frame_read = asyncio.Event()+ release_budget = AsyncMock()+ monkeypatch.setattr(+ "litellm.proxy.spend_tracking.budget_reservation.release_budget_reservation_on_cancel", release_budget+ )++ class _SlowUpstream:+ def __init__(self) -> None:+ self._frames = iter(frames)++ def __aiter__(self):+ return self++ async def __anext__(self) -> bytes:+ frame = next(self._frames, None)+ if frame is None:+ raise StopAsyncIteration+ if first_frame_read.is_set():+ await asyncio.Event().wait()+ first_frame_read.set()+ return frame++ async def aclose(self) -> None:+ events.append("upstream closed")++ async def wait_for_spend_flush(self) -> bool:+ events.append("spend logged")+ return True++ async def hold_until_the_end(response, user_api_key_dict, request_data, guardrails):+ held = [item async for item in response]+ for item in held:+ yield item++ async def client_leaves_once_the_upstream_answers():+ await first_frame_read.wait()+ return {"type": "http.disconnect"}++ request = MagicMock(spec=Request, headers={})+ request.receive = client_leaves_once_the_upstream_answers++ result, body, _, _ = await asyncio.wait_for(+ self._run_converse_stream(+ monkeypatch,+ self._apply_guardrail(),+ frames,+ event_stream_hook=hold_until_the_end,+ stream=_SlowUpstream(),+ request=request,+ ),+ timeout=5,+ )++ assert isinstance(result, JSONResponse)+ assert result.status_code == 499+ assert json.loads(body)["error"]["type"] == "client_disconnect"+ assert events[-1] == "spend logged"+ assert "upstream closed" in events+ self._proxy_logging_obj.post_call_failure_hook.assert_not_awaited()+ release_budget.assert_not_awaited()+ self._proxy_logging_obj.arelease_max_parallel_requests_on_disconnect.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_bedrock_converse_stream_client_leaving_before_bedrock_answers_releases_what_the_request_holds(+ self, monkeypatch+ ):+ events: list[str] = []+ release_budget = AsyncMock()+ monkeypatch.setattr(+ "litellm.proxy.spend_tracking.budget_reservation.release_budget_reservation_on_cancel", release_budget+ )++ class _SilentUpstream:+ def __aiter__(self):+ return self++ async def __anext__(self) -> bytes:+ await asyncio.Event().wait()+ raise StopAsyncIteration++ async def aclose(self) -> None:+ events.append("upstream closed")++ async def wait_for_spend_flush(self) -> bool:+ return False++ async def client_leaves():+ return {"type": "http.disconnect"}++ request = MagicMock(spec=Request, headers={})+ request.receive = client_leaves++ result, _, _, _ = await asyncio.wait_for(+ self._run_converse_stream(+ monkeypatch, self._apply_guardrail(), [], stream=_SilentUpstream(), request=request+ ),+ timeout=5,+ )++ assert isinstance(result, JSONResponse)+ assert result.status_code == 499+ assert "upstream closed" in events+ release_budget.assert_awaited_once_with(None)+ self._proxy_logging_obj.arelease_max_parallel_requests_on_disconnect.assert_awaited_once()++ @pytest.mark.asyncio+ async def test_bedrock_converse_stream_failure_before_the_first_frame_raises(self, monkeypatch):+ events: list[str] = []+ frames = self._converse_stream()++ async def block_before_any_frame(response, user_api_key_dict, request_data, guardrails):+ async for _ in response:+ raise HTTPException(status_code=400, detail="Violated guardrail policy")+ yield b""++ with pytest.raises(HTTPException) as raised:+ await self._run_converse_stream(+ monkeypatch,+ self._apply_guardrail(),+ frames,+ event_stream_hook=block_before_any_frame,+ stream=self._recording_upstream(frames, events),+ )++ assert raised.value.status_code == 400+ assert events[-1] == "spend logged"+ assert "upstream closed" in events+ self._proxy_logging_obj.post_call_failure_hook.assert_not_awaited()@pytest.mark.asyncioasync def test_bedrock_invoke_stream_is_not_buffered(self, monkeypatch):