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
feat(guardrails): streaming text transformation in generic_guardrail_api (#33110)
yucheng-berrib2202cb1aa58
diff --git a/litellm/llms/base_llm/guardrail_translation/base_translation.py b/litellm/llms/base_llm/guardrail_translation/base_translation.pyindex 6c41b46cfa0..bed06832386 100644--- a/litellm/llms/base_llm/guardrail_translation/base_translation.py+++ b/litellm/llms/base_llm/guardrail_translation/base_translation.py@@ -1,4 +1,5 @@from abc import ABC, abstractmethod+from dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, Any, Dict, List, Optionalif TYPE_CHECKING:@@ -11,10 +12,30 @@ if TYPE_CHECKING:from litellm.types.llms.openai import AllMessageValues+@dataclass(slots=True)+class StreamTransformSink:+ """Out-parameter used by ``process_output_streaming_response`` to hand the+ guardrailed streaming state back to the caller.++ The streaming text-transform path must not mutate ``responses_so_far`` (it is+ the raw accumulator the guardrail re-reads every round), so the guardrailed+ accumulated text per choice (``mutated_text_per_choice``, keyed by+ ``StreamingChoices.index``) and the per-choice trailing holdback the guardrail+ requested (``holdback_per_choice``, from ``stream_holdback_chars``) are+ reported here instead of in place. Only the OpenAI chat handler populates this+ today; the hook passes a fresh sink per round and reads it afterwards. A+ mutable dataclass is deliberate: it is a write-once output parameter for a+ single call, not shared state.+ """++ mutated_text_per_choice: dict[int, str] = field(default_factory=dict)+ holdback_per_choice: dict[int, int] = field(default_factory=dict)++class BaseTranslation(ABC):@staticmethoddef transform_user_api_key_dict_to_metadata(- user_api_key_dict: Optional[Any],+ user_api_key_dict: Any | None,) -> Dict[str, Any]:"""Transform user_api_key_dict to a metadata dict with prefixed keys.@@ -73,7 +94,7 @@ class BaseTranslation(ABC):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None,user_api_key_dict: Optional["UserAPIKeyAuth"] = None,- request_data: Optional[dict] = None,+ request_data: dict | None = None,) -> Any:"""Process output response with guardrails.@@ -92,12 +113,15 @@ class BaseTranslation(ABC):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None,user_api_key_dict: Optional["UserAPIKeyAuth"] = None,- request_data: Optional[dict] = None,+ request_data: dict | None = None,+ stream_transform_sink: StreamTransformSink | None = None,) -> Any:"""Process output streaming response with guardrails.- Optional to override in subclasses.+ Optional to override in subclasses. ``stream_transform_sink`` is the+ out-parameter used by handlers that support streaming text+ transformations (see ``StreamTransformSink``); base handlers ignore it."""return responses_so_far@@ -105,8 +129,8 @@ class BaseTranslation(ABC):self,exc: "ModifyResponseException",stream_started: bool = False,- responses_so_far: Optional[list[Any]] = None,- ) -> Optional[list[bytes]]:+ responses_so_far: list[Any] | None = None,+ ) -> list[bytes] | None:"""Build the streaming chunks that deliver a guardrail block message andcleanly terminate the stream in this provider's wire format.@@ -125,7 +149,7 @@ class BaseTranslation(ABC):"""return None- def get_structured_messages(self, data: dict) -> Optional[List["AllMessageValues"]]:+ def get_structured_messages(self, data: dict) -> List["AllMessageValues"] | None:"""Convert request data to OpenAI-spec structured messages.diff --git a/litellm/llms/openai/chat/guardrail_translation/handler.py b/litellm/llms/openai/chat/guardrail_translation/handler.pyindex a6b6a6267c3..fd2c9339248 100644--- a/litellm/llms/openai/chat/guardrail_translation/handler.py+++ b/litellm/llms/openai/chat/guardrail_translation/handler.py@@ -14,11 +14,14 @@ Pattern Overview:This pattern can be replicated for other message formats (e.g., Anthropic)."""-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, cast+from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Union, castimport litellmfrom 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,+ StreamTransformSink,+)from litellm.llms.base_llm.guardrail_translation.utils import (effective_skip_system_message_for_guardrail,effective_skip_tool_message_for_guardrail,@@ -27,6 +30,9 @@ from litellm.llms.base_llm.guardrail_translation.utils import ()from litellm.main import stream_chunk_builderfrom litellm.types.llms.openai import AllMessageValues, ChatCompletionToolParam+from litellm.types.proxy.guardrails.guardrail_hooks.generic_guardrail_api import (+ coerce_stream_holdback_value,+)from litellm.types.utils import (Choices,GenericGuardrailAPIInputs,@@ -50,7 +56,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):Methods can be overridden to customize behavior for different message formats."""- def get_structured_messages(self, data: dict) -> Optional[List[AllMessageValues]]:+ def get_structured_messages(self, data: dict) -> List[AllMessageValues] | None:"""Convert chat completions request data to OpenAI-spec structured messages.@@ -65,7 +71,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):self,data: dict,guardrail_to_apply: "CustomGuardrail",- litellm_logging_obj: Optional[Any] = None,+ litellm_logging_obj: Any | None = None,) -> Any:"""Process input messages by applying guardrails to text content.@@ -80,7 +86,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):texts_to_check: List[str] = []images_to_check: List[str] = []tool_calls_to_check: List[ChatCompletionToolParam] = []- text_task_mappings: List[Tuple[int, Optional[int]]] = []+ text_task_mappings: List[Tuple[int, int | None]] = []tool_call_task_mappings: List[Tuple[int, int]] = []# Step 1: Extract all text content, images, and tool calls@@ -184,7 +190,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):texts_to_check: List[str],images_to_check: List[str],tool_calls_to_check: List[ChatCompletionToolParam],- text_task_mappings: List[Tuple[int, Optional[int]]],+ text_task_mappings: List[Tuple[int, int | None]],tool_call_task_mappings: List[Tuple[int, int]],skip_system_message: bool = False,skip_tool_message: bool = False,@@ -239,7 +245,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):self,messages: List[Dict[str, Any]],responses: List[str],- task_mappings: List[Tuple[int, Optional[int]]],+ task_mappings: List[Tuple[int, int | None]],) -> None:"""Apply guardrail responses back to input message text content.@@ -249,7 +255,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):for task_idx, guardrail_response in enumerate(responses):mapping = task_mappings[task_idx]msg_idx = cast(int, mapping[0])- content_idx_optional = cast(Optional[int], mapping[1])+ content_idx_optional = cast(int | None, mapping[1])# Handle contentcontent = messages[msg_idx].get("content", None)@@ -291,9 +297,9 @@ class OpenAIChatCompletionsHandler(BaseTranslation):self,response: "ModelResponse",guardrail_to_apply: "CustomGuardrail",- litellm_logging_obj: Optional[Any] = None,- user_api_key_dict: Optional[Any] = None,- request_data: Optional[dict] = None,+ litellm_logging_obj: Any | None = None,+ user_api_key_dict: Any | None = None,+ request_data: dict | None = None,) -> Any:"""Process output response by applying guardrails to text content.@@ -320,7 +326,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):texts_to_check: List[str] = []images_to_check: List[str] = []tool_calls_to_check: List[Dict[str, Any]] = []- text_task_mappings: List[Tuple[int, Optional[int]]] = []+ text_task_mappings: List[Tuple[int, int | None]] = []tool_call_task_mappings: List[Tuple[int, int]] = []# text_task_mappings: Track (choice_index, content_index) for each text# content_index is None for string content, int for list content@@ -402,9 +408,10 @@ class OpenAIChatCompletionsHandler(BaseTranslation):self,responses_so_far: List["ModelResponseStream"],guardrail_to_apply: "CustomGuardrail",- litellm_logging_obj: Optional[Any] = None,- user_api_key_dict: Optional[Any] = None,- request_data: Optional[dict] = None,+ litellm_logging_obj: Any | None = None,+ user_api_key_dict: Any | None = None,+ request_data: dict | None = None,+ stream_transform_sink: StreamTransformSink | None = None,) -> List["ModelResponseStream"]:"""Process output streaming responses by applying guardrails to text content.@@ -414,14 +421,50 @@ class OpenAIChatCompletionsHandler(BaseTranslation):guardrail_to_apply: The guardrail instance to applylitellm_logging_obj: Optional logging objectuser_api_key_dict: User API key metadata to pass to guardrails+ stream_transform_sink: Optional out-parameter for the streaming text+ transformation path. When provided, the guardrail runs over the raw+ accumulated text (``responses_so_far`` is left untouched so it stays+ a correct raw accumulator across rounds) and the guardrailed text+ plus requested holdback are reported per choice on the sink.Returns:- Modified list of responses with guardrail applied to content+ The (unmodified) list of responses.Response Format Support:- String content: choice.message.content = "text here"- List content: choice.message.content = [{"type": "text", "text": "text here"}, ...]"""+ if stream_transform_sink is not None:+ await self._process_streaming_transform(+ responses_so_far=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,+ sink=stream_transform_sink,+ )+ return responses_so_far++ return await self._process_streaming_block_only(+ responses_so_far=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,+ )++ async def _process_streaming_block_only(+ self,+ *,+ responses_so_far: list["ModelResponseStream"],+ guardrail_to_apply: "CustomGuardrail",+ litellm_logging_obj: Any | None,+ user_api_key_dict: Any | None,+ request_data: dict | None,+ ) -> list["ModelResponseStream"]:+ """Block-only streaming path: run the guardrail so an in-flight BLOCK can+ terminate the stream. Text rewrites are not propagated to the client here+ (see ``_process_streaming_transform`` for the incremental_diff path)."""# check if the stream has endedhas_stream_ended = Falsefor chunk in responses_so_far:@@ -467,7 +510,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):# Step 2: Create lists for guardrail processingtexts_to_check: List[str] = []images_to_check: List[str] = []- task_mappings: List[Tuple[int, Optional[int]]] = []+ task_mappings: List[Tuple[int, int | None]] = []# Track (choice_index, content_index) for each combined textfor (map_choice_idx, map_content_idx), combined_text in combined_texts.items():@@ -520,9 +563,109 @@ class OpenAIChatCompletionsHandler(BaseTranslation):return responses_so_far+ @staticmethod+ def _accumulate_string_content_by_choice_index(+ responses_so_far: list["ModelResponseStream"],+ ) -> dict[int, str]:+ """Accumulate raw string ``delta.content`` per choice, keyed by+ ``StreamingChoices.index`` (not enumerate position, which collapses to 0+ when each chunk carries a single non-zero-indexed choice for ``n > 1``).++ Only string content participates; list-of-blocks content is out of scope+ for the incremental transform path. Reads ``responses_so_far`` without+ mutating it so it stays a correct raw accumulator across rounds.+ """+ accumulated: dict[int, str] = {}+ for response in responses_so_far:+ for choice in response.choices:+ if isinstance(choice, litellm.StreamingChoices):+ content = choice.delta.content+ elif isinstance(choice, litellm.Choices):+ content = choice.message.content+ else:+ continue+ if isinstance(content, str) and content:+ idx = getattr(choice, "index", 0) or 0+ accumulated[idx] = accumulated.get(idx, "") + content+ return accumulated++ async def _process_streaming_transform(+ self,+ *,+ responses_so_far: list["ModelResponseStream"],+ guardrail_to_apply: "CustomGuardrail",+ litellm_logging_obj: Any | None,+ user_api_key_dict: Any | None,+ request_data: dict | None,+ sink: StreamTransformSink,+ ) -> None:+ """Run the guardrail over the raw accumulated text and report the+ guardrailed text plus requested holdback per choice on ``sink``.++ Unlike the block-only path this never mutates ``responses_so_far``: it+ re-derives the raw accumulated text every round (so a rewrite guardrail+ always sees consistent input) and hands the result back out of band.+ """+ raw_by_index = self._accumulate_string_content_by_choice_index(responses_so_far)+ if not raw_by_index:+ sink.mutated_text_per_choice = {}+ sink.holdback_per_choice = {}+ return++ # Fix #2 — sort by StreamingChoices.index so an n>1 stream that emits+ # choice 1 before choice 0 still hands the guardrail texts in a+ # deterministic index order. Without this, the guardrail's returned+ # texts (aligned to the input order it received) would map back to the+ # wrong choice indices when we rebuild the sink dicts by+ # ``enumerate(indices)``.+ indices = sorted(raw_by_index.keys())+ texts_to_check = [raw_by_index[i] for i in indices]++ if request_data is None:+ request_data = {"responses": responses_so_far}+ elif "responses" not in request_data:+ request_data["responses"] = responses_so_far+ if "litellm_metadata" not in request_data:+ user_metadata = self.transform_user_api_key_dict_to_metadata(user_api_key_dict)+ if user_metadata:+ request_data["litellm_metadata"] = user_metadata++ inputs = GenericGuardrailAPIInputs(texts=texts_to_check)+ if responses_so_far and getattr(responses_so_far[0], "model", None):+ inputs["model"] = responses_so_far[0].model+ guardrailed_inputs = await guardrail_to_apply.apply_guardrail(+ inputs=inputs,+ request_data=request_data,+ input_type="response",+ logging_obj=litellm_logging_obj,+ )++ returned_texts = guardrailed_inputs.get("texts")+ # No "texts" key means the guardrail made no change (action NONE): the raw+ # accumulated text is the guardrailed text. A present-but-shorter list is a+ # guardrail contract violation; those choices are omitted below (withheld,+ # not emitted raw) so a malformed response fails closed instead of leaking.+ if returned_texts is None:+ returned_texts = texts_to_check+ elif len(returned_texts) < len(texts_to_check):+ verbose_proxy_logger.warning(+ "OpenAI Chat Completions: guardrail returned %s transformed texts for %s inputs on the "+ "streaming transform path; withholding the unmatched choices to fail closed.",+ len(returned_texts),+ len(texts_to_check),+ )++ holdback = guardrailed_inputs.get("stream_holdback_chars") or []+ sink.mutated_text_per_choice = {+ idx: returned_texts[i] for i, idx in enumerate(indices) if i < len(returned_texts)+ }+ sink.holdback_per_choice = {+ indices[i]: coerce_stream_holdback_value(holdback[i]) for i in range(len(indices)) if i < len(holdback)+ }+def _combine_streaming_texts(self, responses_so_far: List["ModelResponseStream"]- ) -> Dict[Tuple[int, Optional[int]], str]:+ ) -> Dict[Tuple[int, int | None], str]:"""Combine all streaming chunks into complete text per choice.@@ -534,7 +677,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):Returns:Dict mapping (choice_idx, content_idx) to combined text string"""- combined_texts: Dict[Tuple[int, Optional[int]], str] = {}+ combined_texts: Dict[Tuple[int, int | None], str] = {}for response_idx, response in enumerate(responses_so_far):for choice_idx, choice in enumerate(response.choices):@@ -550,7 +693,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):if isinstance(content, str):# String content - accumulate for this choice- str_key: Tuple[int, Optional[int]] = (choice_idx, None)+ str_key: Tuple[int, int | None] = (choice_idx, None)if str_key not in combined_texts:combined_texts[str_key] = ""combined_texts[str_key] += content@@ -560,7 +703,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):for content_idx, content_item in enumerate(content):text_str = content_item.get("text")if text_str:- list_key: Tuple[int, Optional[int]] = (+ list_key: Tuple[int, int | None] = (choice_idx,content_idx,)@@ -607,7 +750,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):texts_to_check: List[str],images_to_check: List[str],tool_calls_to_check: List[Dict[str, Any]],- text_task_mappings: List[Tuple[int, Optional[int]]],+ text_task_mappings: List[Tuple[int, int | None]],tool_call_task_mappings: List[Tuple[int, int]],) -> None:"""@@ -619,7 +762,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):# Determine content source and tool calls based on choice typecontent = None- tool_calls: Optional[List[Any]] = None+ tool_calls: List[Any] | None = Noneif isinstance(choice, litellm.Choices):content = choice.message.contenttool_calls = choice.message.tool_calls@@ -662,7 +805,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):tool_calls_to_check.append(tool_call_dict)tool_call_task_mappings.append((choice_idx, int(tool_call_idx)))- def _convert_tool_call_to_dict(self, tool_call: Union[Dict[str, Any], Any]) -> Optional[Dict[str, Any]]:+ def _convert_tool_call_to_dict(self, tool_call: Union[Dict[str, Any], Any]) -> Dict[str, Any] | None:"""Convert a tool call object to dictionary format.@@ -691,7 +834,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):self,response: "ModelResponse",responses: List[str],- task_mappings: List[Tuple[int, Optional[int]]],+ task_mappings: List[Tuple[int, int | None]],) -> None:"""Apply guardrail text responses back to output response.@@ -701,7 +844,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):for task_idx, guardrail_response in enumerate(responses):mapping = task_mappings[task_idx]choice_idx = cast(int, mapping[0])- content_idx_optional = cast(Optional[int], mapping[1])+ content_idx_optional = cast(int | None, mapping[1])choice = cast(Choices, response.choices[choice_idx])@@ -755,7 +898,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):self,responses: List["ModelResponseStream"],guardrailed_texts: List[str],- task_mappings: List[Tuple[int, Optional[int]]],+ task_mappings: List[Tuple[int, int | None]],) -> None:"""Apply guardrail responses back to output streaming responses.@@ -771,16 +914,16 @@ class OpenAIChatCompletionsHandler(BaseTranslation):Override this method to customize how responses are applied to streaming responses."""# Build a mapping of what guardrailed text to use for each (choice_idx, content_idx)- guardrail_map: Dict[Tuple[int, Optional[int]], str] = {}+ guardrail_map: Dict[Tuple[int, int | None], str] = {}for task_idx, guardrail_response in enumerate(guardrailed_texts):mapping = task_mappings[task_idx]choice_idx = cast(int, mapping[0])- content_idx_optional = cast(Optional[int], mapping[1])+ content_idx_optional = cast(int | None, mapping[1])guardrail_map[(choice_idx, content_idx_optional)] = guardrail_response# Track which choices we've already set the guardrailed text for# Key: (choice_idx, content_idx), Value: boolean (True if already set)- already_set: Dict[Tuple[int, Optional[int]], bool] = {}+ already_set: Dict[Tuple[int, int | None], bool] = {}# Iterate through all responses and update contentfor response_idx, response in enumerate(responses):@@ -797,7 +940,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):if isinstance(content, str):# String content- str_key: Tuple[int, Optional[int]] = (choice_idx_in_response, None)+ str_key: Tuple[int, int | None] = (choice_idx_in_response, None)if str_key in guardrail_map:if str_key not in already_set:# First chunk - set the complete guardrailed text@@ -817,7 +960,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):# List content - handle each content itemfor content_idx, content_item in enumerate(content):if "text" in content_item:- list_key: Tuple[int, Optional[int]] = (+ list_key: Tuple[int, int | None] = (choice_idx_in_response,content_idx,)diff --git a/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/__init__.py b/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/__init__.pyindex 63ead52baa6..a3ac1b94004 100644--- a/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/__init__.py+++ b/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/__init__.py@@ -38,6 +38,7 @@ def initialize_guardrail(litellm_params: "LitellmParams", guardrail: "Guardrail"default_on=litellm_params.default_on,streaming_end_of_stream_only=_get_config_value(litellm_params, optional_params, "streaming_end_of_stream_only"),streaming_sampling_rate=_get_config_value(litellm_params, optional_params, "streaming_sampling_rate"),+ streaming_transform_mode=_get_config_value(litellm_params, optional_params, "streaming_transform_mode"),)litellm.logging_callback_manager.add_litellm_callback(_generic_guardrail_api_callback)diff --git a/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py b/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.pyindex e29d6e56353..6b1c9a8b2b3 100644--- a/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py+++ b/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py@@ -58,7 +58,7 @@ _HEADER_PRESENT_PLACEHOLDER = "[present]"def _header_value_allowed(header_name: str,- extra_allowlist: Optional[Set[str]] = None,+ extra_allowlist: Set[str] | None = None,) -> bool:"""Return True if this header's value may be forwarded (allowlist, including globs and extra_headers)."""lower = header_name.lower()@@ -74,8 +74,8 @@ def _header_value_allowed(def _sanitize_inbound_headers(headers: Any,- extra_allowlist: Optional[Set[str]] = None,-) -> Optional[Dict[str, str]]:+ extra_allowlist: Set[str] | None = None,+) -> Dict[str, str] | None:"""Sanitize inbound headers before passing them to a 3rd party guardrail service.@@ -105,8 +105,8 @@ def _sanitize_inbound_headers(def _extract_inbound_headers(request_data: dict,logging_obj: Optional["LiteLLMLoggingObj"],- extra_allowlist: Optional[Set[str]] = None,-) -> Optional[Dict[str, str]]:+ extra_allowlist: Set[str] | None = None,+) -> Dict[str, str] | None:"""Extract inbound headers from available request context.@@ -172,15 +172,16 @@ class GenericGuardrailAPI(CustomGuardrail):def __init__(self,- headers: Optional[Dict[str, Any]] = None,- api_base: Optional[str] = None,- api_key: Optional[str] = None,- additional_provider_specific_params: Optional[Dict[str, Any]] = None,+ headers: Dict[str, Any] | None = None,+ api_base: str | None = None,+ api_key: str | None = None,+ additional_provider_specific_params: Dict[str, Any] | None = None,unreachable_fallback: Literal["fail_closed", "fail_open"] = "fail_closed",- fail_on_error: Optional[bool] = True,- extra_headers: Optional[list] = None,- streaming_end_of_stream_only: Optional[bool] = None,- streaming_sampling_rate: Optional[int] = None,+ fail_on_error: bool | None = True,+ extra_headers: list | None = None,+ streaming_end_of_stream_only: bool | None = None,+ streaming_sampling_rate: int | None = None,+ streaming_transform_mode: Literal["block_only", "incremental_diff"] | None = None,**kwargs,):self.async_handler = get_async_httpx_client(llm_provider=httpxSpecialProvider.GuardrailCallback)@@ -221,6 +222,13 @@ class GenericGuardrailAPI(CustomGuardrail):raise ValueError(f"streaming_sampling_rate must be >= 1 (got {streaming_sampling_rate})")self.streaming_sampling_rate: int = 5 if streaming_sampling_rate is None else streaming_sampling_rate+ # Read by UnifiedLLMGuardrails.async_post_call_streaming_iterator_hook.+ # "block_only" (default) drops text rewrites on the streaming path;+ # "incremental_diff" emits them as synthetic deltas.+ self.streaming_transform_mode: Literal["block_only", "incremental_diff"] = (+ "block_only" if streaming_transform_mode is None else streaming_transform_mode+ )+# Set supported event hookskwargs.setdefault("supported_event_hooks", list(self.get_supported_event_hooks()))@@ -280,7 +288,7 @@ class GenericGuardrailAPI(CustomGuardrail):input_type: Literal["request", "response"],logging_obj: Optional["LiteLLMLoggingObj"],error: Exception,- http_status_code: Optional[int] = None,+ http_status_code: int | None = None,) -> GenericGuardrailAPIInputs:status_suffix = f" http_status_code={http_status_code}" if http_status_code else ""verbose_proxy_logger.critical(@@ -326,6 +334,8 @@ class GenericGuardrailAPI(CustomGuardrail):return_inputs["tools"] = guardrail_response.toolselif tools:return_inputs["tools"] = tools+ if guardrail_response.stream_holdback_chars is not None:+ return_inputs["stream_holdback_chars"] = guardrail_response.stream_holdback_charsreturn return_inputsdef _handle_guardrail_request_error(@@ -479,7 +489,7 @@ class GenericGuardrailAPI(CustomGuardrail):return self._handle_guardrail_request_error(e, inputs, input_type, logging_obj, is_unreachable=False)@staticmethod- def get_config_model() -> Optional[type["GuardrailConfigModel"]]:+ def get_config_model() -> type["GuardrailConfigModel"] | None:from litellm.types.proxy.guardrails.guardrail_hooks.generic_guardrail_api import (GenericGuardrailAPIConfigModel,)diff --git a/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py b/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.pyindex e0b387e92c0..8e3abfbf159 100644--- a/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py+++ b/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py@@ -8,7 +8,7 @@ Unified Guardrail, leveraging LiteLLM's /applyGuardrail endpointimport copyimport json-from typing import TYPE_CHECKING, Any, AsyncGenerator, List, Optional, Union+from typing import TYPE_CHECKING, Any, AsyncGenerator, List, Unionfrom fastapi import HTTPException@@ -21,7 +21,13 @@ from litellm.litellm_core_utils.api_route_to_call_types import get_call_types_fofrom litellm.llms import load_guardrail_translation_mappingsfrom litellm.proxy._types import UserAPIKeyAuthfrom litellm.types.guardrails import GuardrailEventHooks-from litellm.types.utils import CallTypes, CallTypesLiteral+from litellm.types.utils import (+ CallTypes,+ CallTypesLiteral,+ Delta,+ ModelResponseStream,+ StreamingChoices,+)if TYPE_CHECKING:# Imported lazily at runtime (inside the streaming hook) to avoid a@@ -34,7 +40,12 @@ A2A_CALL_TYPES = (CallTypes.asend_message, CallTypes.send_message)GUARDRAIL_NAME = "unified_llm_guardrails"-def _get_a2a_request_id(responses_so_far: List[Any], request_data: dict) -> Optional[str]:+class _StreamTerminated(Exception):+ """Internal signal that the incremental transform stream has already emitted+ its terminal chunks (block message or in-stream error) and must stop."""+++def _get_a2a_request_id(responses_so_far: List[Any], request_data: dict) -> str | None:"""Get JSON-RPC request id from first A2A chunk or request body for in-stream error reporting."""for item in responses_so_far:if isinstance(item, dict) and "id" in item:@@ -216,7 +227,7 @@ class UnifiedLLMGuardrails(CustomLogger):verbose_proxy_logger.debug("async_post_call_success_hook response: %s", response)- call_type: Optional[CallTypesLiteral] = None+ call_type: CallTypesLiteral | None = Noneif user_api_key_dict.request_route is not None:call_types = get_call_types_for_route(user_api_key_dict.request_route)if call_types is not None and len(call_types) > 0: # type: ignore@@ -292,6 +303,498 @@ class UnifiedLLMGuardrails(CustomLogger):for chunk in block_chunks:yield chunk+ @staticmethod+ def _resolve_transform_call_type(+ user_api_key_dict: UserAPIKeyAuth,+ mappings: dict,+ ) -> str | None:+ """Resolve the call type for the incremental_diff path, or None if the+ route is unresolvable / unsupported.++ Incremental transformation needs a route we can resolve before the first+ chunk and a handler that supports the streaming text-diff protocol (v1:+ the OpenAI chat completions handler only). Returning None makes the caller+ fall back to block_only.+ """+ from litellm.llms.openai.chat.guardrail_translation.handler import (+ OpenAIChatCompletionsHandler,+ )++ if user_api_key_dict.request_route is None:+ return None+ call_types = get_call_types_for_route(user_api_key_dict.request_route)+ if not call_types:+ return None+ call_type = call_types[0].value+ try:+ mapped = CallTypes(call_type)+ except ValueError:+ return None+ handler_cls = mappings.get(mapped)+ if handler_cls is None or not issubclass(handler_cls, OpenAIChatCompletionsHandler):+ return None+ return call_type++ async def _emit_streaming_http_error(+ self,+ exc: HTTPException,+ call_type: str | None,+ responses_so_far: list[Any],+ request_data: dict,+ ) -> AsyncGenerator[Any, None]:+ """Surface a mid-stream HTTPException. For A2A (NDJSON) call types the+ response has already started, so emit an in-stream JSON-RPC error chunk;+ otherwise re-raise so the proxy can report it.+ """+ if call_type is not None and CallTypes(call_type) in A2A_CALL_TYPES:+ request_id = _get_a2a_request_id(responses_so_far, request_data)+ detail = exc.detail if isinstance(exc.detail, dict) else {"message": str(exc.detail)}+ error_chunk = (+ json.dumps(+ {+ "jsonrpc": "2.0",+ "id": request_id,+ "error": {+ "code": -32603,+ "message": detail.get("error", detail.get("message", str(exc.detail))),+ "data": {k: v for k, v in detail.items() if k not in ("error", "message")},+ },+ }+ )+ + "\n"+ )+ yield error_chunk+ return+ raise exc++ def _build_transform_chunk(+ self,+ *,+ reference_chunk: Any,+ mutated_text_per_choice: dict[int, str],+ emitted_text_per_choice: dict[int, str],+ holdback_per_choice: dict[int, int],+ finish_reason_per_choice: dict[int, str | None],+ is_final: bool,+ ) -> ModelResponseStream | None:+ """Build the synthetic chunk carrying the newly-guardrailed deltas.++ For each choice, the new delta is the mutated accumulated text past what+ has already been emitted, minus a trailing holdback (forced to 0 on the+ final flush). ``emitted_text_per_choice`` holds the exact bytes already+ sent per choice and is extended in place. Returns None when there is no+ text to emit (e.g. a tool-call-only turn) or nothing new and this is not+ the final chunk.++ Raises HTTPException(400, stream_transform_underflow) when the guardrail's+ transform is not a forward extension of what has already been streamed+ (shorter than, or rewrites, the already-sent prefix), since emitted bytes+ cannot be retracted. This makes the framework fail closed rather than+ silently leave un-transformed text on the wire; a guardrail that needs to+ rewrite recent output must withhold it first via ``stream_holdback_chars``.+ """+ if not mutated_text_per_choice:+ # Fix #4 — on the final flush a deferred finish_reason (from a mixed+ # content+tool_calls chunk whose passthrough suppressed it) still+ # needs to reach the client, even if the guardrail returned no text+ # to emit. Build a terminator chunk carrying finish_reason per choice.+ if is_final and finish_reason_per_choice:+ terminator_choices: list[StreamingChoices] = []+ for choice_idx, finish_reason in finish_reason_per_choice.items():+ if finish_reason is None:+ continue+ terminator_choices.append(+ StreamingChoices(+ index=choice_idx,+ delta=Delta(content="", role=None, tool_calls=None),+ finish_reason=finish_reason,+ )+ )+ if terminator_choices:+ return ModelResponseStream(+ id=getattr(reference_chunk, "id", None),+ created=getattr(reference_chunk, "created", None),+ model=getattr(reference_chunk, "model", None),+ choices=terminator_choices,+ )+ return None++ deltas: dict[int, str] = {}+ for choice_idx, text in mutated_text_per_choice.items():+ already = emitted_text_per_choice.get(choice_idx, "")+ if not text.startswith(already):+ raise HTTPException(+ status_code=400,+ detail={+ "error": "stream_transform_underflow",+ "message": (+ f"Guardrail streaming transform for choice {choice_idx} is not a forward "+ f"extension of the {len(already)} chars already streamed to the client "+ "(it is shorter than, or rewrites, the emitted prefix); emitted bytes "+ "cannot be retracted. Withhold recent output via stream_holdback_chars "+ "before rewriting it."+ ),+ },+ )+ holdback = 0 if is_final else max(0, holdback_per_choice.get(choice_idx, 0))+ end = max(len(already), len(text) - holdback)+ deltas[choice_idx] = text[len(already) : end]++ # Iterate the mutated choices (not just those in reference_chunk) so a+ # choice with pending text is never dropped for n > 1. finish_reason is+ # taken per choice from the accumulated map (a choice can finish in an+ # earlier chunk than the stream's last one); tool_calls are dropped since+ # v1 does not transform streamed tool calls (they pass through raw).+ synthetic_choices: list[StreamingChoices] = []+ for choice_idx in mutated_text_per_choice:+ delta_text = deltas.get(choice_idx, "")+ finish_reason = finish_reason_per_choice.get(choice_idx) if is_final else None+ # Skip a choice with nothing to say: no new content and no+ # finish_reason to deliver. This avoids emitting an empty delta for an+ # already-finished choice (e.g. one that terminated via a passed-through+ # tool-call chunk, which already carried its own finish_reason).+ if not delta_text and finish_reason is None:+ continue+ # role="assistant" on this choice's first emitted delta only.+ role = "assistant" if not emitted_text_per_choice.get(choice_idx) else None+ synthetic_choices.append(+ StreamingChoices(+ index=choice_idx,+ delta=Delta(content=delta_text, role=role, tool_calls=None),+ finish_reason=finish_reason,+ )+ )++ if not synthetic_choices:+ return None++ for choice_idx in mutated_text_per_choice:+ emitted_text_per_choice[choice_idx] = emitted_text_per_choice.get(choice_idx, "") + deltas.get(+ choice_idx, ""+ )++ return ModelResponseStream(+ id=getattr(reference_chunk, "id", None),+ created=getattr(reference_chunk, "created", None),+ model=getattr(reference_chunk, "model", None),+ choices=synthetic_choices,+ )++ async def _emit_transform_round(+ self,+ *,+ endpoint_translation: Any,+ guardrail_to_apply: CustomGuardrail,+ request_data: dict,+ user_api_key_dict: UserAPIKeyAuth,+ call_type: str,+ reference_chunk: Any,+ responses_so_far: list[Any],+ responses_yielded: list[Any],+ emitted_text_per_choice: dict[int, str],+ finish_reason_per_choice: dict[int, str | None],+ is_final: bool,+ ) -> AsyncGenerator[Any, None]:+ """Run one guardrail processing round and emit the resulting diff chunk.++ Raises ``_StreamTerminated`` (after emitting the terminal block message or+ in-stream error) when the guardrail blocks or an underflow occurs.+ """+ from litellm.integrations.custom_guardrail import ModifyResponseException+ from litellm.llms.base_llm.guardrail_translation.base_translation import (+ StreamTransformSink,+ )++ sink = StreamTransformSink()+ try:+ await endpoint_translation.process_output_streaming_response(+ responses_so_far=responses_so_far,+ guardrail_to_apply=guardrail_to_apply,+ litellm_logging_obj=request_data.get("litellm_logging_obj"),+ user_api_key_dict=user_api_key_dict,+ request_data=request_data,+ stream_transform_sink=sink,+ )+ synthetic = self._build_transform_chunk(+ reference_chunk=reference_chunk,+ mutated_text_per_choice=sink.mutated_text_per_choice,+ emitted_text_per_choice=emitted_text_per_choice,+ holdback_per_choice=sink.holdback_per_choice,+ finish_reason_per_choice=finish_reason_per_choice,+ is_final=is_final,+ )+ except ModifyResponseException as e:+ if e.original_response is None:+ e.original_response = responses_so_far+ async for block_chunk in self._handle_streaming_block(+ e,+ endpoint_translation,+ stream_started=bool(responses_yielded),+ responses_so_far=responses_yielded,+ ):+ yield block_chunk+ raise _StreamTerminated()+ except HTTPException as e:+ async for error_item in self._emit_streaming_http_error(e, call_type, responses_so_far, request_data):+ yield error_item+ raise _StreamTerminated()++ if synthetic is not None:+ responses_yielded.append(synthetic)+ yield synthetic++ async def _run_incremental_transform_stream(+ self,+ *,+ guardrail_to_apply: CustomGuardrail,+ response: Any,+ request_data: dict,+ user_api_key_dict: UserAPIKeyAuth,+ call_type: str,+ sampling_rate: int,+ end_of_stream_only: bool,+ mappings: dict,+ ) -> AsyncGenerator[Any, None]:+ """Emit guardrail text transformations as new deltas on the stream.++ Raw chunks are withheld and accumulated; on each sampled processing round+ (and once at end of stream) the guardrailed accumulated text is diffed+ against what has already been emitted and the new portion is sent as a+ synthetic chunk. A BLOCK terminates the stream via the shared block+ handler; an underflow surfaces as an HTTPException.+ """+ endpoint_translation = mappings[CallTypes(call_type)]()+ responses_so_far: list[Any] = []+ responses_yielded: list[Any] = []+ emitted_text_per_choice: dict[int, str] = {}+ finish_reason_per_choice: dict[int, str | None] = {}+ chunk_counter = 0+ last_chunk: Any | None = None++ def _round(reference_chunk: Any, is_final: bool) -> AsyncGenerator[Any, None]:+ return self._emit_transform_round(+ endpoint_translation=endpoint_translation,+ guardrail_to_apply=guardrail_to_apply,+ request_data=request_data,+ user_api_key_dict=user_api_key_dict,+ call_type=call_type,+ reference_chunk=reference_chunk,+ responses_so_far=responses_so_far,+ responses_yielded=responses_yielded,+ emitted_text_per_choice=emitted_text_per_choice,+ finish_reason_per_choice=finish_reason_per_choice,+ is_final=is_final,+ )++ saw_tool_calls = False+ saw_text_content = False++ try:+ async for item in response:+ # v1 transforms only text. A chunk carrying tool_calls is passed+ # through raw so function-calling turns are not dropped, but ONLY+ # its tool-call fields are forwarded: content is stripped so any+ # response text (in the same delta, or in another choice of an n>1+ # chunk) can never bypass the transform. The original chunk is kept+ # in responses_so_far so its text is still accumulated + redacted ++ # emitted as synthetic deltas, and so the guardrail inspects the+ # assembled tool calls at end of stream (see the block inspection+ # below), matching block_only. finish_reason rides on the raw+ # tool-only chunk, so it is not recorded for the text flush.+ if self._chunk_has_tool_calls(item):+ saw_tool_calls = True+ responses_so_far.append(item)+ last_chunk = item+ # Fix #3 — flush accumulated text BEFORE the tool-call+ # passthrough. Without this, a stream of text chunks that+ # hasn't yet hit a sampled round can be trailed by a+ # tool-call chunk carrying finish_reason="tool_calls"; an+ # SSE-compliant client stops reading at that finish_reason+ # and drops the end-of-stream text flush that would follow.+ if saw_text_content:+ async for out in _round(item, is_final=False):+ yield out+ # Fix #1 — pass finish_reason_per_choice into the+ # passthrough so a mixed content+tool_call chunk defers its+ # finish_reason to the final text terminator (see the+ # _tool_call_passthrough_chunk docstring).+ tool_only = self._tool_call_passthrough_chunk(+ item, finish_reason_per_choice=finish_reason_per_choice+ )+ responses_yielded.append(tool_only)+ yield tool_only+ continue++ chunk_counter += 1+ responses_so_far.append(item)+ last_chunk = item+ self._record_finish_reasons(item, finish_reason_per_choice)+ if self._chunk_carries_text(item):+ saw_text_content = True+ # Skip the sampled round for a terminal chunk: the end-of-stream+ # flush below processes it once with holdback forced to 0, so a+ # sampled round here would guardrail the same content twice.+ if (+ not end_of_stream_only+ and not self._chunk_has_finish_reason(item)+ and chunk_counter % sampling_rate == 0+ ):+ async for out in _round(item, is_final=False):+ yield out++ # v1 does not transform streamed tool calls, but they must still go+ # through the guardrail's block decision. Run the block_only inspection+ # over the full assembled response so tool calls cannot bypass it.+ #+ # Pass a deep copy of responses_so_far — the block path routes through+ # ``_process_streaming_block_only`` which mutates ``delta.content``+ # in-place on the chunk objects it receives. For an n>1 chunk carrying+ # text on one choice and tool_calls (with finish_reason) on another,+ # ``has_stream_ended`` reads ``choices[0]`` alone and can miss the+ # terminal signal, letting the block path rewrite the raw accumulator.+ # The subsequent final ``_round`` would then re-read the already-mutated+ # text, producing double-application for a non-idempotent guardrail or a+ # ``stream_transform_underflow`` 400 from mismatched prefixes. A shallow+ # list copy wouldn't help — the mutation is on the chunk objects+ # themselves — so we deepcopy.+ if saw_tool_calls:+ async for out in self._inspect_full_response_for_block(+ endpoint_translation=endpoint_translation,+ guardrail_to_apply=guardrail_to_apply,+ request_data=request_data,+ user_api_key_dict=user_api_key_dict,+ responses_so_far=copy.deepcopy(responses_so_far),+ responses_yielded=responses_yielded,+ ):+ yield out++ if last_chunk is not None:+ async for out in _round(last_chunk, is_final=True):+ yield out+ except _StreamTerminated:+ return++ async def _inspect_full_response_for_block(+ self,+ *,+ endpoint_translation: Any,+ guardrail_to_apply: CustomGuardrail,+ request_data: dict,+ user_api_key_dict: UserAPIKeyAuth,+ responses_so_far: list[Any],+ responses_yielded: list[Any],+ ) -> AsyncGenerator[Any, None]:+ """Run the block-only guardrail inspection over the full assembled+ response (text + tool calls) so nothing bypasses the block decision.++ The guardrail's returned transforms are discarded here (v1 does not+ transform tool calls); only its block decision matters. A block is+ surfaced the same way as elsewhere: ModifyResponseException terminates the+ stream via the shared block handler; a GenericGuardrailAPI block raises and+ propagates, matching block_only.+ """+ from litellm.integrations.custom_guardrail import ModifyResponseException++ try:+ await endpoint_translation.process_output_streaming_response(+ responses_so_far=responses_so_far,+ guardrail_to_apply=guardrail_to_apply,+ litellm_logging_obj=request_data.get("litellm_logging_obj"),+ user_api_key_dict=user_api_key_dict,+ request_data=request_data,+ stream_transform_sink=None,+ )+ except ModifyResponseException as e:+ if e.original_response is None:+ e.original_response = responses_so_far+ async for block_chunk in self._handle_streaming_block(+ e,+ endpoint_translation,+ stream_started=bool(responses_yielded),+ responses_so_far=responses_yielded,+ ):+ yield block_chunk+ raise _StreamTerminated()++ @staticmethod+ def _chunk_has_tool_calls(item: Any) -> bool:+ for choice in getattr(item, "choices", None) or []:+ delta = getattr(choice, "delta", None)+ if getattr(delta, "tool_calls", None):+ return True+ return False++ @staticmethod+ def _chunk_carries_text(item: Any) -> bool:+ """True if any choice in this chunk has non-empty string ``delta.content``."""+ for choice in getattr(item, "choices", None) or []:+ delta = getattr(choice, "delta", None)+ content = getattr(delta, "content", None)+ if isinstance(content, str) and content != "":+ return True+ return False++ @staticmethod+ def _tool_call_passthrough_chunk(+ item: Any,+ finish_reason_per_choice: "dict[int, str | None] | None" = None,+ ) -> ModelResponseStream:+ """Copy of a chunk carrying tool calls with all text content stripped.++ Only tool_calls, role and finish_reason are forwarded; content is set to+ None so response text can never be delivered raw (it flows through the+ transform instead). Applies per choice so an n>1 chunk mixing a text+ choice and a tool-call choice does not leak the text choice.++ For a choice that carries BOTH text content AND tool_calls, ``finish_reason``+ is suppressed on the passthrough and recorded on+ ``finish_reason_per_choice`` (when provided) so the final synthetic text+ chunk delivers it. Emitting the passthrough's ``finish_reason`` before the+ text flush would let a spec-compliant SSE client stop reading at+ ``finish_reason`` and silently drop the guardrailed text, defeating the+ redaction purpose.+ """+ synthetic_choices: list[StreamingChoices] = []+ for choice in getattr(item, "choices", None) or []:+ delta = getattr(choice, "delta", None)+ idx = getattr(choice, "index", 0) or 0+ original_finish = getattr(choice, "finish_reason", None)+ has_text = isinstance(getattr(delta, "content", None), str) and getattr(delta, "content", "") != ""+ if has_text and original_finish is not None and finish_reason_per_choice is not None:+ finish_reason_per_choice[idx] = original_finish+ passthrough_finish: str | None = None+ else:+ passthrough_finish = original_finish+ synthetic_choices.append(+ StreamingChoices(+ index=idx,+ delta=Delta(+ content=None,+ role=getattr(delta, "role", None),+ tool_calls=getattr(delta, "tool_calls", None),+ ),+ finish_reason=passthrough_finish,+ )+ )+ return ModelResponseStream(+ id=getattr(item, "id", None),+ created=getattr(item, "created", None),+ model=getattr(item, "model", None),+ choices=synthetic_choices,+ )++ @staticmethod+ def _record_finish_reasons(item: Any, finish_reason_per_choice: dict[int, str | None]) -> None:+ for choice in getattr(item, "choices", None) or []:+ finish_reason = getattr(choice, "finish_reason", None)+ if finish_reason is not None:+ finish_reason_per_choice[getattr(choice, "index", 0) or 0] = finish_reason++ @staticmethod+ def _chunk_has_finish_reason(item: Any) -> bool:+ choices = getattr(item, "choices", None) or []+ return any(getattr(choice, "finish_reason", None) is not None for choice in choices)+async def async_post_call_streaming_iterator_hook(self,user_api_key_dict: UserAPIKeyAuth,@@ -334,6 +837,10 @@ class UnifiedLLMGuardrails(CustomLogger):sampling_rate = _streaming_flag("streaming_sampling_rate", 5)# Only apply the guardrail at end of stream (not per chunk).end_of_stream_only = _streaming_flag("streaming_end_of_stream_only", False)+ # "block_only" (default) drops guardrail text rewrites on the streaming+ # path; "incremental_diff" emits them as synthetic deltas (see+ # _run_incremental_transform_stream).+ streaming_transform_mode = _streaming_flag("streaming_transform_mode", "block_only")# Withhold every chunk until end-of-stream moderation passes, then# release the original chunks (clean) or only the block message# (blocked) -- moderating the whole response *before* any content@@ -380,6 +887,35 @@ class UnifiedLLMGuardrails(CustomLogger):if endpoint_guardrail_translation_mappings is None:endpoint_guardrail_translation_mappings = load_guardrail_translation_mappings()+ # Streaming text transformation (incremental_diff) diverges enough from the+ # block_only path that it runs as its own iterator. It requires a route we+ # can resolve up front to an OpenAI-chat handler (the only supported v1+ # surface); anything else falls back to the block_only behavior below.+ if streaming_transform_mode == "incremental_diff":+ transform_call_type = self._resolve_transform_call_type(+ user_api_key_dict=user_api_key_dict,+ mappings=endpoint_guardrail_translation_mappings,+ )+ if transform_call_type is not None:+ async for transformed_item in self._run_incremental_transform_stream(+ guardrail_to_apply=guardrail_to_apply,+ response=response,+ request_data=request_data,+ user_api_key_dict=user_api_key_dict,+ call_type=transform_call_type,+ sampling_rate=sampling_rate,+ end_of_stream_only=end_of_stream_only,+ mappings=endpoint_guardrail_translation_mappings,+ ):+ yield transformed_item+ return+ verbose_proxy_logger.warning(+ "UnifiedLLMGuardrails: streaming_transform_mode=incremental_diff is only supported "+ "for the OpenAI chat completions streaming path with a resolvable request route; "+ "falling back to block_only for %s",+ getattr(guardrail_to_apply, "guardrail_name", None),+ )+# Infer call type from first chunkcall_type = Nonechunk_counter = 0diff --git a/litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.py b/litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.pyindex d0ac8bb8998..9e198e13902 100644--- a/litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.py+++ b/litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.py@@ -84,6 +84,24 @@ class GenericGuardrailAPIOptionalParams(BaseModel):),)+ streaming_transform_mode: Optional[Literal["block_only", "incremental_diff"]] = Field(+ default=None,+ description=(+ "Controls whether text modifications returned by the guardrail (action="+ "GUARDRAIL_INTERVENED with modified texts) reach the client on the streaming "+ "path. 'block_only' (default) preserves the historical behavior: the raw "+ "upstream chunks are streamed and only a BLOCK terminates the stream; text "+ "rewrites are dropped. 'incremental_diff' withholds the raw chunks and instead "+ "emits the guardrailed text as new deltas computed by diffing the mutated "+ "accumulated text against what has already been sent, enabling PII masking, "+ "pseudonym reversal, redaction and similar rewrites over HTTP. Only supported "+ "for the OpenAI chat completions streaming path (string delta.content) and "+ "ignored when streaming_end_of_stream_only is True except for a single "+ "post-stream synthetic chunk. Defaults to 'block_only' in "+ "GenericGuardrailAPI.__init__ when None."+ ),+ )+class GenericGuardrailAPIConfigModel(GuardrailConfigModel[GenericGuardrailAPIOptionalParams],@@ -126,6 +144,20 @@ class GenericGuardrailAPIRequest(BaseModel):model: Optional[str] = None # the model being used for the LLM call+def coerce_stream_holdback_value(value: Any) -> int:+ """Coerce a single ``stream_holdback_chars`` entry to a non-negative int.++ A guardrail returning a null, non-numeric, or negative holdback element must+ not abort the streaming round, so malformed values degrade to 0 (no holdback)+ rather than raising. Shared by response parsing (``from_dict``) and the+ handler that applies holdback to in-process guardrail return values.+ """+ try:+ return max(0, int(value))+ except (TypeError, ValueError):+ return 0++class GenericGuardrailAPIResponse:"""Response model for the Generic Guardrail API"""@@ -134,6 +166,7 @@ class GenericGuardrailAPIResponse:tools: Optional[List[GuardrailToolParam]]action: strblocked_reason: Optional[str]+ stream_holdback_chars: Optional[List[int]]def __init__(self,@@ -142,19 +175,29 @@ class GenericGuardrailAPIResponse:blocked_reason: Optional[str] = None,images: Optional[List[str]] = None,tools: Optional[List[GuardrailToolParam]] = None,+ stream_holdback_chars: Optional[List[int]] = None,):self.action = actionself.blocked_reason = blocked_reasonself.texts = textsself.images = imagesself.tools = tools+ # Number of trailing chars, indexed the same as ``texts``, that the+ # framework must withhold from streaming emission until the next+ # processing round (word-boundary safety for text transformations).+ self.stream_holdback_chars = stream_holdback_chars@classmethoddef from_dict(cls, data: dict) -> "GenericGuardrailAPIResponse":+ raw_holdback = data.get("stream_holdback_chars")+ stream_holdback_chars = (+ [coerce_stream_holdback_value(value) for value in raw_holdback] if isinstance(raw_holdback, list) else None+ )return cls(action=data.get("action", "NONE"),blocked_reason=data.get("blocked_reason"),texts=data.get("texts"),images=data.get("images"),tools=data.get("tools"),+ stream_holdback_chars=stream_holdback_chars,)diff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex 8799b622ad1..6487a8aa33f 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -3778,3 +3778,6 @@ class GenericGuardrailAPIInputs(TypedDict, total=False):AllMessageValues] # structured messages sent to the LLM - indicates if text is from system or usermodel: Optional[str] # the model being used for the LLM call+ stream_holdback_chars: List[+ int+ ] # trailing chars to withhold from streaming emission per text (word-boundary safety)diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.pyindex 791fdd4077c..5be0d43c250 100644--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py@@ -1150,6 +1150,23 @@ class TestGenericGuardrailAPIStreamingConfig:assert GenericGuardrailAPI.get_config_model() is GenericGuardrailAPIConfigModel+ def test_streaming_transform_mode_defaults_block_only(self):+ guardrail = GenericGuardrailAPI(+ api_base="https://api.test.guardrail.com",+ guardrail_name="test-generic-guardrail",+ event_hook="post_call",+ )+ assert guardrail.streaming_transform_mode == "block_only"++ def test_streaming_transform_mode_override(self):+ guardrail = GenericGuardrailAPI(+ api_base="https://api.test.guardrail.com",+ guardrail_name="test-generic-guardrail",+ event_hook="post_call",+ streaming_transform_mode="incremental_diff",+ )+ assert guardrail.streaming_transform_mode == "incremental_diff"+def test_initialize_guardrail_forwards_streaming_flags(self):from litellm.proxy.guardrails.guardrail_hooks.generic_guardrail_api import (initialize_guardrail,@@ -1306,6 +1323,86 @@ class TestGenericGuardrailAPIStreamingConfig:assert guardrail.streaming_sampling_rate == 2+class TestGenericGuardrailAPIResponseParsing:+ """GenericGuardrailAPIResponse.from_dict handling of the streaming holdback field."""++ def test_from_dict_parses_stream_holdback_chars(self):+ from litellm.types.proxy.guardrails.guardrail_hooks.generic_guardrail_api import (+ GenericGuardrailAPIResponse,+ )++ response = GenericGuardrailAPIResponse.from_dict(+ {+ "action": "GUARDRAIL_INTERVENED",+ "texts": ["Alice went to Berlin"],+ "stream_holdback_chars": [5],+ }+ )++ assert response.action == "GUARDRAIL_INTERVENED"+ assert response.texts == ["Alice went to Berlin"]+ assert response.stream_holdback_chars == [5]++ def test_from_dict_coerces_holdback_values_to_int(self):+ from litellm.types.proxy.guardrails.guardrail_hooks.generic_guardrail_api import (+ GenericGuardrailAPIResponse,+ )++ response = GenericGuardrailAPIResponse.from_dict(+ {"action": "GUARDRAIL_INTERVENED", "texts": ["x", "y"], "stream_holdback_chars": ["3", 0]}+ )++ assert response.stream_holdback_chars == [3, 0]++ def test_from_dict_holdback_absent_is_none(self):+ from litellm.types.proxy.guardrails.guardrail_hooks.generic_guardrail_api import (+ GenericGuardrailAPIResponse,+ )++ response = GenericGuardrailAPIResponse.from_dict({"action": "NONE", "texts": ["hi"]})++ assert response.stream_holdback_chars is None++ def test_from_dict_malformed_holdback_degrades_to_zero(self):+ """A null/non-numeric/negative holdback element must not raise; it degrades+ to 0 (no holdback) so a bad guardrail response can't abort the stream."""+ from litellm.types.proxy.guardrails.guardrail_hooks.generic_guardrail_api import (+ GenericGuardrailAPIResponse,+ )++ response = GenericGuardrailAPIResponse.from_dict(+ {+ "action": "GUARDRAIL_INTERVENED",+ "texts": ["a", "b", "c", "d"],+ "stream_holdback_chars": ["3", None, "bad", -2],+ }+ )++ assert response.stream_holdback_chars == [3, 0, 0, 0]++ @pytest.mark.asyncio+ async def test_apply_guardrail_flows_holdback_back_to_inputs(self, generic_guardrail):+ """A GUARDRAIL_INTERVENED response with stream_holdback_chars is surfaced on+ the returned inputs so the streaming framework can apply it."""+ mock_response = MagicMock()+ mock_response.json.return_value = {+ "action": "GUARDRAIL_INTERVENED",+ "texts": ["Alice went to Berlin"],+ "stream_holdback_chars": [5],+ }+ mock_response.raise_for_status = MagicMock()++ with patch.object(generic_guardrail.async_handler, "post", return_value=mock_response):+ result = await generic_guardrail.apply_guardrail(+ inputs={"texts": ["Zorg went to Xanadu"]},+ request_data={},+ input_type="response",+ )++ assert result["texts"] == ["Alice went to Berlin"]+ assert result["stream_holdback_chars"] == [5]++class TestGenericGuardrailAPIStreamingViaUnified:"""Streaming output checks routed through UnifiedLLMGuardrails."""diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/unified_guardrails/test_unified_guardrail.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/unified_guardrails/test_unified_guardrail.pyindex 6e027fa4941..e84e9b74201 100644--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/unified_guardrails/test_unified_guardrail.py+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/unified_guardrails/test_unified_guardrail.py@@ -648,3 +648,845 @@ class TestUnifiedLLMGuardrails:# Response returned with pages intactassert result.pages[0].markdown == "Some text"+++class _StreamingTextGuardrail(CustomGuardrail):+ """Guardrail whose apply_guardrail rewrites (uppercases) response text.++ Optionally schedules a per-response-call ``stream_holdback_chars`` (indexed+ like ``texts``) and can force the mutated text shorter than the input to+ exercise the streaming underflow guard.+ """++ def __init__(self, *, holdback_schedule=None, shrink_to=None, shrink_after=0, sampling_rate=1):+ super().__init__(guardrail_name="streaming-text-guardrail")+ self.streaming_transform_mode = "incremental_diff"+ self.streaming_sampling_rate = sampling_rate+ self.streaming_end_of_stream_only = False+ self.guardrail_config = {}+ self._holdback_schedule = list(holdback_schedule or [])+ self._shrink_to = shrink_to+ self._shrink_after = shrink_after+ self.response_calls = 0+ self.received_texts = []+ self.received_tool_calls = []++ def should_run_guardrail(self, data, event_type): # type: ignore[override]+ return True++ async def apply_guardrail(self, inputs, request_data, input_type, **kwargs):+ texts = inputs.get("texts", [])+ if input_type != "response":+ return {"texts": [t.upper() for t in texts]}++ if inputs.get("tool_calls"):+ self.received_tool_calls.append(inputs.get("tool_calls"))+ self.received_texts.append(list(texts))+ idx = self.response_calls+ self.response_calls += 1+ if self._shrink_to is not None and idx >= self._shrink_after:+ transformed = [self._shrink_to for _ in texts]+ else:+ transformed = [t.upper() for t in texts]+ result = {"texts": transformed}+ if idx < len(self._holdback_schedule):+ result["stream_holdback_chars"] = [self._holdback_schedule[idx]] * len(texts)+ return result+++def _stream_chunk(content, finish_reason=None, index=0):+ return ModelResponseStream(+ choices=[+ StreamingChoices(+ index=index,+ delta=Delta(content=content, role="assistant"),+ finish_reason=finish_reason,+ )+ ],+ )+++async def _drive_stream(handler, guardrail, chunks, request_route="/v1/chat/completions"):+ async def _mock_stream():+ for chunk in chunks:+ yield chunk++ user_api_key_dict = UserAPIKeyAuth(api_key="test-key", request_route=request_route)+ request_data = {"guardrail_to_apply": guardrail, "model": "gpt-4"}+ out = []+ async for item in handler.async_post_call_streaming_iterator_hook(+ user_api_key_dict=user_api_key_dict,+ response=_mock_stream(),+ request_data=request_data,+ ):+ out.append(item)+ return out+++def _delta_text(item):+ if not getattr(item, "choices", None):+ return ""+ return item.choices[0].delta.content or ""+++class TestStreamingTransform:+ """Streaming text-transformation (incremental_diff) path on the OpenAI chat+ completions streaming surface."""++ @pytest.fixture(autouse=True)+ def _use_openai_handler_mapping(self):+ unified_module.endpoint_guardrail_translation_mappings = {+ CallTypes.acompletion: OpenAIChatCompletionsHandler,+ }+ yield+ unified_module.endpoint_guardrail_translation_mappings = None++ @pytest.mark.asyncio+ async def test_block_only_drops_text_rewrites(self):+ """Default block_only: the guardrail's uppercasing never reaches the+ client; the original lowercase chunks are streamed verbatim."""+ guardrail = _StreamingTextGuardrail()+ guardrail.streaming_transform_mode = "block_only"++ chunks = [+ _stream_chunk("hello "),+ _stream_chunk("world"),+ _stream_chunk("", finish_reason="stop"),+ ]++ out = await _drive_stream(UnifiedLLMGuardrails(), guardrail, chunks)+ streamed = "".join(_delta_text(i) for i in out)++ assert streamed == "hello world"+ assert streamed != streamed.upper()++ @pytest.mark.asyncio+ async def test_incremental_diff_emits_uppercased_deltas(self):+ """incremental_diff: the client receives uppercased deltas whose+ concatenation equals uppercase(full)."""+ guardrail = _StreamingTextGuardrail()++ full = "hello world this is streaming"+ words = ["hello ", "world ", "this ", "is ", "streaming"]+ chunks = [_stream_chunk(w) for w in words]+ chunks.append(_stream_chunk("", finish_reason="stop"))++ out = await _drive_stream(UnifiedLLMGuardrails(), guardrail, chunks)+ streamed = "".join(_delta_text(i) for i in out)++ assert streamed == full.upper()+ # No raw lowercase content leaked onto the wire.+ assert "hello" not in streamed++ @pytest.mark.asyncio+ async def test_incremental_diff_holdback_boundary(self):+ """Holdback=5 on the first sample withholds the trailing chars until the+ next round; the final concatenation matches with no loss or duplication."""+ guardrail = _StreamingTextGuardrail(holdback_schedule=[5, 0])++ # No finish_reason: every sample uses the combined-text branch so the+ # scheduled holdback is applied on the first round.+ chunks = [_stream_chunk("abcdef"), _stream_chunk("ghij")]++ out = await _drive_stream(UnifiedLLMGuardrails(), guardrail, chunks)+ deltas = [_delta_text(i) for i in out]+ streamed = "".join(deltas)++ # First sample: "ABCDEF" with holdback 5 -> only "A" is emitted.+ assert deltas[0] == "A"+ assert streamed == "ABCDEFGHIJ"++ @pytest.mark.asyncio+ async def test_incremental_diff_underflow_raises(self):+ """A transform shorter than what was already streamed cannot retract+ bytes: it raises HTTPException(stream_transform_underflow)."""+ # First sample emits "ABCDEF" (6 chars); second sample shrinks to 3.+ guardrail = _StreamingTextGuardrail(shrink_to="ABC", shrink_after=1)++ chunks = [_stream_chunk("abcdef"), _stream_chunk("ghij")]++ with pytest.raises(unified_module.HTTPException) as exc_info:+ await _drive_stream(UnifiedLLMGuardrails(), guardrail, chunks)++ assert exc_info.value.status_code == 400+ assert exc_info.value.detail["error"] == "stream_transform_underflow"++ @pytest.mark.asyncio+ async def test_incremental_diff_final_chunk_preserves_finish_reason(self):+ """The final synthetic chunk carries the finish_reason of the last raw+ chunk."""+ guardrail = _StreamingTextGuardrail()++ chunks = [+ _stream_chunk("hello "),+ _stream_chunk("world"),+ _stream_chunk("", finish_reason="stop"),+ ]++ out = await _drive_stream(UnifiedLLMGuardrails(), guardrail, chunks)++ assert out, "expected at least one synthetic chunk"+ assert out[-1].choices[0].finish_reason == "stop"+ assert "".join(_delta_text(i) for i in out) == "HELLO WORLD"++ @pytest.mark.asyncio+ async def test_end_of_stream_only_emits_single_final_chunk(self):+ """incremental_diff + streaming_end_of_stream_only: a single post-stream+ synthetic chunk carries the whole guardrailed text and the finish_reason."""+ guardrail = _StreamingTextGuardrail()+ guardrail.streaming_end_of_stream_only = True++ chunks = [+ _stream_chunk("hello "),+ _stream_chunk("world"),+ _stream_chunk("", finish_reason="stop"),+ ]++ out = await _drive_stream(UnifiedLLMGuardrails(), guardrail, chunks)++ non_empty = [i for i in out if _delta_text(i)]+ assert len(non_empty) == 1+ assert _delta_text(non_empty[0]) == "HELLO WORLD"+ assert out[-1].choices[0].finish_reason == "stop"++ @pytest.mark.asyncio+ async def test_unsupported_route_falls_back_to_block_only(self):+ """A route that does not resolve to the OpenAI chat handler falls back to+ block_only rather than transforming."""+ guardrail = _StreamingTextGuardrail()++ chunks = [_stream_chunk("hello "), _stream_chunk("world", finish_reason="stop")]++ # request_route=None => no resolvable call type => block_only fallback.+ out = await _drive_stream(UnifiedLLMGuardrails(), guardrail, chunks, request_route=None)+ streamed = "".join(_delta_text(i) for i in out)++ assert streamed == "hello world"++ @pytest.mark.asyncio+ async def test_emit_streaming_http_error_a2a_yields_jsonrpc_chunk(self):+ """The shared streaming error helper emits an in-stream JSON-RPC error for+ A2A call types instead of raising."""+ import json++ handler = UnifiedLLMGuardrails()+ exc = unified_module.HTTPException(+ status_code=400,+ detail={"error": "stream_transform_underflow", "message": "boom"},+ )++ emitted = []+ async for item in handler._emit_streaming_http_error(+ exc,+ call_type=CallTypes.asend_message.value,+ responses_so_far=[{"id": "req-1"}],+ request_data={},+ ):+ emitted.append(item)++ assert len(emitted) == 1+ payload = json.loads(emitted[0])+ assert payload["error"]["message"] == "stream_transform_underflow"+ assert payload["id"] == "req-1"++ def test_final_chunk_preserves_per_choice_finish_reason(self):+ """The final flush must carry each choice's own finish_reason, not+ choices[0]'s, for n > 1 (e.g. "stop" vs "length")."""+ reference_chunk = ModelResponseStream(choices=[StreamingChoices(index=0, delta=Delta(content="a"))])++ synthetic = UnifiedLLMGuardrails()._build_transform_chunk(+ reference_chunk=reference_chunk,+ mutated_text_per_choice={0: "A", 1: "B"},+ emitted_text_per_choice={},+ holdback_per_choice={},+ finish_reason_per_choice={0: "stop", 1: "length"},+ is_final=True,+ )++ by_index = {c.index: c for c in synthetic.choices}+ assert by_index[0].finish_reason == "stop"+ assert by_index[1].finish_reason == "length"+ assert by_index[0].delta.content == "A"+ assert by_index[1].delta.content == "B"++ def test_synthetic_chunk_drops_raw_tool_calls(self):+ """v1 does not transform streamed tool calls; the synthetic chunk must not+ pass raw upstream tool_calls through (they would bypass the guardrail)."""+ reference_chunk = ModelResponseStream(+ choices=[+ StreamingChoices(+ index=0,+ delta=Delta(+ content="hi",+ tool_calls=[+ {+ "index": 0,+ "id": "call_1",+ "type": "function",+ "function": {"name": "leak", "arguments": '{"ssn": "123-45-6789"}'},+ }+ ],+ ),+ finish_reason=None,+ ),+ ],+ )++ synthetic = UnifiedLLMGuardrails()._build_transform_chunk(+ reference_chunk=reference_chunk,+ mutated_text_per_choice={0: "HI"},+ emitted_text_per_choice={},+ holdback_per_choice={},+ finish_reason_per_choice={},+ is_final=False,+ )++ assert synthetic.choices[0].delta.tool_calls is None+ assert synthetic.choices[0].delta.content == "HI"++ def test_rewriting_already_emitted_prefix_raises(self):+ """If a later transform rewrites bytes already streamed (not a forward+ extension), the framework fails closed rather than leaking the original."""+ reference_chunk = ModelResponseStream(+ choices=[StreamingChoices(index=0, delta=Delta(content="x"), finish_reason=None)],+ )++ with pytest.raises(unified_module.HTTPException) as exc_info:+ UnifiedLLMGuardrails()._build_transform_chunk(+ reference_chunk=reference_chunk,+ # already streamed "My SSN is 123"; the guardrail now wants to+ # redact those already-sent chars -> not a forward extension.+ mutated_text_per_choice={0: "My SSN is [REDACTED]"},+ emitted_text_per_choice={0: "My SSN is 123"},+ holdback_per_choice={},+ finish_reason_per_choice={},+ is_final=False,+ )++ assert exc_info.value.status_code == 400+ assert exc_info.value.detail["error"] == "stream_transform_underflow"++ @pytest.mark.asyncio+ async def test_tool_call_chunks_pass_through_and_not_dropped(self):+ """A tool-call chunk is passed through raw under incremental_diff (v1 does+ not transform tool calls) rather than being withheld and dropped, and no+ bogus empty-choices chunk is emitted for a tool-call-only turn."""+ guardrail = _StreamingTextGuardrail()++ tool_chunk = ModelResponseStream(+ choices=[+ StreamingChoices(+ index=0,+ delta=Delta(+ content=None,+ tool_calls=[+ {+ "index": 0,+ "id": "call_1",+ "type": "function",+ "function": {"name": "get_weather", "arguments": "{}"},+ }+ ],+ ),+ finish_reason="tool_calls",+ )+ ],+ )++ out = await _drive_stream(UnifiedLLMGuardrails(), guardrail, [tool_chunk])++ assert len(out) == 1+ assert out[0].choices[0].delta.tool_calls+ assert out[0].choices[0].finish_reason == "tool_calls"+ # The tool call is delivered raw but still inspected by the guardrail at+ # end of stream (it can block), matching block_only.+ assert guardrail.received_tool_calls++ @pytest.mark.asyncio+ async def test_per_choice_finish_reason_when_choices_finish_in_different_chunks(self):+ """n>1: a choice finishing before the stream's last chunk keeps its own+ finish_reason (it must not be lost because it is not on last_chunk)."""+ guardrail = _StreamingTextGuardrail()+ guardrail.streaming_end_of_stream_only = True # only the flush emits++ chunks = [+ _stream_chunk("aa", index=0),+ _stream_chunk("bb", index=1),+ _stream_chunk("", finish_reason="stop", index=0),+ _stream_chunk("", finish_reason="length", index=1),+ ]++ out = await _drive_stream(UnifiedLLMGuardrails(), guardrail, chunks)++ by_index = {}+ for item in out:+ for choice in item.choices:+ if choice.finish_reason is not None:+ by_index[choice.index] = choice.finish_reason+ assert by_index == {0: "stop", 1: "length"}++ @pytest.mark.asyncio+ async def test_short_guardrail_texts_withheld_not_leaked(self):+ """If the guardrail returns fewer texts than sent (contract violation),+ the unmatched choice is withheld (fail closed), not emitted raw."""++ class _DropsSecondChoice(_StreamingTextGuardrail):+ async def apply_guardrail(self, inputs, request_data, input_type, **kwargs):+ texts = inputs.get("texts", [])+ if input_type != "response":+ return {"texts": [t.upper() for t in texts]}+ # Return only the first choice's transformed text.+ return {"texts": [texts[0].upper()] if texts else []}++ guardrail = _DropsSecondChoice()+ guardrail.streaming_end_of_stream_only = True++ chunks = [+ _stream_chunk("secret-a", index=0),+ _stream_chunk("secret-b", index=1),+ _stream_chunk("", finish_reason="stop", index=0),+ _stream_chunk("", finish_reason="stop", index=1),+ ]++ out = await _drive_stream(UnifiedLLMGuardrails(), guardrail, chunks)++ streamed = "".join(_delta_text(i) for i in out)+ assert "SECRET-A" in streamed+ # Choice 1 had no guardrailed text returned: withheld, never leaked raw.+ assert "secret-b" not in streamed+ assert "SECRET-B" not in streamed++ @pytest.mark.asyncio+ async def test_no_spurious_chunk_after_text_then_tool_call_finish(self):+ """When a choice streams text and then finishes via a tool-call chunk, the+ raw tool-call chunk carries the finish_reason and no spurious empty chunk+ for that choice is emitted afterwards (protocol: no delta after finish)."""+ guardrail = _StreamingTextGuardrail()++ tool_chunk = ModelResponseStream(+ choices=[+ StreamingChoices(+ index=0,+ delta=Delta(+ content=None,+ tool_calls=[+ {+ "index": 0,+ "id": "call_1",+ "type": "function",+ "function": {"name": "get_weather", "arguments": "{}"},+ }+ ],+ ),+ finish_reason="tool_calls",+ )+ ],+ )+ chunks = [_stream_chunk("let me check "), tool_chunk]++ out = await _drive_stream(UnifiedLLMGuardrails(), guardrail, chunks)++ # Exactly: one synthetic text delta, then the raw tool-call chunk. No+ # trailing empty chunk for choice 0 after it already finished.+ assert len(out) == 2+ assert _delta_text(out[0]) == "LET ME CHECK "+ assert out[1].choices[0].delta.tool_calls+ assert out[1].choices[0].finish_reason == "tool_calls"++ @pytest.mark.asyncio+ async def test_tool_call_blocking_guardrail_is_enforced(self):+ """A guardrail that blocks on tool calls must terminate the incremental_diff+ stream: tool calls go through the block decision, not bypass it."""+ from litellm.exceptions import GuardrailRaisedException++ class _ToolCallBlocker(_StreamingTextGuardrail):+ async def apply_guardrail(self, inputs, request_data, input_type, **kwargs):+ if input_type == "response" and inputs.get("tool_calls"):+ raise GuardrailRaisedException(+ guardrail_name="tc-block",+ message="blocked tool call",+ should_wrap_with_default_message=False,+ )+ return await super().apply_guardrail(inputs, request_data, input_type, **kwargs)++ tool_chunk = ModelResponseStream(+ choices=[+ StreamingChoices(+ index=0,+ delta=Delta(+ content=None,+ tool_calls=[+ {+ "index": 0,+ "id": "call_1",+ "type": "function",+ "function": {"name": "exfiltrate", "arguments": "{}"},+ }+ ],+ ),+ finish_reason="tool_calls",+ )+ ],+ )++ with pytest.raises(GuardrailRaisedException):+ await _drive_stream(UnifiedLLMGuardrails(), _ToolCallBlocker(), [tool_chunk])++ @pytest.mark.asyncio+ async def test_mixed_content_and_tool_call_chunk_does_not_leak_text(self):+ """A chunk carrying BOTH delta.content and a tool call must not be yielded+ raw: the text has to go through the transform, only tool-call fields pass+ through raw (content stripped)."""+ guardrail = _StreamingTextGuardrail()++ mixed = ModelResponseStream(+ choices=[+ StreamingChoices(+ index=0,+ delta=Delta(+ content="secret",+ role="assistant",+ tool_calls=[+ {+ "index": 0,+ "id": "call_1",+ "type": "function",+ "function": {"name": "f", "arguments": "{}"},+ }+ ],+ ),+ finish_reason="tool_calls",+ )+ ],+ )++ out = await _drive_stream(UnifiedLLMGuardrails(), guardrail, [mixed])++ streamed = "".join(_delta_text(i) for i in out)+ # Raw text never reaches the client; only the transformed text does.+ assert "secret" not in streamed+ assert "SECRET" in streamed+ # The tool call is delivered, but its chunk carries no text.+ tool_chunks = [i for i in out if i.choices[0].delta.tool_calls]+ assert tool_chunks+ assert all(not (c.choices[0].delta.content or "") for c in tool_chunks)++ @pytest.mark.asyncio+ async def test_n_gt_1_text_and_tool_call_in_same_chunk_no_text_leak(self):+ """n>1 chunk where one choice streams text and another a tool call: the+ text choice must be transformed, not emitted raw alongside the tool call."""+ guardrail = _StreamingTextGuardrail()++ chunk = ModelResponseStream(+ choices=[+ StreamingChoices(index=0, delta=Delta(content="secret", role="assistant"), finish_reason=None),+ StreamingChoices(+ index=1,+ delta=Delta(+ content=None,+ role="assistant",+ tool_calls=[+ {+ "index": 0,+ "id": "call_1",+ "type": "function",+ "function": {"name": "f", "arguments": "{}"},+ }+ ],+ ),+ finish_reason="tool_calls",+ ),+ ],+ )++ out = await _drive_stream(UnifiedLLMGuardrails(), guardrail, [chunk])++ # choice 0's text is transformed, never delivered raw on the tool chunk.+ for item in out:+ for c in item.choices:+ if c.delta.tool_calls:+ assert not (c.delta.content or "")+ all_text = "".join(c.delta.content or "" for i in out for c in i.choices)+ assert "secret" not in all_text+ assert "SECRET" in all_text++ @pytest.mark.asyncio+ async def test_mixed_chunk_finish_reason_arrives_after_transformed_text(self):+ """Fix #1: when a single chunk carries both delta.content and tool_calls+ with finish_reason set, the passthrough must NOT emit finish_reason+ before the transformed text — SSE clients that stop reading at+ finish_reason would silently drop the guardrailed text. finish_reason+ must ride on a terminator after the transformed text."""+ guardrail = _StreamingTextGuardrail()+ mixed = ModelResponseStream(+ choices=[+ StreamingChoices(+ index=0,+ delta=Delta(+ content="secret",+ role="assistant",+ tool_calls=[+ {+ "index": 0,+ "id": "call_1",+ "type": "function",+ "function": {"name": "f", "arguments": "{}"},+ }+ ],+ ),+ finish_reason="tool_calls",+ )+ ],+ )++ out = await _drive_stream(UnifiedLLMGuardrails(), guardrail, [mixed])++ passthrough_idx = next(i for i, item in enumerate(out) if item.choices and item.choices[0].delta.tool_calls)+ # Passthrough MUST NOT carry finish_reason for a mixed chunk (deferred).+ assert out[passthrough_idx].choices[0].finish_reason is None, (+ f"passthrough of mixed chunk leaked finish_reason: {out[passthrough_idx].choices[0].finish_reason}"+ )+ # finish_reason arrives via a terminator that comes AFTER the passthrough,+ # so an SSE client reading top-down sees the transformed text before it+ # sees the terminator.+ finish_carriers = [+ i for i, item in enumerate(out) if item.choices and item.choices[0].finish_reason == "tool_calls"+ ]+ assert finish_carriers, "finish_reason=tool_calls never delivered"+ assert min(finish_carriers) > passthrough_idx+ # And the redacted text ("SECRET") reached the wire on some non-tool+ # chunk (i.e. the text terminator).+ transformed = "".join(+ item.choices[0].delta.content or ""+ for item in out+ if item.choices and not item.choices[0].delta.tool_calls+ )+ assert "SECRET" in transformed+ assert "secret" not in transformed++ @pytest.mark.asyncio+ async def test_text_flush_precedes_tool_call_passthrough(self):+ """Fix #3: text chunks followed by a pure tool-call chunk carrying+ finish_reason="tool_calls" must emit transformed text BEFORE the+ passthrough, otherwise SSE-compliant clients stop reading at+ finish_reason and drop the transformed text."""+ # sampling_rate 5: no mid-stream round would fire on 2 text chunks+ # without the pre-tool-call flush.+ guardrail = _StreamingTextGuardrail(sampling_rate=5)+ chunks = [+ _stream_chunk("hello "),+ _stream_chunk("world"),+ ModelResponseStream(+ choices=[+ StreamingChoices(+ index=0,+ delta=Delta(+ content=None,+ role="assistant",+ tool_calls=[+ {+ "index": 0,+ "id": "call_1",+ "type": "function",+ "function": {"name": "f", "arguments": "{}"},+ }+ ],+ ),+ finish_reason="tool_calls",+ )+ ],+ ),+ ]++ out = await _drive_stream(UnifiedLLMGuardrails(), guardrail, chunks)++ text_indices = [+ i+ for i, item in enumerate(out)+ if item.choices and (item.choices[0].delta.content or "") and not item.choices[0].delta.tool_calls+ ]+ tool_indices = [i for i, item in enumerate(out) if item.choices and item.choices[0].delta.tool_calls]+ assert text_indices, "transformed text was never emitted"+ assert tool_indices, "tool-call passthrough missing"+ assert max(text_indices) < min(tool_indices)+ transformed = "".join(out[i].choices[0].delta.content or "" for i in text_indices)+ assert "HELLO WORLD" in transformed++ @pytest.mark.asyncio+ async def test_final_finish_reason_flushed_when_guardrail_suppresses_text(self):+ """Fix #4: when the guardrail returns texts=[] (full suppression) and a+ mixed content+tool_call chunk had deferred its finish_reason to the+ text flush, the final flush must still emit a terminator chunk carrying+ finish_reason. Otherwise the SSE stream ends without finish_reason."""++ class _SuppressAll(_StreamingTextGuardrail):+ async def apply_guardrail(self, inputs, request_data, input_type, **kwargs):+ self.received_texts.append(list(inputs.get("texts") or []))+ return {"texts": []}++ mixed = ModelResponseStream(+ choices=[+ StreamingChoices(+ index=0,+ delta=Delta(+ content="secret",+ role="assistant",+ tool_calls=[+ {+ "index": 0,+ "id": "call_1",+ "type": "function",+ "function": {"name": "f", "arguments": "{}"},+ }+ ],+ ),+ finish_reason="tool_calls",+ )+ ],+ )++ out = await _drive_stream(UnifiedLLMGuardrails(), _SuppressAll(), [mixed])+ finishes = [c.finish_reason for item in out for c in item.choices if c.index == 0]+ assert "tool_calls" in finishes++ @pytest.mark.asyncio+ async def test_transform_sends_texts_sorted_by_choice_index(self):+ """Fix #2: for n>1 streams where choice 1 emits before choice 0, the+ transform must send texts to the guardrail in ascending choice-index+ order so its returned texts realign to the correct choice indices."""++ class _RecordingGuardrail(_StreamingTextGuardrail):+ async def apply_guardrail(self, inputs, request_data, input_type, **kwargs):+ self.received_texts.append(list(inputs.get("texts") or []))+ return {"texts": list(inputs.get("texts") or [])}++ guardrail = _RecordingGuardrail()+ chunks = [+ _stream_chunk("beta", index=1),+ _stream_chunk("alpha", index=0),+ _stream_chunk("", index=0, finish_reason="stop"),+ ]+ await _drive_stream(UnifiedLLMGuardrails(), guardrail, chunks)+ last = guardrail.received_texts[-1]+ # Sorted ascending: alpha (index 0) before beta (index 1).+ assert last[0].startswith("alpha")+ assert last[1].startswith("beta")++ @pytest.mark.asyncio+ async def test_non_idempotent_guardrail_not_double_applied_on_tool_call_streams(self):+ """A non-idempotent guardrail must not see its own output as input on a+ subsequent round. Regression guard for the bug where+ ``_inspect_full_response_for_block`` shared ``responses_so_far`` with a+ block-only path that mutated ``delta.content`` in place — the next+ ``_round(is_final=True)`` would then re-read the already-guardrailed text+ and re-apply the transform.++ Uses an n>1 chunk with text on choice 0 and tool_calls (with+ finish_reason) on choice 1 — the exact shape that trips the+ ``has_stream_ended=False → block path mutates anyway`` failure mode.+ The test guardrail replaces the literal 'John' with '[REDACTED]', which is+ non-idempotent: '[REDACTED]' does not contain 'John' so a second pass+ produces the same output, BUT the raw accumulator would concat as+ '[REDACTED]' + partial-raw, tripping stream_transform_underflow or+ producing double-output. Assert the guardrail was called with the raw+ text each time, not with any already-guardrailed prefix."""++ class _RedactJohn(_StreamingTextGuardrail):+ async def apply_guardrail(self, inputs, request_data, input_type, **kwargs):+ texts = list(inputs.get("texts") or [])+ self.received_texts.append(texts)+ return {"texts": [t.replace("John", "[REDACTED]") for t in texts]}++ guardrail = _RedactJohn(sampling_rate=5)++ chunks = [+ _stream_chunk("John "),+ _stream_chunk("went home."),+ ModelResponseStream(+ choices=[+ StreamingChoices(index=0, delta=Delta(content=None, role="assistant", tool_calls=None), finish_reason=None),+ StreamingChoices(+ index=1,+ delta=Delta(+ content=None,+ role="assistant",+ tool_calls=[+ {+ "index": 0,+ "id": "call_1",+ "type": "function",+ "function": {"name": "f", "arguments": "{}"},+ }+ ],+ ),+ finish_reason="tool_calls",+ ),+ ],+ ),+ ]++ await _drive_stream(UnifiedLLMGuardrails(), guardrail, chunks)++ # Every text the guardrail saw as input must be raw ("John " not "[REDACTED]").+ # If the block path mutated the shared accumulator, the final _round would+ # send "[REDACTED] went home." instead of "John went home.".+ for received in guardrail.received_texts:+ for text in received:+ assert "[REDACTED]" not in text, (+ f"guardrail was re-invoked with its own already-redacted output "+ f"— shared accumulator mutation regression: {received!r}"+ )+ """The guardrail must receive the raw accumulated output each round, not a+ transformed-prefix + raw-suffix mix (responses_so_far stays untouched)."""+ guardrail = _StreamingTextGuardrail()++ chunks = [_stream_chunk("aa "), _stream_chunk("bb "), _stream_chunk("cc", finish_reason="stop")]++ await _drive_stream(UnifiedLLMGuardrails(), guardrail, chunks)++ # Every recorded input is the cumulative RAW (lowercase) text; if the+ # accumulator were corrupted by write-back, later rounds would contain+ # uppercased prefixes like "AA bb ".+ for received in guardrail.received_texts:+ assert received[0] == received[0].lower()+ assert guardrail.received_texts[-1] == ["aa bb cc"]++ def test_accumulate_keys_by_choice_index_not_position(self):+ """Single-choice chunks carrying a non-zero .index (n>1 streaming) must be+ keyed by index, not enumerate position (which would collapse to 0)."""+ handler = OpenAIChatCompletionsHandler()+ chunks = [+ _stream_chunk("hello", index=1),+ _stream_chunk(" world", index=1),+ ]++ accumulated = handler._accumulate_string_content_by_choice_index(chunks)++ assert accumulated == {1: "hello world"}++ @pytest.mark.asyncio+ async def test_terminal_chunk_not_guardrailed_twice(self):+ """A terminal (finish_reason) chunk that is also a sampling boundary must+ be processed once by the end-of-stream flush, not by a sampled round too."""+ guardrail = _StreamingTextGuardrail() # sampling_rate=1++ chunks = [_stream_chunk("aa "), _stream_chunk("bb", finish_reason="stop")]++ await _drive_stream(UnifiedLLMGuardrails(), guardrail, chunks)++ # Round 1 (chunk 1) + end-of-stream flush = 2 calls. Without the terminal+ # skip, chunk 2 would be guardrailed by a sampled round AND the flush (3).+ assert guardrail.response_calls == 2++ @pytest.mark.asyncio+ async def test_malformed_holdback_from_in_process_guardrail_degrades(self):+ """An in-process guardrail (bypassing from_dict) returning a null holdback+ must degrade to 0 in the handler, not raise and abort the stream."""+ guardrail = _StreamingTextGuardrail(holdback_schedule=[None])++ chunks = [_stream_chunk("abc"), _stream_chunk("def", finish_reason="stop")]++ out = await _drive_stream(UnifiedLLMGuardrails(), guardrail, chunks)++ # None holdback treated as 0: full text emitted, no crash.+ assert "".join(_delta_text(i) for i in out) == "ABCDEF"