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]

[internal copy of #29511] feat(guardrails): add sensitive data routing to on-premise models (#29531)

Mateo Wang812a2217ca64
diff --git a/litellm/exceptions.py b/litellm/exceptions.py
index 17f5b43c273..15f6030d4a3 100644
--- a/litellm/exceptions.py
+++ b/litellm/exceptions.py
@@ -1062,3 +1062,37 @@ class GuardrailInterventionNormalStringError(
def __repr__(self):
return self.__str__()
+
+
+class SensitiveDataRouteException(Exception):
+ """
+ Exception raised when a guardrail detects sensitive data and wants to reroute the request.
+
+ Instead of blocking the request, this exception signals that the request should be
+ routed to a different model (typically an on-premise model for data privacy).
+
+ The proxy catches this exception and:
+ 1. Reroutes the current request to the specified model
+ 2. When sticky_session_routing is True, stores the routing decision in session
+ cache so all subsequent requests in the same session are routed to the same model
+ """
+
+ def __init__(
+ self,
+ route_to_model: str,
+ session_id: str,
+ guardrail_name: Optional[str] = None,
+ detection_info: Optional[Dict[str, Any]] = None,
+ message: Optional[str] = None,
+ sticky_session_routing: bool = True,
+ ):
+ self.route_to_model = route_to_model
+ self.session_id = session_id
+ self.guardrail_name = guardrail_name
+ self.detection_info = detection_info or {}
+ self.sticky_session_routing = sticky_session_routing
+ self.message = (
+ message
+ or f"Sensitive data detected by {guardrail_name}. Routing to model: {route_to_model}"
+ )
+ super().__init__(self.message)
diff --git a/litellm/integrations/custom_guardrail.py b/litellm/integrations/custom_guardrail.py
index 6d0d73e033d..fc5f0429b63 100644
--- a/litellm/integrations/custom_guardrail.py
+++ b/litellm/integrations/custom_guardrail.py
@@ -47,9 +47,29 @@ from litellm.exceptions import (
BlockedPiiEntityError,
GuardrailRaisedException,
ModifyResponseException,
+ SensitiveDataRouteException,
)
+def get_session_id_from_request_data(request_data: Dict[str, Any]) -> Optional[str]:
+ """Extract session_id from request data (litellm_session_id or metadata)."""
+ session_id = request_data.get("litellm_session_id")
+ if session_id:
+ return str(session_id)
+
+ metadata = request_data.get("metadata") or {}
+ session_id = metadata.get("session_id")
+ if session_id:
+ return str(session_id)
+
+ litellm_metadata = request_data.get("litellm_metadata") or {}
+ session_id = litellm_metadata.get("session_id")
+ if session_id:
+ return str(session_id)
+
+ return None
+
+
class CustomGuardrail(CustomLogger):
# If True, during_call runs async_moderation_hook instead of the unified apply_guardrail path.
use_native_during_call_hook: ClassVar[bool] = False
@@ -68,6 +88,9 @@ class CustomGuardrail(CustomLogger):
end_session_after_n_fails: Optional[int] = None,
on_violation: Optional[str] = None,
realtime_violation_message: Optional[str] = None,
+ on_sensitive_data: Optional[str] = None,
+ sensitive_data_route_to_model: Optional[str] = None,
+ sticky_session_routing: bool = True,
**kwargs,
):
"""
@@ -83,6 +106,9 @@ class CustomGuardrail(CustomLogger):
end_session_after_n_fails: For /v1/realtime sessions, end the session after this many violations
on_violation: For /v1/realtime sessions, 'warn' or 'end_session'
realtime_violation_message: Message the bot speaks aloud when a /v1/realtime guardrail fires
+ on_sensitive_data: Action when sensitive data is detected. 'block' (default) or 'route'
+ sensitive_data_route_to_model: Model to route to when on_sensitive_data='route'
+ sticky_session_routing: When True, all subsequent requests in the session use the same model
"""
self.guardrail_name = guardrail_name
self.supported_event_hooks = supported_event_hooks
@@ -96,6 +122,11 @@ class CustomGuardrail(CustomLogger):
self.end_session_after_n_fails: Optional[int] = end_session_after_n_fails
self.on_violation: Optional[str] = on_violation
self.realtime_violation_message: Optional[str] = realtime_violation_message
+ self.on_sensitive_data: Optional[str] = on_sensitive_data
+ self.sensitive_data_route_to_model: Optional[str] = (
+ sensitive_data_route_to_model
+ )
+ self.sticky_session_routing: bool = sticky_session_routing
if supported_event_hooks:
## validate event_hook is in supported_event_hooks
@@ -167,6 +198,108 @@ class CustomGuardrail(CustomLogger):
detection_info=detection_info,
)
+ def raise_sensitive_data_route_exception(
+ self,
+ route_to_model: str,
+ request_data: Dict[str, Any],
+ detection_info: Optional[Dict[str, Any]] = None,
+ ) -> None:
+ """
+ Raise an exception to reroute the request to a different model.
+
+ Use this when sensitive data is detected and the guardrail is configured
+ to route to an on-premise model instead of blocking.
+
+ The exception will reroute this request to the specified model. When
+ sticky_session_routing is enabled (the default), it also stores the
+ routing decision so subsequent requests in this session reuse the model.
+
+ Args:
+ route_to_model: The model to route this request (and session) to
+ request_data: The original request data dictionary
+ detection_info: Optional non-sensitive detection metadata (e.g. matched
+ entity types, rule ids, scores). This is surfaced in request metadata
+ and logs, so it must not contain the raw detected sensitive values.
+
+ Raises:
+ SensitiveDataRouteException: Always raises to trigger rerouting
+ """
+ session_id = self._get_session_id_from_request_data(request_data)
+ if not session_id:
+ raise ValueError(
+ "Cannot route sensitive data without a session_id. "
+ "Ensure the request includes a session_id in metadata or headers."
+ )
+
+ raise SensitiveDataRouteException(
+ route_to_model=route_to_model,
+ session_id=session_id,
+ guardrail_name=self.guardrail_name,
+ detection_info=detection_info,
+ sticky_session_routing=self.sticky_session_routing,
+ )
+
+ def _get_session_id_from_request_data(
+ self, request_data: Dict[str, Any]
+ ) -> Optional[str]:
+ """Extract session_id from request data."""
+ return get_session_id_from_request_data(request_data)
+
+ def should_route_on_sensitive_data(self) -> bool:
+ """
+ Returns True if this guardrail is configured to route requests
+ to a different model when sensitive data is detected.
+ """
+ return (
+ self.on_sensitive_data == "route"
+ and self.sensitive_data_route_to_model is not None
+ )
+
+ def handle_sensitive_data_detection(
+ self,
+ request_data: Dict[str, Any],
+ detection_info: Optional[Dict[str, Any]] = None,
+ ) -> None:
+ """
+ Handle sensitive data detection based on guardrail configuration.
+
+ If on_sensitive_data='route', raises SensitiveDataRouteException to reroute.
+ Otherwise, raises GuardrailRaisedException to block. When routing is
+ configured but the request carries no session_id, routing is not possible
+ so the request falls back to a graceful block.
+
+ Args:
+ request_data: The request data dictionary
+ detection_info: Optional non-sensitive detection metadata. When routing,
+ this is surfaced in request metadata and logs, so it must not contain
+ the raw detected sensitive values.
+
+ Raises:
+ SensitiveDataRouteException: When configured to route and a session_id is present
+ GuardrailRaisedException: When configured to block, or when routing is
+ configured but no session_id is available
+ """
+ if self.should_route_on_sensitive_data():
+ try:
+ self.raise_sensitive_data_route_exception(
+ route_to_model=self.sensitive_data_route_to_model, # type: ignore
+ request_data=request_data,
+ detection_info=detection_info,
+ )
+ except ValueError:
+ raise GuardrailRaisedException(
+ message=(
+ f"Sensitive data detected by {self.guardrail_name} "
+ "(routing skipped: request has no session_id)"
+ ),
+ guardrail_name=self.guardrail_name,
+ )
+ else:
+ raise GuardrailRaisedException(
+ message=f"Sensitive data detected by {self.guardrail_name}",
+ guardrail_name=self.guardrail_name,
+ )
+
@staticmethod
def get_config_model() -> Optional[Type["GuardrailConfigModel"]]:
"""
@@ -753,12 +886,20 @@ class CustomGuardrail(CustomLogger):
Guardrails signal intentional blocks by raising:
- GuardrailRaisedException (generic guardrail API, tool permission)
- BlockedPiiEntityError (Presidio PII detection)
+ - SensitiveDataRouteException (sensitive-data reroute to on-premise model)
- HTTPException with status 400 (content policy violation)
- ModifyResponseException (passthrough mode violation)
"""
if isinstance(e, ModifyResponseException):
return True
- if isinstance(e, (GuardrailRaisedException, BlockedPiiEntityError)):
+ if isinstance(
+ e,
+ (
+ GuardrailRaisedException,
+ BlockedPiiEntityError,
+ SensitiveDataRouteException,
+ ),
+ ):
return True
if (
HTTPException is not None
diff --git a/litellm/integrations/prometheus.py b/litellm/integrations/prometheus.py
index 9fc09807369..648fe671140 100644
--- a/litellm/integrations/prometheus.py
+++ b/litellm/integrations/prometheus.py
@@ -2690,7 +2690,7 @@ class PrometheusLogger(CustomLogger):
Args:
guardrail_name: Name of the guardrail
latency_seconds: Execution latency in seconds
- status: "success" or "error"
+ status: "success", "error", or "intervened"
error_type: Type of error if any, None otherwise
hook_type: "pre_call", "during_call", or "post_call"
"""
diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py
index 5c502c56ffe..eedab7fc36c 100644
--- a/litellm/llms/custom_httpx/llm_http_handler.py
+++ b/litellm/llms/custom_httpx/llm_http_handler.py
@@ -2586,6 +2586,8 @@ class BaseLLMHTTPHandler:
headers=headers,
)
+ headers.setdefault("Content-Type", "application/json")
+
## LOGGING
logging_obj.pre_call(
input=input,
@@ -2676,6 +2678,8 @@ class BaseLLMHTTPHandler:
headers=headers,
)
+ headers.setdefault("Content-Type", "application/json")
+
## LOGGING
logging_obj.pre_call(
input=input,
diff --git a/litellm/proxy/hooks/__init__.py b/litellm/proxy/hooks/__init__.py
index 34505427d79..0db661fb508 100644
--- a/litellm/proxy/hooks/__init__.py
+++ b/litellm/proxy/hooks/__init__.py
@@ -10,6 +10,7 @@ from .max_iterations_limiter import _PROXY_MaxIterationsHandler
from .parallel_request_limiter import _PROXY_MaxParallelRequestsHandler
from .parallel_request_limiter_v3 import _PROXY_MaxParallelRequestsHandler_v3
from .responses_id_security import ResponsesIDSecurity
+from .sensitive_data_routing import _PROXY_SensitiveDataRoutingHandler
# List of all available hooks that can be enabled.
# Defined before the enterprise import below so that any module re-imported
@@ -23,6 +24,7 @@ PROXY_HOOKS = {
"litellm_skills": SkillsInjectionHook,
"max_iterations_limiter": _PROXY_MaxIterationsHandler,
"max_budget_per_session_limiter": _PROXY_MaxBudgetPerSessionHandler,
+ "sensitive_data_routing": _PROXY_SensitiveDataRoutingHandler,
}
## FEATURE FLAG HOOKS ##
diff --git a/litellm/proxy/hooks/sensitive_data_routing.py b/litellm/proxy/hooks/sensitive_data_routing.py
new file mode 100644
index 00000000000..0a907b1d71c
--- /dev/null
+++ b/litellm/proxy/hooks/sensitive_data_routing.py
@@ -0,0 +1,206 @@
+"""
+Sensitive Data Routing Hook for LiteLLM Proxy.
+
+When a guardrail detects sensitive data and is configured with on_sensitive_data='route',
+this hook manages:
+1. Storing the routing decision (session_id -> model) in cache
+2. Checking incoming requests for existing routing overrides
+3. Applying sticky routing so all subsequent requests in a session go to the same model
+
+Works across multiple proxy instances via DualCache (in-memory + Redis).
+"""
+
+import os
+from typing import TYPE_CHECKING, Any, Optional, Union
+
+from litellm._logging import verbose_proxy_logger
+from litellm.caching.caching import DualCache
+from litellm.integrations.custom_guardrail import get_session_id_from_request_data
+from litellm.integrations.custom_logger import CustomLogger
+from litellm.proxy._types import UserAPIKeyAuth
+
+if TYPE_CHECKING:
+ from litellm.proxy.utils import InternalUsageCache as _InternalUsageCache
+
+ InternalUsageCache = _InternalUsageCache
+else:
+ InternalUsageCache = Any
+
+
+SENSITIVE_ROUTING_CACHE_PREFIX = "sensitive_route"
+DEFAULT_SENSITIVE_ROUTING_TTL = 3600
+
+
+class _PROXY_SensitiveDataRoutingHandler(CustomLogger):
+ """
+ Pre-call hook that checks for existing sensitive data routing overrides
+ and applies them to incoming requests.
+
+ This hook runs early in the pre-call chain and modifies the request's
+ model field if a routing override exists for the session.
+ """
+
+ def __init__(self, internal_usage_cache: InternalUsageCache):
+ self.internal_usage_cache = internal_usage_cache
+ self.ttl = int(
+ os.getenv(
+ "LITELLM_SENSITIVE_ROUTING_TTL",
+ str(DEFAULT_SENSITIVE_ROUTING_TTL),
+ )
+ )
+
+ def _make_cache_key(self, session_id: str, tenant: str) -> str:
+ return f"{{{SENSITIVE_ROUTING_CACHE_PREFIX}:{tenant}:{session_id}}}:model"
+
+ @staticmethod
+ def _resolve_tenant(user_api_key_dict: Optional[UserAPIKeyAuth]) -> str:
+ """
+ Identify the authenticated principal the routing override belongs to.
+
+ API-key auth is scoped by the hashed key. JWT (and other keyless) auth
+ has no api_key, so fall back to a stable identity claim. Without this,
+ every keyless caller would share the ``default`` namespace and could read
+ or overwrite another principal's session routing.
+ """
+ if user_api_key_dict is None:
+ return "default"
+ if user_api_key_dict.api_key:
+ return user_api_key_dict.api_key
+ principal = [
+ f"{label}:{value}"
+ for label, value in (
+ ("user", user_api_key_dict.user_id),
+ ("team", user_api_key_dict.team_id),
+ ("org", user_api_key_dict.org_id),
+ )
+ if value
+ ]
+ return "|".join(principal) if principal else "default"
+
+ async def _get_routed_model(
+ self, session_id: str, user_api_key_dict: Optional[UserAPIKeyAuth]
+ ) -> Optional[str]:
+ """Get the model this session should be routed to, if any."""
+ cache_key = self._make_cache_key(
+ session_id, self._resolve_tenant(user_api_key_dict)
+ )
+
+ if self.internal_usage_cache.dual_cache.redis_cache is not None:
+ try:
+ result = await self.internal_usage_cache.dual_cache.redis_cache.async_get_cache(
+ key=cache_key
+ )
+ if result is not None:
+ routed_model = str(result)
+ remaining_ttl = await self.internal_usage_cache.dual_cache.redis_cache.async_get_ttl(
+ key=cache_key
+ )
+ await self.internal_usage_cache.async_set_cache(
+ key=cache_key,
+ value=routed_model,
+ ttl=remaining_ttl if remaining_ttl is not None else self.ttl,
+ litellm_parent_otel_span=None,
+ local_only=True,
+ )
+ return routed_model
+ except Exception as e:
+ verbose_proxy_logger.warning(
+ "SensitiveDataRoutingHandler: Redis GET failed, falling back to in-memory: %s",
+ str(e),
+ )
+
+ result = await self.internal_usage_cache.async_get_cache(
+ key=cache_key,
+ litellm_parent_otel_span=None,
+ local_only=True,
+ )
+ if result is not None:
+ return str(result)
+ return None
+
+ async def set_session_routing(
+ self,
+ session_id: str,
+ model: str,
+ user_api_key_dict: Optional[UserAPIKeyAuth] = None,
+ guardrail_name: Optional[str] = None,
+ ) -> None:
+ """
+ Store a routing override for a session.
+
+ Called by guardrails when they detect sensitive data and want to
+ route the session to a specific model. The override is scoped to the
+ requesting principal so sessions from different tenants cannot collide.
+ """
+ cache_key = self._make_cache_key(
+ session_id, self._resolve_tenant(user_api_key_dict)
+ )
+
+ verbose_proxy_logger.info(
+ "SensitiveDataRoutingHandler: Setting session routing session_id=%s model=%s guardrail=%s ttl=%s",
+ session_id,
+ model,
+ guardrail_name,
+ self.ttl,
+ )
+
+ if self.internal_usage_cache.dual_cache.redis_cache is not None:
+ try:
+ await self.internal_usage_cache.dual_cache.redis_cache.async_set_cache(
+ key=cache_key,
+ value=model,
+ ttl=self.ttl,
+ )
+ except Exception as e:
+ verbose_proxy_logger.warning(
+ "SensitiveDataRoutingHandler: Redis SET failed, falling back to in-memory: %s",
+ str(e),
+ )
+
+ await self.internal_usage_cache.async_set_cache(
+ key=cache_key,
+ value=model,
+ ttl=self.ttl,
+ litellm_parent_otel_span=None,
+ local_only=True,
+ )
+
+ async def async_pre_call_hook(
+ self,
+ user_api_key_dict: UserAPIKeyAuth,
+ cache: DualCache,
+ data: dict,
+ call_type: str,
+ ) -> Optional[Union[Exception, str, dict]]:
+ """
+ Before each LLM call, check if this session has a routing override.
+ If so, modify the request's model field.
+ """
+ session_id = get_session_id_from_request_data(data)
+ if session_id is None:
+ return None
+
+ routed_model = await self._get_routed_model(session_id, user_api_key_dict)
+ if routed_model is None:
+ return None
+
+ original_model = data.get("model")
+ if original_model == routed_model:
+ return None
+
+ verbose_proxy_logger.info(
+ "SensitiveDataRoutingHandler: Applying session routing override "
+ "session_id=%s original_model=%s routed_model=%s",
+ session_id,
+ original_model,
+ routed_model,
+ )
+
+ data["model"] = routed_model
+
+ metadata = data.get("metadata") or {}
+ metadata["sensitive_data_routing_applied"] = True
+ metadata["sensitive_data_routing_original_model"] = original_model
+ data["metadata"] = metadata
+
+ return data
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
index 8bd50a50a38..e77e24c9e71 100644
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -89,11 +89,14 @@ from litellm._logging import _redact_string, verbose_proxy_logger
from litellm._service_logger import ServiceLogging, ServiceTypes
from litellm.caching.caching import DualCache, RedisCache
from litellm.caching.dual_cache import LimitedSizeOrderedDict
-from litellm.exceptions import RejectedRequestError
+from litellm.exceptions import RejectedRequestError, SensitiveDataRouteException
from litellm.integrations.custom_guardrail import (
CustomGuardrail,
ModifyResponseException,
)
+from litellm.proxy.hooks.sensitive_data_routing import (
+ _PROXY_SensitiveDataRoutingHandler,
+)
from litellm.integrations.custom_logger import CustomLogger
from litellm.integrations.SlackAlerting.slack_alerting import SlackAlerting
from litellm.integrations.SlackAlerting.utils import _add_langfuse_trace_id_to_alert
@@ -1151,6 +1154,9 @@ class ProxyLogging:
response=response, data=data, call_type=call_type
)
+ except SensitiveDataRouteException:
+ status = "intervened"
+ raise
except Exception as e:
status = "error"
error_type = type(e).__name__
@@ -1460,47 +1466,57 @@ class ProxyLogging:
self._process_guardrail_metadata(data)
return data
+ deferred_route_exc: Optional[SensitiveDataRouteException] = None
for _callback in caps.resolved_callbacks:
start_time = time.time()
- if isinstance(_callback, CustomGuardrail) and data is not None:
- # Skip guardrails managed by a pipeline
- if (
- _callback.guardrail_name
- and _callback.guardrail_name in pipeline_managed
- ):
- continue
-
- result = await self._process_guardrail_callback(
- callback=_callback,
- data=data, # type: ignore
- user_api_key_dict=user_api_key_dict,
- call_type=call_type,
- event_type=GuardrailEventHooks.pre_call,
- )
- if result is None:
- continue
- data = result
+ try:
+ if isinstance(_callback, CustomGuardrail) and data is not None:
+ # Skip guardrails managed by a pipeline
+ if (
+ _callback.guardrail_name
+ and _callback.guardrail_name in pipeline_managed
+ ):
+ continue
- elif (
- _callback is not None
- and isinstance(_callback, CustomLogger)
- and "async_pre_call_hook" in vars(_callback.__class__)
- and _callback.__class__.async_pre_call_hook
- != CustomLogger.async_pre_call_hook
- ):
- if call_type == "call_mcp_tool" and user_api_key_dict is None:
- continue
+ result = await self._process_guardrail_callback(
+ callback=_callback,
+ data=data, # type: ignore
+ user_api_key_dict=user_api_key_dict,
+ call_type=call_type,
+ event_type=GuardrailEventHooks.pre_call,
+ )
+ if result is None:
+ continue
+ data = result
+
+ elif (
+ _callback is not None
+ and isinstance(_callback, CustomLogger)
+ and "async_pre_call_hook" in vars(_callback.__class__)
+ and _callback.__class__.async_pre_call_hook
+ != CustomLogger.async_pre_call_hook
+ ):
+ if call_type == "call_mcp_tool" and user_api_key_dict is None:
+ continue
- response = await _callback.async_pre_call_hook(
- user_api_key_dict=user_api_key_dict,
- cache=self.call_details["user_api_key_cache"],
- data=data, # type: ignore
- call_type=call_type, # type: ignore
- )
- if response is not None:
- data = await self.process_pre_call_hook_response(
- response=response, data=data, call_type=call_type
+ response = await _callback.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=self.call_details["user_api_key_cache"],
+ data=data, # type: ignore
+ call_type=call_type, # type: ignore
)
+ if response is not None:
+ data = await self.process_pre_call_hook_response(
+ response=response, data=data, call_type=call_type
+ )
+ except SensitiveDataRouteException as e:
+ # Defer the reroute until remaining guardrails have run so later
+ # security checks are not skipped; the first reroute wins and a
+ # later guardrail that blocks still propagates. Fall through to the
+ # service-span recording below so the triggering guardrail is still
+ # timed like every other callback.
+ if deferred_route_exc is None:
+ deferred_route_exc = e
end_time = time.time()
duration = end_time - start_time
@@ -1516,13 +1532,76 @@ class ProxyLogging:
end_time=end_time,
)
+ if deferred_route_exc is not None and data is not None:
+ data = await self._handle_sensitive_data_route_exception(
+ deferred_route_exc, data, user_api_key_dict
+ )
+
if data is not None:
self._process_guardrail_metadata(data)
return data
+ except SensitiveDataRouteException as e:
+ data = await self._handle_sensitive_data_route_exception(
+ e, data, user_api_key_dict
+ )
+ if data is not None:
+ self._process_guardrail_metadata(data)
+ return data
except Exception as e:
raise e
+ async def _handle_sensitive_data_route_exception(
+ self,
+ exc: SensitiveDataRouteException,
+ data: Optional[dict],
+ user_api_key_dict: Optional[UserAPIKeyAuth],
+ ) -> Optional[dict]:
+ """
+ Handle SensitiveDataRouteException by rerouting the current request to
+ the target model and, when sticky_session_routing is enabled, persisting
+ the session override so subsequent requests reuse the same model.
+ """
+ if data is None:
+ return None
+
+ verbose_proxy_logger.info(
+ "SensitiveDataRouteException caught: session_id=%s route_to_model=%s guardrail=%s sticky=%s",
+ exc.session_id,
+ exc.route_to_model,
+ exc.guardrail_name,
+ exc.sticky_session_routing,
+ )
+
+ if exc.sticky_session_routing:
+ sensitive_routing_hook = self.get_proxy_hook("sensitive_data_routing")
+ if isinstance(sensitive_routing_hook, _PROXY_SensitiveDataRoutingHandler):
+ await sensitive_routing_hook.set_session_routing(
+ session_id=exc.session_id,
+ model=exc.route_to_model,
+ user_api_key_dict=user_api_key_dict,
+ guardrail_name=exc.guardrail_name,
+ )
+ else:
+ verbose_proxy_logger.warning(
+ "SensitiveDataRouteException requested sticky routing for session_id=%s "
+ "but the 'sensitive_data_routing' hook is not registered. Only this request "
+ "will be rerouted; subsequent requests will not be sticky.",
+ exc.session_id,
+ )
+
+ original_model = data.get("model")
+ data["model"] = exc.route_to_model
+
+ metadata = data.get("metadata") or {}
+ metadata["sensitive_data_routing_applied"] = True
+ metadata["sensitive_data_routing_original_model"] = original_model
+ metadata["sensitive_data_routing_guardrail"] = exc.guardrail_name
+ metadata["sensitive_data_routing_detection_info"] = exc.detection_info
+ data["metadata"] = metadata
+
+ return data
+
@staticmethod
async def _run_guardrail_task_with_enrichment(
callback: Any, coro: Awaitable[Any]
diff --git a/litellm/types/guardrails.py b/litellm/types/guardrails.py
index 25c0bcabb4a..0d81e25592d 100644
--- a/litellm/types/guardrails.py
+++ b/litellm/types/guardrails.py
@@ -2,7 +2,7 @@ from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Literal, Optional, Union
-from pydantic import BaseModel, ConfigDict, Field, field_validator
+from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from typing_extensions import Required, TypedDict
from litellm.types.proxy.guardrails.guardrail_hooks.akto import (
@@ -771,6 +771,58 @@ class BaseLitellmParams(
),
)
+ on_sensitive_data: Optional[Literal["block", "route"]] = Field(
+ default=None,
+ description=(
+ "Action to take when sensitive data is detected. "
+ "'block' raises an exception (default behavior). "
+ "'route' reroutes the request to the model specified in sensitive_data_route_to_model."
+ ),
+ )
+
+ sensitive_data_route_to_model: Optional[str] = Field(
+ default=None,
+ description=(
+ "Model to route requests to when sensitive data is detected and on_sensitive_data='route'. "
+ "This is typically an on-premise model for data privacy. "
+ "The routing decision persists for the entire session."
+ ),
+ )
+
+ sticky_session_routing: Optional[bool] = Field(
+ default=True,
+ description=(
+ "When True (default), after sensitive data is detected and routed, all subsequent "
+ "requests in the same session will continue routing to the same model."
+ ),
+ )
+
+ @field_validator(
+ "mode",
+ "default_action",
+ "on_disallowed_action",
+ "unreachable_fallback",
+ "on_sensitive_data",
+ mode="before",
+ check_fields=False,
+ )
+ @classmethod
+ def normalize_lowercase(cls, v):
+ """Normalize string and list fields to lowercase for ALL guardrail types."""
+ if isinstance(v, str):
+ return v.lower()
+ if isinstance(v, list):
+ return [x.lower() if isinstance(x, str) else x for x in v]
+ return v
+
+ @model_validator(mode="after")
+ def validate_sensitive_data_routing(self) -> "BaseLitellmParams":
+ if self.on_sensitive_data == "route" and not self.sensitive_data_route_to_model:
+ raise ValueError(
+ "sensitive_data_route_to_model must be set when on_sensitive_data='route'"
+ )
+ return self
+
model_config = ConfigDict(extra="allow", protected_namespaces=())
@@ -811,23 +863,6 @@ class LitellmParams(
description="When to apply the guardrail (pre_call, post_call, during_call, logging_only)"
)
- @field_validator(
- "mode",
- "default_action",
- "on_disallowed_action",
- "unreachable_fallback",
- mode="before",
- check_fields=False,
- )
- @classmethod
- def normalize_lowercase(cls, v):
- """Normalize string and list fields to lowercase for ALL guardrail types."""
- if isinstance(v, str):
- return v.lower()
- if isinstance(v, list):
- return [x.lower() if isinstance(x, str) else x for x in v]
- return v
-
@field_validator("timeout", mode="before", check_fields=False)
@classmethod
def coerce_timeout(cls, v):
diff --git a/tests/test_litellm/integrations/test_custom_guardrail.py b/tests/test_litellm/integrations/test_custom_guardrail.py
index 4956fccb8db..f0bc7b8ebed 100644
--- a/tests/test_litellm/integrations/test_custom_guardrail.py
+++ b/tests/test_litellm/integrations/test_custom_guardrail.py
@@ -1249,3 +1249,47 @@ class TestCustomGuardrailSpendLogMatchRedaction:
slg = request_data["metadata"]["standard_logging_guardrail_information"][0]
assert slg["guardrail_response"]["filters"][0]["regex"] == "[REDACTED]"
assert raw["filters"][0]["regex"] == r"\d{3}-\d{2}-\d{4}"
+
+
+class TestGuardrailInterventionClassification:
+ """A routing decision is a deliberate guardrail intervention, not a failure."""
+
+ def test_sensitive_data_route_exception_is_intervention(self):
+ from litellm.exceptions import SensitiveDataRouteException
+
+ exc = SensitiveDataRouteException(
+ route_to_model="on-prem-model",
+ session_id="sess-1",
+ guardrail_name="pii-rail",
+ )
+ assert CustomGuardrail._is_guardrail_intervention(exc) is True
+
+ @pytest.mark.asyncio
+ async def test_routing_logged_as_intervened_not_failed(self):
+ from litellm.exceptions import SensitiveDataRouteException
+ from litellm.integrations.custom_guardrail import log_guardrail_information
+ from litellm.types.guardrails import GuardrailEventHooks
+
+ class RoutingGuardrail(CustomGuardrail):
+ def __init__(self):
+ super().__init__(
+ guardrail_name="pii-rail",
+ event_hook=GuardrailEventHooks.pre_call,
+ )
+
+ @log_guardrail_information
+ async def async_pre_call_hook(self, data, **kwargs):
+ raise SensitiveDataRouteException(
+ route_to_model="on-prem-model",
+ session_id="sess-1",
+ guardrail_name=self.guardrail_name,
+ )
+
+ guardrail = RoutingGuardrail()
+ request_data: dict = {"metadata": {}}
+
+ with pytest.raises(SensitiveDataRouteException):
+ await guardrail.async_pre_call_hook(data=request_data)
+
+ slg = request_data["metadata"]["standard_logging_guardrail_information"][0]
+ assert slg["guardrail_status"] == "guardrail_intervened"
diff --git a/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py b/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py
index 083f4a97ab6..279e9730e69 100644
--- a/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py
+++ b/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py
@@ -564,6 +564,46 @@ def test_sync_delete_responses_omits_body_for_azure():
)
+def _content_type(headers: dict) -> str:
+ for key, value in headers.items():
+ if key.lower() == "content-type":
+ return value
+ return ""
+
+
+def test_async_delete_responses_sets_json_content_type():
+ """OpenAI rejects a responses DELETE with no Content-Type by treating it as
+ application/octet-stream. The handler must declare application/json."""
+ captured: dict = {}
+ fake_async_delete, _ = _build_delete_response_mock(captured)
+
+ async def run():
+ with patch.object(AsyncHTTPHandler, "delete", new=fake_async_delete):
+ await litellm.adelete_responses(
+ response_id="resp_xyz",
+ custom_llm_provider="openai",
+ api_key="test-key",
+ )
+
+ asyncio.run(run())
+
+ assert _content_type(captured["headers"]) == "application/json"
+
+
+def test_sync_delete_responses_sets_json_content_type():
+ captured: dict = {}
+ _, fake_sync_delete = _build_delete_response_mock(captured)
+
+ with patch.object(HTTPHandler, "delete", new=fake_sync_delete):
+ litellm.delete_responses(
+ response_id="resp_xyz",
+ custom_llm_provider="openai",
+ api_key="test-key",
+ )
+
+ assert _content_type(captured["headers"]) == "application/json"
+
+
# ---------------------------------------------------------------------------
# Parity tests: request-body is serialized once and reused for the wire.
# (_async_post_anthropic_messages_with_http_error_retry)
diff --git a/tests/test_litellm/proxy/hooks/test_sensitive_data_routing.py b/tests/test_litellm/proxy/hooks/test_sensitive_data_routing.py
new file mode 100644
index 00000000000..78d2c3af0f3
--- /dev/null
+++ b/tests/test_litellm/proxy/hooks/test_sensitive_data_routing.py
@@ -0,0 +1,1036 @@
+"""
+Tests for Sensitive Data Routing feature.
+
+This feature allows guardrails to route requests to a different model
+(typically on-premise) when sensitive data is detected, instead of blocking.
+All subsequent requests in the same session are routed to the same model.
+"""
+
+import asyncio
+from typing import Any, Dict, Optional
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from litellm.caching.caching import DualCache
+from litellm.exceptions import SensitiveDataRouteException
+from litellm.integrations.custom_guardrail import (
+ CustomGuardrail,
+ get_session_id_from_request_data,
+)
+from litellm.proxy._types import UserAPIKeyAuth
+from litellm.proxy.hooks.sensitive_data_routing import (
+ _PROXY_SensitiveDataRoutingHandler,
+ SENSITIVE_ROUTING_CACHE_PREFIX,
+ DEFAULT_SENSITIVE_ROUTING_TTL,
+)
+
+
+class MockInternalUsageCache:
+ def __init__(self):
+ self._cache: Dict[str, Any] = {}
+ self._ttls: Dict[str, int] = {}
+ self.dual_cache = MagicMock()
+ self.dual_cache.redis_cache = None
+
+ async def async_get_cache(self, key: str, **kwargs) -> Optional[Any]:
+ return self._cache.get(key)
+
+ async def async_set_cache(self, key: str, value: Any, ttl: int = 3600, **kwargs):
+ self._cache[key] = value
+ self._ttls[key] = ttl
+
+
+class TestSensitiveDataRoutingHandler:
+ @pytest.fixture
+ def handler(self):
+ cache = MockInternalUsageCache()
+ return _PROXY_SensitiveDataRoutingHandler(internal_usage_cache=cache)
+
+ @pytest.fixture
+ def user_api_key_dict(self):
+ return UserAPIKeyAuth(api_key="test-key")
+
+ @pytest.mark.asyncio
+ async def test_set_session_routing(self, handler):
+ key = UserAPIKeyAuth(api_key="hashed-key")
+ await handler.set_session_routing(
+ session_id="test-session-123",
+ model="on-premise-model",
+ user_api_key_dict=key,
+ guardrail_name="test-guardrail",
+ )
+
+ routed_model = await handler._get_routed_model("test-session-123", key)
+ assert routed_model == "on-premise-model"
+
+ def test_get_session_id_from_metadata(self):
+ data = {"metadata": {"session_id": "session-from-metadata"}}
+ session_id = get_session_id_from_request_data(data)
+ assert session_id == "session-from-metadata"
+
+ def test_get_session_id_from_litellm_metadata(self):
+ data = {"litellm_metadata": {"session_id": "session-from-litellm-metadata"}}
+ session_id = get_session_id_from_request_data(data)
+ assert session_id == "session-from-litellm-metadata"
+
+ def test_get_session_id_from_litellm_session_id(self):
+ data = {"litellm_session_id": "session-direct"}
+ session_id = get_session_id_from_request_data(data)
+ assert session_id == "session-direct"
+
+ @pytest.mark.asyncio
+ async def test_pre_call_hook_no_session(self, handler, user_api_key_dict):
+ data = {"model": "gpt-4"}
+ result = await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=DualCache(),
+ data=data,
+ call_type="completion",
+ )
+ assert result is None
+ assert data["model"] == "gpt-4"
+
+ @pytest.mark.asyncio
+ async def test_pre_call_hook_with_routing_override(
+ self, handler, user_api_key_dict
+ ):
+ await handler.set_session_routing(
+ session_id="routed-session",
+ model="on-premise-model",
+ user_api_key_dict=user_api_key_dict,
+ )
+
+ data = {
+ "model": "gpt-4",
+ "metadata": {"session_id": "routed-session"},
+ }
+ result = await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=DualCache(),
+ data=data,
+ call_type="completion",
+ )
+
+ assert result is not None
+ assert result["model"] == "on-premise-model"
+ assert result["metadata"]["sensitive_data_routing_applied"] is True
+ assert result["metadata"]["sensitive_data_routing_original_model"] == "gpt-4"
+
+ @pytest.mark.asyncio
+ async def test_pre_call_hook_no_override_needed(self, handler, user_api_key_dict):
+ data = {
+ "model": "gpt-4",
+ "metadata": {"session_id": "no-override-session"},
+ }
+ result = await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=DualCache(),
+ data=data,
+ call_type="completion",
+ )
+ assert result is None
+ assert data["model"] == "gpt-4"
+
+
+class TestSensitiveDataRouteException:
+ def test_exception_creation(self):
+ exc = SensitiveDataRouteException(
+ route_to_model="on-premise-model",
+ session_id="test-session",
+ guardrail_name="test-guardrail",
+ detection_info={"detected_entities": ["SSN", "CREDIT_CARD"]},
+ )
+
+ assert exc.route_to_model == "on-premise-model"
+ assert exc.session_id == "test-session"
+ assert exc.guardrail_name == "test-guardrail"
+ assert "SSN" in exc.detection_info["detected_entities"]
+
+
+class TestCustomGuardrailSensitiveDataRouting:
+ def test_should_route_on_sensitive_data_false_by_default(self):
+ guardrail = CustomGuardrail(guardrail_name="test")
+ assert guardrail.should_route_on_sensitive_data() is False
+
+ def test_should_route_on_sensitive_data_true(self):
+ guardrail = CustomGuardrail(
+ guardrail_name="test",
+ on_sensitive_data="route",
+ sensitive_data_route_to_model="on-premise-model",
+ )
+ assert guardrail.should_route_on_sensitive_data() is True
+
+ def test_should_route_on_sensitive_data_missing_model(self):
+ guardrail = CustomGuardrail(
+ guardrail_name="test",
+ on_sensitive_data="route",
+ )
+ assert guardrail.should_route_on_sensitive_data() is False
+
+ def test_raise_sensitive_data_route_exception(self):
+ guardrail = CustomGuardrail(
+ guardrail_name="test",
+ on_sensitive_data="route",
+ sensitive_data_route_to_model="on-premise-model",
+ )
+
+ request_data = {"model": "gpt-4", "metadata": {"session_id": "test-session"}}
+
+ with pytest.raises(SensitiveDataRouteException) as exc_info:
+ guardrail.raise_sensitive_data_route_exception(
+ route_to_model="on-premise-model",
+ request_data=request_data,
+ detection_info={"type": "PII"},
+ )
+
+ assert exc_info.value.route_to_model == "on-premise-model"
+ assert exc_info.value.session_id == "test-session"
+
+ def test_raise_exception_carries_sticky_flag_false(self):
+ guardrail = CustomGuardrail(
+ guardrail_name="test",
+ on_sensitive_data="route",
+ sensitive_data_route_to_model="on-premise-model",
+ sticky_session_routing=False,
+ )
+
+ request_data = {"metadata": {"session_id": "test-session"}}
+
+ with pytest.raises(SensitiveDataRouteException) as exc_info:
+ guardrail.raise_sensitive_data_route_exception(
+ route_to_model="on-premise-model",
+ request_data=request_data,
+ )
+
+ assert exc_info.value.sticky_session_routing is False
+
+ def test_raise_exception_carries_sticky_flag_default_true(self):
+ guardrail = CustomGuardrail(
+ guardrail_name="test",
+ on_sensitive_data="route",
+ sensitive_data_route_to_model="on-premise-model",
+ )
+
+ request_data = {"metadata": {"session_id": "test-session"}}
+
+ with pytest.raises(SensitiveDataRouteException) as exc_info:
+ guardrail.raise_sensitive_data_route_exception(
+ route_to_model="on-premise-model",
+ request_data=request_data,
+ )
+
+ assert exc_info.value.sticky_session_routing is True
+
+ def test_raise_sensitive_data_route_exception_missing_session(self):
+ guardrail = CustomGuardrail(guardrail_name="test")
+
+ request_data = {"model": "gpt-4"}
+
+ with pytest.raises(ValueError) as exc_info:
+ guardrail.raise_sensitive_data_route_exception(
+ route_to_model="on-premise-model",
+ request_data=request_data,
+ )
+
+ assert "session_id" in str(exc_info.value)
+
+ def test_handle_sensitive_data_detection_route(self):
+ guardrail = CustomGuardrail(
+ guardrail_name="test",
+ on_sensitive_data="route",
+ sensitive_data_route_to_model="on-premise-model",
+ )
+
+ request_data = {"model": "gpt-4", "metadata": {"session_id": "test-session"}}
+
+ with pytest.raises(SensitiveDataRouteException) as exc_info:
+ guardrail.handle_sensitive_data_detection(
+ request_data=request_data,
+ detection_info={"type": "PII"},
+ )
+
+ assert exc_info.value.route_to_model == "on-premise-model"
+
+ def test_handle_sensitive_data_detection_block(self):
+ from litellm.exceptions import GuardrailRaisedException
+
+ guardrail = CustomGuardrail(guardrail_name="test")
+
+ request_data = {"model": "gpt-4", "metadata": {"session_id": "test-session"}}
+
+ with pytest.raises(GuardrailRaisedException):
+ guardrail.handle_sensitive_data_detection(
+ request_data=request_data,
+ )
+
+ def test_handle_sensitive_data_detection_route_no_session_falls_back_to_block(self):
+ from litellm.exceptions import GuardrailRaisedException
+
+ guardrail = CustomGuardrail(
+ guardrail_name="test",
+ on_sensitive_data="route",
+ sensitive_data_route_to_model="on-premise-model",
+ )
+
+ request_data = {"model": "gpt-4"}
+
+ with pytest.raises(GuardrailRaisedException) as exc_info:
+ guardrail.handle_sensitive_data_detection(
+ request_data=request_data,
+ detection_info={"type": "PII"},
+ )
+
+ assert "session_id" in str(exc_info.value)
+
+
+class TestStickySessionRouting:
+ @pytest.fixture
+ def handler(self):
+ cache = MockInternalUsageCache()
+ return _PROXY_SensitiveDataRoutingHandler(internal_usage_cache=cache)
+
+ @pytest.fixture
+ def user_api_key_dict(self):
+ return UserAPIKeyAuth(api_key="test-key")
+
+ @pytest.mark.asyncio
+ async def test_sticky_routing_persists(self, handler, user_api_key_dict):
+ session_id = "sticky-session"
+ await handler.set_session_routing(
+ session_id=session_id,
+ model="on-premise-model",
+ user_api_key_dict=user_api_key_dict,
+ )
+
+ for i in range(5):
+ data = {
+ "model": f"gpt-{i}",
+ "metadata": {"session_id": session_id},
+ }
+ result = await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=DualCache(),
+ data=data,
+ call_type="completion",
+ )
+
+ assert result is not None
+ assert result["model"] == "on-premise-model"
+ assert (
+ result["metadata"]["sensitive_data_routing_original_model"]
+ == f"gpt-{i}"
+ )
+
+ @pytest.mark.asyncio
+ async def test_different_sessions_independent(self, handler, user_api_key_dict):
+ await handler.set_session_routing(
+ session_id="session-a",
+ model="on-premise-model-a",
+ user_api_key_dict=user_api_key_dict,
+ )
+ await handler.set_session_routing(
+ session_id="session-b",
+ model="on-premise-model-b",
+ user_api_key_dict=user_api_key_dict,
+ )
+
+ data_a = {"model": "gpt-4", "metadata": {"session_id": "session-a"}}
+ data_b = {"model": "gpt-4", "metadata": {"session_id": "session-b"}}
+ data_c = {"model": "gpt-4", "metadata": {"session_id": "session-c"}}
+
+ result_a = await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=DualCache(),
+ data=data_a,
+ call_type="completion",
+ )
+ result_b = await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=DualCache(),
+ data=data_b,
+ call_type="completion",
+ )
+ result_c = await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=DualCache(),
+ data=data_c,
+ call_type="completion",
+ )
+
+ assert result_a["model"] == "on-premise-model-a"
+ assert result_b["model"] == "on-premise-model-b"
+ assert result_c is None
+
+ @pytest.mark.asyncio
+ async def test_routing_is_isolated_per_api_key(self, handler):
+ shared_session = "shared-session-id"
+ await handler.set_session_routing(
+ session_id=shared_session,
+ model="on-premise-model",
+ user_api_key_dict=UserAPIKeyAuth(api_key="tenant-a"),
+ )
+
+ data_for_tenant_b = {
+ "model": "gpt-4",
+ "metadata": {"session_id": shared_session},
+ }
+ result = await handler.async_pre_call_hook(
+ user_api_key_dict=UserAPIKeyAuth(api_key="tenant-b"),
+ cache=DualCache(),
+ data=data_for_tenant_b,
+ call_type="completion",
+ )
+ assert result is None
+ assert data_for_tenant_b["model"] == "gpt-4"
+
+ data_for_tenant_a = {
+ "model": "gpt-4",
+ "metadata": {"session_id": shared_session},
+ }
+ result = await handler.async_pre_call_hook(
+ user_api_key_dict=UserAPIKeyAuth(api_key="tenant-a"),
+ cache=DualCache(),
+ data=data_for_tenant_a,
+ call_type="completion",
+ )
+ assert result is not None
+ assert result["model"] == "on-premise-model"
+
+
+class TestCacheKeyAndTTL:
+ def test_cache_prefix_constant(self):
+ assert SENSITIVE_ROUTING_CACHE_PREFIX == "sensitive_route"
+
+ def test_default_ttl_constant(self):
+ assert DEFAULT_SENSITIVE_ROUTING_TTL == 3600
+
+ def test_make_cache_key_format(self):
+ cache = MockInternalUsageCache()
+ handler = _PROXY_SensitiveDataRoutingHandler(internal_usage_cache=cache)
+ key = handler._make_cache_key("test-session-123", "hashed-key")
+ assert key == "{sensitive_route:hashed-key:test-session-123}:model"
+
+ def test_make_cache_key_is_tenant_scoped(self):
+ cache = MockInternalUsageCache()
+ handler = _PROXY_SensitiveDataRoutingHandler(internal_usage_cache=cache)
+ key_a = handler._make_cache_key("shared-session", "key-a")
+ key_b = handler._make_cache_key("shared-session", "key-b")
+ assert key_a != key_b
+
+ def test_resolve_tenant_prefers_api_key(self):
+ tenant = _PROXY_SensitiveDataRoutingHandler._resolve_tenant(
+ UserAPIKeyAuth(api_key="hashed-key", user_id="alice")
+ )
+ assert tenant == "hashed-key"
+
+ def test_resolve_tenant_falls_back_to_jwt_principal(self):
+ tenant = _PROXY_SensitiveDataRoutingHandler._resolve_tenant(
+ UserAPIKeyAuth(api_key=None, user_id="alice", team_id="t1", org_id="o1")
+ )
+ assert tenant == "user:alice|team:t1|org:o1"
+
+ def test_resolve_tenant_distinguishes_keyless_principals(self):
+ tenant_a = _PROXY_SensitiveDataRoutingHandler._resolve_tenant(
+ UserAPIKeyAuth(api_key=None, user_id="alice")
+ )
+ tenant_b = _PROXY_SensitiveDataRoutingHandler._resolve_tenant(
+ UserAPIKeyAuth(api_key=None, user_id="bob")
+ )
+ assert tenant_a != tenant_b
+
+ def test_resolve_tenant_defaults_when_anonymous(self):
+ assert _PROXY_SensitiveDataRoutingHandler._resolve_tenant(None) == "default"
+ assert (
+ _PROXY_SensitiveDataRoutingHandler._resolve_tenant(
+ UserAPIKeyAuth(api_key=None)
+ )
+ == "default"
+ )
+
+
+class TestCustomGuardrailSessionIdExtraction:
+ def test_get_session_id_from_litellm_session_id(self):
+ guardrail = CustomGuardrail(guardrail_name="test")
+ request_data = {"litellm_session_id": "session-direct-123"}
+ session_id = guardrail._get_session_id_from_request_data(request_data)
+ assert session_id == "session-direct-123"
+
+ def test_get_session_id_from_metadata(self):
+ guardrail = CustomGuardrail(guardrail_name="test")
+ request_data = {"metadata": {"session_id": "session-metadata-456"}}
+ session_id = guardrail._get_session_id_from_request_data(request_data)
+ assert session_id == "session-metadata-456"
+
+ def test_get_session_id_from_litellm_metadata(self):
+ guardrail = CustomGuardrail(guardrail_name="test")
+ request_data = {"litellm_metadata": {"session_id": "session-litellm-meta-789"}}
+ session_id = guardrail._get_session_id_from_request_data(request_data)
+ assert session_id == "session-litellm-meta-789"
+
+ def test_get_session_id_returns_none_when_missing(self):
+ guardrail = CustomGuardrail(guardrail_name="test")
+ request_data = {"model": "gpt-4"}
+ session_id = guardrail._get_session_id_from_request_data(request_data)
+ assert session_id is None
+
+ def test_get_session_id_priority_litellm_session_id_first(self):
+ guardrail = CustomGuardrail(guardrail_name="test")
+ request_data = {
+ "litellm_session_id": "priority-session",
+ "metadata": {"session_id": "should-not-use"},
+ "litellm_metadata": {"session_id": "also-not-this"},
+ }
+ session_id = guardrail._get_session_id_from_request_data(request_data)
+ assert session_id == "priority-session"
+
+ def test_get_session_id_converts_to_string(self):
+ guardrail = CustomGuardrail(guardrail_name="test")
+ request_data = {"litellm_session_id": 12345}
+ session_id = guardrail._get_session_id_from_request_data(request_data)
+ assert session_id == "12345"
+ assert isinstance(session_id, str)
+
+
+class TestCustomGuardrailInit:
+ def test_init_with_routing_config(self):
+ guardrail = CustomGuardrail(
+ guardrail_name="test-guardrail",
+ on_sensitive_data="route",
+ sensitive_data_route_to_model="on-premise-model",
+ sticky_session_routing=True,
+ )
+ assert guardrail.on_sensitive_data == "route"
+ assert guardrail.sensitive_data_route_to_model == "on-premise-model"
+ assert guardrail.sticky_session_routing is True
+
+ def test_init_default_values(self):
+ guardrail = CustomGuardrail(guardrail_name="test")
+ assert guardrail.on_sensitive_data is None
+ assert guardrail.sensitive_data_route_to_model is None
+ assert guardrail.sticky_session_routing is True
+
+
+class TestSensitiveDataRouteExceptionStr:
+ def test_exception_str_representation(self):
+ exc = SensitiveDataRouteException(
+ route_to_model="on-premise-model",
+ session_id="test-session",
+ guardrail_name="pii-detector",
+ )
+ assert (
+ str(exc)
+ == "Sensitive data detected by pii-detector. Routing to model: on-premise-model"
+ )
+
+ def test_exception_custom_message(self):
+ exc = SensitiveDataRouteException(
+ route_to_model="on-premise-model",
+ session_id="test-session",
+ guardrail_name="pii-detector",
+ message="Custom error message",
+ )
+ assert str(exc) == "Custom error message"
+ assert exc.message == "Custom error message"
+
+
+class TestRedisCache:
+ @pytest.fixture
+ def handler_with_redis(self):
+ cache = MockInternalUsageCache()
+ mock_redis = AsyncMock()
+ cache.dual_cache.redis_cache = mock_redis
+ return _PROXY_SensitiveDataRoutingHandler(internal_usage_cache=cache)
+
+ @pytest.mark.asyncio
+ async def test_get_routed_model_from_redis(self, handler_with_redis):
+ handler_with_redis.internal_usage_cache.dual_cache.redis_cache.async_get_cache = AsyncMock(
+ return_value="redis-model"
+ )
+ result = await handler_with_redis._get_routed_model(
+ "session-123", UserAPIKeyAuth(api_key="hashed-key")
+ )
+ assert result == "redis-model"
+
+ @pytest.mark.asyncio
+ async def test_get_routed_model_backfills_in_memory_after_redis_hit(
+ self, handler_with_redis
+ ):
+ cache_key = "{sensitive_route:hashed-key:session-123}:model"
+ key = UserAPIKeyAuth(api_key="hashed-key")
+ handler_with_redis.internal_usage_cache.dual_cache.redis_cache.async_get_cache = AsyncMock(
+ return_value="on-premise-model"
+ )
+ handler_with_redis.internal_usage_cache.dual_cache.redis_cache.async_get_ttl = (
+ AsyncMock(return_value=120)
+ )
+
+ first = await handler_with_redis._get_routed_model("session-123", key)
+ assert first == "on-premise-model"
+ assert handler_with_redis.internal_usage_cache._cache[cache_key] == (
+ "on-premise-model"
+ )
+
+ handler_with_redis.internal_usage_cache.dual_cache.redis_cache.async_get_cache = AsyncMock(
+ side_effect=Exception("Redis went down")
+ )
+ second = await handler_with_redis._get_routed_model("session-123", key)
+ assert second == "on-premise-model"
+
+ @pytest.mark.asyncio
+ async def test_backfill_uses_remaining_redis_ttl(self, handler_with_redis):
+ cache_key = "{sensitive_route:hashed-key:session-123}:model"
+ key = UserAPIKeyAuth(api_key="hashed-key")
+ handler_with_redis.internal_usage_cache.dual_cache.redis_cache.async_get_cache = AsyncMock(
+ return_value="on-premise-model"
+ )
+ handler_with_redis.internal_usage_cache.dual_cache.redis_cache.async_get_ttl = (
+ AsyncMock(return_value=42)
+ )
+
+ await handler_with_redis._get_routed_model("session-123", key)
+
+ assert handler_with_redis.internal_usage_cache._ttls[cache_key] == 42
+
+ @pytest.mark.asyncio
+ async def test_backfill_falls_back_to_full_ttl_when_redis_ttl_missing(
+ self, handler_with_redis
+ ):
+ cache_key = "{sensitive_route:hashed-key:session-123}:model"
+ key = UserAPIKeyAuth(api_key="hashed-key")
+ handler_with_redis.internal_usage_cache.dual_cache.redis_cache.async_get_cache = AsyncMock(
+ return_value="on-premise-model"
+ )
+ handler_with_redis.internal_usage_cache.dual_cache.redis_cache.async_get_ttl = (
+ AsyncMock(return_value=None)
+ )
+
+ await handler_with_redis._get_routed_model("session-123", key)
+
+ assert (
+ handler_with_redis.internal_usage_cache._ttls[cache_key]
+ == handler_with_redis.ttl
+ )
+
+ @pytest.mark.asyncio
+ async def test_get_routed_model_redis_fallback_on_error(self, handler_with_redis):
+ handler_with_redis.internal_usage_cache.dual_cache.redis_cache.async_get_cache = AsyncMock(
+ side_effect=Exception("Redis connection error")
+ )
+ handler_with_redis.internal_usage_cache._cache[
+ "{sensitive_route:hashed-key:session-123}:model"
+ ] = "fallback-model"
+ result = await handler_with_redis._get_routed_model(
+ "session-123", UserAPIKeyAuth(api_key="hashed-key")
+ )
+ assert result == "fallback-model"
+
+ @pytest.mark.asyncio
+ async def test_set_session_routing_with_redis(self, handler_with_redis):
+ handler_with_redis.internal_usage_cache.dual_cache.redis_cache.async_set_cache = (
+ AsyncMock()
+ )
+ await handler_with_redis.set_session_routing(
+ session_id="session-456",
+ model="on-premise-model",
+ user_api_key_dict=UserAPIKeyAuth(api_key="hashed-key"),
+ guardrail_name="test-guardrail",
+ )
+ handler_with_redis.internal_usage_cache.dual_cache.redis_cache.async_set_cache.assert_called_once()
+
+ @pytest.mark.asyncio
+ async def test_set_session_routing_redis_fallback_on_error(
+ self, handler_with_redis
+ ):
+ handler_with_redis.internal_usage_cache.dual_cache.redis_cache.async_set_cache = AsyncMock(
+ side_effect=Exception("Redis connection error")
+ )
+ await handler_with_redis.set_session_routing(
+ session_id="session-789",
+ model="on-premise-model",
+ user_api_key_dict=UserAPIKeyAuth(api_key="hashed-key"),
+ )
+ cache_key = "{sensitive_route:hashed-key:session-789}:model"
+ assert (
+ handler_with_redis.internal_usage_cache._cache[cache_key]
+ == "on-premise-model"
+ )
+
+
+class TestPreCallHookEdgeCases:
+ @pytest.fixture
+ def handler(self):
+ cache = MockInternalUsageCache()
+ return _PROXY_SensitiveDataRoutingHandler(internal_usage_cache=cache)
+
+ @pytest.fixture
+ def user_api_key_dict(self):
+ return UserAPIKeyAuth(api_key="test-key")
+
+ @pytest.mark.asyncio
+ async def test_pre_call_hook_same_model_no_change(self, handler, user_api_key_dict):
+ await handler.set_session_routing(
+ session_id="same-model-session",
+ model="gpt-4",
+ user_api_key_dict=user_api_key_dict,
+ )
+ data = {
+ "model": "gpt-4",
+ "metadata": {"session_id": "same-model-session"},
+ }
+ result = await handler.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=DualCache(),
+ data=data,
+ call_type="completion",
+ )
+ assert result is None
+
+
+class TestHandleSensitiveDataDetectionWithRouting:
+ def test_handle_sensitive_data_detection_full_flow(self):
+ guardrail = CustomGuardrail(
+ guardrail_name="pii-guardrail",
+ on_sensitive_data="route",
+ sensitive_data_route_to_model="on-premise-model",
+ )
+
+ request_data = {
+ "model": "gpt-4",
+ "metadata": {"session_id": "flow-test-session"},
+ "messages": [{"role": "user", "content": "My SSN is 123-45-6789"}],
+ }
+
+ with pytest.raises(SensitiveDataRouteException) as exc_info:
+ guardrail.handle_sensitive_data_detection(
+ request_data=request_data,
+ detection_info={"detected_entities": ["SSN"]},
+ )
+
+ exc = exc_info.value
+ assert exc.route_to_model == "on-premise-model"
+ assert exc.session_id == "flow-test-session"
+ assert exc.guardrail_name == "pii-guardrail"
+ assert exc.detection_info == {"detected_entities": ["SSN"]}
+
+
+class TestProxyHandleSensitiveDataRouteException:
+ @pytest.fixture
+ def proxy_logging(self):
+ from litellm.proxy.utils import ProxyLogging
+
+ return ProxyLogging(user_api_key_cache=DualCache())
+
+ @pytest.fixture
+ def routing_hook(self):
+ cache = MockInternalUsageCache()
+ return _PROXY_SensitiveDataRoutingHandler(internal_usage_cache=cache)
+
+ @pytest.mark.asyncio
+ async def test_sticky_routing_persists_override(self, proxy_logging, routing_hook):
+ proxy_logging.proxy_hook_mapping["sensitive_data_routing"] = routing_hook
+ exc = SensitiveDataRouteException(
+ route_to_model="on-premise-model",
+ session_id="sess-sticky",
+ guardrail_name="pii",
+ sticky_session_routing=True,
+ )
+ data = {"model": "gpt-4", "metadata": {"session_id": "sess-sticky"}}
+
+ result = await proxy_logging._handle_sensitive_data_route_exception(
+ exc, data, UserAPIKeyAuth(api_key="tenant-a")
+ )
+
+ assert result["model"] == "on-premise-model"
+ assert (
+ await routing_hook._get_routed_model(
+ "sess-sticky", UserAPIKeyAuth(api_key="tenant-a")
+ )
+ == "on-premise-model"
+ )
+
+ @pytest.mark.asyncio
+ async def test_non_sticky_routing_does_not_persist_override(
+ self, proxy_logging, routing_hook
+ ):
+ proxy_logging.proxy_hook_mapping["sensitive_data_routing"] = routing_hook
+ exc = SensitiveDataRouteException(
+ route_to_model="on-premise-model",
+ session_id="sess-non-sticky",
+ guardrail_name="pii",
+ sticky_session_routing=False,
+ )
+ data = {"model": "gpt-4", "metadata": {"session_id": "sess-non-sticky"}}
+
+ result = await proxy_logging._handle_sensitive_data_route_exception(
+ exc, data, UserAPIKeyAuth(api_key="tenant-a")
+ )
+
+ assert result["model"] == "on-premise-model"
+ assert (
+ await routing_hook._get_routed_model(
+ "sess-non-sticky", UserAPIKeyAuth(api_key="tenant-a")
+ )
+ is None
+ )
+
+ @pytest.mark.asyncio
+ async def test_sticky_routing_handles_none_user_api_key_dict(
+ self, proxy_logging, routing_hook
+ ):
+ proxy_logging.proxy_hook_mapping["sensitive_data_routing"] = routing_hook
+ exc = SensitiveDataRouteException(
+ route_to_model="on-premise-model",
+ session_id="sess-no-key",
+ guardrail_name="pii",
+ sticky_session_routing=True,
+ )
+ data = {"model": "gpt-4", "metadata": {"session_id": "sess-no-key"}}
+
+ result = await proxy_logging._handle_sensitive_data_route_exception(
+ exc, data, None
+ )
+
+ assert result["model"] == "on-premise-model"
+ assert (
+ await routing_hook._get_routed_model("sess-no-key", None)
+ == "on-premise-model"
+ )
+
+ @pytest.mark.asyncio
+ async def test_sticky_routing_scopes_jwt_users_by_principal(
+ self, proxy_logging, routing_hook
+ ):
+ proxy_logging.proxy_hook_mapping["sensitive_data_routing"] = routing_hook
+ exc = SensitiveDataRouteException(
+ route_to_model="on-premise-model",
+ session_id="shared-jwt-session",
+ guardrail_name="pii",
+ sticky_session_routing=True,
+ )
+ attacker = UserAPIKeyAuth(api_key=None, user_id="attacker", team_id="team-x")
+ await proxy_logging._handle_sensitive_data_route_exception(
+ exc,
+ {"model": "gpt-4", "metadata": {"session_id": "shared-jwt-session"}},
+ attacker,
+ )
+
+ victim = UserAPIKeyAuth(api_key=None, user_id="victim", team_id="team-y")
+ victim_data = {
+ "model": "gpt-4",
+ "metadata": {"session_id": "shared-jwt-session"},
+ }
+ result = await routing_hook.async_pre_call_hook(
+ user_api_key_dict=victim,
+ cache=DualCache(),
+ data=victim_data,
+ call_type="completion",
+ )
+ assert result is None
+ assert victim_data["model"] == "gpt-4"
+
+ attacker_data = {
+ "model": "gpt-4",
+ "metadata": {"session_id": "shared-jwt-session"},
+ }
+ result = await routing_hook.async_pre_call_hook(
+ user_api_key_dict=attacker,
+ cache=DualCache(),
+ data=attacker_data,
+ call_type="completion",
+ )
+ assert result is not None
+ assert result["model"] == "on-premise-model"
+
+ @pytest.mark.asyncio
+ async def test_sticky_routing_warns_when_hook_not_registered(self, proxy_logging):
+ exc = SensitiveDataRouteException(
+ route_to_model="on-premise-model",
+ session_id="sess-no-hook",
+ sticky_session_routing=True,
+ )
+ data = {"model": "gpt-4", "metadata": {"session_id": "sess-no-hook"}}
+
+ with patch("litellm.proxy.utils.verbose_proxy_logger.warning") as mock_warning:
+ result = await proxy_logging._handle_sensitive_data_route_exception(
+ exc, data, UserAPIKeyAuth(api_key="tenant-a")
+ )
+
+ assert result["model"] == "on-premise-model"
+ mock_warning.assert_called_once()
+
+
+class _RoutingGuardrail(CustomGuardrail):
+ async def async_pre_call_hook(self, user_api_key_dict, cache, data, call_type):
+ self.handle_sensitive_data_detection(request_data=data)
+
+
+class _RecordingGuardrail(CustomGuardrail):
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self.ran = False
+
+ async def async_pre_call_hook(self, user_api_key_dict, cache, data, call_type):
+ self.ran = True
+ return None
+
+
+class _BlockingGuardrail(CustomGuardrail):
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self.ran = False
+
+ async def async_pre_call_hook(self, user_api_key_dict, cache, data, call_type):
+ from litellm.exceptions import GuardrailRaisedException
+
+ self.ran = True
+ raise GuardrailRaisedException(
+ message="blocked", guardrail_name=self.guardrail_name
+ )
+
+
+class TestPreCallHookDeferredRouting:
+ """Guardrails after the one that triggers routing must still run."""
+
+ @pytest.fixture
+ def proxy_logging(self):
+ from litellm.proxy.utils import ProxyLogging
+
+ return ProxyLogging(user_api_key_cache=DualCache())
+
+ @pytest.fixture(autouse=True)
+ def restore_callbacks(self):
+ import litellm
+
+ original = litellm.callbacks
+ litellm.callbacks = []
+ yield
+ litellm.callbacks = original
+
+ @pytest.mark.asyncio
+ async def test_later_guardrail_runs_and_routing_applied(self, proxy_logging):
+ import litellm
+
+ router = _RoutingGuardrail(
+ guardrail_name="router",
+ default_on=True,
+ event_hook="pre_call",
+ on_sensitive_data="route",
+ sensitive_data_route_to_model="on-prem-model",
+ sticky_session_routing=False,
+ )
+ recorder = _RecordingGuardrail(
+ guardrail_name="recorder",
+ default_on=True,
+ event_hook="pre_call",
+ )
+ litellm.callbacks = [router, recorder]
+
+ data = {"model": "gpt-4", "metadata": {"session_id": "sess-defer"}}
+ result = await proxy_logging.pre_call_hook(
+ user_api_key_dict=UserAPIKeyAuth(api_key="tenant-a"),
+ data=data,
+ call_type="completion",
+ )
+
+ assert recorder.ran is True
+ assert result["model"] == "on-prem-model"
+ assert result["metadata"]["sensitive_data_routing_applied"] is True
+
+ @pytest.mark.asyncio
+ async def test_later_blocking_guardrail_overrides_routing(self, proxy_logging):
+ import litellm
+ from litellm.exceptions import GuardrailRaisedException
+
+ router = _RoutingGuardrail(
+ guardrail_name="router",
+ default_on=True,
+ event_hook="pre_call",
+ on_sensitive_data="route",
+ sensitive_data_route_to_model="on-prem-model",
+ sticky_session_routing=False,
+ )
+ blocker = _BlockingGuardrail(
+ guardrail_name="blocker",
+ default_on=True,
+ event_hook="pre_call",
+ )
+ litellm.callbacks = [router, blocker]
+
+ data = {"model": "gpt-4", "metadata": {"session_id": "sess-block"}}
+ with pytest.raises(GuardrailRaisedException):
+ await proxy_logging.pre_call_hook(
+ user_api_key_dict=UserAPIKeyAuth(api_key="tenant-a"),
+ data=data,
+ call_type="completion",
+ )
+
+ assert blocker.ran is True
+
+ @pytest.mark.asyncio
+ async def test_routing_guardrail_records_service_span(self, proxy_logging):
+ import litellm
+ from litellm.types.services import ServiceTypes
+
+ class _SlowRoutingGuardrail(CustomGuardrail):
+ async def async_pre_call_hook(
+ self, user_api_key_dict, cache, data, call_type
+ ):
+ await asyncio.sleep(0.02)
+ self.handle_sensitive_data_detection(request_data=data)
+
+ router = _SlowRoutingGuardrail(
+ guardrail_name="router",
+ default_on=True,
+ event_hook="pre_call",
+ on_sensitive_data="route",
+ sensitive_data_route_to_model="on-prem-model",
+ sticky_session_routing=False,
+ )
+ litellm.callbacks = [router]
+
+ recorded = AsyncMock()
+ proxy_logging.service_logging_obj.async_service_success_hook = recorded
+
+ data = {"model": "gpt-4", "metadata": {"session_id": "sess-span"}}
+ result = await proxy_logging.pre_call_hook(
+ user_api_key_dict=UserAPIKeyAuth(api_key="tenant-a"),
+ data=data,
+ call_type="completion",
+ )
+
+ assert result["model"] == "on-prem-model"
+ recorded.assert_called_once()
+ assert recorded.call_args.kwargs["call_type"] == "_SlowRoutingGuardrail"
+ assert recorded.call_args.kwargs["service"] == ServiceTypes.PROXY_PRE_CALL
+
+ @pytest.mark.asyncio
+ async def test_routing_recorded_as_intervention_not_prometheus_error(
+ self, proxy_logging
+ ):
+ import litellm
+ from litellm.integrations.prometheus import PrometheusLogger
+
+ router = _RoutingGuardrail(
+ guardrail_name="router",
+ default_on=True,
+ event_hook="pre_call",
+ on_sensitive_data="route",
+ sensitive_data_route_to_model="on-prem-model",
+ sticky_session_routing=False,
+ )
+ prom = MagicMock(spec=PrometheusLogger)
+ litellm.callbacks = [router, prom]
+
+ data = {"model": "gpt-4", "metadata": {"session_id": "sess-prom"}}
+ result = await proxy_logging.pre_call_hook(
+ user_api_key_dict=UserAPIKeyAuth(api_key="tenant-a"),
+ data=data,
+ call_type="completion",
+ )
+
+ assert result["model"] == "on-prem-model"
+ prom._record_guardrail_metrics.assert_called_once()
+ metrics_kwargs = prom._record_guardrail_metrics.call_args.kwargs
+ assert metrics_kwargs["status"] == "intervened"
+ assert metrics_kwargs["error_type"] is None
diff --git a/tests/test_litellm/types/test_guardrails_case_normalization.py b/tests/test_litellm/types/test_guardrails_case_normalization.py
index e1e03fe6b88..3e7a573ea8e 100644
--- a/tests/test_litellm/types/test_guardrails_case_normalization.py
+++ b/tests/test_litellm/types/test_guardrails_case_normalization.py
@@ -3,7 +3,9 @@ Test case normalization in LitellmParams for all guardrail types
"""
import pytest
-from litellm.types.guardrails import LitellmParams
+from pydantic import ValidationError
+
+from litellm.types.guardrails import BaseLitellmParams, LitellmParams
class TestLitellmParamsCaseNormalization:
@@ -89,3 +91,66 @@ class TestLitellmParamsCaseNormalization:
)
assert params.on_disallowed_action in ["block", "rewrite"]
assert params.on_disallowed_action.islower()
+
+
+class TestSensitiveDataRoutingValidation:
+ """on_sensitive_data='route' requires a target model to be set"""
+
+ def test_route_with_target_model_is_valid(self):
+ params = LitellmParams(
+ guardrail="presidio",
+ mode="pre_call",
+ on_sensitive_data="route",
+ sensitive_data_route_to_model="on-prem-model",
+ )
+ assert params.on_sensitive_data == "route"
+ assert params.sensitive_data_route_to_model == "on-prem-model"
+
+ def test_route_without_target_model_raises(self):
+ with pytest.raises(ValidationError, match="sensitive_data_route_to_model"):
+ LitellmParams(
+ guardrail="presidio",
+ mode="pre_call",
+ on_sensitive_data="route",
+ )
+
+ def test_base_params_route_without_target_model_raises(self):
+ with pytest.raises(ValidationError, match="sensitive_data_route_to_model"):
+ BaseLitellmParams(on_sensitive_data="route")
+
+ def test_base_params_normalize_on_sensitive_data_case(self):
+ params = BaseLitellmParams(
+ on_sensitive_data="Route",
+ sensitive_data_route_to_model="on-prem-model",
+ )
+ assert params.on_sensitive_data == "route"
+
+ def test_base_params_capitalized_route_without_target_model_raises(self):
+ with pytest.raises(ValidationError, match="sensitive_data_route_to_model"):
+ BaseLitellmParams(on_sensitive_data="ROUTE")
+
+ def test_block_without_target_model_is_valid(self):
+ params = LitellmParams(
+ guardrail="presidio",
+ mode="pre_call",
+ on_sensitive_data="block",
+ )
+ assert params.on_sensitive_data == "block"
+ assert params.sensitive_data_route_to_model is None
+
+ def test_on_sensitive_data_is_case_normalized(self):
+ params = LitellmParams(
+ guardrail="presidio",
+ mode="pre_call",
+ on_sensitive_data="Route",
+ sensitive_data_route_to_model="on-prem-model",
+ )
+ assert params.on_sensitive_data == "route"
+
+ def test_on_sensitive_data_uppercase_block_normalized(self):
+ params = LitellmParams(
+ guardrail="presidio",
+ mode="pre_call",
+ on_sensitive_data="BLOCK",
+ )
+ assert params.on_sensitive_data == "block"