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] Presidio Improvements - Allow adding presidio api base on UI, Test presidio on Test Key, fixes for running presidio hook (#10840)

Ishaan Jaff2a994d701655
diff --git a/litellm/proxy/guardrails/guardrail_hooks/presidio.py b/litellm/proxy/guardrails/guardrail_hooks/presidio.py
index 222b506301d..f4ead5a5799 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/presidio.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/presidio.py
@@ -31,6 +31,7 @@ from litellm.types.proxy.guardrails.guardrail_hooks.presidio import (
PresidioAnalyzeRequest,
PresidioAnalyzeResponseItem,
)
+from litellm.types.utils import CallTypes as LitellmCallTypes
from litellm.utils import (
EmbeddingResponse,
ImageResponse,
@@ -357,8 +358,10 @@ class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):
content_safety = data.get("content_safety", None)
verbose_proxy_logger.debug("content_safety: %s", content_safety)
presidio_config = self.get_presidio_settings_from_request_data(data)
-
- if call_type == "completion": # /chat/completions requests
+ if call_type in [
+ LitellmCallTypes.completion.value,
+ LitellmCallTypes.acompletion.value,
+ ]:
messages = data["messages"]
tasks = []
@@ -388,6 +391,10 @@ class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):
f"Presidio PII Masking: Redacted pii message: {data['messages']}"
)
data["messages"] = messages
+ else:
+ verbose_proxy_logger.debug(
+ f"Not running async_pre_call_hook for call_type={call_type}"
+ )
return data
except Exception as e:
raise e
@@ -525,3 +532,17 @@ class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):
print(print_statement) # noqa
except Exception:
pass
+
+ async def apply_guardrail(self, input_text: str) -> 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,
+ output_parse_pii=self.output_parse_pii,
+ presidio_config=None,
+ request_data={},
+ )
+ return text
diff --git a/litellm/proxy/guardrails/guardrail_registry.py b/litellm/proxy/guardrails/guardrail_registry.py
index 2d7bce7b704..999f85d77ff 100644
--- a/litellm/proxy/guardrails/guardrail_registry.py
+++ b/litellm/proxy/guardrails/guardrail_registry.py
@@ -17,7 +17,7 @@ from .guardrail_initializers import (
initialize_presidio,
)
-guardrail_registry = {
+guardrail_initializer_registry = {
SupportedGuardrailIntegrations.APORIA.value: initialize_aporia,
SupportedGuardrailIntegrations.BEDROCK.value: initialize_bedrock,
SupportedGuardrailIntegrations.LAKERA.value: initialize_lakera,
@@ -114,8 +114,9 @@ class GuardrailRegistry:
except Exception as e:
raise Exception(f"Error updating guardrail in DB: {str(e)}")
+ @staticmethod
async def get_all_guardrails_from_db(
- self, prisma_client: PrismaClient
+ prisma_client: PrismaClient,
) -> List[Guardrail]:
"""
Get all guardrails from the database
diff --git a/litellm/proxy/guardrails/init_guardrails.py b/litellm/proxy/guardrails/init_guardrails.py
index d08dcaba253..dd7a46388d9 100644
--- a/litellm/proxy/guardrails/init_guardrails.py
+++ b/litellm/proxy/guardrails/init_guardrails.py
@@ -10,13 +10,14 @@ from litellm.proxy.common_utils.callback_utils import initialize_callbacks_on_pr
# v2 implementation
from litellm.types.guardrails import (
Guardrail,
+ GuardrailEventHooks,
GuardrailItem,
GuardrailItemSpec,
LakeraCategoryThresholds,
LitellmParams,
)
-from .guardrail_registry import guardrail_registry
+from .guardrail_registry import guardrail_initializer_registry
all_guardrails: List[GuardrailItem] = []
@@ -88,9 +89,34 @@ def init_guardrails_v2(
all_guardrails: List[Dict],
config_file_path: Optional[str] = None,
):
- guardrail_list = []
+ guardrail_list: List[Guardrail] = []
for guardrail in all_guardrails:
+ initialized_guardrail = InitializeGuardrails.initialize_guardrail(
+ guardrail=guardrail,
+ config_file_path=config_file_path,
+ )
+ if initialized_guardrail:
+ guardrail_list.append(initialized_guardrail)
+
+ verbose_proxy_logger.info(f"\nGuardrail List:{guardrail_list}\n")
+
+
+class InitializeGuardrails:
+ """
+ Class that handles initializing guardrails and adding them to the CallbackManager
+ """
+
+ @staticmethod
+ def initialize_guardrail(
+ guardrail: Dict,
+ config_file_path: Optional[str] = None,
+ ) -> Optional[Guardrail]:
+ """
+ Initialize a guardrail from a dictionary and add it to the litellm callback manager
+
+ Returns a Guardrail object if the guardrail is initialized successfully
+ """
litellm_params_data = guardrail["litellm_params"]
verbose_proxy_logger.debug("litellm_params= %s", litellm_params_data)
@@ -109,55 +135,29 @@ def init_guardrails_v2(
)
litellm_params["category_thresholds"] = lakera_category_thresholds
- if litellm_params["api_key"] and litellm_params["api_key"].startswith(
- "os.environ/"
- ):
+ api_key: Optional[str] = litellm_params.get("api_key")
+ if api_key and api_key.startswith("os.environ/"):
litellm_params["api_key"] = str(get_secret(litellm_params["api_key"])) # type: ignore
- if litellm_params["api_base"] and litellm_params["api_base"].startswith(
- "os.environ/"
- ):
+ api_base: Optional[str] = litellm_params.get("api_base")
+ if api_base and api_base.startswith("os.environ/"):
litellm_params["api_base"] = str(get_secret(litellm_params["api_base"])) # type: ignore
- guardrail_type = litellm_params["guardrail"]
+ guardrail_type: Optional[str] = litellm_params.get("guardrail")
+ if guardrail_type is None:
+ raise ValueError("guardrail_type is required")
- initializer = guardrail_registry.get(guardrail_type)
+ initializer = guardrail_initializer_registry.get(guardrail_type)
if initializer:
initializer(litellm_params, guardrail)
elif isinstance(guardrail_type, str) and "." in guardrail_type:
- if not config_file_path:
- raise Exception(
- "GuardrailsAIException - Please pass the config_file_path to initialize_guardrails_v2"
- )
-
- _file_name, _class_name = guardrail_type.split(".")
- verbose_proxy_logger.debug(
- "Initializing custom guardrail: %s, file_name: %s, class_name: %s",
- guardrail_type,
- _file_name,
- _class_name,
- )
-
- directory = os.path.dirname(config_file_path)
- module_file_path = os.path.join(directory, _file_name) + ".py"
-
- spec = importlib.util.spec_from_file_location(_class_name, module_file_path) # type: ignore
- if not spec:
- raise ImportError(
- f"Could not find a module specification for {module_file_path}"
- )
-
- module = importlib.util.module_from_spec(spec) # type: ignore
- spec.loader.exec_module(module) # type: ignore
- _guardrail_class = getattr(module, _class_name)
-
- _guardrail_callback = _guardrail_class(
- guardrail_name=guardrail["guardrail_name"],
- event_hook=litellm_params["mode"],
- default_on=litellm_params["default_on"],
+ InitializeGuardrails.initialize_custom_guardrail(
+ guardrail=guardrail,
+ guardrail_type=guardrail_type,
+ litellm_params=litellm_params,
+ config_file_path=config_file_path,
)
- litellm.logging_callback_manager.add_litellm_callback(_guardrail_callback) # type: ignore
else:
raise ValueError(f"Unsupported guardrail: {guardrail_type}")
@@ -166,6 +166,56 @@ def init_guardrails_v2(
litellm_params=litellm_params,
)
- guardrail_list.append(parsed_guardrail)
+ return parsed_guardrail
+
+ @staticmethod
+ def initialize_custom_guardrail(
+ guardrail: Dict,
+ guardrail_type: str,
+ litellm_params: LitellmParams,
+ config_file_path: Optional[str] = None,
+ ) -> None:
+ """
+ Initialize a Custom Guardrail from a python file
+
+ This initializes it by adding it to the litellm callback manager
+ """
+ if not config_file_path:
+ raise Exception(
+ "GuardrailsAIException - Please pass the config_file_path to initialize_guardrails_v2"
+ )
- verbose_proxy_logger.info(f"\nGuardrail List:{guardrail_list}\n")
+ _file_name, _class_name = guardrail_type.split(".")
+ verbose_proxy_logger.debug(
+ "Initializing custom guardrail: %s, file_name: %s, class_name: %s",
+ guardrail_type,
+ _file_name,
+ _class_name,
+ )
+
+ directory = os.path.dirname(config_file_path)
+ module_file_path = os.path.join(directory, _file_name) + ".py"
+
+ spec = importlib.util.spec_from_file_location(_class_name, module_file_path) # type: ignore
+ if not spec:
+ raise ImportError(
+ f"Could not find a module specification for {module_file_path}"
+ )
+
+ module = importlib.util.module_from_spec(spec) # type: ignore
+ spec.loader.exec_module(module) # type: ignore
+ _guardrail_class = getattr(module, _class_name)
+
+ mode: Optional[str] = litellm_params.get("mode")
+ if mode is None:
+ raise ValueError(
+ f"mode is required for guardrail {guardrail_type} please set mode to one of the following: {', '.join(GuardrailEventHooks)}"
+ )
+
+ default_on: Optional[bool] = litellm_params.get("default_on")
+ _guardrail_callback = _guardrail_class(
+ guardrail_name=guardrail["guardrail_name"],
+ event_hook=mode,
+ default_on=default_on,
+ )
+ litellm.logging_callback_manager.add_litellm_callback(_guardrail_callback) # type: ignore
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 18e1d8d98a7..04872c6dae0 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -813,9 +813,9 @@ model_max_budget_limiter = _PROXY_VirtualKeyModelMaxBudgetLimiter(
dual_cache=user_api_key_cache
)
litellm.logging_callback_manager.add_litellm_callback(model_max_budget_limiter)
-redis_usage_cache: Optional[RedisCache] = (
- None # redis cache used for tracking spend, tpm/rpm limits
-)
+redis_usage_cache: Optional[
+ RedisCache
+] = None # redis cache used for tracking spend, tpm/rpm limits
user_custom_auth = None
user_custom_key_generate = None
user_custom_sso = None
@@ -1142,9 +1142,9 @@ async def update_cache( # noqa: PLR0915
_id = "team_id:{}".format(team_id)
try:
# Fetch the existing cost for the given user
- existing_spend_obj: Optional[LiteLLM_TeamTable] = (
- await user_api_key_cache.async_get_cache(key=_id)
- )
+ existing_spend_obj: Optional[
+ LiteLLM_TeamTable
+ ] = await user_api_key_cache.async_get_cache(key=_id)
if existing_spend_obj is None:
# do nothing if team not in api key cache
return
@@ -2676,8 +2676,8 @@ class ProxyConfig:
db_general_settings=db_general_settings.param_value,
)
- # initialize vector stores table in db
- await self._init_vector_stores_in_db(prisma_client=prisma_client)
+ # initialize vector stores, guardrails, etc. table in db
+ await self._init_non_llm_objects_in_db(prisma_client=prisma_client)
except Exception as e:
verbose_proxy_logger.exception(
@@ -2686,6 +2686,42 @@ class ProxyConfig:
)
)
+ async def _init_non_llm_objects_in_db(self, prisma_client: PrismaClient):
+ """
+ Use this to read non-llm objects from the db and initialize them
+
+ ex. Vector Stores, Guardrails, MCP tools, etc.
+ """
+ await self._init_guardrails_in_db(prisma_client=prisma_client)
+ await self._init_vector_stores_in_db(prisma_client=prisma_client)
+
+ async def _init_guardrails_in_db(self, prisma_client: PrismaClient):
+ from litellm.proxy.guardrails.guardrail_registry import (
+ Guardrail,
+ GuardrailRegistry,
+ )
+ from litellm.proxy.guardrails.init_guardrails import InitializeGuardrails
+
+ try:
+ guardrails_in_db: List[
+ Guardrail
+ ] = await GuardrailRegistry.get_all_guardrails_from_db(
+ prisma_client=prisma_client
+ )
+ verbose_proxy_logger.debug(
+ "guardrails from the DB %s", str(guardrails_in_db)
+ )
+ for guardrail in guardrails_in_db:
+ InitializeGuardrails.initialize_guardrail(
+ guardrail=dict(guardrail),
+ )
+ except Exception as e:
+ verbose_proxy_logger.exception(
+ "litellm.proxy.proxy_server.py::ProxyConfig:_init_guardrails_in_db - {}".format(
+ str(e)
+ )
+ )
+
async def _init_vector_stores_in_db(self, prisma_client: PrismaClient):
from litellm.vector_stores.vector_store_registry import VectorStoreRegistry
@@ -2868,9 +2904,9 @@ async def initialize( # noqa: PLR0915
user_api_base = api_base
dynamic_config[user_model]["api_base"] = api_base
if api_version:
- os.environ["AZURE_API_VERSION"] = (
- api_version # set this for azure - litellm can read this from the env
- )
+ os.environ[
+ "AZURE_API_VERSION"
+ ] = api_version # set this for azure - litellm can read this from the env
if max_tokens: # model-specific param
dynamic_config[user_model]["max_tokens"] = max_tokens
if temperature: # model-specific param
@@ -7874,9 +7910,9 @@ async def get_config_list(
hasattr(sub_field_info, "description")
and sub_field_info.description is not None
):
- nested_fields[idx].field_description = (
- sub_field_info.description
- )
+ nested_fields[
+ idx
+ ].field_description = sub_field_info.description
idx += 1
_stored_in_db = None
diff --git a/litellm/types/guardrails.py b/litellm/types/guardrails.py
index 4a730327b22..7844cef1abd 100644
--- a/litellm/types/guardrails.py
+++ b/litellm/types/guardrails.py
@@ -289,8 +289,8 @@ class GuardrailInfoResponse(BaseModel):
guardrail_name: str
litellm_params: GuardrailLiteLLMParamsResponse
guardrail_info: Optional[Dict]
- created_at: Optional[datetime]
- updated_at: Optional[datetime]
+ created_at: Optional[datetime] = None
+ updated_at: Optional[datetime] = None
def __init__(self, **kwargs):
super().__init__(**kwargs)
diff --git a/tests/logging_callback_tests/test_custom_guardrail.py b/tests/guardrails_tests/test_custom_guardrail.py
similarity index 100%
rename from tests/logging_callback_tests/test_custom_guardrail.py
rename to tests/guardrails_tests/test_custom_guardrail.py
diff --git a/tests/guardrails_tests/test_presidio_pii.py b/tests/guardrails_tests/test_presidio_pii.py
index 7a3977758ee..b7142b51ce1 100644
--- a/tests/guardrails_tests/test_presidio_pii.py
+++ b/tests/guardrails_tests/test_presidio_pii.py
@@ -12,6 +12,7 @@ from litellm.types.guardrails import PiiEntityType, PiiAction
from litellm.proxy._types import UserAPIKeyAuth
from litellm.caching.caching import DualCache
from litellm.exceptions import BlockedPiiEntityError
+from litellm.types.utils import CallTypes as LitellmCallTypes
@@ -154,8 +155,9 @@ async def test_presidio_pre_call_hook_with_blocked_entities():
@pytest.mark.asyncio
-async def test_presidio_pre_call_hook_with_entities_config():
- """Test for Presidio guardrail pre-call hook with entities config on a chat completion request"""
[email protected]("call_type", ["completion", "acompletion"])
+async def test_presidio_pre_call_hook_with_different_call_types(call_type):
+ """Test for Presidio guardrail pre-call hook with both completion and acompletion call types"""
# Setup the guardrail with specific entities config
pii_entities_config = {
PiiEntityType.CREDIT_CARD: PiiAction.MASK,
@@ -168,7 +170,7 @@ async def test_presidio_pre_call_hook_with_entities_config():
presidio_anonymizer_api_base=os.environ.get("PRESIDIO_ANONYMIZER_API_BASE")
)
- # Create a sample chat completion request with PII data
+ # Create a sample request with PII data
data = {
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
@@ -181,12 +183,12 @@ async def test_presidio_pre_call_hook_with_entities_config():
user_api_key_dict = UserAPIKeyAuth(api_key="test_key")
cache = DualCache()
- # Call the pre-call hook
+ # Call the pre-call hook with the specified call type
modified_data = await presidio_guardrail.async_pre_call_hook(
user_api_key_dict=user_api_key_dict,
cache=cache,
data=data,
- call_type="completion"
+ call_type=call_type
)
# Verify the messages have been modified to mask PII
@@ -199,7 +201,7 @@ async def test_presidio_pre_call_hook_with_entities_config():
# Since this entity is not in the config, it should not be masked
assert "555-123-4567" in user_message
- print(f"Modified user message: {user_message}")
+ print(f"Modified user message for call_type={call_type}: {user_message}")
@pytest.mark.parametrize(
diff --git a/tests/litellm/proxy/guardrails/test_init_guardrails.py b/tests/litellm/proxy/guardrails/test_init_guardrails.py
new file mode 100644
index 00000000000..e30a80c78e3
--- /dev/null
+++ b/tests/litellm/proxy/guardrails/test_init_guardrails.py
@@ -0,0 +1,40 @@
+import json
+import os
+import sys
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+sys.path.insert(
+ 0, os.path.abspath("../../..")
+) # Adds the parent directory to the system path
+
+from litellm.proxy.guardrails.init_guardrails import InitializeGuardrails
+from litellm.types.guardrails import SupportedGuardrailIntegrations
+
+
+def test_initialize_presidio_guardrail():
+ """
+ Test that initialize_guardrail correctly uses registered initializers
+ for presidio guardrail
+ """
+ # Setup test data for a non-custom guardrail (using Presidio as an example)
+ test_guardrail = {
+ "guardrail_name": "test_presidio_guardrail",
+ "litellm_params": {
+ "guardrail": SupportedGuardrailIntegrations.PRESIDIO.value,
+ "mode": "pre_call",
+ },
+ }
+
+ # Call the initialize_guardrail method
+ result = InitializeGuardrails.initialize_guardrail(
+ guardrail=test_guardrail,
+ )
+
+ assert result["guardrail_name"] == "test_presidio_guardrail"
+ assert (
+ result["litellm_params"]["guardrail"]
+ == SupportedGuardrailIntegrations.PRESIDIO.value
+ )
+ assert result["litellm_params"]["mode"] == "pre_call"
diff --git a/ui/litellm-dashboard/src/components/chat_ui.tsx b/ui/litellm-dashboard/src/components/chat_ui.tsx
index 30978698ea0..1fa28af2af9 100644
--- a/ui/litellm-dashboard/src/components/chat_ui.tsx
+++ b/ui/litellm-dashboard/src/components/chat_ui.tsx
@@ -35,6 +35,7 @@ import { coy } from 'react-syntax-highlighter/dist/esm/styles/prism';
import EndpointSelector from "./chat_ui/EndpointSelector";
import TagSelector from "./tag_management/TagSelector";
import VectorStoreSelector from "./vector_store_management/VectorStoreSelector";
+import GuardrailSelector from "./guardrails/GuardrailSelector";
import { determineEndpointType } from "./chat_ui/EndpointUtils";
import { MessageType } from "./chat_ui/types";
import ReasoningContent from "./chat_ui/ReasoningContent";
@@ -50,7 +51,8 @@ import {
LoadingOutlined,
TagsOutlined,
DatabaseOutlined,
- InfoCircleOutlined
+ InfoCircleOutlined,
+ SafetyOutlined
} from "@ant-design/icons";
const { TextArea } = Input;
@@ -87,6 +89,7 @@ const ChatUI: React.FC<ChatUIProps> = ({
const abortControllerRef = useRef<AbortController | null>(null);
const [selectedTags, setSelectedTags] = useState<string[]>([]);
const [selectedVectorStores, setSelectedVectorStores] = useState<string[]>([]);
+ const [selectedGuardrails, setSelectedGuardrails] = useState<string[]>([]);
const [messageTraceId, setMessageTraceId] = useState<string | null>(null);
const chatEndRef = useRef<HTMLDivElement>(null);
@@ -333,7 +336,8 @@ const ChatUI: React.FC<ChatUIProps> = ({
updateTimingData,
updateUsageData,
traceId,
- selectedVectorStores.length > 0 ? selectedVectorStores : undefined
+ selectedVectorStores.length > 0 ? selectedVectorStores : undefined,
+ selectedGuardrails.length > 0 ? selectedGuardrails : undefined
);
} else if (endpointType === EndpointType.IMAGE) {
// For image generation
@@ -360,7 +364,8 @@ const ChatUI: React.FC<ChatUIProps> = ({
updateTimingData,
updateUsageData,
traceId,
- selectedVectorStores.length > 0 ? selectedVectorStores : undefined
+ selectedVectorStores.length > 0 ? selectedVectorStores : undefined,
+ selectedGuardrails.length > 0 ? selectedGuardrails : undefined
);
}
}
@@ -530,6 +535,27 @@ const ChatUI: React.FC<ChatUIProps> = ({
accessToken={accessToken || ""}
/>
</div>
+
+ <div>
+ <Text className="font-medium block mb-2 text-gray-700 flex items-center">
+ <SafetyOutlined className="mr-2" /> Guardrails
+ <Tooltip
+ className="ml-1"
+ title={
+ <span>
+ Select guardrail(s) to use for this LLM API call. You can set up your guardrails <a href="?page=guardrails" style={{ color: '#1890ff' }}>here</a>.
+ </span>
+ }>
+ <InfoCircleOutlined />
+ </Tooltip>
+ </Text>
+ <GuardrailSelector
+ value={selectedGuardrails}
+ onChange={setSelectedGuardrails}
+ className="mb-4"
+ accessToken={accessToken || ""}
+ />
+ </div>
<Button
onClick={clearChatHistory}
diff --git a/ui/litellm-dashboard/src/components/chat_ui/llm_calls/chat_completion.tsx b/ui/litellm-dashboard/src/components/chat_ui/llm_calls/chat_completion.tsx
index 56e31186605..8488794b597 100644
--- a/ui/litellm-dashboard/src/components/chat_ui/llm_calls/chat_completion.tsx
+++ b/ui/litellm-dashboard/src/components/chat_ui/llm_calls/chat_completion.tsx
@@ -14,7 +14,8 @@ export async function makeOpenAIChatCompletionRequest(
onTimingData?: (timeToFirstToken: number) => void,
onUsageData?: (usage: TokenUsage) => void,
traceId?: string,
- vector_store_ids?: string[]
+ vector_store_ids?: string[],
+ guardrails?: string[]
) {
// base url should be the current base_url
const isLocal = process.env.NODE_ENV === "development";
@@ -58,6 +59,7 @@ export async function makeOpenAIChatCompletionRequest(
litellm_trace_id: traceId,
messages: chatHistory as ChatCompletionMessageParam[],
...(vector_store_ids ? { vector_store_ids } : {}),
+ ...(guardrails ? { guardrails } : {}),
}, { signal });
for await (const chunk of response) {
diff --git a/ui/litellm-dashboard/src/components/chat_ui/llm_calls/responses_api.tsx b/ui/litellm-dashboard/src/components/chat_ui/llm_calls/responses_api.tsx
index b5811115cc3..7ebf53a2724 100644
--- a/ui/litellm-dashboard/src/components/chat_ui/llm_calls/responses_api.tsx
+++ b/ui/litellm-dashboard/src/components/chat_ui/llm_calls/responses_api.tsx
@@ -14,7 +14,8 @@ export async function makeOpenAIResponsesRequest(
onTimingData?: (timeToFirstToken: number) => void,
onUsageData?: (usage: TokenUsage) => void,
traceId?: string,
- vector_store_ids?: string[]
+ vector_store_ids?: string[],
+ guardrails?: string[]
) {
if (!accessToken) {
throw new Error("API key is required");
@@ -62,6 +63,7 @@ export async function makeOpenAIResponsesRequest(
stream: true,
litellm_trace_id: traceId,
...(vector_store_ids ? { vector_store_ids } : {}),
+ ...(guardrails ? { guardrails } : {}),
}, { signal });
for await (const event of response) {
diff --git a/ui/litellm-dashboard/src/components/guardrails/GuardrailSelector.tsx b/ui/litellm-dashboard/src/components/guardrails/GuardrailSelector.tsx
new file mode 100644
index 00000000000..b6f072cdfab
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/guardrails/GuardrailSelector.tsx
@@ -0,0 +1,74 @@
+import React, { useEffect, useState } from 'react';
+import { Select, Typography, Tooltip } from 'antd';
+import { InfoCircleOutlined } from '@ant-design/icons';
+import { Guardrail } from './types';
+import { getGuardrailsList } from '../networking';
+
+interface GuardrailSelectorProps {
+ onChange: (selectedGuardrails: string[]) => void;
+ value?: string[];
+ className?: string;
+ accessToken: string;
+}
+
+const GuardrailSelector: React.FC<GuardrailSelectorProps> = ({
+ onChange,
+ value,
+ className,
+ accessToken
+}) => {
+ const [guardrails, setGuardrails] = useState<Guardrail[]>([]);
+ const [loading, setLoading] = useState(false);
+
+ useEffect(() => {
+ const fetchGuardrails = async () => {
+ if (!accessToken) return;
+
+ setLoading(true);
+ try {
+ const response = await getGuardrailsList(accessToken);
+ console.log("Guardrails response:", response);
+ if (response.guardrails) {
+ console.log("Guardrails data:", response.guardrails);
+ setGuardrails(response.guardrails);
+ }
+ } catch (error) {
+ console.error("Error fetching guardrails:", error);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ fetchGuardrails();
+ }, [accessToken]);
+
+ const handleGuardrailChange = (selectedValues: string[]) => {
+ console.log("Selected guardrails:", selectedValues);
+ onChange(selectedValues);
+ };
+
+ return (
+ <div>
+ <Select
+ mode="multiple"
+ placeholder="Select guardrails"
+ onChange={handleGuardrailChange}
+ value={value}
+ loading={loading}
+ className={className}
+ options={guardrails.map(guardrail => {
+ console.log("Mapping guardrail:", guardrail);
+ return {
+ label: `${guardrail.guardrail_name}`,
+ value: guardrail.guardrail_name,
+ }
+ })}
+ optionFilterProp="label"
+ showSearch
+ style={{ width: '100%' }}
+ />
+ </div>
+ );
+};
+
+export default GuardrailSelector;
\ No newline at end of file
diff --git a/ui/litellm-dashboard/src/components/guardrails/add_guardrail_form.tsx b/ui/litellm-dashboard/src/components/guardrails/add_guardrail_form.tsx
index d606172bff0..b6fe36fea04 100644
--- a/ui/litellm-dashboard/src/components/guardrails/add_guardrail_form.tsx
+++ b/ui/litellm-dashboard/src/components/guardrails/add_guardrail_form.tsx
@@ -2,9 +2,10 @@ import React, { useState, useEffect } from 'react';
import { Card, Form, Typography, Select, Input, Switch, Tooltip, Modal, message, Divider, Space, Tag, Image, Steps } from 'antd';
import { Button, TextInput } from '@tremor/react';
import type { FormInstance } from 'antd';
-import { GuardrailProviders, guardrail_provider_map, provider_specific_fields, guardrailLogoMap } from './guardrail_info_helpers';
+import { GuardrailProviders, guardrail_provider_map, shouldRenderPIIConfigSettings, guardrailLogoMap } from './guardrail_info_helpers';
import { createGuardrailCall, getGuardrailUISettings } from '../networking';
import PiiConfiguration from './pii_configuration';
+import GuardrailProviderFields from './guardrail_provider_fields';
const { Title, Text, Link } = Typography;
const { Option } = Select;
@@ -69,7 +70,9 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({
setSelectedProvider(value);
// Reset form fields that are provider-specific
form.setFieldsValue({
- config: undefined
+ config: undefined,
+ presidio_analyzer_api_base: undefined,
+ presidio_anonymizer_api_base: undefined
});
// Reset PII selections when changing provider
@@ -99,6 +102,19 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({
// Validate current step fields
if (currentStep === 0) {
await form.validateFields(['guardrail_name', 'provider', 'mode', 'default_on']);
+ // Also validate provider-specific fields if applicable
+ if (selectedProvider) {
+ // This will automatically validate any required fields for the selected provider
+ const fieldsToValidate = ['guardrail_name', 'provider', 'mode', 'default_on'];
+
+ if (selectedProvider === 'PresidioPII') {
+ fieldsToValidate.push('presidio_analyzer_api_base', 'presidio_anonymizer_api_base');
+ } else if (selectedProvider === 'Bedrock') {
+ fieldsToValidate.push('config');
+ }
+
+ await form.validateFields(fieldsToValidate);
+ }
}
setCurrentStep(currentStep + 1);
} catch (error) {
@@ -126,7 +142,7 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({
const handleSubmit = async () => {
try {
setLoading(true);
- // First validate currently visible fields (step 1)
+ // First validate currently visible fields
await form.validateFields();
// After validation, fetch *all* form values (including those from previous steps)
@@ -163,6 +179,14 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({
});
guardrailData.litellm_params.pii_entities_config = piiEntitiesConfig;
+
+ // Add Presidio API bases if provided
+ if (values.presidio_analyzer_api_base) {
+ guardrailData.litellm_params.presidio_analyzer_api_base = values.presidio_analyzer_api_base;
+ }
+ if (values.presidio_anonymizer_api_base) {
+ guardrailData.litellm_params.presidio_anonymizer_api_base = values.presidio_anonymizer_api_base;
+ }
}
// Add config values to the guardrail_info if provided
else if (values.config) {
@@ -260,6 +284,9 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({
</Select>
</Form.Item>
+ {/* Use the GuardrailProviderFields component to render provider-specific fields */}
+ <GuardrailProviderFields selectedProvider={selectedProvider} />
+
<Form.Item
name="mode"
label="Mode"
@@ -306,131 +333,13 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({
);
};
- const renderProviderSpecificConfig = () => {
- if (!selectedProvider || selectedProvider === 'PresidioPII') return null;
-
- switch (selectedProvider) {
- case 'Aporia':
- return (
- <Form.Item
- label="Aporia Configuration"
- name="config"
- tooltip="JSON configuration for Aporia"
- >
- <Input.TextArea
- rows={4}
- placeholder={`{
- "api_key": "your_aporia_api_key",
- "project_name": "your_project_name"
-}`}
- />
- </Form.Item>
- );
- case 'AimSecurity':
- return (
- <Form.Item
- label="Aim Security Configuration"
- name="config"
- tooltip="JSON configuration for Aim Security"
- >
- <Input.TextArea
- rows={4}
- placeholder={`{
- "api_key": "your_aim_api_key"
-}`}
- />
- </Form.Item>
- );
- case 'Bedrock':
- return (
- <Form.Item
- label="Amazon Bedrock Configuration"
- name="config"
- tooltip="JSON configuration for Amazon Bedrock guardrails"
- >
- <Input.TextArea
- rows={4}
- placeholder={`{
- "guardrail_id": "your_guardrail_id",
- "guardrail_version": "your_guardrail_version"
-}`}
- />
- </Form.Item>
- );
- case 'GuardrailsAI':
- return (
- <Form.Item
- label="Guardrails.ai Configuration"
- name="config"
- tooltip="JSON configuration for Guardrails.ai"
- >
- <Input.TextArea
- rows={4}
- placeholder={`{
- "api_key": "your_guardrails_api_key",
- "guardrail_id": "your_guardrail_id"
-}`}
- />
- </Form.Item>
- );
- case 'LakeraAI':
- return (
- <Form.Item
- label="Lakera AI Configuration"
- name="config"
- tooltip="JSON configuration for Lakera AI"
- >
- <Input.TextArea
- rows={4}
- placeholder={`{
- "api_key": "your_lakera_api_key"
-}`}
- />
- </Form.Item>
- );
- case 'PromptInjection':
- return (
- <Form.Item
- label="Prompt Injection Configuration"
- name="config"
- tooltip="JSON configuration for prompt injection detection"
- >
- <Input.TextArea
- rows={4}
- placeholder={`{
- "threshold": 0.8
-}`}
- />
- </Form.Item>
- );
- default:
- return (
- <Form.Item
- label="Custom Configuration"
- name="config"
- tooltip="JSON configuration for your custom guardrail"
- >
- <Input.TextArea
- rows={4}
- placeholder={`{
- "key1": "value1",
- "key2": "value2"
-}`}
- />
- </Form.Item>
- );
- }
- };
-
const renderStepContent = () => {
switch (currentStep) {
case 0:
return renderBasicInfo();
case 1:
- if (selectedProvider === 'PresidioPII') {
+ if (shouldRenderPIIConfigSettings(selectedProvider)) {
return renderPiiConfiguration();
- } else {
- return renderProviderSpecificConfig();
}
default:
return null;
diff --git a/ui/litellm-dashboard/src/components/guardrails/guardrail_info_helpers.tsx b/ui/litellm-dashboard/src/components/guardrails/guardrail_info_helpers.tsx
index 1c0a9908fc2..9abda743164 100644
--- a/ui/litellm-dashboard/src/components/guardrails/guardrail_info_helpers.tsx
+++ b/ui/litellm-dashboard/src/components/guardrails/guardrail_info_helpers.tsx
@@ -6,9 +6,16 @@ export const guardrail_provider_map: Record<string, string> = {
PresidioPII: "presidio",
};
-// Define which providers need specific fields
-export const provider_specific_fields: Record<string, string[]> = {
- PresidioPII: ["pii_entities", "pii_actions"]
+
+// Decides if we should render the PII config settings for a given provider
+// For now we only support PII config settings for Presidio PII
+export const shouldRenderPIIConfigSettings = (provider: string | null) => {
+ if (!provider) {
+ return false;
+ }
+ // cast provider to GuardrailProviders enum
+ const providerEnum = GuardrailProviders[provider as keyof typeof GuardrailProviders];
+ return providerEnum === GuardrailProviders.PresidioPII;
};
const asset_logos_folder = '../ui/assets/logos/';
diff --git a/ui/litellm-dashboard/src/components/guardrails/guardrail_provider_fields.tsx b/ui/litellm-dashboard/src/components/guardrails/guardrail_provider_fields.tsx
new file mode 100644
index 00000000000..97e48622ffb
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/guardrails/guardrail_provider_fields.tsx
@@ -0,0 +1,93 @@
+import React from "react";
+import { Form, Select } from "antd";
+import { TextInput } from "@tremor/react";
+import { GuardrailProviders } from './guardrail_info_helpers';
+
+interface GuardrailProviderFieldsProps {
+ selectedProvider: string | null;
+}
+
+interface ProviderField {
+ key: string;
+ label: string;
+ placeholder?: string;
+ tooltip?: string;
+ required?: boolean;
+ type?: "text" | "password" | "select";
+ options?: string[];
+ defaultValue?: string;
+}
+
+// Define fields for each guardrail provider
+const GUARDRAIL_PROVIDER_FIELDS: Record<string, ProviderField[]> = {
+ // Presidio PII fields
+ PresidioPII: [
+ {
+ key: "presidio_analyzer_api_base",
+ label: "Presidio Analyzer API Base",
+ placeholder: "https://your-analyzer-api-url",
+ tooltip: "The base URL for your Presidio Analyzer API",
+ required: true
+ },
+ {
+ key: "presidio_anonymizer_api_base",
+ label: "Presidio Anonymizer API Base",
+ placeholder: "https://your-anonymizer-api-url",
+ tooltip: "The base URL for your Presidio Anonymizer API",
+ required: true
+ }
+ ],
+ // Add more provider specific fields here as needed
+ Bedrock: [
+ {
+ key: "config",
+ label: "Configuration",
+ placeholder: '{"guardrail_id": "...", "guardrail_version": "..."}',
+ tooltip: "JSON configuration for Bedrock guardrail including guardrail_id and guardrail_version",
+ type: "text",
+ required: false
+ }
+ ]
+};
+
+const GuardrailProviderFields: React.FC<GuardrailProviderFieldsProps> = ({
+ selectedProvider
+}) => {
+ // If no provider is selected or if the provider doesn't have specific fields, return null
+ if (!selectedProvider || !GUARDRAIL_PROVIDER_FIELDS[selectedProvider]) {
+ return null;
+ }
+
+ const providerFields = GUARDRAIL_PROVIDER_FIELDS[selectedProvider];
+
+ return (
+ <>
+ {providerFields.map((field) => (
+ <Form.Item
+ key={field.key}
+ name={field.key}
+ label={field.label}
+ tooltip={field.tooltip}
+ rules={field.required ? [{ required: true, message: `Please enter ${field.label}` }] : undefined}
+ >
+ {field.type === "select" ? (
+ <Select placeholder={field.placeholder} defaultValue={field.defaultValue}>
+ {field.options?.map((option) => (
+ <Select.Option key={option} value={option}>
+ {option}
+ </Select.Option>
+ ))}
+ </Select>
+ ) : (
+ <TextInput
+ placeholder={field.placeholder}
+ type={field.type === "password" ? "password" : "text"}
+ />
+ )}
+ </Form.Item>
+ ))}
+ </>
+ );
+};
+
+export default GuardrailProviderFields;
\ No newline at end of file
diff --git a/ui/litellm-dashboard/src/components/guardrails/guardrail_provider_specific_fields.tsx b/ui/litellm-dashboard/src/components/guardrails/guardrail_provider_specific_fields.tsx
new file mode 100644
index 00000000000..5ae3bb3024f
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/guardrails/guardrail_provider_specific_fields.tsx
@@ -0,0 +1,71 @@
+import React from 'react';
+import { Form, Tooltip } from 'antd';
+import { TextInput } from '@tremor/react';
+import { GuardrailProviders } from './guardrail_info_helpers';
+
+interface GuardrailProviderSpecificFieldsProps {
+ selectedProvider: string;
+}
+
+interface FieldConfig {
+ key: string;
+ label: string;
+ placeholder?: string;
+ tooltip?: string;
+ required?: boolean;
+ type?: 'text' | 'password';
+}
+
+// Define field configurations for each guardrail provider
+const PROVIDER_FIELD_CONFIG: Record<string, FieldConfig[]> = {
+ [GuardrailProviders.PresidioPII]: [
+ {
+ key: 'presidio_analyzer_api_base',
+ label: 'Presidio Analyzer API Base',
+ placeholder: 'http://analyzer:3000',
+ tooltip: 'Base URL for the Presidio Analyzer API',
+ required: false,
+ type: 'text'
+ },
+ {
+ key: 'presidio_anonymizer_api_base',
+ label: 'Presidio Anonymizer API Base',
+ placeholder: 'http://anonymizer:3000',
+ tooltip: 'Base URL for the Presidio Anonymizer API',
+ required: false,
+ type: 'text'
+ }
+ ]
+};
+
+const GuardrailProviderSpecificFields: React.FC<GuardrailProviderSpecificFieldsProps> = ({
+ selectedProvider
+}) => {
+ // Get field configurations for the selected provider
+ const fieldConfigs = PROVIDER_FIELD_CONFIG[selectedProvider] || [];
+
+ if (fieldConfigs.length === 0) {
+ return null;
+ }
+
+ return (
+ <>
+ {fieldConfigs.map((field) => (
+ <Form.Item
+ key={field.key}
+ name={field.key}
+ label={field.label}
+ tooltip={field.tooltip}
+ rules={field.required ? [{ required: true, message: 'Required' }] : undefined}
+ >
+ <TextInput
+ placeholder={field.placeholder}
+ type={field.type || 'text'}
+ />
+ </Form.Item>
+ ))}
+ </>
+ );
+};
+
+export default GuardrailProviderSpecificFields;
\ No newline at end of file
diff --git a/ui/litellm-dashboard/src/components/guardrails/types.ts b/ui/litellm-dashboard/src/components/guardrails/types.ts
index 333b987f58e..2e24f77ee3e 100644
--- a/ui/litellm-dashboard/src/components/guardrails/types.ts
+++ b/ui/litellm-dashboard/src/components/guardrails/types.ts
@@ -16,4 +16,19 @@ export interface PiiConfigurationProps {
onEntitySelect: (entity: string) => void;
onActionSelect: (entity: string, action: string) => void;
entityCategories?: PiiEntityCategory[];
+}
+
+export interface Guardrail {
+ guardrail_id: string;
+ guardrail_name: string | null;
+ litellm_params: {
+ guardrail: string;
+ mode: string;
+ default_on: boolean;
+ pii_entities_config?: {[key: string]: string};
+ [key: string]: any;
+ };
+ guardrail_info: Record<string, any> | null;
+ created_at?: string;
+ updated_at?: string;
}
\ No newline at end of file