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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_bedrock_guardrail_stream_audit
mateo-berria23f0fc3c3ee
diff --cc litellm/llms/anthropic/chat/guardrail_translation/handler.pyindex 6cb2e568d0f,b9ca18c7843..b09b51167d0--- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py+++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py@@@ -167,19 -165,6 +167,19 @@@ class AnthropicMessagesHandler(BaseTranreturn self._block_continuation_chunks(exc, responses_so_far or [])return self._standalone_block_chunks(exc)+ def build_stream_error_items(+ self,+ exc: "HTTPException",+ responses_so_far: Sequence[Any] | None = None,+ ) -> Sequence[Any] | None:+ from litellm.proxy.common_request_processing import (+ serialize_http_exception_detail,+ )+ from litellm.proxy.guardrails.anthropic_sse import anthropic_sse_error_frames++ message, _ = serialize_http_exception_detail(exc.detail)- return list(anthropic_sse_error_frames(message))++ return tuple(anthropic_sse_error_frames(message))+def _standalone_block_chunks(self, exc: "ModifyResponseException") -> list[bytes]:import uuiddiff --cc litellm/llms/openai/chat/guardrail_translation/handler.pyindex e61fb719c98,54673c77f80..de15fefe943--- a/litellm/llms/openai/chat/guardrail_translation/handler.py+++ b/litellm/llms/openai/chat/guardrail_translation/handler.py@@@ -47,9 -46,8 +47,10 @@@ from litellm.types.utils import)if TYPE_CHECKING:+ from fastapi import HTTPException+from litellm.integrations.custom_guardrail import CustomGuardrail+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObjclass OpenAIChatCompletionsHandler(BaseTranslation):@@@ -585,18 -591,6 +586,18 @@@return responses_so_far+ 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: {json.dumps({'error': error_obj})}\n\n".encode()]++ return (f'data: {{"error": {json.dumps(error_obj)}}}\n\n'.encode(),)+@staticmethoddef _accumulate_string_content_by_choice_index(responses_so_far: list["ModelResponseStream"],diff --cc litellm/llms/openai/responses/guardrail_translation/handler.pyindex 50d7f7452a8,7c5d8ac99ad..24dbd7c08d0--- a/litellm/llms/openai/responses/guardrail_translation/handler.py+++ b/litellm/llms/openai/responses/guardrail_translation/handler.py@@@ -84,14 -80,6 +84,14 @@@ class ResponsesStreamChunk(TypedDict, ttext: ReadOnly[str]+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)- for item in reversed(responses_so_far or [])++ for item in reversed(responses_so_far or ())+ )+ return next((n + 1 for n in sequence_numbers if isinstance(n, int)), 0)++class OpenAIResponsesHandler(BaseTranslation):"""Handler for processing OpenAI Responses API with guardrails.@@@ -632,29 -620,6 +632,29 @@@}return responses_so_far[-1].get("type") in terminal_types+ def build_stream_error_items(+ self,+ exc: "HTTPException",+ responses_so_far: Sequence[Any] | None = None,+ ) -> Sequence[Any] | None:+ from litellm.proxy.common_request_processing import (+ serialize_http_exception_detail,+ )++ message, _ = serialize_http_exception_detail(exc.detail)- return [++ return (+ ErrorEvent(+ type=ResponsesAPIStreamEvents.ERROR,+ sequence_number=_next_stream_sequence_number(responses_so_far),+ error=ErrorEventError(+ type="guardrail_error",+ code=str(exc.status_code),+ message=message,+ param=None,+ ),- )- ]++ ),++ )+def get_streaming_string_so_far(self, responses_so_far: Sequence[ResponsesStreamChunk]) -> str:"""Get the string so far from the responses so far.diff --cc litellm/proxy/common_request_processing.pyindex 69c2cb3f0f0,a23669af462..5c3e1530722--- a/litellm/proxy/common_request_processing.py+++ b/litellm/proxy/common_request_processing.py@@@ -533,6 -533,21 +533,21 @@@ def serialize_http_exception_detailreturn str(detail), None+ def proxy_exception_from_http_exception(exc: HTTPException, headers: dict[str, str]) -> ProxyException:+ raw_detail: Final = _getattr_object(exc, "detail", str(exc))- message, structured_fields = _serialize_http_exception_detail(raw_detail)++ message, structured_fields = serialize_http_exception_detail(raw_detail)+ existing_fields: Final = getattr(exc, "provider_specific_fields", None) or {}+ merged_fields: Final = {**existing_fields, **structured_fields} if structured_fields else (existing_fields or None)+ return ProxyException(+ message=message,+ type=getattr(exc, "type", "None"),+ param=getattr(exc, "param", "None"),+ code=getattr(exc, "status_code", status.HTTP_400_BAD_REQUEST),+ provider_specific_fields=merged_fields,+ headers=headers,+ )++def _collect_response_file_search_vector_store_ids(data: Mapping[str, object]) -> set[str]:vector_store_ids: Final[set[str]] = set()tools: Final = data.get("tools")diff --cc litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.pyindex 951cbc13290,dd76a27c80f..a6635ea0776--- a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py+++ b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py@@@ -18,6 -18,6 +18,7 @@@ import timfrom collections.abc import AsyncGenerator, Mapping, Sequencefrom datetime import datetime, timezonefrom itertools import accumulate, groupby++from types import MappingProxyTypefrom typing import TYPE_CHECKING, Any, ClassVar, Final, Literal, NamedTuple, Optional, castimport httpx@@@ -232,15 -224,6 +233,17 @@@ class BedrockGuardrail(CustomGuardrail**kwargs,):self.async_handler = get_async_httpx_client(llm_provider=httpxSpecialProvider.GuardrailCallback)+ self._set_streaming_params(+ BedrockGuardrailStreamingParams.from_extras(- {- "streaming_buffer_until_moderated": streaming_buffer_until_moderated,- "streaming_sampling_rate": streaming_sampling_rate,- "streaming_end_of_stream_only": streaming_end_of_stream_only,- }++ MappingProxyType(++ {++ "streaming_buffer_until_moderated": streaming_buffer_until_moderated,++ "streaming_sampling_rate": streaming_sampling_rate,++ "streaming_end_of_stream_only": streaming_end_of_stream_only,++ }++ )+ )+ )self.guardrailIdentifier = guardrailIdentifierself.guardrailVersion = guardrailVersionself.guardrail_provider = "bedrock"diff --cc litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.pyindex 6647ac4c293,e95e97bfe74..46b00829b74--- a/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py+++ b/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py@@@ -429,14 -416,6 +429,14 @@@ class UnifiedLLMGuardrails(CustomLoggerif call_type is not None and CallTypes(call_type) in A2A_CALL_TYPES:yield _a2a_jsonrpc_error_chunk(exc, _get_a2a_request_id(responses_so_far, request_data))return+ if stream_started and endpoint_translation is not None:+ error_items: Final = endpoint_translation.build_stream_error_items(- exc, responses_so_far=list(responses_yielded) if responses_yielded is not None else None++ exc, responses_so_far=tuple(responses_yielded) if responses_yielded is not None else None+ )+ if error_items is not None:+ for error_item in error_items:+ yield error_item+ returnraise excdef _build_transform_chunk(diff --cc litellm/types/guardrails.pyindex c5398160c69,9be78757511..4cf4fa62eff--- a/litellm/types/guardrails.py+++ b/litellm/types/guardrails.py@@@ -1,6 -1,5 +1,7 @@@+from collections.abc import Mappingfrom datetime import datetimefrom enum import Enum++from types import MappingProxyTypefrom typing import Any, Final, Literalfrom pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator@@@ -551,37 -550,6 +552,40 @@@ class BedrockGuardrailConfigModel(BaseM)+class BedrockGuardrailStreamingParams(BaseModel):+ streaming_buffer_until_moderated: bool = Field(+ default=True,+ description="If True (default), withhold every streamed chunk until the end-of-stream "+ "ApplyGuardrail scan passes, so no flagged content reaches the client before a block. "+ "If False, chunks stream through unbuffered, so flagged content can reach the client "+ "before the scan finishes; a flagged scan still ends the stream, with a block message "+ "when disable_exception_on_block is true and an in-stream error frame otherwise.",+ )+ streaming_sampling_rate: int = Field(+ default=5,+ ge=1,+ description="When not buffering and not end-of-stream-only, scan the accumulated response "+ "every Nth streamed chunk. Each sampled scan is a full ApplyGuardrail call that delays "+ "that chunk, so lower values add latency and AWS text-unit cost.",+ )+ streaming_end_of_stream_only: bool = Field(+ default=False,+ description="When not buffering, skip per-chunk sampling and run one ApplyGuardrail scan "+ "on the assembled response at end of stream. Combined with "+ "streaming_buffer_until_moderated=false the full response streams live before the scan "+ "and the scan result lands in guardrail_information; a flagged response still ends the "+ "stream with a block message (disable_exception_on_block=true) or an error frame.",+ )++ @classmethod+ def from_extras(cls, extras: Mapping[str, object] | None) -> "BedrockGuardrailStreamingParams":- source: Final[Mapping[str, object]] = extras or {}- return cls.model_validate({name: source[name] for name in cls.model_fields if source.get(name) is not None})++ if not extras:++ return cls()++ return cls.model_validate(++ MappingProxyType({name: extras[name] for name in cls.model_fields if extras.get(name) is not None})++ )++class LakeraV2GuardrailConfigModel(BaseModel):"""Configuration parameters for the Lakera AI v2 guardrail"""diff --cc tests/test_litellm/proxy/test_common_request_processing.pyindex 0fea239625a,dd5049b0f28..7f99fe1bd39--- a/tests/test_litellm/proxy/test_common_request_processing.py+++ b/tests/test_litellm/proxy/test_common_request_processing.py@@@ -1681,8 -1681,36 +1681,36 @@@ class TestCommonRequestProcessingHelperassert msg == _json.dumps({"weird": ["a", "b"]})assert fields == {"weird": ["a", "b"]}- assert _serialize_http_exception_detail(42) == ("42", None)+ assert serialize_http_exception_detail(42) == ("42", None)+ async def test_proxy_exception_from_http_exception_helper(self):+ """The shared HTTPException -> ProxyException conversion keeps a clean+ message, merges structured detail over existing provider_specific_fields,+ and passes headers through."""+ from litellm.proxy.common_request_processing import (+ proxy_exception_from_http_exception,+ )++ exc = HTTPException(+ status_code=400,+ detail={"error": "Content blocked", "guardrail": "keyword-block"},+ )+ exc.provider_specific_fields = {"existing": "field", "guardrail": "stale"}+ result = proxy_exception_from_http_exception(exc, {"x-litellm-call-id": "abc"})+ assert result.message == "Content blocked"+ assert result.code == "400"+ assert result.provider_specific_fields == {+ "existing": "field",+ "error": "Content blocked",+ "guardrail": "keyword-block",+ }+ assert result.headers == {"x-litellm-call-id": "abc"}++ plain = proxy_exception_from_http_exception(HTTPException(status_code=429, detail="slow down"), {})+ assert plain.message == "slow down"+ assert plain.code == "429"+ assert plain.provider_specific_fields is None+async def test_create_streaming_response_first_chunk_error_string_code(self):"""Test that when the first chunk contains a string error code, a JSON error response is returned