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 branch 'litellm_fix_post_call_policy_pipeline' into litellm_post_call_pipeline_stream_rewrite

mateo-berri2d7697569a07
diff --cc litellm/llms/openai/chat/guardrail_translation/handler.py
index 182dec81937,96a5ed663fc..8d9f6b88aa5
--- a/litellm/llms/openai/chat/guardrail_translation/handler.py
+++ b/litellm/llms/openai/chat/guardrail_translation/handler.py
@@@ -438,10 -447,9 +449,10 @@@ class OpenAIChatCompletionsHandler(Base
responses_so_far: list["ModelResponseStream"],
guardrail_to_apply: "CustomGuardrail",
litellm_logging_obj: "LiteLLMLoggingObj | None" = None,
- user_api_key_dict: Any | None = None,
+ user_api_key_dict: "UserAPIKeyAuth | None" = None,
request_data: dict | None = None,
stream_transform_sink: StreamTransformSink | None = None,
+ deliver_ended_stream_rewrites: bool = False,
) -> list["ModelResponseStream"]:
"""
Process output streaming responses by applying guardrails to text content.
@@@ -494,9 -497,8 +505,9 @@@
responses_so_far: list["ModelResponseStream"],
guardrail_to_apply: "CustomGuardrail",
litellm_logging_obj: "LiteLLMLoggingObj | None",
- user_api_key_dict: Any | None,
+ user_api_key_dict: "UserAPIKeyAuth | None",
request_data: dict | None,
+ deliver_ended_stream_rewrites: bool = False,
) -> 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
@@@ -590,39 -597,6 +601,39 @@@
return responses_so_far
+ async def _process_ended_stream(
+ self,
+ *,
+ responses_so_far: list["ModelResponseStream"], # mutable-ok: rewrites the caller's buffered chunks in place
+ guardrail_to_apply: "CustomGuardrail",
+ litellm_logging_obj: "LiteLLMLoggingObj | None",
- user_api_key_dict: object,
++ user_api_key_dict: "UserAPIKeyAuth | None",
+ request_data: dict[str, object] | None, # mutable-ok: same request-payload shape the hooks take
+ deliver_ended_stream_rewrites: bool,
+ ) -> None:
+ """Ended-stream path: rebuild the full response, run the non-streaming
+ output guardrail against it, and (when opted in) write any text rewrite
+ back across the buffered chunks."""
+ model_response: Final = cast(
+ ModelResponse,
+ stream_chunk_builder(chunks=responses_so_far, logging_obj=litellm_logging_obj),
+ )
+ pre_guardrail_texts: Final = self._string_choice_contents(model_response)
+ await self.process_output_response(
+ response=model_response,
+ guardrail_to_apply=guardrail_to_apply,
+ litellm_logging_obj=litellm_logging_obj,
+ user_api_key_dict=user_api_key_dict,
+ request_data=request_data,
+ )
+ if deliver_ended_stream_rewrites:
+ await self._write_ended_stream_text_rewrites(
+ responses_so_far=responses_so_far,
+ guardrailed_response=model_response,
+ pre_guardrail_texts=pre_guardrail_texts,
+ guardrail_name=guardrail_to_apply.guardrail_name or "unknown",
+ )
+
def build_stream_error_items(
self,
exc: "HTTPException",
diff --cc litellm/llms/openai/responses/guardrail_translation/handler.py
index ebd1070a8e8,1530c154e93..8b808348c79
--- a/litellm/llms/openai/responses/guardrail_translation/handler.py
+++ b/litellm/llms/openai/responses/guardrail_translation/handler.py
@@@ -28,8 -28,10 +28,11 @@@ Output: response.output is List[Generic
- text: str
"""
+ import time
+ import uuid
from collections.abc import Mapping, Sequence
+ from dataclasses import dataclass
+from itertools import chain, repeat
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Final, Union, cast
@@@ -84,17 -104,12 +105,21 @@@ class ResponsesStreamChunk(TypedDict, t
type: ReadOnly[str]
text: ReadOnly[str]
+ delta: ReadOnly[str]
+ item_id: ReadOnly[str]
+ output_index: ReadOnly[int]
+ content_index: ReadOnly[int]
+_TERMINAL_ENVELOPE_EVENT_TYPES: Final = frozenset(
+ {
+ ResponsesAPIStreamEvents.RESPONSE_COMPLETED.value,
+ ResponsesAPIStreamEvents.RESPONSE_FAILED.value,
+ ResponsesAPIStreamEvents.RESPONSE_INCOMPLETE.value,
+ }
+)
+
+
def _next_stream_sequence_number(responses_so_far: Sequence[Any] | None) -> int:
sequence_numbers: Final = (
item.get("sequence_number") if isinstance(item, dict) else getattr(item, "sequence_number", None)
@@@ -634,20 -625,13 +659,14 @@@ class OpenAIResponsesHandler(BaseTransl
return responses_so_far
# ------------------------------------------------------------------ #
- # Fallback: apply guardrail to the accumulated text string. When a #
- # caller expects rewrites delivered and only output_text.delta events #
- # carried the text (a stream cut off before any .done or terminal #
- # envelope), the delta text is scanned instead so nothing escapes #
- # unchecked. No structured write-back is possible here; guardrails #
- # that only need to block/flag (not rewrite) still work correctly, #
- # and a rewrite a caller expects delivered fails closed instead. #
+ # Fallback: apply guardrail to the accumulated text string. #
+ # No structured write-back is possible here; guardrails that only #
- # need to block/flag (not rewrite) still work correctly. #
++ # need to block/flag (not rewrite) still work correctly, and a #
++ # rewrite a caller expects delivered fails closed instead. #
# ------------------------------------------------------------------ #
string_so_far: Final = self.get_streaming_string_so_far(responses_so_far)
- text_to_check: Final = string_so_far or (
- self._delta_text_so_far(responses_so_far) if deliver_ended_stream_rewrites else ""
- )
- if text_to_check:
- fallback_inputs: Final = GenericGuardrailAPIInputs(texts=[text_to_check])
+ if string_so_far:
+ fallback_inputs: Final = GenericGuardrailAPIInputs(texts=[string_so_far])
response_model = (
final_chunk.get("response", {}).get("model") if isinstance(final_chunk.get("response"), dict) else None
)
@@@ -659,70 -643,8 +678,70 @@@
input_type="response",
logging_obj=litellm_logging_obj,
)
+ fallback_texts: Final = fallback_outputs.get("texts")
- if deliver_ended_stream_rewrites and fallback_texts and tuple(fallback_texts) != (text_to_check,):
++ if deliver_ended_stream_rewrites and fallback_texts and tuple(fallback_texts) != (string_so_far,):
+ from litellm.proxy.policy_engine.pipeline_executor import UndeliverableStreamRewrite
+
+ raise UndeliverableStreamRewrite(guardrail_to_apply.guardrail_name or "unknown")
return responses_so_far
+ @staticmethod
+ def _write_event_field(event: object, field: str, value: str) -> None:
+ if isinstance(event, dict):
+ event[field] = value # rebind-ok: delivering the rewrite means editing the buffered event in place
+ else:
+ setattr(event, field, value)
+
+ def _sync_stream_events_with_rewrites(
+ self,
+ stream_events: Sequence[Any],
+ rewrites_by_position: Mapping[tuple[int, int], str],
+ ) -> None:
+ """Sync pre-completion stream events with the rewritten completed
+ response, keyed by ``(output_index, content_index)``: the first
+ ``output_text.delta`` for a rewritten item carries the full rewritten
+ text and the rest are blanked, while ``output_text.done``,
+ ``content_part.done``, and ``output_item.done`` events carry the full
+ rewritten text, so every event a client may read agrees with the
+ rewritten ``response.completed`` payload."""
+ delta_replacements: Final = MappingProxyType(
+ {position: chain((rewritten,), repeat("")) for position, rewritten in rewrites_by_position.items()}
+ )
+ for event in stream_events:
+ if not (isinstance(event, dict) or hasattr(event, "get")):
+ continue
+ event_type = event.get("type")
+ output_index = event.get("output_index")
+ content_index = event.get("content_index")
+ if event_type == "response.output_item.done" and isinstance(output_index, int):
+ self._sync_output_item_done_event(event.get("item"), output_index, rewrites_by_position)
+ continue
+ if not isinstance(output_index, int) or not isinstance(content_index, int):
+ continue
+ position = (output_index, content_index)
+ if event_type == "response.output_text.delta" and position in delta_replacements:
+ self._write_event_field(event, "delta", next(delta_replacements[position]))
+ elif event_type == "response.output_text.done" and position in rewrites_by_position:
+ self._write_event_field(event, "text", rewrites_by_position[position])
+ elif event_type == "response.content_part.done" and position in rewrites_by_position:
+ part = event.get("part")
+ if isinstance(part, dict) or hasattr(part, "text"):
+ self._write_event_field(part, "text", rewrites_by_position[position])
+
+ @staticmethod
+ def _sync_output_item_done_event(
+ item: object,
+ output_index: int,
+ rewrites_by_position: Mapping[tuple[int, int], str],
+ ) -> None:
+ content: Final = item.get("content") if isinstance(item, dict) else getattr(item, "content", None)
+ if not isinstance(content, list):
+ return
+ for (item_idx, content_idx), rewritten in rewrites_by_position.items():
+ if item_idx != output_index or content_idx >= len(content):
+ continue
+ OpenAIResponsesHandler._write_event_field(content[content_idx], "text", rewritten)
+
def _check_streaming_has_ended(self, responses_so_far: Sequence[ResponsesStreamChunk]) -> bool:
"""
Check if the streaming has ended.
diff --cc tests/test_litellm/llms/openai/responses/test_openai_responses_guardrail_handler.py
index ae3700b1123,315b6948bd8..155b9ef9810
--- a/tests/test_litellm/llms/openai/responses/test_openai_responses_guardrail_handler.py
+++ b/tests/test_litellm/llms/openai/responses/test_openai_responses_guardrail_handler.py
@@@ -1104,190 -1122,31 +1122,188 @@@ class TestOpenAIResponsesHandlerStreami
output_text = result[-1]["response"]["output"][0]["content"][0]["text"]
assert output_text == original_text
+ @staticmethod
+ def _ended_stream_events() -> List[dict]:
+ content = [{"type": "output_text", "text": "hello world"}]
+ item = {
+ "type": "message",
+ "id": "msg_123",
+ "status": "completed",
+ "role": "assistant",
+ "content": content,
+ }
+ return [
+ {"type": "response.output_text.delta", "output_index": 0, "content_index": 0, "delta": "hello "},
+ {"type": "response.output_text.delta", "output_index": 0, "content_index": 0, "delta": "world"},
+ {"type": "response.output_text.done", "output_index": 0, "content_index": 0, "text": "hello world"},
+ {
+ "type": "response.content_part.done",
+ "output_index": 0,
+ "content_index": 0,
+ "part": {"type": "output_text", "text": "hello world"},
+ },
+ {"type": "response.output_item.done", "output_index": 0, "item": {**item, "content": [dict(c) for c in content]}},
+ {
+ "type": "response.completed",
+ "response": {
+ "id": "resp_123",
+ "model": "gpt-4o",
+ "output": [{**item, "content": [dict(c) for c in content]}],
+ "status": "completed",
+ },
+ },
+ ]
+
+ @staticmethod
+ def _masking_guardrail() -> CustomGuardrail:
+ class MaskWorld(CustomGuardrail):
+ async def apply_guardrail(
+ self,
+ inputs: GenericGuardrailAPIInputs,
+ request_data: dict,
+ input_type: Literal["request", "response"],
+ logging_obj: Optional[Any] = None,
+ ) -> GenericGuardrailAPIInputs:
+ texts = inputs.get("texts", [])
+ return {**inputs, "texts": [t.replace("world", "[MASKED]") for t in texts]}
+
+ return MaskWorld(guardrail_name="test-mask")
+
+ @pytest.mark.asyncio
+ async def test_deliver_ended_stream_rewrites_syncs_all_stream_events(self):
+ handler = OpenAIResponsesHandler()
+ events = self._ended_stream_events()
+
+ result = await handler.process_output_streaming_response(
+ responses_so_far=events,
+ guardrail_to_apply=self._masking_guardrail(),
+ litellm_logging_obj=None,
+ deliver_ended_stream_rewrites=True,
+ )
+
+ assert result is events
+ assert events[0]["delta"] == "hello [MASKED]"
+ assert events[1]["delta"] == ""
+ assert events[2]["text"] == "hello [MASKED]"
+ assert events[3]["part"]["text"] == "hello [MASKED]"
+ assert events[4]["item"]["content"][0]["text"] == "hello [MASKED]"
+ assert events[5]["response"]["output"][0]["content"][0]["text"] == "hello [MASKED]"
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("terminal_type", ["response.incomplete", "response.failed"])
+ async def test_deliver_ended_stream_rewrites_syncs_non_completed_terminals(self, terminal_type):
+ handler = OpenAIResponsesHandler()
+ events = self._ended_stream_events()
+ events[-1]["type"] = terminal_type
+ events[-1]["response"]["status"] = terminal_type.split(".")[-1]
+
+ result = await handler.process_output_streaming_response(
+ responses_so_far=events,
+ guardrail_to_apply=self._masking_guardrail(),
+ litellm_logging_obj=None,
+ deliver_ended_stream_rewrites=True,
+ )
+
+ assert result is events
+ assert events[0]["delta"] == "hello [MASKED]"
+ assert events[1]["delta"] == ""
+ assert events[2]["text"] == "hello [MASKED]"
+ assert events[3]["part"]["text"] == "hello [MASKED]"
+ assert events[4]["item"]["content"][0]["text"] == "hello [MASKED]"
+ assert events[5]["response"]["output"][0]["content"][0]["text"] == "hello [MASKED]"
+
+ @pytest.mark.asyncio
+ async def test_fallback_rewrite_with_delivery_expected_fails_closed(self):
+ from litellm.proxy.policy_engine.pipeline_executor import UndeliverableStreamRewrite
+
+ handler = OpenAIResponsesHandler()
+ events = [
+ {"type": "response.output_text.delta", "output_index": 0, "content_index": 0, "delta": "hello "},
+ {"type": "response.output_text.done", "output_index": 0, "content_index": 0, "text": "hello world"},
+ ]
+
+ with pytest.raises(UndeliverableStreamRewrite):
+ await handler.process_output_streaming_response(
+ responses_so_far=events,
+ guardrail_to_apply=self._masking_guardrail(),
+ litellm_logging_obj=None,
+ deliver_ended_stream_rewrites=True,
+ )
+
- @staticmethod
- def _recording_guardrail() -> "tuple[CustomGuardrail, List[List[str]]]":
- seen: List[List[str]] = []
-
- class Recorder(CustomGuardrail):
- async def apply_guardrail(
- self,
- inputs: GenericGuardrailAPIInputs,
- request_data: dict,
- input_type: Literal["request", "response"],
- logging_obj: Optional[Any] = None,
- ) -> GenericGuardrailAPIInputs:
- seen.append(list(inputs.get("texts", [])))
- return inputs
-
- return Recorder(guardrail_name="recorder"), seen
-
+ @pytest.mark.asyncio
+ async def test_fallback_delta_only_rewrite_with_delivery_expected_fails_closed(self):
+ from litellm.proxy.policy_engine.pipeline_executor import UndeliverableStreamRewrite
+
+ handler = OpenAIResponsesHandler()
+ events = [
+ {"type": "response.output_text.delta", "output_index": 0, "content_index": 0, "delta": "hello "},
+ {"type": "response.output_text.delta", "output_index": 0, "content_index": 0, "delta": "world"},
+ ]
+
+ with pytest.raises(UndeliverableStreamRewrite):
+ await handler.process_output_streaming_response(
+ responses_so_far=events,
+ guardrail_to_apply=self._masking_guardrail(),
+ litellm_logging_obj=None,
+ deliver_ended_stream_rewrites=True,
+ )
+
+ @pytest.mark.asyncio
- async def test_fallback_scans_delta_text_when_delivery_expected(self):
++ async def test_fallback_rewrite_without_delivery_expected_does_not_raise(self):
+ handler = OpenAIResponsesHandler()
- guardrail, seen = self._recording_guardrail()
+ events = [
- {"type": "response.output_text.delta", "output_index": 0, "content_index": 0, "delta": "hello "},
- {"type": "response.output_text.delta", "output_index": 0, "content_index": 0, "delta": "there"},
++ {"type": "response.output_text.done", "output_index": 0, "content_index": 0, "text": "hello world"},
+ ]
+
+ result = await handler.process_output_streaming_response(
+ responses_so_far=events,
- guardrail_to_apply=guardrail,
++ guardrail_to_apply=self._masking_guardrail(),
+ litellm_logging_obj=None,
- deliver_ended_stream_rewrites=True,
+ )
+
+ assert result is events
- assert seen == [["hello there"]]
+
+ @pytest.mark.asyncio
- async def test_fallback_ignores_delta_text_without_delivery_expected(self):
++ async def test_ended_stream_rewrite_leaves_delta_events_untouched_by_default(self):
+ handler = OpenAIResponsesHandler()
- guardrail, seen = self._recording_guardrail()
- events = [
- {"type": "response.output_text.delta", "output_index": 0, "content_index": 0, "delta": "hello world"},
- ]
++ events = self._ended_stream_events()
+
- result = await handler.process_output_streaming_response(
++ await handler.process_output_streaming_response(
+ responses_so_far=events,
- guardrail_to_apply=guardrail,
++ guardrail_to_apply=self._masking_guardrail(),
+ litellm_logging_obj=None,
+ )
+
- assert result is events
- assert seen == []
++ assert events[0]["delta"] == "hello "
++ assert events[1]["delta"] == "world"
++ assert events[2]["text"] == "hello world"
++ assert events[5]["response"]["output"][0]["content"][0]["text"] == "hello [MASKED]"
+
@pytest.mark.asyncio
- async def test_fallback_rewrite_without_delivery_expected_does_not_raise(self):
+ async def test_failed_stream_scans_delta_text(self):
+ """A stream ending in response.failed has text only in delta events; the
+ fallback scan must assemble and scan it instead of skipping on an empty string."""
handler = OpenAIResponsesHandler()
- events = [
- {"type": "response.output_text.done", "output_index": 0, "content_index": 0, "text": "hello world"},
+ guardrail = MockRecordingGuardrail(guardrail_name="test")
+
+ responses_so_far = [
+ {"type": "response.created", "response": {"id": "resp_123"}},
+ {"type": "response.output_item.added", "item": {"type": "message", "id": "msg_123"}},
+ {
+ "type": "response.output_text.delta",
+ "item_id": "msg_123",
+ "output_index": 0,
+ "content_index": 0,
+ "delta": "Hello",
+ },
+ {
+ "type": "response.output_text.delta",
+ "item_id": "msg_123",
+ "output_index": 0,
+ "content_index": 0,
+ "delta": " world",
+ },
+ {"type": "response.failed", "response": {"id": "resp_123", "status": "failed"}},
]
result = await handler.process_output_streaming_response(