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_fix_post_call_policy_pipeline' into litellm_post_call_pipeline_stream_rewrite

mateo-berriec677e5e74a8
diff --cc litellm/llms/anthropic/chat/guardrail_translation/handler.py
index 89c8431dfe4,c7d12e5cf3a..091ad8ecba9
--- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py
+++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
@@@ -13,13 -13,12 +13,13 @@@ Pattern Overview
"""
import json
-from collections.abc import Mapping, Sequence
+from collections.abc import Iterator, Mapping, Sequence
from copy import deepcopy
from dataclasses import dataclass
+from itertools import chain, repeat
- from typing import TYPE_CHECKING, Any, Final, cast
+ from typing import TYPE_CHECKING, Any, Final, Protocol, cast, overload, runtime_checkable
- from typing_extensions import assert_never
+ from typing_extensions import ReadOnly, TypedDict, assert_never
from litellm._logging import verbose_proxy_logger
from litellm.llms.anthropic.chat.transformation import AnthropicConfig
@@@ -934,8 -1010,7 +1013,8 @@@ class AnthropicMessagesHandler(BaseTran
litellm_logging_obj: "LiteLLMLoggingObj | None" = None,
user_api_key_dict: "UserAPIKeyAuth | None" = None,
request_data: dict | None = None,
+ deliver_ended_stream_rewrites: bool = False,
- ) -> list[Any]:
+ ) -> Sequence[object]:
"""
Process output streaming response by applying guardrails to text content.
@@@ -1108,64 -1176,7 +1191,64 @@@
inputs["model"] = response_model
return inputs
+ @staticmethod
+ def _write_ended_stream_text_rewrite(
+ responses_so_far: list[Any], # mutable-ok: rewrites the caller's buffered chunks in place
+ rewritten_text: str,
+ ) -> None:
+ """Deliver an ended-stream guardrail text rewrite by rewriting the
+ buffered chunks in place: the first ``text_delta`` carries the full
+ rewritten text and every later one is blanked, leaving the surrounding
+ message and content-block framing untouched. Handles both chunk formats
+ this stream carries (parsed event dicts and raw SSE bytes)."""
+ replacements: Final = chain((rewritten_text,), repeat(""))
+ for idx, item in enumerate(responses_so_far):
+ if isinstance(item, dict):
+ delta = item.get("delta")
+ if item.get("type") == "content_block_delta" and isinstance(delta, dict):
+ if delta.get("type") == "text_delta":
+ delta["text"] = next(replacements)
+ elif isinstance(item, (bytes, bytearray)):
+ responses_so_far[idx] = ( # rebind-ok: delivers the rewrite into the caller's buffer
+ AnthropicMessagesHandler._rewrite_sse_text_deltas(bytes(item), replacements)
+ )
+
+ @staticmethod
+ def _rewrite_sse_text_deltas(sse_bytes: bytes, replacements: "Iterator[str]") -> bytes:
+ """Rewrite every ``text_delta`` data line in one SSE chunk with the next
+ replacement text, leaving all other events and framing byte-identical."""
+ try:
+ decoded: Final = sse_bytes.decode("utf-8")
+ except UnicodeDecodeError:
+ return sse_bytes
+ return "\n\n".join(
+ AnthropicMessagesHandler._rewrite_sse_block(block, replacements) for block in decoded.split("\n\n")
+ ).encode("utf-8")
+
+ @staticmethod
+ def _rewrite_sse_block(block: str, replacements: "Iterator[str]") -> str:
+ return "\n".join(AnthropicMessagesHandler._rewrite_sse_line(line, replacements) for line in block.split("\n"))
+
+ @staticmethod
+ def _rewrite_sse_line(line: str, replacements: "Iterator[str]") -> str:
+ if not line.startswith("data:"):
+ return line
+ try:
+ data: Final[str | int | float | bool | None | Sequence[object] | Mapping[str, object]] = json.loads(
+ line[len("data:") :].strip()
+ )
+ except json.JSONDecodeError:
+ return line
+ if not isinstance(data, dict) or data.get("type") != "content_block_delta":
+ return line
+ delta: Final = data.get("delta")
+ if not isinstance(delta, dict) or delta.get("type") != "text_delta":
+ return line
+ return "data: " + json.dumps(
+ {**data, "delta": {**delta, "text": next(replacements)}} # mutable-ok: json.dumps needs plain dicts
+ )
+
- def get_streaming_string_so_far(self, responses_so_far: list[Any]) -> str:
+ def get_streaming_string_so_far(self, responses_so_far: Sequence[object]) -> str:
"""
Parse streaming responses and extract accumulated text content.
diff --cc litellm/llms/base_llm/guardrail_translation/base_translation.py
index 4b0cc0fd97c,b07a6b986d7..8f575321e5b
--- a/litellm/llms/base_llm/guardrail_translation/base_translation.py
+++ b/litellm/llms/base_llm/guardrail_translation/base_translation.py
@@@ -1,8 -1,11 +1,11 @@@
from abc import ABC, abstractmethod
+ from collections.abc import Sequence
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, Any, Final, Optional
+from typing import TYPE_CHECKING, Any, ClassVar, Final, Optional
if TYPE_CHECKING:
+ from fastapi import HTTPException
+
from litellm.integrations.custom_guardrail import (
CustomGuardrail,
ModifyResponseException,
diff --cc litellm/llms/openai/chat/guardrail_translation/handler.py
index 1358cf7c37a,de15fefe943..fcb447d5277
--- a/litellm/llms/openai/chat/guardrail_translation/handler.py
+++ b/litellm/llms/openai/chat/guardrail_translation/handler.py
@@@ -595,38 -586,18 +590,50 @@@ class OpenAIChatCompletionsHandler(Base
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,
+ 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,
+ )
+
+ def build_stream_error_items(
+ self,
+ exc: "HTTPException",
+ responses_so_far: Sequence[Any] | None = None,
+ ) -> Sequence[Any] | None:
+ import json
+
+ from litellm.proxy.common_request_processing import sse_error_payload
+
+ _, error_obj = sse_error_payload(exc)
+ return (f'data: {{"error": {json.dumps(error_obj)}}}\n\n'.encode(),)
+
@staticmethod
def _accumulate_string_content_by_choice_index(
responses_so_far: list["ModelResponseStream"],
diff --cc litellm/proxy/policy_engine/pipeline_executor.py
index 73970d20e33,069fbd46185..160938b723c
--- a/litellm/proxy/policy_engine/pipeline_executor.py
+++ b/litellm/proxy/policy_engine/pipeline_executor.py
@@@ -254,47 -246,8 +250,43 @@@ class PipelineExecutor
# action == "next" → continue to next step
# Ran out of steps without a terminal action → default allow
- return PipelineExecutionResult(
- terminal_action="allow",
- step_results=step_results,
- modified_data=working_data if working_data != data else None,
- )
+ return _allow_result(step_results=step_results, working_data=working_data, request_data=data)
+ @staticmethod
+ async def _run_streaming_step(
+ step: PipelineStep,
+ callback: CustomGuardrail,
+ endpoint_translation: "BaseTranslation",
+ streaming_chunks: list[object], # mutable-ok: shared buffered-stream chunks the translation rewrites in place
+ hook_input: dict[str, object], # mutable-ok: same request-payload shape as data
+ user_api_key_dict: "UserAPIKeyAuth | None",
+ 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 and raising
+ ``UndeliverableStreamRewrite`` for any rewrite that cannot reach the client."""
+ observer: Final = _StreamRewriteObserver(callback)
+ deliver_rewrites: Final = type(endpoint_translation).delivers_ended_stream_text_rewrites
+ if deliver_rewrites:
+ await endpoint_translation.process_output_streaming_response(
+ responses_so_far=streaming_chunks,
+ guardrail_to_apply=observer,
+ litellm_logging_obj=litellm_logging_obj,
+ user_api_key_dict=user_api_key_dict,
+ request_data=hook_input,
+ deliver_ended_stream_rewrites=True,
+ )
+ else:
+ await endpoint_translation.process_output_streaming_response(
+ responses_so_far=streaming_chunks,
+ guardrail_to_apply=observer,
+ litellm_logging_obj=litellm_logging_obj,
+ user_api_key_dict=user_api_key_dict,
+ request_data=hook_input,
+ )
+ if observer.rewrote_tool_calls or (observer.rewrote_texts and not deliver_rewrites):
+ raise UndeliverableStreamRewrite(step.guardrail)
+
@staticmethod
async def _run_step(
step: PipelineStep,