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: origin/main into litellm_lit_7346_multi_choice_stream_guardrails

mateo-berri114fc165547c
diff --cc litellm/llms/anthropic/chat/guardrail_translation/handler.py
index c7ba5daec56,5e1e2565972..24ff63c9433
--- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py
+++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
@@@ -1277,7 -1442,22 +1442,24 @@@ class AnthropicMessagesHandler(BaseTran
"""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."""
+ message and content-block framing untouched. A buffer with no
+ ``text_delta`` has nowhere to carry the rewrite, so the pipeline
+ executor discards it and releases the original chunks."""
+
+ def is_text_delta(event: Mapping[str, object]) -> bool:
+ delta: Final = event.get("delta")
+ return (
+ event.get("type") == "content_block_delta"
+ and isinstance(delta, Mapping)
+ and delta.get("type") == "text_delta"
+ )
+
+ if not any(is_text_delta(event) for item in responses_so_far for event in cls._iter_sse_events(item)):
+ from litellm.proxy.policy_engine.pipeline_executor import UndeliverableStreamRewrite
+
- raise UndeliverableStreamRewrite(guardrail_name)
++ raise UndeliverableStreamRewrite(
++ guardrail_name, "the buffered stream carries no text_delta event to land the text rewrite on"
++ )
replacements: Final = chain((rewritten_text,), repeat(""))
def rewrite_text_delta(event: Mapping[str, object]) -> _SSEFieldRewrite | None:
diff --cc litellm/llms/openai/responses/guardrail_translation/handler.py
index 2be36a826f7,5bcae5f608e..ddfd2199822
--- a/litellm/llms/openai/responses/guardrail_translation/handler.py
+++ b/litellm/llms/openai/responses/guardrail_translation/handler.py
@@@ -963,6 -964,47 +964,51 @@@ class OpenAIResponsesHandler(BaseTransl
)
return responses_so_far
+ def _spread_text_rewrite_over_stream_events(
+ self,
+ stream_events: Sequence[Any],
+ rewritten_text: str,
+ guardrail_name: str,
+ ) -> None:
+ """Deliver a text rewrite on a stream with no completed envelope by
+ spreading it over the text parts the guardrail scanned, in stream
+ order: the whole rewrite on the first part and every later part
+ blanked, through the same sync the envelope path uses. A scanned
+ event the sync cannot place (one that is not an ``output_text`` delta
+ or done, or lacks integer ``output_index`` / ``content_index``) makes
+ the rewrite undeliverable, so the pipeline executor discards it and
+ releases the original events."""
+ scanned_events: Final = tuple(
+ event
+ for event in stream_events
+ if isinstance(stream_item_field(event, "text"), str) or isinstance(stream_item_field(event, "delta"), str)
+ )
+ scanned_positions: Final = tuple(
+ dict.fromkeys(
+ (stream_item_field(event, "output_index"), stream_item_field(event, "content_index"))
+ for event in scanned_events
+ )
+ )
+ placeable_positions: Final = tuple(
+ (output_index, content_index)
+ for output_index, content_index in scanned_positions
+ if isinstance(output_index, int) and isinstance(content_index, int)
+ )
+ if len(placeable_positions) != len(scanned_positions) or any(
+ stream_item_field(event, "type") not in _OUTPUT_TEXT_EVENT_TYPES for event in scanned_events
+ ):
+ from litellm.proxy.policy_engine.pipeline_executor import UndeliverableStreamRewrite
+
- raise UndeliverableStreamRewrite(guardrail_name)
++ raise UndeliverableStreamRewrite(
++ guardrail_name,
++ "the scanned text events are not all output_text deltas with an integer output_index and "
++ "content_index, so the text rewrite has nowhere to land",
++ )
+ self._sync_stream_events_with_rewrites(
+ stream_events=stream_events,
+ rewrites_by_position=MappingProxyType(dict(zip(placeable_positions, chain((rewritten_text,), repeat(""))))),
+ )
+
@staticmethod
def _write_event_field(event: object, field: str, value: str) -> None:
if isinstance(event, dict):
diff --cc litellm/proxy/_lazy_openapi_snapshot.json
index 7a110eff080,06e157498aa..391f0042ed0
--- a/litellm/proxy/_lazy_openapi_snapshot.json
+++ b/litellm/proxy/_lazy_openapi_snapshot.json
@@@ -18968,7 -19632,7 +19632,7 @@@
}
}
},
-- "description": "\n Unified rate-limit error.\n\n Every rate-limit condition surfaced by litellm \u2014 whether it originated from\n an upstream LLM provider, a vendor batch endpoint, or one of litellm's own\n proxy-side limiters (parallel-requests, dynamic-rate, batch-rate, budget,\n max-iterations, etc.) \u2014 is raised as an instance of this class.\n\n The :attr:`category` attribute lets callers distinguish the source. See\n :class:`RateLimitErrorCategory` for the available values.\n "
++ "description": "\nUnified rate-limit error.\n\nEvery rate-limit condition surfaced by litellm \u2014 whether it originated from\nan upstream LLM provider, a vendor batch endpoint, or one of litellm's own\nproxy-side limiters (parallel-requests, dynamic-rate, batch-rate, budget,\nmax-iterations, etc.) \u2014 is raised as an instance of this class.\n\nThe :attr:`category` attribute lets callers distinguish the source. See\n:class:`RateLimitErrorCategory` for the available values.\n"
},
"500": {
"content": {
diff --cc litellm/proxy/policy_engine/pipeline_executor.py
index 26dd806b3e5,ed193c7f434..cfb0dc4b617
--- a/litellm/proxy/policy_engine/pipeline_executor.py
+++ b/litellm/proxy/policy_engine/pipeline_executor.py
@@@ -50,24 -50,14 +50,15 @@@ except ImportError
class UndeliverableStreamRewrite(Exception):
- def __init__(self, guardrail_name: str) -> None:
+ def __init__(self, guardrail_name: str, reason: str) -> None:
super().__init__(
- f"Guardrail '{guardrail_name}' rewrote the streamed response in a way this endpoint's "
- "streaming pipeline cannot deliver"
+ f"Guardrail '{guardrail_name}' rewrote the streamed response but the rewrite cannot be written "
+ f"back to the stream: {reason}"
)
self.guardrail_name: Final = guardrail_name
+ self.reason: Final = reason
- class UnappliableRequestRewrite(Exception):
- def __init__(self, guardrail_name: str) -> None:
- super().__init__(
- f"Guardrail '{guardrail_name}' rewrote the request in a way this endpoint cannot apply, "
- "so the request was rejected rather than sent unrewritten"
- )
- self.guardrail_name: Final = guardrail_name
-
-
def _tool_call_shape(tool_call: object) -> tuple[object, object]:
plain: Final = tool_call.model_dump() if isinstance(tool_call, BaseModel) else tool_call
function: Final = plain.get("function") if isinstance(plain, Mapping) else None