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_fix_post_call_policy_pipeline

mateo-berri0d5ea553dae7
diff --cc litellm/llms/anthropic/chat/guardrail_translation/handler.py
index fc276dd7fe6,c23797f72af..da30d85e26b
--- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py
+++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
@@@ -27,7 -26,10 +27,11 @@@ from litellm.llms.anthropic.experimenta
LiteLLMAnthropicMessagesAdapter,
is_provider_native_tool_dict,
)
- from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
+ from litellm.llms.base_llm.guardrail_translation.base_translation import (
+ BaseTranslation,
+ StreamingScanKey,
++ StreamTransformSink,
+ )
from litellm.llms.base_llm.guardrail_translation.utils import (
anthropic_tool_name,
anthropic_tool_names,
@@@ -1013,7 -1014,6 +1018,8 @@@ class AnthropicMessagesHandler(BaseTran
litellm_logging_obj: "LiteLLMLoggingObj | 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,
) -> Sequence[object]:
"""
Process output streaming response by applying guardrails to text content.
@@@ -1197,62 -1180,24 +1203,81 @@@
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_scan_key(self, responses_so_far: Sequence[object]) -> StreamingScanKey | None:
+ stream_ended: Final = self._check_streaming_has_ended(responses_so_far)
+ return StreamingScanKey(
+ texts=(self.get_streaming_string_so_far(responses_so_far),),
+ tool_calls=self._streamed_tool_use_fingerprints(responses_so_far) if stream_ended else (),
+ stream_ended=stream_ended,
+ )
+
+ @classmethod
+ def _streamed_tool_use_fingerprints(cls, responses_so_far: Sequence[object]) -> tuple[str, ...]:
+ return tuple(
+ stream_item_fingerprint(block)
+ for item in responses_so_far
+ for event in cls._iter_sse_events(item)
+ if event.get("type") == "content_block_start"
+ and isinstance(block := event.get("content_block"), Mapping)
+ and block.get("type") == "tool_use"
+ )
def get_streaming_string_so_far(self, responses_so_far: Sequence[object]) -> str:
"""
diff --cc litellm/llms/base_llm/guardrail_translation/base_translation.py
index 591d26ae027,96152141a7c..770fac6e443
--- a/litellm/llms/base_llm/guardrail_translation/base_translation.py
+++ b/litellm/llms/base_llm/guardrail_translation/base_translation.py
@@@ -35,14 -35,23 +35,30 @@@ class StreamTransformSink
holdback_per_choice: dict[int, int] = field(default_factory=dict)
+ @dataclass(frozen=True, slots=True)
+ class StreamingScanKey:
+ """What a streaming guardrail round would hand to ``apply_guardrail``. Two keys
+ compare equal when the round would scan the same content again; ``stream_ended``
+ stays out of the comparison and only says whether the handler is on its
+ end-of-stream path, where an empty payload is still scanned today."""
+
+ texts: tuple[str, ...]
+ tool_calls: tuple[str, ...] = ()
+ stream_ended: bool = field(default=False, compare=False)
+
+ @property
+ def has_nothing_to_scan(self) -> bool:
+ return not self.stream_ended and not any(self.texts) and not self.tool_calls
+
+
class BaseTranslation(ABC):
+ delivers_ended_stream_text_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 instead of withholding the
+ stream. Tool-call rewrites stay undeliverable everywhere."""
+
@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 8d9f6b88aa5,d41c8557d72..4b7b1cc2700
--- a/litellm/llms/openai/chat/guardrail_translation/handler.py
+++ b/litellm/llms/openai/chat/guardrail_translation/handler.py
@@@ -511,18 -505,18 +514,13 @@@ class OpenAIChatCompletionsHandler(Base
) -> 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)."""
+ (see ``_process_streaming_transform`` for the incremental_diff path) unless
+ ``deliver_ended_stream_rewrites`` opts the ended-stream branch in."""
- # check if the stream has ended
- has_stream_ended = False
- for chunk in responses_so_far:
- if chunk.choices and chunk.choices[0].finish_reason is not None:
- has_stream_ended = True
- break
+ has_stream_ended: Final = self._first_choice_has_finished(responses_so_far)
if has_stream_ended:
- # convert to model response
- model_response: Final = cast(
- ModelResponse,
- stream_chunk_builder(chunks=responses_so_far, logging_obj=litellm_logging_obj),
- )
- # run process_output_response
- await self.process_output_response(
- response=model_response,
+ await self._process_ended_stream(
+ 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,
diff --cc litellm/llms/openai/responses/guardrail_translation/handler.py
index 724a0a1d2f0,2dec2b3f178..b543c7f1e17
--- a/litellm/llms/openai/responses/guardrail_translation/handler.py
+++ b/litellm/llms/openai/responses/guardrail_translation/handler.py
@@@ -32,20 -33,23 +33,24 @@@ import tim
import uuid
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
- from itertools import chain, repeat
-from itertools import accumulate
++from itertools import accumulate, chain, repeat
from types import MappingProxyType
- from typing import TYPE_CHECKING, Any, Final, Union, cast
+ from typing import TYPE_CHECKING, Any, Final, NamedTuple, Union, cast
from openai.types.responses.response_function_tool_call import ResponseFunctionToolCall
- from openai.types.responses.tool_param import FunctionToolParam
from pydantic import BaseModel, TypeAdapter
from typing_extensions import ReadOnly, TypedDict
from litellm._logging import verbose_proxy_logger
from litellm.completion_extras.litellm_responses_transformation.transformation import (
+ LiteLLMResponsesTransformationHandler,
OpenAiResponsesToChatCompletionStreamIterator,
)
- from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
+ from litellm.llms.base_llm.guardrail_translation.base_translation import (
+ BaseTranslation,
+ StreamingScanKey,
++ StreamTransformSink,
+ )
from litellm.llms.base_llm.guardrail_translation.utils import (
blocked_responses_stream_usage,
stream_item_field,
@@@ -111,16 -118,200 +119,209 @@@ class ResponsesStreamChunk(TypedDict, t
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:
+ _PATCHABLE_ITEM_FIELDS: Final[Mapping[str, str]] = MappingProxyType(
+ {"function_call_output": "output", "message": "content"}
+ )
+
+ _EMPTY_RESPONSES_REQUEST: Final[ResponsesAPIOptionalRequestParams] = {}
+
+
+ def _item_rewrite_field(item: Mapping[str, object]) -> str | None:
+ item_type: Final = item.get("type")
+ if item_type is None:
+ return "content" if "content" in item else None
+ if not isinstance(item_type, str):
+ return None
+ return _PATCHABLE_ITEM_FIELDS.get(item_type)
+
+
+ def _rewritten_input_item(item: Mapping[str, object], rewritten: object) -> Mapping[str, object] | None:
+ field: Final = _item_rewrite_field(item)
+ if field is None or not isinstance(rewritten, Mapping):
+ return None
+ rewritten_content: Final = rewritten.get("content")
+ if isinstance(item.get(field), str) and isinstance(rewritten_content, str):
+ return {**item, field: rewritten_content} # mutable-ok: request input items must stay JSON-plain dicts
+ rewritten_row: Final = cast("AllMessageValues", rewritten) # cast-ok: guardrails hand back chat-shaped rows
+ converted_items, _ = LiteLLMResponsesTransformationHandler().convert_chat_completion_messages_to_responses_api(
+ [rewritten_row] # mutable-ok: converter signature takes a list
+ )
+ if len(converted_items) != 1 or not isinstance(converted_items[0], Mapping):
+ return None
+ first_converted: Final = cast("Mapping[str, object]", converted_items[0]) # cast-ok: isinstance-checked above
+ converted_value: Final = first_converted.get(field)
+ if converted_value is None:
+ return None
+ return {**item, field: converted_value} # mutable-ok: request input items must stay JSON-plain dicts
+
+
+ def _is_function_call_item(item: object) -> bool:
+ return isinstance(item, Mapping) and item.get("type") in ("function_call", "custom_tool_call")
+
+
+ def _last_message_role(messages: Sequence[object]) -> str | None:
+ if not messages:
+ return None
+ last: Final = messages[-1]
+ role: Final = last.get("role") if isinstance(last, Mapping) else getattr(last, "role", None)
+ return role if isinstance(role, str) else None
+
+
+ def _provenance_unit_bounds(
+ raw_input: Sequence[object],
+ solo_conversions: Sequence[Sequence[object]],
+ ) -> tuple[tuple[int, int], ...]:
+ trailing_roles: Final = tuple(
+ accumulate(
+ (_last_message_role(messages) for messages in solo_conversions),
+ lambda previous, current: current if current is not None else previous,
+ )
+ )
+ start_indexes: Final = tuple(
+ index
+ for index in range(len(raw_input))
+ if index == 0 or not (_is_function_call_item(raw_input[index]) and trailing_roles[index - 1] == "assistant")
+ )
+ return tuple(zip(start_indexes, (*start_indexes[1:], len(raw_input))))
+
+
+ def _input_item_provenance(
+ raw_input: Sequence[object],
+ expected_messages: Sequence[object],
+ ) -> tuple[Mapping[int, int], frozenset[int]] | None:
+ if not all(isinstance(item, Mapping) for item in raw_input):
+ return None
+ solo_conversions: Final = tuple(
+ LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(
+ input=cast("ResponseInputParam", [item]), # cast-ok: items checked as Mappings above
+ responses_api_request=_EMPTY_RESPONSES_REQUEST,
+ )
+ for item in raw_input
+ )
+ full_conversion: Final = tuple(
+ LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(
+ input=cast("ResponseInputParam", list(raw_input)), # cast-ok: items checked as Mappings above
+ responses_api_request=_EMPTY_RESPONSES_REQUEST,
+ )
+ )
+ if full_conversion != tuple(expected_messages):
+ return None
+ units: Final = _provenance_unit_bounds(raw_input, solo_conversions)
+ unit_messages: Final = tuple(
+ tuple(solo_conversions[start])
+ if end - start == 1
+ else tuple(
+ LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(
+ input=cast("ResponseInputParam", list(raw_input[start:end])), # cast-ok: checked as Mappings above
+ responses_api_request=_EMPTY_RESPONSES_REQUEST,
+ )
+ )
+ for start, end in units
+ )
+ if tuple(message for messages in unit_messages for message in messages) != full_conversion:
+ return None
+ boundaries: Final = tuple(accumulate((len(messages) for messages in unit_messages), initial=0))
+ item_for_message: Final = MappingProxyType(
+ {
+ message_index: start
+ for unit_index, (start, end) in enumerate(units)
+ if end - start == 1
+ for message_index in range(boundaries[unit_index], boundaries[unit_index + 1])
+ }
+ )
+ tainted: Final = frozenset(
+ message_index
+ for unit_index, (start, end) in enumerate(units)
+ if end - start > 1
+ for message_index in range(boundaries[unit_index], boundaries[unit_index + 1])
+ )
+ return item_for_message, tainted
+
+
+ class _RequestFields(NamedTuple):
+ input: tuple[object, ...]
+ instructions: str | None
+
+
+ class _ExtractedInputs(NamedTuple):
+ inputs: GenericGuardrailAPIInputs
+ task_mappings: tuple[tuple[int, int | None], ...]
+
+
+ def _patched_request_fields(
+ raw_input: object,
+ instructions: object,
+ original_messages: Sequence[object],
+ structured_messages: Sequence[object],
+ ) -> _RequestFields | None:
+ if not isinstance(raw_input, list) or len(original_messages) != len(structured_messages):
+ return None
+ offset: Final = 1 if instructions else 0
+ provenance: Final = _input_item_provenance(raw_input, tuple(original_messages)[offset:])
+ if provenance is None:
+ return None
+ item_for_message, tainted = provenance
+ changed: Final = tuple(
+ (index, rewritten)
+ for index, (original, rewritten) in enumerate(zip(original_messages, structured_messages))
+ if original != rewritten
+ )
+ instruction_rewrites: Final = tuple(rewritten for index, rewritten in changed if index < offset)
+ rewritten_instructions: Final = (
+ instruction_rewrites[0].get("content")
+ if instruction_rewrites and isinstance(instruction_rewrites[0], Mapping)
+ else instructions
+ )
+ instructions_value: Final = rewritten_instructions if isinstance(rewritten_instructions, str) else None
+ if rewritten_instructions is not None and instructions_value is None:
+ return None
+ body_changes: Final = tuple((index - offset, rewritten) for index, rewritten in changed if index >= offset)
+ if any(message_index in tainted or message_index not in item_for_message for message_index, _ in body_changes):
+ return None
+ replacements: Final = MappingProxyType(
+ {
+ item_for_message[message_index]: _rewritten_input_item(
+ cast("Mapping[str, object]", raw_input[item_for_message[message_index]]), # cast-ok: checked Mappings
+ rewritten,
+ )
+ for message_index, rewritten in body_changes
+ }
+ )
+ if len(replacements) != len(body_changes) or any(item is None for item in replacements.values()):
+ return None
+ return _RequestFields(
+ input=tuple(replacements.get(index, item) for index, item in enumerate(raw_input)),
+ instructions=instructions_value,
+ )
+
+
+ def _patch_or_convert_request_fields(
+ raw_input: object,
+ instructions: object,
+ original_messages: Sequence[object],
+ structured_messages: Sequence[AllMessageValues],
+ ) -> _RequestFields | None:
+ if not isinstance(structured_messages, list):
+ return None
+ patched: Final = _patched_request_fields(raw_input, instructions, original_messages, structured_messages)
+ if patched is not None:
+ return patched
+ input_items, converted_instructions = (
+ LiteLLMResponsesTransformationHandler().convert_chat_completion_messages_to_responses_api(structured_messages)
+ )
+ return _RequestFields(input=tuple(input_items), instructions=converted_instructions)
+
+
+ def _next_stream_sequence_number(responses_so_far: Sequence[object] | None) -> int:
sequence_numbers: Final = (
item.get("sequence_number") if isinstance(item, dict) else getattr(item, "sequence_number", None)
for item in reversed(responses_so_far or ())
@@@ -532,7 -667,6 +679,8 @@@ class OpenAIResponsesHandler(BaseTransl
litellm_logging_obj: "LiteLLMLoggingObj | 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[Any]:
"""
Process output streaming response by applying guardrails to text content.
@@@ -681,77 -790,57 +829,112 @@@
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) != (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:
+ def _check_streaming_has_ended(self, responses_so_far: Sequence[object]) -> bool:
"""
Check if the streaming has ended.
"""
if not responses_so_far:
return False
- return responses_so_far[-1].get("type") in _TERMINAL_ENVELOPE_EVENT_TYPES
- terminal_types: Final = frozenset(
- (
- ResponsesAPIStreamEvents.RESPONSE_COMPLETED.value,
- ResponsesAPIStreamEvents.RESPONSE_FAILED.value,
- ResponsesAPIStreamEvents.RESPONSE_INCOMPLETE.value,
- )
- )
- return stream_item_field(responses_so_far[-1], "type") in terminal_types
++ return stream_item_field(responses_so_far[-1], "type") in _TERMINAL_ENVELOPE_EVENT_TYPES
+
+ def get_streaming_scan_key(self, responses_so_far: Sequence[object]) -> StreamingScanKey | None:
+ if not responses_so_far or not hasattr(responses_so_far[-1], "get"):
+ return None
+ last_event: Final = responses_so_far[-1]
+ last_event_type: Final = stream_item_field(last_event, "type")
+ if last_event_type == ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE.value:
+ return None
+ if last_event_type == ResponsesAPIStreamEvents.RESPONSE_COMPLETED.value:
+ return self._completed_response_scan_key(stream_item_field(last_event, "response"))
+ return StreamingScanKey(
+ texts=(self.get_streaming_string_so_far(responses_so_far),),
+ stream_ended=self._check_streaming_has_ended(responses_so_far),
+ )
+
+ @staticmethod
+ def _completed_response_scan_key(response: object) -> StreamingScanKey:
+ output_items: Final = stream_item_items(response, "output")
+ message_items: Final = tuple(
+ item for item in output_items if stream_item_field(item, "type") != "function_call"
+ )
+ return StreamingScanKey(
+ texts=tuple(
+ text
+ for item in message_items
+ for part in stream_item_items(item, "content")
+ if isinstance(text := stream_item_field(part, "text"), str) and text
+ ),
+ tool_calls=tuple(
+ stream_item_fingerprint(item)
+ for item in output_items
+ if stream_item_field(item, "type") == "function_call"
+ ),
+ stream_ended=True,
+ )
def build_stream_error_items(
self,
diff --cc litellm/proxy/utils.py
index 63dc5a03804,ddf31cb1d8a..ca8e48b5dfa
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@@ -153,9 -152,9 +153,9 @@@ from litellm.proxy.hooks.parallel_reque
from litellm.proxy.hooks.sensitive_data_routing import (
_PROXY_SensitiveDataRoutingHandler,
)
- from litellm.proxy.litellm_pre_call_utils import LiteLLMProxyRequestSetup
+ from litellm.proxy.litellm_pre_call_utils import LiteLLMProxyRequestSetup, add_guardrails_from_auth_metadata
from litellm.proxy.management_helpers.key_settings_audit import with_settings_updated_at
-from litellm.proxy.policy_engine.pipeline_executor import PipelineExecutor
+from litellm.proxy.policy_engine.pipeline_executor import PipelineExecutor, UndeliverableStreamRewrite
from litellm.repositories.budget_repository import BudgetRepository
from litellm.repositories.config_repository import ConfigRepository
from litellm.repositories.table_repositories import (
diff --cc tests/test_litellm/llms/openai/chat/guardrail_translation/test_openai_guardrail_handler.py
index af22390f80c,36e715d5804..aff0530ee8b
--- a/tests/test_litellm/llms/openai/chat/guardrail_translation/test_openai_guardrail_handler.py
+++ b/tests/test_litellm/llms/openai/chat/guardrail_translation/test_openai_guardrail_handler.py
@@@ -1073,155 -1074,38 +1074,186 @@@ class TestOpenAIChatCompletionsHandlerS
# Should return the responses
assert result == responses_so_far
+ @staticmethod
+ def _ended_stream_chunks() -> list:
+ from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices
+
+ return [
+ ModelResponseStream(
+ id="chatcmpl-123",
+ created=1234567890,
+ model="gpt-4",
+ object="chat.completion.chunk",
+ choices=[StreamingChoices(index=0, delta=Delta(content="Hello"), finish_reason=None)],
+ ),
+ ModelResponseStream(
+ id="chatcmpl-123",
+ created=1234567890,
+ model="gpt-4",
+ object="chat.completion.chunk",
+ choices=[StreamingChoices(index=0, delta=Delta(content=" world"), finish_reason="stop")],
+ ),
+ ]
+
+ @pytest.mark.asyncio
+ async def test_deliver_ended_stream_rewrites_writes_text_back_into_chunks(self):
+ handler = OpenAIChatCompletionsHandler()
+ guardrail = MockGuardrail(guardrail_name="test")
+ chunks = self._ended_stream_chunks()
+
+ result = await handler.process_output_streaming_response(
+ responses_so_far=chunks,
+ guardrail_to_apply=guardrail,
+ litellm_logging_obj=None,
+ deliver_ended_stream_rewrites=True,
+ )
+
+ assert result is chunks
+ assert chunks[0].choices[0].delta.content == "HELLO WORLD"
+ assert chunks[1].choices[0].delta.content in (None, "")
+ assert chunks[1].choices[0].finish_reason == "stop"
+
+ @pytest.mark.asyncio
+ async def test_ended_stream_rewrite_leaves_chunks_untouched_by_default(self):
+ handler = OpenAIChatCompletionsHandler()
+ guardrail = MockGuardrail(guardrail_name="test")
+ chunks = self._ended_stream_chunks()
+
+ await handler.process_output_streaming_response(
+ responses_so_far=chunks,
+ guardrail_to_apply=guardrail,
+ litellm_logging_obj=None,
+ )
+
+ assert chunks[0].choices[0].delta.content == "Hello"
+ assert chunks[1].choices[0].delta.content == " world"
+ assert chunks[1].choices[0].finish_reason == "stop"
+
+ @staticmethod
+ def _two_choice_stream_chunks() -> list:
+ from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices
+
+ def chunk(index: int, content: str, finish_reason: Optional[str] = None) -> ModelResponseStream:
+ return ModelResponseStream(
+ id="chatcmpl-123",
+ created=1234567890,
+ model="gpt-4",
+ object="chat.completion.chunk",
+ choices=[StreamingChoices(index=index, delta=Delta(content=content), finish_reason=finish_reason)],
+ )
+
+ return [
+ chunk(0, "safe "),
+ chunk(1, "hello "),
+ chunk(0, "text", "stop"),
+ chunk(1, "world", "stop"),
+ ]
+
+ @staticmethod
+ def _world_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_rewrite_on_multi_choice_stream_fails_closed(self):
+ from litellm.proxy.policy_engine.pipeline_executor import UndeliverableStreamRewrite
+
+ handler = OpenAIChatCompletionsHandler()
+ chunks = self._two_choice_stream_chunks()
+
+ with pytest.raises(UndeliverableStreamRewrite):
+ await handler.process_output_streaming_response(
+ responses_so_far=chunks,
+ guardrail_to_apply=self._world_masking_guardrail(),
+ litellm_logging_obj=None,
+ deliver_ended_stream_rewrites=True,
+ )
+
+ @pytest.mark.asyncio
+ async def test_deliver_ended_stream_clean_multi_choice_stream_released_untouched(self):
+ handler = OpenAIChatCompletionsHandler()
+ chunks = self._two_choice_stream_chunks()
+
+ result = await handler.process_output_streaming_response(
+ responses_so_far=chunks,
+ guardrail_to_apply=MockPassThroughGuardrail(guardrail_name="test"),
+ litellm_logging_obj=None,
+ deliver_ended_stream_rewrites=True,
+ )
+
+ assert result is chunks
+ assert [c.choices[0].delta.content for c in chunks] == ["safe ", "hello ", "text", "world"]
+
+ @pytest.mark.asyncio
+ async def test_deliver_ended_stream_rewrite_lands_on_nonzero_choice_index(self):
+ from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices
+
+ handler = OpenAIChatCompletionsHandler()
+
+ def chunk(content: str, finish_reason: Optional[str]) -> ModelResponseStream:
+ return ModelResponseStream(
+ id="chatcmpl-123",
+ created=1234567890,
+ model="gpt-4",
+ object="chat.completion.chunk",
+ choices=[StreamingChoices(index=1, delta=Delta(content=content), finish_reason=finish_reason)],
+ )
+
+ chunks = [chunk("hello ", None), chunk("world", "stop")]
+
+ result = await handler.process_output_streaming_response(
+ responses_so_far=chunks,
+ guardrail_to_apply=self._world_masking_guardrail(),
+ litellm_logging_obj=None,
+ deliver_ended_stream_rewrites=True,
+ )
+
+ assert result is chunks
+ assert chunks[0].choices[0].delta.content == "hello [MASKED]"
+ assert chunks[1].choices[0].delta.content in (None, "")
+
+ class TestUndecoratedGuardrailIsRecorded:
+ """LIT-5983 regression: the handler calls apply_guardrail bare, so a custom guardrail
+ without @log_guardrail_information must still end up in the request's guardrail
+ information on both the request and response paths."""
+
+ @pytest.mark.asyncio
+ async def test_request_path_records_undecorated_guardrail(self):
+ handler = OpenAIChatCompletionsHandler()
+ guardrail = MockGuardrail(guardrail_name="docs-style")
+ data = {"messages": [{"role": "user", "content": "hello"}], "metadata": {}}
+
+ await handler.process_input_messages(data, guardrail)
+
+ entries = data["metadata"]["standard_logging_guardrail_information"]
+ assert [(e["guardrail_name"], e["guardrail_status"]) for e in entries] == [("docs-style", "success")]
+
+ @pytest.mark.asyncio
+ async def test_response_path_records_undecorated_guardrail(self):
+ handler = OpenAIChatCompletionsHandler()
+ guardrail = MockGuardrail(guardrail_name="docs-style")
+ response = ModelResponse(
+ choices=[Choices(finish_reason="stop", index=0, message=Message(content="hi", role="assistant"))]
+ )
+ request_data: dict = {"metadata": {}}
+
+ await handler.process_output_response(response, guardrail, request_data=request_data)
+
+ entries = request_data["metadata"]["standard_logging_guardrail_information"]
+ assert [(e["guardrail_name"], e["guardrail_status"]) for e in entries] == [("docs-style", "success")]
+
+
class TestGetStructuredMessages:
"""Test the get_structured_messages method."""