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]

[Feat - Guardrails] Expose /apply_guardrail endpoint for directly calling guardrail (#10867)

Ishaan Jaff3d37cc68f6ac
diff --git a/enterprise/litellm_enterprise/proxy/guardrails/endpoints.py b/enterprise/litellm_enterprise/proxy/guardrails/endpoints.py
new file mode 100644
index 00000000000..cdf86dcea67
--- /dev/null
+++ b/enterprise/litellm_enterprise/proxy/guardrails/endpoints.py
@@ -0,0 +1,41 @@
+"""
+Enterprise Guardrail Routes on LiteLLM Proxy
+
+To see all free guardrails see litellm/proxy/guardrails/*
+
+
+Exposed Routes:
+- /mask_pii
+"""
+from typing import Optional
+
+from fastapi import APIRouter, Depends
+
+from litellm.integrations.custom_guardrail import CustomGuardrail
+from litellm.proxy._types import UserAPIKeyAuth
+from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
+from litellm.proxy.guardrails.guardrail_endpoints import GUARDRAIL_REGISTRY
+from litellm.types.guardrails import ApplyGuardrailRequest, ApplyGuardrailResponse
+
+router = APIRouter(tags=["guardrails"], prefix="/guardrails")
+
+
[email protected]("/apply_guardrail", response_model=ApplyGuardrailResponse)
+async def apply_guardrail(
+ request: ApplyGuardrailRequest,
+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
+):
+ """
+ Mask PII from a given text, requires a guardrail to be added to litellm.
+ """
+ active_guardrail: Optional[
+ CustomGuardrail
+ ] = GUARDRAIL_REGISTRY.get_initialized_guardrail_callback(
+ guardrail_name=request.guardrail_name
+ )
+ if active_guardrail is None:
+ raise Exception(f"Guardrail {request.guardrail_name} not found")
+
+ return await active_guardrail.apply_guardrail(
+ text=request.text, language=request.language, entities=request.entities
+ )
diff --git a/litellm/integrations/custom_guardrail.py b/litellm/integrations/custom_guardrail.py
index 3737422ce19..c157b3aa605 100644
--- a/litellm/integrations/custom_guardrail.py
+++ b/litellm/integrations/custom_guardrail.py
@@ -2,7 +2,11 @@ from typing import Dict, List, Literal, Optional, Union
from litellm._logging import verbose_logger
from litellm.integrations.custom_logger import CustomLogger
-from litellm.types.guardrails import DynamicGuardrailParams, GuardrailEventHooks
+from litellm.types.guardrails import (
+ DynamicGuardrailParams,
+ GuardrailEventHooks,
+ PiiEntityType,
+)
from litellm.types.utils import StandardLoggingGuardrailInformation
@@ -215,6 +219,31 @@ class CustomGuardrail(CustomLogger):
"unable to log guardrail information. No metadata found in request_data"
)
+ async def apply_guardrail(
+ self,
+ text: str,
+ language: Optional[str] = None,
+ entities: Optional[List[PiiEntityType]] = None,
+ ) -> str:
+ """
+ Apply your guardrail logic to the given text
+
+ Args:
+ text: The text to apply the guardrail to
+ language: The language of the text
+ entities: The entities to mask, optional
+
+ Any of the custom guardrails can override this method to provide custom guardrail logic
+
+ Returns the text with the guardrail applied
+
+ Raises:
+ Exception:
+ - If the guardrail raises an exception
+
+ """
+ return text
+
def log_guardrail_information(func):
"""
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index 938a2c88a73..04a58702e45 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -334,7 +334,16 @@ class LiteLLMRoutes(enum.Enum):
"/mcp/tools/call",
]
- llm_api_routes = openai_routes + anthropic_routes + mapped_pass_through_routes
+ apply_guardrail_routes = [
+ "/guardrails/apply_guardrail",
+ ]
+
+ llm_api_routes = (
+ openai_routes
+ + anthropic_routes
+ + mapped_pass_through_routes
+ + apply_guardrail_routes
+ )
info_routes = [
"/key/info",
"/key/health",
diff --git a/litellm/proxy/guardrails/guardrail_hooks/presidio.py b/litellm/proxy/guardrails/guardrail_hooks/presidio.py
index f4ead5a5799..95fc6915ad0 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/presidio.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/presidio.py
@@ -14,7 +14,6 @@ import uuid
from typing import Any, Dict, List, Optional, Tuple, Union, cast
import aiohttp
-from pydantic import BaseModel
import litellm # noqa: E401
from litellm import get_secret
@@ -26,7 +25,12 @@ from litellm.integrations.custom_guardrail import (
log_guardrail_information,
)
from litellm.proxy._types import UserAPIKeyAuth
-from litellm.types.guardrails import GuardrailEventHooks, PiiAction, PiiEntityType
+from litellm.types.guardrails import (
+ GuardrailEventHooks,
+ PiiAction,
+ PiiEntityType,
+ PresidioPerRequestConfig,
+)
from litellm.types.proxy.guardrails.guardrail_hooks.presidio import (
PresidioAnalyzeRequest,
PresidioAnalyzeResponseItem,
@@ -40,15 +44,6 @@ from litellm.utils import (
)
-class PresidioPerRequestConfig(BaseModel):
- """
- presdio params that can be controlled per request, api key
- """
-
- language: Optional[str] = None
- entities: Optional[List[PiiEntityType]] = None
-
-
class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):
user_api_key_cache = None
ad_hoc_recognizers = None
@@ -533,14 +528,19 @@ class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):
except Exception:
pass
- async def apply_guardrail(self, input_text: str) -> str:
+ async def apply_guardrail(
+ self,
+ text: str,
+ language: Optional[str] = None,
+ entities: Optional[List[PiiEntityType]] = None,
+ ) -> str:
"""
UI will call this function to check:
1. If the connection to the guardrail is working
2. When Testing the guardrail with some text, this function will be called with the input text and returns a text after applying the guardrail
"""
text = await self.check_pii(
- text=input_text,
+ text=text,
output_parse_pii=self.output_parse_pii,
presidio_config=None,
request_data={},
diff --git a/litellm/proxy/guardrails/guardrail_registry.py b/litellm/proxy/guardrails/guardrail_registry.py
index 999f85d77ff..6ad48521f0d 100644
--- a/litellm/proxy/guardrails/guardrail_registry.py
+++ b/litellm/proxy/guardrails/guardrail_registry.py
@@ -3,6 +3,8 @@
from datetime import datetime, timezone
from typing import List, Optional
+import litellm
+from litellm.integrations.custom_guardrail import CustomGuardrail
from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
from litellm.proxy.utils import PrismaClient
from litellm.types.guardrails import Guardrail, SupportedGuardrailIntegrations
@@ -38,6 +40,26 @@ class GuardrailRegistry:
def __init__(self):
pass
+ ###########################################################
+ ########### In memory management helpers for guardrails ###########
+ ############################################################
+ def get_initialized_guardrail_callback(
+ self, guardrail_name: str
+ ) -> Optional[CustomGuardrail]:
+ """
+ Returns the initialized guardrail callback for a given guardrail name
+ """
+ active_guardrails = (
+ litellm.logging_callback_manager.get_custom_loggers_for_type(
+ callback_type=CustomGuardrail
+ )
+ )
+ for active_guardrail in active_guardrails:
+ if isinstance(active_guardrail, CustomGuardrail):
+ if active_guardrail.guardrail_name == guardrail_name:
+ return active_guardrail
+ return None
+
###########################################################
########### DB management helpers for guardrails ###########
############################################################
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 5844f333fd1..1825e360041 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -393,9 +393,11 @@ except Exception:
###################
# Import enterprise routes
try:
- from litellm_enterprise.proxy.enterprise_routes import router as enterprise_router
+ from litellm_enterprise.proxy.enterprise_routes import router as _enterprise_router
+
+ enterprise_router = _enterprise_router
except ImportError:
- enterprise_router = APIRouter()
+ pass
###################
server_root_path = os.getenv("SERVER_ROOT_PATH", "")
diff --git a/litellm/types/guardrails.py b/litellm/types/guardrails.py
index 7844cef1abd..97e0f8fb036 100644
--- a/litellm/types/guardrails.py
+++ b/litellm/types/guardrails.py
@@ -305,3 +305,23 @@ class GuardrailUIAddGuardrailSettings(BaseModel):
supported_actions: List[PiiAction]
supported_modes: List[GuardrailEventHooks]
pii_entity_categories: List[PiiEntityCategoryMap]
+
+
+class PresidioPerRequestConfig(BaseModel):
+ """
+ presdio params that can be controlled per request, api key
+ """
+
+ language: Optional[str] = None
+ entities: Optional[List[PiiEntityType]] = None
+
+
+class ApplyGuardrailRequest(BaseModel):
+ guardrail_name: str
+ text: str
+ language: Optional[str] = None
+ entities: Optional[List[PiiEntityType]] = None
+
+
+class ApplyGuardrailResponse(BaseModel):
+ response_text: str
diff --git a/tests/guardrails_tests/test_presidio_pii.py b/tests/guardrails_tests/test_presidio_pii.py
index b7142b51ce1..1a8e4723068 100644
--- a/tests/guardrails_tests/test_presidio_pii.py
+++ b/tests/guardrails_tests/test_presidio_pii.py
@@ -66,6 +66,27 @@ async def test_presidio_with_entities_config():
print(f"Redacted text: {redacted_text}")
+async def test_presidio_apply_guardrail():
+ """Test for Presidio guardrail apply guardrail - requires actual Presidio API"""
+ litellm._turn_on_debug()
+ presidio_guardrail = _OPTIONAL_PresidioPIIMasking(
+ pii_entities_config={},
+ presidio_analyzer_api_base=os.environ.get("PRESIDIO_ANALYZER_API_BASE"),
+ presidio_anonymizer_api_base=os.environ.get("PRESIDIO_ANONYMIZER_API_BASE")
+ )
+
+
+ response = await presidio_guardrail.apply_guardrail(
+ text="My credit card number is 4111-1111-1111-1111 and my email is [email protected]",
+ language="en",
+ )
+ print("response from apply guardrail for presidio: ", response)
+
+ # assert tthe default config masks the credit card and email
+ assert "4111-1111-1111-1111" not in response
+ assert "[email protected]" not in response
+
@pytest.mark.asyncio
async def test_presidio_with_blocked_entities():
"""Test for Presidio guardrail with blocked entities - requires actual Presidio API"""