Skip to content

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]

Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_legacy_hook_streaming_pipeline_step

mateo-berri5fdbb2a1c8b5
diff --cc litellm/llms/anthropic/chat/guardrail_translation/handler.py
index b83235f660f,6f966ae1a02..9d50345d70d
--- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py
+++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
@@@ -170,8 -212,7 +212,8 @@@ class AnthropicMessagesHandler(BaseTran
them through guardrail rewrites; downstream provider handling is out of scope.
"""
- delivers_ended_stream_text_rewrites = True
+ delivers_ended_stream_rewrites = True
+ assembles_streamed_response = True
def __init__(self):
super().__init__()
diff --cc litellm/llms/base_llm/guardrail_translation/base_translation.py
index 375b22ff5f6,6d1a9ab1c3e..f1143425ced
--- a/litellm/llms/base_llm/guardrail_translation/base_translation.py
+++ b/litellm/llms/base_llm/guardrail_translation/base_translation.py
@@@ -52,28 -52,15 +52,29 @@@ class StreamingScanKey
class BaseTranslation(ABC):
- delivers_ended_stream_text_rewrites: ClassVar[bool] = False
+ delivers_ended_stream_rewrites: ClassVar[bool] = False
"""Whether ``process_output_streaming_response`` accepts
``deliver_ended_stream_rewrites=True`` and, on an ended (fully buffered)
- stream, writes guardrail text rewrites back across ``responses_so_far`` so
- a buffered pipeline can release rewritten chunks. Tool-call rewrites, and
- text rewrites on every other translation, are undeliverable: the pipeline
- executor discards them and releases the original chunks."""
+ stream, writes guardrail text and tool-call rewrites back across
+ ``responses_so_far`` so a buffered pipeline can release rewritten chunks,
+ raising ``UndeliverableStreamRewrite`` for a shape it cannot place. Rewrites
+ on every other translation are undeliverable: the pipeline executor
+ discards them and releases the original chunks."""
+ assembles_streamed_response: ClassVar[bool] = False
+ """Whether ``process_output_streaming_response`` stores the assembled response of an
+ ended stream under ``request_data["response"]`` before scanning it, the way the chat,
+ Responses, and Messages translations do. A streaming pipeline runs a guardrail that only
+ has the legacy post-call hook against that response, so on a translation without it such
+ a guardrail keeps running on its own."""
+
+ def post_call_hook_response(self, response: object) -> object:
+ """The ``response`` this endpoint's non-streaming post-call hooks receive, derived from
+ the object the translation stores under ``request_data["response"]`` while scanning an
+ ended stream. Chat and Responses scan that shape already; a translation that scans a
+ different one (Messages scans an OpenAI-shaped ModelResponse) overrides this."""
+ return response
+
@staticmethod
def transform_user_api_key_dict_to_metadata(
user_api_key_dict: Any | None,
diff --cc litellm/llms/openai/chat/guardrail_translation/handler.py
index b9b88061fec,42c95ac3316..58ff03e6a0d
--- a/litellm/llms/openai/chat/guardrail_translation/handler.py
+++ b/litellm/llms/openai/chat/guardrail_translation/handler.py
@@@ -78,8 -80,7 +80,8 @@@ class OpenAIChatCompletionsHandler(Base
Methods can be overridden to customize behavior for different message formats.
"""
- delivers_ended_stream_text_rewrites = True
+ delivers_ended_stream_rewrites = True
+ assembles_streamed_response = True
def get_structured_messages(self, data: dict) -> list[AllMessageValues] | None:
"""
diff --cc litellm/llms/openai/responses/guardrail_translation/handler.py
index e0ba80706df,280a8670c36..33b2320e35d
--- a/litellm/llms/openai/responses/guardrail_translation/handler.py
+++ b/litellm/llms/openai/responses/guardrail_translation/handler.py
@@@ -340,8 -356,7 +356,8 @@@ class OpenAIResponsesHandler(BaseTransl
Methods can be overridden to customize behavior for different message formats.
"""
- delivers_ended_stream_text_rewrites = True
+ delivers_ended_stream_rewrites = True
+ assembles_streamed_response = True
def get_structured_messages(self, data: dict) -> list[AllMessageValues] | None:
"""
diff --cc litellm/proxy/policy_engine/pipeline_executor.py
index ab5ad01fda9,a51468cc0fb..ed193c7f434
--- a/litellm/proxy/policy_engine/pipeline_executor.py
+++ b/litellm/proxy/policy_engine/pipeline_executor.py
@@@ -388,25 -304,14 +396,25 @@@ class PipelineExecutor
litellm_logging_obj: "LiteLLMLoggingObj | None",
) -> None:
"""Run one streaming post_call step through the endpoint translation, delivering
- text rewrites on translations that support ended-stream write-back. A guardrail
- without the unified interface runs its legacy post-call hook against the assembled
- response through ``_LegacyHookStreamAdapter``. A rewrite that cannot reach the client
- yet (a tool-call rewrite, a text rewrite on a translation without write-back, or one
- the translation or adapter refused with ``UndeliverableStreamRewrite``) is discarded:
- the buffered chunks go back to the originals and the step passes, so the client gets
- the stream the merge base sent, and the guardrail stays out of the applied-guardrails
- header since its output never reached the client. The response an earlier step's translation stored under
- ``request_data["response"]`` is dropped first, so this step's hook sees the stream as
- the steps before it left it."""
+ text and tool-call rewrites on translations that support ended-stream write-back. A
- rewrite that cannot reach the client yet (one on a translation without write-back, or
- one the translation refused with ``UndeliverableStreamRewrite``) is discarded: the
- buffered chunks go back to the originals and the step passes, so the client gets the
- stream the merge base sent."""
- observer: Final = _StreamRewriteObserver(callback)
++ guardrail without the unified interface runs its legacy post-call hook against the
++ assembled response through ``_LegacyHookStreamAdapter``. A rewrite that cannot reach the
++ client yet (one on a translation without write-back, one that drops or adds a tool call,
++ or one the translation or adapter refused with ``UndeliverableStreamRewrite``) is
++ discarded: the buffered chunks go back to the originals and the step passes, so the
++ client gets the stream the merge base sent, and the guardrail stays out of the
++ applied-guardrails header since its output never reached the client. The response an
++ earlier step's translation stored under ``request_data["response"]`` is dropped first,
++ so this step's hook sees the stream as the steps before it left it."""
+ scanner: Final = (
+ callback
+ if PipelineExecutor.supports_unified_execution(callback)
+ else _LegacyHookStreamAdapter(callback, endpoint_translation, user_api_key_dict)
+ )
+ observer: Final = _StreamRewriteObserver(scanner)
- deliver_rewrites: Final = type(endpoint_translation).delivers_ended_stream_text_rewrites
+ deliver_rewrites: Final = type(endpoint_translation).delivers_ended_stream_rewrites
originals: Final = copy.deepcopy(streaming_chunks)
+ hook_input.pop("response", None) # rebind-ok: an earlier step's stored response goes so this step's is stored
try:
if deliver_rewrites:
await endpoint_translation.process_output_streaming_response(
@@@ -427,10 -332,11 +435,12 @@@
)
except UndeliverableStreamRewrite:
_release_original_chunks(step.guardrail, streaming_chunks, originals)
- else:
- if observer.changed_tool_call_count or (
- not deliver_rewrites and (observer.rewrote_texts or observer.rewrote_tool_calls)
- ):
- _release_original_chunks(step.guardrail, streaming_chunks, originals)
+ return
- if observer.rewrote_tool_calls or (observer.rewrote_texts and not deliver_rewrites):
++ if observer.changed_tool_call_count or (
++ not deliver_rewrites and (observer.rewrote_texts or observer.rewrote_tool_calls)
++ ):
+ _release_original_chunks(step.guardrail, streaming_chunks, originals)
+ return
if not callback.records_own_guardrail_information:
add_guardrail_to_applied_guardrails_header(request_data=hook_input, guardrail_name=step.guardrail)
diff --cc litellm/proxy/utils.py
index f323f40dbf1,2be77bf023d..1e5edc6c987
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@@ -538,35 -534,135 +542,145 @@@ def _post_call_pipelines(data: Mapping[
)
- def _warn_background_skips_post_call_pipelines(data: Mapping[str, object]) -> None:
- if data.get("background") is not True:
+ _PENDING_BACKGROUND_RESPONSE_STATUSES: Final = frozenset(("queued", "in_progress"))
+
+
+ def _is_pending_background_response(response: LLMResponseTypes) -> bool:
+ return isinstance(response, ResponsesAPIResponse) and response.status in _PENDING_BACKGROUND_RESPONSE_STATUSES
+
+
+ def _guardrails_outside_pipeline(policy_name: str, pipeline: "GuardrailPipeline") -> frozenset[str]:
+ resolved: Final = PolicyResolver.resolve_policy_guardrails(
+ policy_name=policy_name, policies=get_policy_registry().get_all_policies()
+ )
+ return frozenset(resolved.guardrails) - frozenset(step.guardrail for step in pipeline.steps)
+
+
+ def _guardrails_run_standalone_pre_call(data: Mapping[str, object]) -> frozenset[str]:
+ return frozenset(
+ callback.guardrail_name
+ for callback in litellm.callbacks
+ if isinstance(callback, CustomGuardrail)
+ and callback.guardrail_name is not None
+ and callback.should_run_guardrail(data=data, event_type=GuardrailEventHooks.pre_call)
+ )
+
+
+ def _without_names(
+ bucket: dict[str, object], # mutable-ok: the applied_* header slots live in the request-state dict hooks write
+ slot: str,
+ names: frozenset[str],
+ ) -> None:
+ claimed: Final = bucket.get(slot)
+ if not isinstance(claimed, list):
return
- policy_names: Final = tuple(policy_name for policy_name, _pipeline in _post_call_pipelines(data))
- if not policy_names:
+ remaining: Final = [ # mutable-ok: the slot stays a list, the shape every applied_* header writer appends to
+ name for name in claimed if name not in names
+ ]
+ if remaining:
+ bucket[slot] = remaining # rebind-ok: the slot lives in the shared request-state dict, rewritten in place
+ else:
+ bucket.pop(slot)
+
+
+ def _withdraw_deferred_claims(
+ data: dict[str, object], # mutable-ok: same request-payload shape as post_call_success_hook's data
+ deferred: Sequence[tuple[str, "GuardrailPipeline"]],
+ ) -> None:
+ outside_by_policy: Final = MappingProxyType(
+ {policy_name: _guardrails_outside_pipeline(policy_name, pipeline) for policy_name, pipeline in deferred}
+ )
- running_elsewhere: Final = _pipeline_managed_guardrail_names(data, "pre_call").union(
++ running_elsewhere: Final = pipeline_managed_guardrail_names(data, "pre_call").union(
+ _guardrails_run_standalone_pre_call(data), *outside_by_policy.values()
+ )
+ withdrawn_policies: Final = frozenset(name for name, outside in outside_by_policy.items() if not outside)
+ withdrawn_guardrails: Final = _pipeline_step_guardrail_names(deferred) - running_elsewhere
+ _, bucket = get_or_create_metadata_bucket(data)
+ _without_names(bucket, "applied_policies", withdrawn_policies)
+ _without_names(bucket, "applied_guardrails", withdrawn_guardrails)
+ sources: Final = bucket.get("policy_sources")
+ if not isinstance(sources, dict):
return
- verbose_proxy_logger.warning(
- "Policies with post_call guardrail pipelines do not run on background responses yet; "
- "the response is released ungoverned by them: %s",
- ", ".join(policy_names),
+ remaining_sources: Final = { # mutable-ok: policy_sources stays a dict, the shape its writer updates in place
+ name: reason for name, reason in sources.items() if name not in withdrawn_policies
+ }
+ if remaining_sources:
+ bucket["policy_sources"] = remaining_sources
+ else:
+ bucket.pop("policy_sources")
+
+
+ def _defer_post_call_pipelines(
+ data: dict[str, object], # mutable-ok: same request-payload shape as post_call_success_hook's data
+ response: ResponsesAPIResponse,
+ ) -> None:
+ deferred: Final = _post_call_pipelines(data)
+ if not deferred:
+ return
+ verbose_proxy_logger.debug(
+ "Post_call guardrail pipelines wait for background response %s (status=%s) to be retrieved complete: %s",
+ response.id,
+ response.status,
+ ", ".join(policy_name for policy_name, _pipeline in deferred),
)
+ tag_matched: Final = _tag_matched_deferrals(data, deferred)
+ if tag_matched:
+ verbose_proxy_logger.warning(
+ "Policy engine: background response %s matched post_call policies through a request tag at submit; "
+ "retrieval re-matches only the key, team, and model scopes, so a tag carried in the request body "
+ "does not govern the completed response: %s",
+ response.id,
+ ", ".join(tag_matched),
+ )
+ body_selected: Final = _body_selected_deferrals(data, deferred)
+ if body_selected:
+ verbose_proxy_logger.warning(
+ "Policy engine: background response %s matched post_call policies through the request body's policies "
+ "list at submit; retrieval carries no request body, so those policies do not govern the completed "
+ "response: %s",
+ response.id,
+ ", ".join(body_selected),
+ )
+ _withdraw_deferred_claims(data, deferred)
+
+
+ def _tag_matched_deferrals(
+ data: Mapping[str, object], deferred: Sequence[tuple[str, "GuardrailPipeline"]]
+ ) -> tuple[str, ...]:
+ sources: Final = _policy_state_metadata(data).get("policy_sources")
+ if not isinstance(sources, dict):
+ return ()
+ return tuple(
+ policy_name
+ for policy_name, _pipeline in deferred
+ if policy_name in sources and "tag:" in str(sources[policy_name])
+ )
+
+
+ def _body_selected_deferrals(
+ data: Mapping[str, object], deferred: Sequence[tuple[str, "GuardrailPipeline"]]
+ ) -> tuple[str, ...]:
+ sources: Final = _policy_state_metadata(data).get("policy_sources")
+ attributed: Final = frozenset(sources) if isinstance(sources, dict) else frozenset()
+ return tuple(policy_name for policy_name, _pipeline in deferred if policy_name not in attributed)
-def _pipeline_is_streamable(policy_name: str, pipeline: "GuardrailPipeline") -> bool:
- unsupported: Final = tuple(
+def _pipeline_unsupported_streaming_guardrails(
+ pipeline: "GuardrailPipeline", translation: "BaseTranslation | None"
+) -> tuple[str, ...]:
+ return tuple(
dict.fromkeys(
- step.guardrail for step in pipeline.steps if not _pipeline_step_supports_unified_streaming(step.guardrail)
+ step.guardrail
+ for step in pipeline.steps
+ if not _pipeline_step_supports_streaming(step.guardrail, translation)
)
)
+
+
+def _pipeline_is_streamable(
+ policy_name: str, pipeline: "GuardrailPipeline", translation: "BaseTranslation | None"
+) -> bool:
+ unsupported: Final = _pipeline_unsupported_streaming_guardrails(pipeline, translation)
if not unsupported:
return True
verbose_proxy_logger.warning(
@@@ -580,22 -674,14 +694,16 @@@
return False
-def _route_supports_streaming_pipelines(user_api_key_dict: UserAPIKeyAuth) -> bool:
- return resolve_endpoint_translation(user_api_key_dict, None) is not None
+def _streaming_pipeline_translation(user_api_key_dict: UserAPIKeyAuth) -> "BaseTranslation | None":
+ resolved: Final = resolve_endpoint_translation(user_api_key_dict, None)
+ return None if resolved is None else resolved[1]
- def _route_supports_streaming_pipelines(
- user_api_key_dict: UserAPIKeyAuth, translation: "BaseTranslation | None"
- ) -> bool:
- return not user_api_key_dict.request_route or translation is not None
-
-
-def _stream_gated_guardrail_names(
+def stream_gated_guardrail_names(
request_data: Mapping[str, object], user_api_key_dict: UserAPIKeyAuth
) -> frozenset[str]:
- if not _route_supports_streaming_pipelines(user_api_key_dict):
+ translation: Final = _streaming_pipeline_translation(user_api_key_dict)
- if not _route_supports_streaming_pipelines(user_api_key_dict, translation):
++ if translation is None:
return frozenset()
return _pipeline_step_guardrail_names(
tuple(
@@@ -624,8 -708,7 +732,8 @@@ def _streamable_post_call_pipelines
post_call_pipelines: Final = _post_call_pipelines(request_data)
if not post_call_pipelines:
return ()
- if not _route_supports_streaming_pipelines(user_api_key_dict):
+ translation: Final = _streaming_pipeline_translation(user_api_key_dict)
- if not _route_supports_streaming_pipelines(user_api_key_dict, translation):
++ if translation is None:
verbose_proxy_logger.warning(
"Policies with post_call guardrail pipelines cannot scan streaming responses on route %s yet "
"(no endpoint guardrail translation); the stream skips the pipelines and their guardrails run "
diff --cc tests/test_litellm/proxy/policy_engine/test_pipeline_executor.py
index e2523567065,16401ccdaad..0a2641082dc
--- a/tests/test_litellm/proxy/policy_engine/test_pipeline_executor.py
+++ b/tests/test_litellm/proxy/policy_engine/test_pipeline_executor.py
@@@ -1293,350 -1329,3 +1328,350 @@@ async def test_streaming_step_restores_
_assert_passed_with_discard_warning(result, caplog)
assert chunks == [_chunk()]
+
+
+class _LegacyHookGuardrail(CustomGuardrail):
+ """A guardrail with only the legacy post-call hook: it never defines apply_guardrail."""
+
+ def __init__(self, replacement=None, raises=None, guardrail_name="masker", rewrite_in_place=None):
+ super().__init__(guardrail_name=guardrail_name, event_hook="post_call", default_on=True)
+ self.replacement = replacement
+ self.raises = raises
+ self.rewrite_in_place = rewrite_in_place
+ self.calls = []
+
+ async def async_post_call_success_hook(self, data, user_api_key_dict, response):
+ self.calls.append({"data": data, "user_api_key_dict": user_api_key_dict, "response": response})
+ if self.raises is not None:
+ raise self.raises
+ if self.rewrite_in_place is not None:
+ response["text"] = self.rewrite_in_place
+ return self.replacement
+
+
+class _NativeHooksGuardrail(_LegacyHookGuardrail):
+ use_native_lifecycle_hooks = True
+
+ async def apply_guardrail(self, inputs, request_data, input_type, logging_obj=None):
+ raise AssertionError("a guardrail that keeps its native hooks never runs apply_guardrail")
+
+
+class _LegacyScanningTranslation:
+ """Stores the assembled response under request_data["response"] before scanning, like the
+ chat, Responses, and Messages handlers, hands hooks a route-native shape, and re-extracts one
+ text per entry of a replacement's "texts"."""
+
- delivers_ended_stream_text_rewrites = True
++ delivers_ended_stream_rewrites = True
+
+ def post_call_hook_response(self, response):
+ return {"native": True, "text": response["text"], "tool_calls": response["tool_calls"]}
+
+ async def process_output_streaming_response(
+ self,
+ responses_so_far,
+ guardrail_to_apply,
+ litellm_logging_obj=None,
+ user_api_key_dict=None,
+ request_data=None,
+ deliver_ended_stream_rewrites=False,
+ ):
+ request_data.setdefault(
+ "response", {"text": responses_so_far[0]["text"], "tool_calls": [dict(responses_so_far[0]["tool_call"])]}
+ )
+ outputs = await guardrail_to_apply.apply_guardrail(
+ inputs={"texts": [responses_so_far[0]["text"]], "tool_calls": [dict(responses_so_far[0]["tool_call"])]},
+ request_data=request_data,
+ input_type="response",
+ logging_obj=litellm_logging_obj,
+ )
+ responses_so_far[0]["text"] = outputs["texts"][0]
+ return responses_so_far
+
+ async def process_output_response(
+ self, response, guardrail_to_apply, litellm_logging_obj=None, user_api_key_dict=None, request_data=None
+ ):
+ inputs = {"texts": [response["text"]] if "text" in response else list(response["texts"])}
+ if response.get("tool_calls"):
+ inputs["tool_calls"] = list(response["tool_calls"])
+ await guardrail_to_apply.apply_guardrail(
+ inputs=inputs,
+ request_data={"response": response},
+ input_type="response",
+ logging_obj=litellm_logging_obj,
+ )
+ return response
+
+
+class _ToolOnlyLegacyScanningTranslation(_LegacyScanningTranslation):
+ """Like the Messages handler on a tool-only message: the ended-stream scan omits "texts" from
+ the inputs, while the non-streaming scan of the same response sends an empty list."""
+
+ async def process_output_streaming_response(
+ self,
+ responses_so_far,
+ guardrail_to_apply,
+ litellm_logging_obj=None,
+ user_api_key_dict=None,
+ request_data=None,
+ deliver_ended_stream_rewrites=False,
+ ):
+ request_data.setdefault("response", {"text": "", "tool_calls": [dict(responses_so_far[0]["tool_call"])]})
+ await guardrail_to_apply.apply_guardrail(
+ inputs={"tool_calls": [dict(responses_so_far[0]["tool_call"])]},
+ request_data=request_data,
+ input_type="response",
+ logging_obj=litellm_logging_obj,
+ )
+ return responses_so_far
+
+ async def process_output_response(
+ self, response, guardrail_to_apply, litellm_logging_obj=None, user_api_key_dict=None, request_data=None
+ ):
+ await guardrail_to_apply.apply_guardrail(
+ inputs={"texts": [], "tool_calls": list(response.get("tool_calls") or [])},
+ request_data={"response": response},
+ input_type="response",
+ logging_obj=litellm_logging_obj,
+ )
+ return response
+
+
+def _tool_only_chunk():
+ return {"text": "", "tool_call": _chunk()["tool_call"]}
+
+
+def _native(text):
+ return {"native": True, "text": text, "tool_calls": [_chunk()["tool_call"]]}
+
+
+def _legacy_replacement(*texts, tool_calls=None):
+ return {"texts": list(texts), "tool_calls": [_chunk()["tool_call"]] if tool_calls is None else tool_calls}
+
+
+async def _run_legacy_streaming_step(
+ monkeypatch, guardrail, chunks, on_fail="block", on_error="next", translation=None
+):
+ return await _run_legacy_streaming_steps(
+ monkeypatch, [guardrail], chunks, on_fail=on_fail, on_error=on_error, translation=translation
+ )
+
+
+async def _run_legacy_streaming_steps(
+ monkeypatch, guardrails, chunks, on_fail="block", on_error="next", translation=None
+):
+ monkeypatch.setattr(litellm, "callbacks", list(guardrails))
+ return await PipelineExecutor.execute_steps(
+ steps=[
+ PipelineStep(
+ guardrail=guardrail.guardrail_name,
+ on_pass="next" if position + 1 < len(guardrails) else "allow",
+ on_fail=on_fail,
+ on_error=on_error,
+ )
+ for position, guardrail in enumerate(guardrails)
+ ],
+ mode="post_call",
+ data={"model": "m"},
+ user_api_key_dict=MagicMock(),
+ call_type="completion",
+ policy_name="p",
+ streaming_chunks=chunks,
+ endpoint_translation=_LegacyScanningTranslation() if translation is None else translation,
+ )
+
+
[email protected]("guardrail_class", [_LegacyHookGuardrail, _NativeHooksGuardrail])
+async def test_streaming_step_runs_legacy_hook_and_delivers_its_rewrite(monkeypatch, caplog, guardrail_class):
+ guardrail = guardrail_class(replacement=_legacy_replacement("[REWRITTEN] hello world"))
+ chunks = [_chunk()]
+
+ with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):
+ result = await _run_legacy_streaming_step(monkeypatch, guardrail, chunks)
+
+ assert result.terminal_action == "allow"
+ assert [step.outcome for step in result.step_results] == ["pass"]
+ assert chunks[0]["text"] == "[REWRITTEN] hello world"
+ assert [call["response"] for call in guardrail.calls] == [_native("hello world")]
+ assert guardrail.calls[0]["data"]["model"] == "m"
+ assert result.modified_data["metadata"]["applied_guardrails"] == ["masker"]
+ assert not any("discarded" in record.getMessage() for record in caplog.records)
+
+
+async def test_streaming_step_delivers_a_legacy_rewrite_made_in_place(monkeypatch, caplog):
+ guardrail = _LegacyHookGuardrail(rewrite_in_place="[REWRITTEN] hello world")
+ chunks = [_chunk()]
+
+ with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):
+ result = await _run_legacy_streaming_step(monkeypatch, guardrail, chunks)
+
+ assert result.terminal_action == "allow"
+ assert [step.outcome for step in result.step_results] == ["pass"]
+ assert chunks[0]["text"] == "[REWRITTEN] hello world"
+ assert not any("discarded" in record.getMessage() for record in caplog.records)
+
+
+async def test_streaming_step_passes_untouched_when_legacy_hook_returns_none(monkeypatch, caplog):
+ guardrail = _LegacyHookGuardrail(replacement=None)
+ chunks = [_chunk()]
+
+ with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):
+ result = await _run_legacy_streaming_step(monkeypatch, guardrail, chunks)
+
+ assert result.terminal_action == "allow"
+ assert len(guardrail.calls) == 1
+ assert chunks == [_chunk()]
+ assert not any("discarded" in record.getMessage() for record in caplog.records)
+
+
[email protected](HTTPException is None, reason="fastapi not installed")
+async def test_streaming_step_blocks_with_the_legacy_hook_exception(monkeypatch):
+ exc = HTTPException(status_code=400, detail={"error": "output blocked"})
+ chunks = [_chunk()]
+
+ result = await _run_legacy_streaming_step(monkeypatch, _LegacyHookGuardrail(raises=exc), chunks)
+
+ assert result.terminal_action == "block"
+ assert [step.outcome for step in result.step_results] == ["fail"]
+ assert result.original_exception is exc
+ assert chunks == [_chunk()]
+
+
+async def test_streaming_step_takes_on_error_when_legacy_hook_crashes(monkeypatch):
+ chunks = [_chunk()]
+
+ result = await _run_legacy_streaming_step(
+ monkeypatch, _LegacyHookGuardrail(raises=ValueError("boom")), chunks, on_error="block"
+ )
+
+ assert result.terminal_action == "block"
+ assert [step.outcome for step in result.step_results] == ["error"]
+ assert result.step_results[0].error_detail == "boom"
+
+
+async def test_streaming_step_discards_legacy_rewrite_whose_texts_do_not_line_up(monkeypatch, caplog):
+ guardrail = _LegacyHookGuardrail(replacement=_legacy_replacement("split", "in two"))
+ chunks = [_chunk()]
+
+ with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):
+ result = await _run_legacy_streaming_step(monkeypatch, guardrail, chunks)
+
+ _assert_passed_with_discard_warning(result, caplog)
+ assert chunks == [_chunk()]
+
+
+async def test_streaming_step_discards_legacy_rewrite_that_changes_a_tool_call(monkeypatch, caplog):
+ masked_tool_call = {"function": {"name": "lookup", "arguments": '{"ssn": "[MASKED]"}'}}
+ guardrail = _LegacyHookGuardrail(
+ replacement=_legacy_replacement("[REWRITTEN] hello world", tool_calls=[masked_tool_call])
+ )
+ chunks = [_chunk()]
+
+ with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):
+ result = await _run_legacy_streaming_step(monkeypatch, guardrail, chunks)
+
+ _assert_passed_with_discard_warning(result, caplog)
+ assert chunks == [_chunk()]
+
+
+async def test_streaming_step_discards_legacy_rewrite_that_drops_the_tool_calls(monkeypatch, caplog):
+ guardrail = _LegacyHookGuardrail(replacement=_legacy_replacement("[REWRITTEN] hello world", tool_calls=[]))
+ chunks = [_chunk()]
+
+ with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):
+ result = await _run_legacy_streaming_step(monkeypatch, guardrail, chunks)
+
+ _assert_passed_with_discard_warning(result, caplog)
+ assert chunks == [_chunk()]
+
+
+async def test_streaming_step_passes_a_tool_only_stream_the_legacy_hook_left_alone(monkeypatch, caplog):
+ guardrail = _LegacyHookGuardrail(replacement=None)
+ chunks = [_tool_only_chunk()]
+
+ with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):
+ result = await _run_legacy_streaming_step(
+ monkeypatch, guardrail, chunks, translation=_ToolOnlyLegacyScanningTranslation()
+ )
+
+ assert result.terminal_action == "allow"
+ assert [step.outcome for step in result.step_results] == ["pass"]
+ assert result.modified_data["metadata"]["applied_guardrails"] == ["masker"]
+ assert chunks == [_tool_only_chunk()]
+ assert not any("discarded" in record.getMessage() for record in caplog.records)
+
+
+async def test_streaming_step_discards_a_legacy_tool_call_rewrite_on_a_tool_only_stream(monkeypatch, caplog):
+ masked_tool_call = {"function": {"name": "lookup", "arguments": '{"ssn": "[MASKED]"}'}}
+ guardrail = _LegacyHookGuardrail(replacement=_legacy_replacement(tool_calls=[masked_tool_call]))
+ chunks = [_tool_only_chunk()]
+
+ with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):
+ result = await _run_legacy_streaming_step(
+ monkeypatch, guardrail, chunks, translation=_ToolOnlyLegacyScanningTranslation()
+ )
+
+ _assert_passed_with_discard_warning(result, caplog)
+ assert chunks == [_tool_only_chunk()]
+
+
+class _NoHooksGuardrail(CustomGuardrail):
+ pass
+
+
+class _IteratorAndLegacyHookGuardrail(_LegacyHookGuardrail):
+ async def async_post_call_streaming_iterator_hook(self, user_api_key_dict, response, request_data):
+ async for item in response:
+ yield item
+
+
+class _UnscannableRewriteTranslation(_LegacyScanningTranslation):
+ """Like the chat handler on a response whose choices are plain dicts: the non-streaming scan
+ never hands anything to the guardrail."""
+
+ async def process_output_response(
+ self, response, guardrail_to_apply, litellm_logging_obj=None, user_api_key_dict=None, request_data=None
+ ):
+ return response
+
+
+def test_streaming_execution_runs_legacy_hooks_only_when_that_hook_is_their_only_streaming_path():
+ assert PipelineExecutor.supports_streaming_execution(_LegacyHookGuardrail()) is True
+ assert PipelineExecutor.supports_streaming_execution(_NativeHooksGuardrail()) is True
+ assert PipelineExecutor.supports_streaming_execution(_IteratorAndLegacyHookGuardrail()) is False
+ assert PipelineExecutor.supports_streaming_execution(_NoHooksGuardrail(guardrail_name="neither")) is False
+
+
+async def test_streaming_step_discards_a_legacy_rewrite_the_translation_cannot_rescan(monkeypatch, caplog):
+ guardrail = _LegacyHookGuardrail(replacement=_legacy_replacement("hello [MASKED]"))
+ chunks = [_chunk()]
+
+ result = await _run_legacy_streaming_step(monkeypatch, guardrail, chunks, translation=_UnscannableRewriteTranslation())
+
+ _assert_passed_with_discard_warning(result, caplog)
+ assert chunks == [_chunk()]
+
+
+async def test_later_legacy_step_sees_the_stream_as_the_earlier_step_left_it(monkeypatch):
+ masker = _LegacyHookGuardrail(replacement=_legacy_replacement("[REWRITTEN] hello world"))
+ auditor = _LegacyHookGuardrail(replacement=None, guardrail_name="auditor")
+ chunks = [_chunk()]
+
+ result = await _run_legacy_streaming_steps(monkeypatch, [masker, auditor], chunks, on_fail="next")
+
+ assert result.terminal_action == "allow"
+ assert [step.outcome for step in result.step_results] == ["pass", "pass"]
+ assert chunks[0]["text"] == "[REWRITTEN] hello world"
+ assert [call["response"] for call in masker.calls] == [_native("hello world")]
+ assert [call["response"] for call in auditor.calls] == [_native("[REWRITTEN] hello world")]
diff --cc tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py
index ac303e8a027,7732dfbda58..dfe106a3f52
--- a/tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py
+++ b/tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py
@@@ -11,8 -11,8 +11,9 @@@ from __future__ import annotation
import asyncio
import json
+from copy import deepcopy
import logging
+ from collections.abc import Iterator
from typing import Any, Callable, Dict, List
from unittest.mock import AsyncMock, MagicMock, patch
@@@ -26,11 -26,13 +27,13 @@@ from litellm.integrations.custom_guardr
ModifyResponseException,
)
from litellm.integrations.prometheus import PrometheusLogger
+ from litellm.llms.base_llm.guardrail_translation.utils import stream_item_field
from litellm.proxy._types import UserAPIKeyAuth
from litellm.proxy.common_utils.callback_utils import add_guardrail_to_applied_guardrails_header
-from litellm.proxy.utils import ProxyLogging, _streamable_post_call_pipelines
+from litellm.proxy.utils import ProxyLogging, _streamable_post_call_pipelines, stream_gated_guardrail_names
from litellm.proxy.guardrails.guardrail_hooks.litellm_content_filter.content_filter import ContentFilterGuardrail
from litellm.types.guardrails import BlockedWord, ContentFilterAction, GuardrailEventHooks
+ from litellm.types.llms.openai import ResponsesAPIResponse
from litellm.types.proxy.policy_engine.pipeline_types import (
GuardrailPipeline,
PipelineStep,
@@@ -1498,129 -1723,31 +1724,131 @@@ async def _async_chunk_iter(chunks: Lis
yield chunk
-def test_streamable_post_call_pipelines_keeps_supported_and_drops_unsupported(
+def _legacy_hook_stream_guardrail(
+ seen: Dict[str, Any],
+ rewrite: Callable[[Any], Any] | None = None,
+ raises: Exception | None = None,
+ native_lifecycle: bool = False,
+) -> CustomGuardrail:
+ class LegacyHookGuardrail(CustomGuardrail):
+ use_native_lifecycle_hooks = native_lifecycle
+
+ async def async_post_call_success_hook(self, data, user_api_key_dict, response):
+ seen["count"] = seen.get("count", 0) + 1
+ seen["data"] = data
+ seen["user_api_key_dict"] = user_api_key_dict
+ seen["response"] = deepcopy(response)
+ if raises is not None:
+ raise raises
+ return None if rewrite is None else rewrite(response)
+
+ if native_lifecycle:
+
+ class NativeLifecycleGuardrail(LegacyHookGuardrail):
+ async def apply_guardrail(self, inputs, request_data, input_type, logging_obj=None):
+ raise AssertionError("a guardrail that keeps its native hooks never runs apply_guardrail")
+
+ return NativeLifecycleGuardrail(
+ guardrail_name="gr-post", event_hook=GuardrailEventHooks.post_call, default_on=False
+ )
+ return LegacyHookGuardrail(guardrail_name="gr-post", event_hook=GuardrailEventHooks.post_call, default_on=False)
+
+
+def _iterator_hook_only_guardrail(name: str, seen: Dict[str, Any]) -> CustomGuardrail:
+ class IteratorHookGuardrail(CustomGuardrail):
+ async def async_post_call_streaming_iterator_hook(self, user_api_key_dict, response, request_data):
+ seen["count"] = seen.get("count", 0) + 1
+ async for item in response:
+ item.choices[0].delta.content = f"[governed] {item.choices[0].delta.content}"
+ yield item
+
+ return IteratorHookGuardrail(guardrail_name=name, event_hook=GuardrailEventHooks.post_call, default_on=True)
+
+
+def _iterator_and_legacy_hook_guardrail(name: str, seen: Dict[str, Any]) -> CustomGuardrail:
+ class IteratorAndLegacyHookGuardrail(CustomGuardrail):
+ async def async_post_call_success_hook(self, data, user_api_key_dict, response):
+ seen["success_hook_calls"] = seen.get("success_hook_calls", 0) + 1
+ return None
+
+ async def async_post_call_streaming_iterator_hook(self, user_api_key_dict, response, request_data):
+ seen["iterator_hook_calls"] = seen.get("iterator_hook_calls", 0) + 1
+ async for item in response:
+ item.choices[0].delta.content = f"[governed] {item.choices[0].delta.content}"
+ yield item
+
+ return IteratorAndLegacyHookGuardrail(guardrail_name=name, event_hook=GuardrailEventHooks.post_call, default_on=True)
+
+
+def _rewritten_model_response(response: Any) -> litellm.ModelResponse:
+ payload = response.model_dump()
+ payload["choices"][0]["message"]["content"] = "[REWRITTEN] " + payload["choices"][0]["message"]["content"]
+ return litellm.ModelResponse(**payload)
+
+
+def test_streamable_post_call_pipelines_keeps_hook_guardrails_and_drops_iterator_only(
make_user_api_key_auth, monkeypatch, caplog
):
- class NativeOnlyGuardrail(CustomGuardrail):
- pass
-
supported = _unified_stream_guardrail({})
- native_only = NativeOnlyGuardrail(guardrail_name="gr-native", event_hook=GuardrailEventHooks.post_call)
- monkeypatch.setattr(litellm, "callbacks", [supported, native_only])
- governed = GuardrailPipeline(mode="post_call", steps=[PipelineStep(guardrail="gr-post", on_fail="block")])
+ legacy = _legacy_hook_stream_guardrail({})
+ legacy.guardrail_name = "gr-legacy"
+ iterator_only = _iterator_hook_only_guardrail("gr-iterator", {})
+ monkeypatch.setattr(litellm, "callbacks", [supported, legacy, iterator_only])
+ governed = GuardrailPipeline(
+ mode="post_call",
+ steps=[PipelineStep(guardrail="gr-post", on_fail="next"), PipelineStep(guardrail="gr-legacy", on_fail="block")],
+ )
ungoverned = GuardrailPipeline(
mode="post_call",
- steps=[PipelineStep(guardrail="gr-post", on_fail="next"), PipelineStep(guardrail="gr-native", on_fail="block")],
+ steps=[PipelineStep(guardrail="gr-post", on_fail="next"), PipelineStep(guardrail="gr-iterator", on_fail="block")],
)
- pre_call = GuardrailPipeline(mode="pre_call", steps=[PipelineStep(guardrail="gr-native", on_fail="block")])
+ pre_call = GuardrailPipeline(mode="pre_call", steps=[PipelineStep(guardrail="gr-iterator", on_fail="block")])
- data = {"metadata": {"_guardrail_pipelines": [("governed", governed), ("ungoverned", ungoverned), ("req", pre_call)]}}
+ data = {
+ "metadata": {"_guardrail_pipelines": [("governed", governed), ("ungoverned", ungoverned), ("req", pre_call)]}
+ }
with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):
streamable = _streamable_post_call_pipelines(data, make_user_api_key_auth(request_route="/v1/chat/completions"))
assert streamable == (("governed", governed),)
- assert any("'ungoverned'" in message and "gr-native" in message for message in _warnings(caplog))
- assert not any("'governed'" in message for message in _warnings(caplog))
+ assert any("'ungoverned'" in message and "gr-iterator" in message for message in _warnings(caplog))
+ assert not any("'governed'" in message or "gr-legacy" in message for message in _warnings(caplog))
+
+
+ "request_route",
- [None, "/v1/completions", "/v1beta/models/gemini-2.5-flash:streamGenerateContent", "/a2a/agent"],
++ ["/v1/completions", "/v1beta/models/gemini-2.5-flash:streamGenerateContent", "/a2a/agent"],
+)
+def test_streamable_post_call_pipelines_keeps_legacy_hooks_off_routes_that_assemble_no_response(
+ make_user_api_key_auth, monkeypatch, caplog, request_route
+):
+ monkeypatch.setattr(litellm, "callbacks", [_legacy_hook_stream_guardrail({})])
+ legacy = GuardrailPipeline(mode="post_call", steps=[PipelineStep(guardrail="gr-post", on_fail="block")])
+ data = {"metadata": {"_guardrail_pipelines": [("legacy-governance", legacy)]}}
+ auth = make_user_api_key_auth(request_route=request_route)
+
+ with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):
+ streamable = _streamable_post_call_pipelines(data, auth)
+
+ assert streamable == ()
+ assert stream_gated_guardrail_names(data, auth) == frozenset()
+ assert any("'legacy-governance'" in message and "gr-post" in message for message in _warnings(caplog))
+
+
+def test_streamable_post_call_pipelines_keeps_guardrails_with_their_own_iterator_hook_on_their_own_path(
+ make_user_api_key_auth, monkeypatch, caplog
+):
+ monkeypatch.setattr(litellm, "callbacks", [_iterator_and_legacy_hook_guardrail("gr-post", {})])
+ both_hooks = GuardrailPipeline(mode="post_call", steps=[PipelineStep(guardrail="gr-post", on_fail="block")])
+ data = {"metadata": {"_guardrail_pipelines": [("both-hooks", both_hooks)]}}
+ auth = make_user_api_key_auth(request_route="/v1/chat/completions")
+
+ with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):
+ streamable = _streamable_post_call_pipelines(data, auth)
+
+ assert streamable == ()
+ assert stream_gated_guardrail_names(data, auth) == frozenset()
+ assert any("'both-hooks'" in message and "gr-post" in message for message in _warnings(caplog))
def test_streamable_post_call_pipelines_is_empty_on_route_without_translation(