Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions litellm/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -1697,6 +1697,7 @@ class ServerStreamingClassification(str, Enum):
AZURE_SPEECH_STT_DOMAIN: Final = "stt.speech.microsoft.com"
AZURE_SPEECH_COGNITIVE_SERVICES_DOMAIN: Final = "api.cognitive.microsoft.com"
AZURE_SPEECH_SUBSCRIPTION_KEY_HEADER: Final = "Ocp-Apim-Subscription-Key"
AWS_ERROR_TYPE_HEADER: Final = "x-amzn-errortype"
AZURE_SPEECH_SHORT_AUDIO_MODEL: Final = "short-audio"
AZURE_SPEECH_BATCH_MODEL: Final = "batch-transcription"
AZURE_SPEECH_FAST_TRANSCRIPTION_MODEL: Final = "fast-transcription"
Expand Down
10 changes: 10 additions & 0 deletions litellm/proxy/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -3808,6 +3808,16 @@ def sanitized_internal_message(self) -> str:
return self.internal_message.replace("\r", "").replace("\n", "")


class AwsErrorTypeProxyException(Exception):
"""A ProxyException answered to an AWS SDK, which reads the error code from the ``x-amzn-errortype`` header and
the message from a top-level ``message`` field."""

def __init__(self, error: ProxyException, aws_error_type: str) -> None:
super().__init__(error.message)
self.error: Final = error
self.aws_error_type: Final = aws_error_type


from litellm.types.proxy.common_proxy_errors import ( # noqa: E402 # public re-export
CommonProxyErrors as CommonProxyErrors, # noqa: PLC0414 # public re-export
)
Expand Down
84 changes: 73 additions & 11 deletions litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from litellm._logging import verbose_proxy_logger
from litellm.constants import (
ALLOWED_VERTEX_AI_PASSTHROUGH_HEADERS,
AWS_ERROR_TYPE_HEADER,
AZURE_SPEECH_BATCH_PATH_PREFIX,
AZURE_SPEECH_COGNITIVE_SERVICES_DOMAIN,
AZURE_SPEECH_CUSTOM_LLM_PROVIDER,
Expand All @@ -44,7 +45,8 @@
AZURE_SPEECH_SUBSCRIPTION_KEY_HEADER,
BEDROCK_AGENT_RUNTIME_PASS_THROUGH_ROUTES,
)
from litellm.integrations.custom_guardrail import guardrail_request_data_with_streaming
from litellm.exceptions import BlockedPiiEntityError, GuardrailRaisedException
from litellm.integrations.custom_guardrail import guardrail_request_data_with_streaming, is_guardrail_intervention
from litellm.litellm_core_utils.aws_partition import get_aws_dns_suffix
from litellm.llms.anthropic.common_utils import AnthropicModelInfo, merge_anthropic_beta_headers
from litellm.llms.azure.passthrough.transformation import (
Expand Down Expand Up @@ -79,7 +81,11 @@
user_api_key_auth_websocket,
user_api_key_auth_websocket_for_model,
)
from litellm.proxy.common_request_processing import model_deployments_support_stream_options, open_sse_before_first_byte
from litellm.proxy.common_request_processing import (
ProxyBaseLLMRequestProcessing,
model_deployments_support_stream_options,
open_sse_before_first_byte,
)
from litellm.proxy.common_utils.http_parsing_utils import ( # noqa: F401 # legacy module exports
_read_request_body, # pyright: ignore[reportPrivateUsage,reportUnusedImport] # backwards-compatible package export
_safe_get_request_headers, # pyright: ignore[reportPrivateUsage,reportUnusedImport] # backwards-compatible package export
Expand Down Expand Up @@ -1056,6 +1062,67 @@ def extract_model_from_bedrock_endpoint(endpoint: str) -> str:
_extract_model_from_bedrock_endpoint: Final = extract_model_from_bedrock_endpoint


def _guardrail_refusal_status(error: Exception) -> int | None:
"""The status a guardrail blocked the request with. None for a request check that answers with the same 400, 403
or 422, for a guardrail that failed closed because it could not get a verdict, and for a guardrail block raised
with a plain-string detail.

Guardrail hooks stamp ``guardrail_name`` onto the dict detail of an HTTPException they raise."""
match error:
case HTTPException():
detail: Final[object] = error.detail
stamped: Final = isinstance(detail, dict) and "guardrail_name" in detail
return error.status_code if stamped and is_guardrail_intervention(error) else None
case GuardrailRaisedException(blocked_content=True) | BlockedPiiEntityError():
return error.status_code
case _:
return None


Comment thread
yucheng-berri marked this conversation as resolved.
Resolved
def _bedrock_error_response(error: Exception, handled: HTTPException) -> Response | None:
"""Bedrock's own error response, for an error Bedrock answered with an AWS error type."""
if not isinstance(error, httpx.HTTPStatusError):
return None
upstream: Final = error.response
if AWS_ERROR_TYPE_HEADER not in upstream.headers:
return None
Comment thread
yucheng-berri marked this conversation as resolved.
Resolved
passed_through: Final = {
name: upstream.headers[name] for name in (AWS_ERROR_TYPE_HEADER, "content-type") if name in upstream.headers
}
return Response(
content=upstream.content,
status_code=upstream.status_code,
headers={**(handled.headers or {}), **passed_through},
)


async def bedrock_passthrough_error_response(
processor: ProxyBaseLLMRequestProcessing,
error: Exception,
user_api_key_dict: UserAPIKeyAuth,
proxy_logging_obj: ProxyLoggingType,
) -> Response:
"""Run the shared error handling for a Bedrock passthrough request, then answer a guardrail block or an error
Bedrock returned the way Bedrock does, so an AWS SDK reads its code and message. Anything else is raised as the
shared handler raises it."""
try:
await processor.handle_llm_api_exception(
e=error,
user_api_key_dict=user_api_key_dict,
proxy_logging_obj=proxy_logging_obj,
)
except HTTPException as handled:
response: Final = _bedrock_error_response(error, handled)
if response is None:
raise
return response
except ProxyException as handled:
refusal_status: Final = _guardrail_refusal_status(error)
if refusal_status is not None and str(refusal_status) == handled.code:
raise AwsErrorTypeProxyException(handled, "ValidationException") from handled
raise


async def handle_bedrock_passthrough_router_model(
model: str,
endpoint: str,
Expand Down Expand Up @@ -1140,11 +1207,8 @@ async def handle_bedrock_passthrough_router_model(
)
return result
except Exception as e:
# Use common exception handling
raise await base_llm_response_processor.handle_llm_api_exception(
e=e,
user_api_key_dict=user_api_key_dict,
proxy_logging_obj=proxy_logging_obj,
return await bedrock_passthrough_error_response(
base_llm_response_processor, e, user_api_key_dict, proxy_logging_obj
)


Expand Down Expand Up @@ -1343,10 +1407,8 @@ async def bedrock_llm_proxy_route(

return result
except Exception as e:
raise await base_llm_response_processor.handle_llm_api_exception(
e=e,
user_api_key_dict=user_api_key_dict,
proxy_logging_obj=proxy_logging_obj,
return await bedrock_passthrough_error_response(
base_llm_response_processor, e, user_api_key_dict, proxy_logging_obj
)


Expand Down
13 changes: 13 additions & 0 deletions litellm/proxy/proxy_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
AIOHTTP_NEEDS_CLEANUP_CLOSED,
AIOHTTP_TTL_DNS_CACHE,
AUDIO_SPEECH_CHUNK_SIZE,
AWS_ERROR_TYPE_HEADER,
BACKGROUND_HEALTH_CHECK_DB_SAVE_JOB_NAME,
BASE_MCP_ROUTE,
DAILY_TAG_SPEND_BATCH_MULTIPLIER,
Expand Down Expand Up @@ -91,6 +92,7 @@
from litellm.litellm_core_utils.token_counter import offload_token_count
from litellm.proxy._types import (
UI_TEAM_ID,
AwsErrorTypeProxyException,
CallbackDelete,
CallInfo,
CommonProxyErrors,
Expand Down Expand Up @@ -2069,6 +2071,17 @@ async def openai_exception_handler(request: Request, exc: ProxyException):
)


@app.exception_handler(AwsErrorTypeProxyException)
async def aws_error_type_exception_handler(request: Request, exc: AwsErrorTypeProxyException) -> Response:
"""The ProxyException response plus the ``x-amzn-errortype`` header and top-level ``message`` an AWS SDK reads."""
response: Final = await openai_exception_handler(request, exc.error)
return JSONResponse(
status_code=response.status_code,
content={"message": exc.error.message, **JSON_OBJECT.validate_json(bytes(response.body))},
headers={**exc.error.headers, AWS_ERROR_TYPE_HEADER: exc.aws_error_type},
)


@app.exception_handler(StarletteHTTPException)
async def otlp_http_exception_handler(connection: Request | WebSocket, exc: StarletteHTTPException) -> Response | None:
if isinstance(connection, WebSocket):
Expand Down
Loading
Loading