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_stream_modify_response_chunks

mateo-berri158220f1512d
diff --cc basedpyright-code-budget.json
index 88a612fde98,229d1eca3e8..17682702867
--- a/basedpyright-code-budget.json
+++ b/basedpyright-code-budget.json
@@@ -105,19 -105,19 +105,19 @@@
"limit": 109
},
"reportUnknownMemberType": {
- "limit": 38721
+ "limit": 38468
},
"reportUnknownParameterType": {
- "limit": 19778
+ "limit": 19665
},
"reportUnknownVariableType": {
- "limit": 30290
+ "limit": 30066
},
"reportUnnecessaryCast": {
- "limit": 117
+ "limit": 111
},
"reportUnnecessaryComparison": {
- "limit": 696
- "limit": 695
++ "limit": 693
},
"reportUnnecessaryContains": {
"limit": 5
diff --cc litellm/llms/openai/chat/guardrail_translation/handler.py
index 31a36822c89,de15fefe943..05716e65137
--- a/litellm/llms/openai/chat/guardrail_translation/handler.py
+++ b/litellm/llms/openai/chat/guardrail_translation/handler.py
@@@ -54,10 -47,9 +54,12 @@@ from litellm.types.utils import
)
if TYPE_CHECKING:
+ from fastapi import HTTPException
+
- from litellm.integrations.custom_guardrail import CustomGuardrail
+ from litellm.integrations.custom_guardrail import (
+ CustomGuardrail,
+ ModifyResponseException,
+ )
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
diff --cc litellm/llms/openai/responses/guardrail_translation/handler.py
index 9a58899eccd,24dbd7c08d0..811c4feeacc
--- a/litellm/llms/openai/responses/guardrail_translation/handler.py
+++ b/litellm/llms/openai/responses/guardrail_translation/handler.py
@@@ -52,22 -46,12 +52,24 @@@ from litellm.responses.litellm_completi
)
from litellm.types.llms.openai import (
AllMessageValues,
+ BaseLiteLLMOpenAIResponseObject,
ChatCompletionToolCallChunk,
ChatCompletionToolParam,
+ ContentPartAddedEvent,
+ ContentPartDoneEvent,
+ ContentPartDonePartOutputText,
+ ErrorEvent,
+ ErrorEventError,
OpenAIMcpServerTool,
+ OutputItemAddedEvent,
+ OutputItemDoneEvent,
+ OutputTextDeltaEvent,
+ OutputTextDoneEvent,
+ ResponseAPIUsage,
+ ResponseCompletedEvent,
+ ResponsesAPIResponse,
ResponsesAPIStreamEvents,
+ ResponsesAPIStreamingResponse,
)
from litellm.types.responses.main import (
GenericResponseOutputItem,
@@@ -77,10 -61,9 +79,12 @@@
from litellm.types.utils import GenericGuardrailAPIInputs
if TYPE_CHECKING:
+ from fastapi import HTTPException
+
- from litellm.integrations.custom_guardrail import CustomGuardrail
+ from litellm.integrations.custom_guardrail import (
+ CustomGuardrail,
+ ModifyResponseException,
+ )
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.proxy._types import UserAPIKeyAuth
from litellm.types.llms.openai import ResponseInputParam
@@@ -822,183 -837,3 +857,182 @@@ class OpenAIResponsesHandler(BaseTransl
content[content_idx]["text"] = guardrail_response
elif hasattr(content[content_idx], "text"):
content[content_idx].text = guardrail_response
+
+ def build_block_sse_chunks(
+ self,
+ exc: "ModifyResponseException",
+ stream_started: bool = False,
+ responses_so_far: Sequence[object] | None = None,
+ ) -> Sequence[bytes]:
+ """
+ Build Responses API SSE events that deliver the guardrail block message
+ and terminate the stream cleanly, mirroring the non-streaming block
+ response: a completed response whose only output is the violation text,
+ with the real usage the upstream call consumed.
+
+ - ``stream_started`` False (buffered / pre-stream): nothing has been
+ sent, so emit the full synthetic sequence (``response.created``
+ through ``response.completed``).
+ - ``stream_started`` True (sampling / mid-stream): events already
+ reached the client, so continue the in-progress response: deliver the
+ block message as a new output item under the same response id and
+ close with a ``response.completed`` carrying only the replacement
+ item.
+
+ The proxy's data generator appends ``data: [DONE]`` itself.
+ """
+ events: Final = (
+ self._block_continuation_events(exc, responses_so_far or ())
+ if stream_started
+ else self._standalone_block_events(exc)
+ )
+ return tuple(
+ f"data: {event.model_dump_json(exclude_none=True, exclude_unset=True)}\n\n".encode() for event in events
+ )
+
+ @staticmethod
+ def _standalone_block_events(exc: "ModifyResponseException") -> Sequence[ResponsesAPIStreamingResponse]:
+ from litellm.responses.streaming_iterator import build_synthetic_response_events
+
+ return build_synthetic_response_events(
+ transformed=_blocked_response(exc, response_id=f"resp_{uuid.uuid4()}", model=exc.model),
+ logging_obj=None,
+ chunk_size=max(len(exc.message), 1),
+ )
+
+ @staticmethod
+ def _block_continuation_events(
+ exc: "ModifyResponseException", responses_so_far: Sequence[object]
+ ) -> Sequence[ResponsesAPIStreamingResponse]:
+ response_id, model, output_index = _continuation_identity(exc, responses_so_far)
+ item: Final = _blocked_output_item(exc)
- item_id: Final = item["id"]
- item_model: Final = BaseLiteLLMOpenAIResponseObject.model_validate(item)
++ item_id: Final = item.id
+ part: Final[_BlockedContentPart] = {"type": "output_text", "text": exc.message, "annotations": ()}
+ done_part: Final[_BlockedDoneContentPart] = {
+ "type": "output_text",
+ "text": exc.message,
+ "annotations": (),
+ "logprobs": None,
+ }
+ return (
+ OutputItemAddedEvent(
+ type=ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED,
+ output_index=output_index,
- item=item_model,
++ item=item,
+ ),
+ ContentPartAddedEvent(
+ type=ResponsesAPIStreamEvents.CONTENT_PART_ADDED,
+ item_id=item_id,
+ output_index=output_index,
+ content_index=0,
+ part=BaseLiteLLMOpenAIResponseObject.model_validate(part),
+ ),
+ OutputTextDeltaEvent(
+ type=ResponsesAPIStreamEvents.OUTPUT_TEXT_DELTA,
+ item_id=item_id,
+ output_index=output_index,
+ content_index=0,
+ delta=exc.message,
+ ),
+ OutputTextDoneEvent(
+ type=ResponsesAPIStreamEvents.OUTPUT_TEXT_DONE,
+ item_id=item_id,
+ output_index=output_index,
+ content_index=0,
+ text=exc.message,
+ ),
+ ContentPartDoneEvent(
+ type=ResponsesAPIStreamEvents.CONTENT_PART_DONE,
+ item_id=item_id,
+ output_index=output_index,
+ content_index=0,
+ part=ContentPartDonePartOutputText.model_validate(done_part),
+ ),
+ OutputItemDoneEvent(
+ type=ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE,
+ output_index=output_index,
- item=item_model,
++ item=item,
+ ),
+ ResponseCompletedEvent(
+ type=ResponsesAPIStreamEvents.RESPONSE_COMPLETED,
+ response=_blocked_response(exc, response_id=response_id, model=model, output_item=item),
+ ),
+ )
+
+
+class _BlockedContentPart(TypedDict):
+ type: ReadOnly[str]
+ text: ReadOnly[str]
+ annotations: ReadOnly[tuple[object, ...]]
+
+
+class _BlockedDoneContentPart(TypedDict):
+ type: ReadOnly[str]
+ text: ReadOnly[str]
+ annotations: ReadOnly[tuple[object, ...]]
+ logprobs: ReadOnly[None]
+
+
- class _BlockedOutputItem(TypedDict):
++class _BlockedItemPayload(TypedDict):
+ type: ReadOnly[str]
+ id: ReadOnly[str]
+ status: ReadOnly[str]
+ role: ReadOnly[str]
+ content: ReadOnly[tuple[_BlockedContentPart, ...]]
+
+
+class _BlockedResponsePayload(TypedDict):
+ id: ReadOnly[str]
+ object: ReadOnly[str]
+ created_at: ReadOnly[int]
+ model: ReadOnly[str]
- output: ReadOnly[tuple[_BlockedOutputItem, ...]]
++ output: ReadOnly[tuple[GenericResponseOutputItem, ...]]
+ status: ReadOnly[str]
+ usage: ReadOnly[ResponseAPIUsage]
+
+
- def _blocked_output_item(exc: "ModifyResponseException") -> _BlockedOutputItem:
- item: Final[_BlockedOutputItem] = {
++def _blocked_output_item(exc: "ModifyResponseException") -> GenericResponseOutputItem:
++ payload: Final[_BlockedItemPayload] = {
+ "type": "message",
+ "id": f"msg_{uuid.uuid4()}",
+ "status": "completed",
+ "role": "assistant",
+ "content": ({"type": "output_text", "text": exc.message, "annotations": ()},),
+ }
- return item
++ return GenericResponseOutputItem.model_validate(payload)
+
+
+def _blocked_response(
+ exc: "ModifyResponseException",
+ response_id: str,
+ model: str,
- output_item: _BlockedOutputItem | None = None,
++ output_item: GenericResponseOutputItem | None = None,
+) -> ResponsesAPIResponse:
+ payload: Final[_BlockedResponsePayload] = {
+ "id": response_id,
+ "object": "response",
+ "created_at": int(time.time()),
+ "model": model,
+ "output": (output_item if output_item is not None else _blocked_output_item(exc),),
+ "status": "completed",
+ "usage": blocked_responses_stream_usage(exc.original_response),
+ }
+ return ResponsesAPIResponse.model_validate(payload)
+
+
+def _continuation_identity(exc: "ModifyResponseException", responses_so_far: Sequence[object]) -> tuple[str, str, int]:
+ responses: Final = tuple(
+ response for item in responses_so_far if (response := stream_item_field(item, "response")) is not None
+ )
+ response_id: Final = next(
+ (rid for response in responses if isinstance(rid := stream_item_field(response, "id"), str) and rid),
+ f"resp_{uuid.uuid4()}",
+ )
+ model: Final = next(
+ (m for response in responses if isinstance(m := stream_item_field(response, "model"), str) and m),
+ exc.model,
+ )
+ indices: Final = tuple(
+ index for item in responses_so_far if isinstance(index := stream_item_field(item, "output_index"), int)
+ )
+ return response_id, model, max(indices) + 1 if indices else 0
diff --cc type-discipline-budget.json
index f17d0b7af4a,c27844a0004..d5eb0f0e5da
--- a/type-discipline-budget.json
+++ b/type-discipline-budget.json
@@@ -1,9 -1,9 +1,9 @@@
{
"LIT001": {
- "limit": 22698
- "limit": 22521
++ "limit": 22518
},
"LIT002": {
- "limit": 26853
+ "limit": 26820
},
"LIT003": {
"limit": 269