The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
UI - Add Azure Content Safety Guardrails (improved UX) (#12330)
Krish Dholakiadf4700881800
diff --git a/litellm/integrations/custom_guardrail.py b/litellm/integrations/custom_guardrail.pyindex 2cb80b3d698..8d6182b7e06 100644--- a/litellm/integrations/custom_guardrail.py+++ b/litellm/integrations/custom_guardrail.py@@ -1,5 +1,5 @@from datetime import datetime-from typing import Dict, List, Literal, Optional, Union+from typing import Dict, List, Literal, Optional, Type, Unionfrom litellm._logging import verbose_loggerfrom litellm.integrations.custom_logger import CustomLogger@@ -9,6 +9,7 @@ from litellm.types.guardrails import (LitellmParams,PiiEntityType,)+from litellm.types.proxy.guardrails.guardrail_hooks.base import GuardrailConfigModelfrom litellm.types.utils import StandardLoggingGuardrailInformation@@ -51,6 +52,15 @@ class CustomGuardrail(CustomLogger):self._validate_event_hook(event_hook, supported_event_hooks)super().__init__(**kwargs)+ @staticmethod+ def get_config_model() -> Optional[Type["GuardrailConfigModel"]]:+ """+ Returns the config model for the guardrail++ This is used to render the config model in the UI.+ """+ return None+def _validate_event_hook(self,event_hook: Optional[Union[GuardrailEventHooks, List[GuardrailEventHooks]]],diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.jsonindex 05f13716736..5565cf72f6a 100644--- a/litellm/model_prices_and_context_window_backup.json+++ b/litellm/model_prices_and_context_window_backup.json@@ -750,10 +750,10 @@"max_tokens": 100000,"max_input_tokens": 200000,"max_output_tokens": 100000,- "input_cost_per_token": 10e-06,- "output_cost_per_token": 40e-06,+ "input_cost_per_token": 1e-05,+ "output_cost_per_token": 4e-05,"input_cost_per_token_batches": 5e-06,- "output_cost_per_token_batches": 20e-06,+ "output_cost_per_token_batches": 2e-05,"cache_read_input_token_cost": 2.5e-06,"litellm_provider": "openai","mode": "responses",@@ -783,10 +783,10 @@"max_tokens": 100000,"max_input_tokens": 200000,"max_output_tokens": 100000,- "input_cost_per_token": 10e-06,- "output_cost_per_token": 40e-06,+ "input_cost_per_token": 1e-05,+ "output_cost_per_token": 4e-05,"input_cost_per_token_batches": 5e-06,- "output_cost_per_token_batches": 20e-06,+ "output_cost_per_token_batches": 2e-05,"cache_read_input_token_cost": 2.5e-06,"litellm_provider": "openai","mode": "responses",@@ -994,7 +994,7 @@"output_cost_per_token": 8e-06,"input_cost_per_token_batches": 1e-06,"output_cost_per_token_batches": 4e-06,- "cache_read_input_token_cost": 0.5e-06,+ "cache_read_input_token_cost": 5e-07,"litellm_provider": "openai","mode": "responses","supported_endpoints": [@@ -1027,7 +1027,7 @@"output_cost_per_token": 8e-06,"input_cost_per_token_batches": 1e-06,"output_cost_per_token_batches": 4e-06,- "cache_read_input_token_cost": 0.5e-06,+ "cache_read_input_token_cost": 5e-07,"litellm_provider": "openai","mode": "responses","supported_endpoints": [@@ -10944,8 +10944,7 @@"output_cost_per_token": 2.4e-05,"litellm_provider": "bedrock","mode": "chat",- "supports_function_calling": true,- "supports_tool_choice": true+ "supports_function_calling": true},"mistral.mistral-large-2407-v1:0": {"max_tokens": 8191,@@ -10966,8 +10965,7 @@"output_cost_per_token": 3e-06,"litellm_provider": "bedrock","mode": "chat",- "supports_function_calling": true,- "supports_tool_choice": true+ "supports_function_calling": true},"bedrock/us-west-2/mistral.mixtral-8x7b-instruct-v0:1": {"max_tokens": 8191,@@ -11037,8 +11035,7 @@"output_cost_per_token": 2.4e-05,"litellm_provider": "bedrock","mode": "chat",- "supports_function_calling": true,- "supports_tool_choice": true+ "supports_function_calling": true},"bedrock/us-west-2/mistral.mistral-large-2402-v1:0": {"max_tokens": 8191,@@ -11048,8 +11045,7 @@"output_cost_per_token": 2.4e-05,"litellm_provider": "bedrock","mode": "chat",- "supports_function_calling": true,- "supports_tool_choice": true+ "supports_function_calling": true},"bedrock/eu-west-3/mistral.mistral-large-2402-v1:0": {"max_tokens": 8191,@@ -11059,8 +11055,7 @@"output_cost_per_token": 3.12e-05,"litellm_provider": "bedrock","mode": "chat",- "supports_function_calling": true,- "supports_tool_choice": true+ "supports_function_calling": true},"amazon.nova-micro-v1:0": {"max_tokens": 10000,@@ -15755,7 +15750,7 @@},"elevenlabs/scribe_v1": {"mode": "audio_transcription",- "input_cost_per_second": 0.0000611,+ "input_cost_per_second": 6.11e-05,"output_cost_per_second": 0.0,"litellm_provider": "elevenlabs","supported_endpoints": [@@ -15770,7 +15765,7 @@},"elevenlabs/scribe_v1_experimental": {"mode": "audio_transcription",- "input_cost_per_second": 0.0000611,+ "input_cost_per_second": 6.11e-05,"output_cost_per_second": 0.0,"litellm_provider": "elevenlabs","supported_endpoints": [@@ -15783,4 +15778,4 @@"notes": "ElevenLabs Scribe v1 experimental - enhanced version of the main Scribe model"}}-}+}\ No newline at end of filediff --git a/litellm/proxy/guardrails/guardrail_endpoints.py b/litellm/proxy/guardrails/guardrail_endpoints.pyindex cb79fc0871c..7680bf394f4 100644--- a/litellm/proxy/guardrails/guardrail_endpoints.py+++ b/litellm/proxy/guardrails/guardrail_endpoints.py@@ -2,7 +2,7 @@CRUD ENDPOINTS FOR GUARDRAILS"""-from typing import Any, Dict, List, Optional, Type, cast+from typing import Any, Dict, List, Optional, Type, Union, castfrom fastapi import APIRouter, Depends, HTTPExceptionfrom pydantic import BaseModel@@ -12,13 +12,10 @@ from litellm.proxy.auth.user_api_key_auth import user_api_key_authfrom litellm.proxy.guardrails.guardrail_registry import GuardrailRegistryfrom litellm.types.guardrails import (PII_ENTITY_CATEGORIES_MAP,- AzureContentSafetyPromptShieldConfigModel,- AzureContentSafetyTextModerationConfigModel,BedrockGuardrailConfigModel,Guardrail,GuardrailEventHooks,GuardrailInfoResponse,- GuardrailParamUITypes,GuardrailUIAddGuardrailSettings,LakeraV2GuardrailConfigModel,ListGuardrailsResponse,@@ -689,32 +686,217 @@ async def get_guardrail_ui_settings():)-def _get_fields_from_model(model_class: Type[BaseModel]) -> List[Dict[str, Any]]:+def _get_field_type_from_annotation(field_annotation: Any) -> str:"""- Get the fields from a Pydantic model+ Convert a Python type annotation to a UI-friendly type string"""- fields = []- for field_name, field in model_class.model_fields.items():- # Get field metadata- description = field.description or field_name+ # Handle Union types (like Optional[T])+ if (+ hasattr(field_annotation, "__origin__")+ and field_annotation.__origin__ is Union+ and hasattr(field_annotation, "__args__")+ ):+ # For Optional[T], get the non-None type+ args = field_annotation.__args__+ non_none_args = [arg for arg in args if arg is not type(None)]+ if non_none_args:+ field_annotation = non_none_args[0]++ # Handle List types+ if hasattr(field_annotation, "__origin__") and field_annotation.__origin__ is list:+ return "array"++ # Handle Dict types+ if hasattr(field_annotation, "__origin__") and field_annotation.__origin__ is dict:+ return "dict"++ # Handle Literal types+ if hasattr(field_annotation, "__origin__") and hasattr(+ field_annotation, "__args__"+ ):+ # Check for Literal types (Python 3.8+)+ origin = field_annotation.__origin__+ if hasattr(origin, "__name__") and origin.__name__ == "Literal":+ return "select" # For dropdown/select inputs++ # Handle basic types+ if field_annotation is str:+ return "string"+ elif field_annotation is int:+ return "number"+ elif field_annotation is float:+ return "number"+ elif field_annotation is bool:+ return "boolean"+ elif field_annotation is dict:+ return "object"+ elif field_annotation is list:+ return "array"++ # Default to string for unknown types+ return "string"+++def _extract_literal_values(annotation: Any) -> List[str]:+ """+ Extract literal values from a Literal type annotation+ """+ if hasattr(annotation, "__origin__") and hasattr(annotation, "__args__"):+ origin = annotation.__origin__+ if hasattr(origin, "__name__") and origin.__name__ == "Literal":+ return list(annotation.__args__)+ return []- # Check if this field is in the required_fields class variable- required = field.is_required()- field_type: Optional[GuardrailParamUITypes] = None- field_json_schema_extra = getattr(field, "json_schema_extra", {})- if field_json_schema_extra and "ui_type" in field_json_schema_extra:- field_type = field_json_schema_extra["ui_type"]+def _get_dict_key_options(field_annotation: Any) -> Optional[List[str]]:+ """+ Extract key options from Dict[Literal[...], T] types+ """+ if (+ hasattr(field_annotation, "__origin__")+ and field_annotation.__origin__ is dict+ and hasattr(field_annotation, "__args__")+ ):+ args = field_annotation.__args__+ if len(args) >= 2:+ key_type = args[0]+ return _extract_literal_values(key_type)+ return None+++def _get_dict_value_type(field_annotation: Any) -> str:+ """+ Get the value type from Dict[K, V] types+ """+ if (+ hasattr(field_annotation, "__origin__")+ and field_annotation.__origin__ is dict+ and hasattr(field_annotation, "__args__")+ ):+ args = field_annotation.__args__+ if len(args) >= 2:+ value_type = args[1]+ return _get_field_type_from_annotation(value_type)+ return "string"+++def _get_list_element_options(field_annotation: Any) -> Optional[List[str]]:+ """+ Extract element options from List[Literal[...]] types+ """+ if (+ hasattr(field_annotation, "__origin__")+ and field_annotation.__origin__ is list+ and hasattr(field_annotation, "__args__")+ ):+ args = field_annotation.__args__+ if len(args) >= 1:+ element_type = args[0]+ return _extract_literal_values(element_type)+ return None+++def _get_fields_from_model(model_class: Type[BaseModel]) -> Dict[str, Any]:+ """+ Get the fields from a Pydantic model as a nested dictionary structure+ """+ import inspect++ def _extract_fields_recursive(model: Type[BaseModel]) -> Dict[str, Any]:+ fields = {}++ for field_name, field in model.model_fields.items():+ # Get field metadata+ description = field.description or field_name++ # Check if this field is required+ required = field.is_required()++ # Check if the field annotation is a BaseModel subclass+ field_annotation = field.annotation++ # Handle Optional types and get the actual type+ if field_annotation is None:+ continue++ if (+ hasattr(field_annotation, "__origin__")+ and field_annotation.__origin__ is Union+ and hasattr(field_annotation, "__args__")+ ):+ # For Optional[BaseModel], get the non-None type+ args = field_annotation.__args__+ non_none_args = [arg for arg in args if arg is not type(None)]+ if non_none_args:+ field_annotation = non_none_args[0]++ # Check if this is a BaseModel subclass+ is_basemodel_subclass = (+ inspect.isclass(field_annotation)+ and issubclass(field_annotation, BaseModel)+ and field_annotation is not BaseModel+ )- fields.append(- {- "param": field_name,- "description": description,- "required": required,- "type": field_type.value if field_type else None,- }- )- return fields+ if is_basemodel_subclass:+ # Recursively get fields from the nested model+ nested_fields = _extract_fields_recursive(+ cast(Type[BaseModel], field_annotation)+ )+ fields[field_name] = {+ "description": description,+ "required": required,+ "type": "nested",+ "fields": nested_fields,+ }+ else:+ # Determine the field type from annotation+ field_type = _get_field_type_from_annotation(field_annotation)++ # Check for custom UI type override+ field_json_schema_extra = getattr(field, "json_schema_extra", {})+ if field_json_schema_extra and "ui_type" in field_json_schema_extra:+ field_type = field_json_schema_extra["ui_type"].value+ elif field_json_schema_extra and "type" in field_json_schema_extra:+ field_type = field_json_schema_extra["type"]++ # Add the field to the dictionary+ field_dict = {+ "description": description,+ "required": required,+ "type": field_type,+ }++ # Extract options from type annotations+ if field_type == "dict":+ # For Dict[Literal[...], T] types, extract key options+ dict_key_options = _get_dict_key_options(field_annotation)+ if dict_key_options:+ field_dict["dict_key_options"] = dict_key_options++ # Extract value type for the dict values+ dict_value_type = _get_dict_value_type(field_annotation)+ field_dict["dict_value_type"] = dict_value_type++ elif field_type == "array":+ # For List[Literal[...]] types, extract element options+ list_element_options = _get_list_element_options(field_annotation)+ if list_element_options:+ field_dict["options"] = list_element_options+ field_dict["type"] = "multiselect"++ # Add options if they exist in json_schema_extra (this takes precedence)+ if field_json_schema_extra and "options" in field_json_schema_extra:+ field_dict["options"] = field_json_schema_extra["options"]++ # Add default value if it exists+ if field.default is not None and field.default is not ...:+ field_dict["default_value"] = field.default++ fields[field_name] = field_dict++ return fields++ return _extract_fields_recursive(model_class)@router.get(@@ -732,36 +914,44 @@ async def get_provider_specific_params():Example Response:```json{- "bedrock": [- {- "param": "guardrailIdentifier",+ "bedrock": {+ "guardrailIdentifier": {"description": "The ID of your guardrail on Bedrock",- "required": true+ "required": true,+ "type": null},- {- "param": "guardrailVersion",+ "guardrailVersion": {"description": "The version of your Bedrock guardrail (e.g., DRAFT or version number)",- "required": true+ "required": true,+ "type": null}- ],- "presidio": [- {- "param": "presidio_analyzer_api_base",- "description": "Base URL for the Presidio analyzer API",- "required": true- },- {- "param": "presidio_anonymizer_api_base",- "description": "Base URL for the Presidio anonymizer API",- "required": true- },- {- "param": "output_parse_pii",- "description": "Whether to parse PII in model outputs",+ },+ "azure_content_safety_text_moderation": {+ "api_key": {+ "description": "API key for the Azure Content Safety Text Moderation guardrail","required": false,- "type": "bool"+ "type": null+ },+ "optional_params": {+ "description": "Optional parameters for the Azure Content Safety Text Moderation guardrail",+ "required": true,+ "type": "nested",+ "fields": {+ "severity_threshold": {+ "description": "Severity threshold for the Azure Content Safety Text Moderation guardrail across all categories",+ "required": false,+ "type": null+ },+ "categories": {+ "description": "Categories to scan for the Azure Content Safety Text Moderation guardrail",+ "required": false,+ "type": "multiselect",+ "options": ["Hate", "SelfHarm", "Sexual", "Violence"],+ "default_value": None+ }+ }}- ]+ }}```"""@@ -769,20 +959,22 @@ async def get_provider_specific_params():bedrock_fields = _get_fields_from_model(BedrockGuardrailConfigModel)presidio_fields = _get_fields_from_model(PresidioPresidioConfigModelUserInterface)lakera_v2_fields = _get_fields_from_model(LakeraV2GuardrailConfigModel)- azure_content_safety_prompt_shield_fields = _get_fields_from_model(- AzureContentSafetyPromptShieldConfigModel- )- azure_content_safety_text_moderation_fields = _get_fields_from_model(- AzureContentSafetyTextModerationConfigModel- )# Return the provider-specific parametersprovider_params = {SupportedGuardrailIntegrations.BEDROCK.value: bedrock_fields,SupportedGuardrailIntegrations.PRESIDIO.value: presidio_fields,SupportedGuardrailIntegrations.LAKERA_V2.value: lakera_v2_fields,- SupportedGuardrailIntegrations.AZURE_PROMPT_SHIELD.value: azure_content_safety_prompt_shield_fields,- SupportedGuardrailIntegrations.AZURE_TEXT_MODERATIONS.value: azure_content_safety_text_moderation_fields,}+ ### get the config model for the guardrail - go through the registry and get the config model for the guardrail+ from litellm.proxy.guardrails.guardrail_registry import guardrail_class_registry++ for guardrail_name, guardrail_class in guardrail_class_registry.items():+ guardrail_config_model = guardrail_class.get_config_model()++ if guardrail_config_model:+ fields = _get_fields_from_model(guardrail_config_model)+ provider_params[guardrail_name] = fields+return provider_paramsdiff --git a/litellm/proxy/guardrails/guardrail_hooks/azure/__init__.py b/litellm/proxy/guardrails/guardrail_hooks/azure/__init__.pyindex 39501ca470d..9f69c71303b 100644--- a/litellm/proxy/guardrails/guardrail_hooks/azure/__init__.py+++ b/litellm/proxy/guardrails/guardrail_hooks/azure/__init__.py@@ -2,6 +2,9 @@ from typing import TYPE_CHECKING, Unionfrom litellm.types.guardrails import SupportedGuardrailIntegrations+from .prompt_shield import AzureContentSafetyPromptShieldGuardrail+from .text_moderation import AzureContentSafetyTextModerationGuardrail+if TYPE_CHECKING:from litellm.types.guardrails import Guardrail, LitellmParams@@ -9,9 +12,6 @@ if TYPE_CHECKING:def initialize_guardrail(litellm_params: "LitellmParams", guardrail: "Guardrail"):import litellm- from .prompt_shield import AzureContentSafetyPromptShieldGuardrail- from .text_moderation import AzureContentSafetyTextModerationGuardrail-if not litellm_params.api_key:raise ValueError("Azure Content Safety: api_key is required")if not litellm_params.api_base:@@ -57,3 +57,9 @@ guardrail_initializer_registry = {SupportedGuardrailIntegrations.AZURE_PROMPT_SHIELD.value: initialize_guardrail,SupportedGuardrailIntegrations.AZURE_TEXT_MODERATIONS.value: initialize_guardrail,}+++guardrail_class_registry = {+ SupportedGuardrailIntegrations.AZURE_PROMPT_SHIELD.value: AzureContentSafetyPromptShieldGuardrail,+ SupportedGuardrailIntegrations.AZURE_TEXT_MODERATIONS.value: AzureContentSafetyTextModerationGuardrail,+}diff --git a/litellm/proxy/guardrails/guardrail_hooks/azure/prompt_shield.py b/litellm/proxy/guardrails/guardrail_hooks/azure/prompt_shield.pyindex 7624a963b77..fc589263f57 100644--- a/litellm/proxy/guardrails/guardrail_hooks/azure/prompt_shield.py+++ b/litellm/proxy/guardrails/guardrail_hooks/azure/prompt_shield.py@@ -3,7 +3,7 @@Azure Prompt Shield Native Guardrail Integrationfor LiteLLM"""-from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, cast+from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Type, castfrom fastapi import HTTPException@@ -25,6 +25,7 @@ if TYPE_CHECKING:from litellm.types.proxy.guardrails.guardrail_hooks.azure.azure_prompt_shield import (AzurePromptShieldGuardrailResponse,)+ from litellm.types.proxy.guardrails.guardrail_hooks.base import GuardrailConfigModelfrom litellm.types.utils import ModelResponse@@ -183,3 +184,14 @@ class AzureContentSafetyPromptShieldGuardrail(AzureGuardrailBase, CustomGuardrai)return response++ @staticmethod+ def get_config_model() -> Optional[Type["GuardrailConfigModel"]]:+ """+ Get the config model for the Azure Prompt Shield guardrail.+ """+ from litellm.types.proxy.guardrails.guardrail_hooks.azure.azure_prompt_shield import (+ AzurePromptShieldGuardrailConfigModel,+ )++ return AzurePromptShieldGuardrailConfigModeldiff --git a/litellm/proxy/guardrails/guardrail_hooks/azure/text_moderation.py b/litellm/proxy/guardrails/guardrail_hooks/azure/text_moderation.pyindex d1f154daead..1e7c294ed5b 100644--- a/litellm/proxy/guardrails/guardrail_hooks/azure/text_moderation.py+++ b/litellm/proxy/guardrails/guardrail_hooks/azure/text_moderation.py@@ -3,7 +3,7 @@Azure Text Moderation Native Guardrail Integrationfor LiteLLM"""-from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Union, cast+from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Type, Union, castfrom fastapi import HTTPException@@ -21,11 +21,13 @@ from litellm.proxy._types import UserAPIKeyAuthfrom .base import AzureGuardrailBaseif TYPE_CHECKING:+from litellm.proxy._types import UserAPIKeyAuthfrom litellm.types.llms.openai import AllMessageValuesfrom litellm.types.proxy.guardrails.guardrail_hooks.azure.azure_text_moderation import (AzureTextModerationGuardrailResponse,)+ from litellm.types.proxy.guardrails.guardrail_hooks.base import GuardrailConfigModelfrom litellm.types.utils import EmbeddingResponse, ImageResponse, ModelResponse@@ -96,6 +98,14 @@ class AzureContentSafetyTextModerationGuardrail(AzureGuardrailBase, CustomGuardrf"Initialized Azure Prompt Shield Guardrail: {guardrail_name}")+ @staticmethod+ def get_config_model() -> Optional[Type["GuardrailConfigModel"]]:+ from litellm.types.proxy.guardrails.guardrail_hooks.azure.azure_text_moderation import (+ AzureContentSafetyTextModerationConfigModel,+ )++ return AzureContentSafetyTextModerationConfigModel+async def async_make_request(self, text: str) -> "AzureTextModerationGuardrailResponse":diff --git a/litellm/proxy/guardrails/guardrail_registry.py b/litellm/proxy/guardrails/guardrail_registry.pyindex fb6810a1893..4fec8e4830f 100644--- a/litellm/proxy/guardrails/guardrail_registry.py+++ b/litellm/proxy/guardrails/guardrail_registry.py@@ -4,7 +4,7 @@ import importlibimport osimport uuidfrom datetime import datetime, timezone-from typing import Dict, List, Optional, cast+from typing import Dict, List, Optional, Type, castimport litellmfrom litellm._logging import verbose_proxy_logger@@ -48,6 +48,8 @@ guardrail_initializer_registry = {SupportedGuardrailIntegrations.PANW_PRISMA_AIRS.value: initialize_panw_prisma_airs,}+guardrail_class_registry: Dict[str, Type[CustomGuardrail]] = {}+def get_guardrail_initializer_from_hooks():"""@@ -125,6 +127,74 @@ def get_guardrail_initializer_from_hooks():return discovered_initializers+def get_guardrail_class_from_hooks():+ """+ Get guardrail classes by discovering them from the guardrail_hooks directory structure.+ """+ """+ Get guardrail initializers by discovering them from the guardrail_hooks directory structure.++ Scans the guardrail_hooks directory for subdirectories containing __init__.py files+ with either guardrail_initializer_registry or initialize_guardrail functions.++ Returns:+ Dict[str, Callable]: A dictionary mapping guardrail types to their initializer functions+ """+ discovered_classes = {}++ try:+ # Get the path to the guardrail_hooks directory+ current_dir = os.path.dirname(__file__)+ hooks_dir = os.path.join(current_dir, "guardrail_hooks")++ if not os.path.exists(hooks_dir):+ verbose_proxy_logger.debug("guardrail_hooks directory not found")+ return discovered_classes++ # Scan each subdirectory in guardrail_hooks+ for item in os.listdir(hooks_dir):+ item_path = os.path.join(hooks_dir, item)++ # Skip files and __pycache__ directories+ if not os.path.isdir(item_path) or item.startswith("__"):+ continue++ # Check if the directory has an __init__.py file+ init_file = os.path.join(item_path, "__init__.py")++ if not os.path.exists(init_file):+ continue++ module_path = f"litellm.proxy.guardrails.guardrail_hooks.{item}"++ try:+ # Import the module+ verbose_proxy_logger.debug(f"Discovering guardrails in: {module_path}")++ module = importlib.import_module(module_path)++ # Check for guardrail_initializer_registry dictionary+ if hasattr(module, "guardrail_class_registry"):+ registry = getattr(module, "guardrail_class_registry")+ if isinstance(registry, dict):+ discovered_classes.update(registry)++ except ImportError as e:+ verbose_proxy_logger.debug(f"Could not import {module_path}: {e}")+ continue+ except Exception as e:+ verbose_proxy_logger.error(f"Error processing {module_path}: {e}")+ continue++ except Exception as e:+ verbose_proxy_logger.error(f"Error discovering guardrail initializers: {e}")++ return discovered_classes+++guardrail_class_registry.update(get_guardrail_class_from_hooks())++# Merge with dynamically discovered guardrail initializers_discovered_initializers = get_guardrail_initializer_from_hooks()diff --git a/litellm/types/guardrails.py b/litellm/types/guardrails.pyindex 96dc572ac32..742dcf82b5a 100644--- a/litellm/types/guardrails.py+++ b/litellm/types/guardrails.py@@ -339,59 +339,6 @@ class LassoGuardrailConfigModel(BaseModel):)-class AzureContentSafetyConfigModel(BaseModel):- """Configuration parameters for the Azure Content Safety Prompt Shield guardrail"""-- api_key: Optional[str] = Field(- default=None,- description="API key for the Azure Content Safety Prompt Shield guardrail",- )-- api_base: Optional[str] = Field(- default=None,- description="Base URL for the Azure Content Safety Prompt Shield guardrail",- )- api_version: Optional[str] = Field(- default=None,- description="API version for the Azure Content Safety Prompt Shield guardrail",- )---class AzureContentSafetyPromptShieldConfigModel(AzureContentSafetyConfigModel):- """Configuration parameters for the Azure Content Safety Prompt Shield guardrail"""-- pass---class AzureContentSafetyTextModerationConfigModel(AzureContentSafetyConfigModel):-- severity_threshold: Optional[int] = Field(- default=None,- description="Severity threshold for the Azure Content Safety Text Moderation guardrail across all categories",- )- severity_threshold_by_category: Optional[Dict[str, int]] = Field(- default=None,- description="Severity threshold by category for the Azure Content Safety Text Moderation guardrail. See list of categories - https://learn.microsoft.com/en-us/azure/ai-services/content-safety/concepts/harm-categories?tabs=warning",- )-- categories: Optional[List[str]] = Field(- default=None,- description="Categories to scan for the Azure Content Safety Text Moderation guardrail. See list of categories - https://learn.microsoft.com/en-us/azure/ai-services/content-safety/concepts/harm-categories?tabs=warning",- )- blocklistNames: Optional[List[str]] = Field(- default=None,- description="Blocklist names to scan for the Azure Content Safety Text Moderation guardrail. Learn more - https://learn.microsoft.com/en-us/azure/ai-services/content-safety/quickstart-text",- )- haltOnBlocklistHit: Optional[bool] = Field(- default=None,- description="Whether to halt the request if a blocklist hit is detected",- )- outputType: Optional[Literal["FourSeverityLevels", "EightSeverityLevels"]] = Field(- default=None,- description="Output type for the Azure Content Safety Text Moderation guardrail. Learn more - https://learn.microsoft.com/en-us/azure/ai-services/content-safety/quickstart-text",- )--class LitellmParams(PresidioConfigModel,BedrockGuardrailConfigModel,diff --git a/litellm/types/proxy/guardrails/guardrail_hooks/azure/azure_prompt_shield.py b/litellm/types/proxy/guardrails/guardrail_hooks/azure/azure_prompt_shield.pyindex 6b7f1da7620..1683b3841dd 100644--- a/litellm/types/proxy/guardrails/guardrail_hooks/azure/azure_prompt_shield.py+++ b/litellm/types/proxy/guardrails/guardrail_hooks/azure/azure_prompt_shield.py@@ -1,5 +1,9 @@from typing import Any, Dict, List, TypedDict+from litellm.types.proxy.guardrails.guardrail_hooks.base import GuardrailConfigModel++from .base import AzureContentSafetyConfigModel+class AzurePromptShieldGuardrailRequestBody(TypedDict):"""Configuration parameters for the Azure Prompt Shield guardrail"""@@ -17,3 +21,10 @@ class AzurePromptShieldGuardrailResponse(TypedDict):userPromptAnalysis: UserPromptAnalysisdocumentsAnalysis: List[Dict[str, Any]]+++class AzurePromptShieldGuardrailConfigModel(+ AzureContentSafetyConfigModel,+ GuardrailConfigModel,+):+ passdiff --git a/litellm/types/proxy/guardrails/guardrail_hooks/azure/azure_text_moderation.py b/litellm/types/proxy/guardrails/guardrail_hooks/azure/azure_text_moderation.pyindex 39fad0553b7..8d339c6ded7 100644--- a/litellm/types/proxy/guardrails/guardrail_hooks/azure/azure_text_moderation.py+++ b/litellm/types/proxy/guardrails/guardrail_hooks/azure/azure_text_moderation.py@@ -1,5 +1,13 @@from typing import Any, Dict, List, Literal, Optional, Required, TypedDict+from pydantic import BaseModel, Field++from ..base import GuardrailConfigModel+from .base import AzureContentSafetyConfigModel++# Shared Azure Content Safety categories+AZURE_CONTENT_SAFETY_CATEGORIES = ["Hate", "SelfHarm", "Sexual", "Violence"]+class AzureTextModerationRequestBodyOptionalParams(TypedDict, total=False):"""Optional parameters for the Azure Text Moderation guardrail"""@@ -30,3 +38,44 @@ class AzureTextModerationGuardrailResponse(TypedDict):blocklistsMatch: List[Dict[str, Any]]categoriesAnalysis: List[AzureTextModerationGuardrailResponseCategoriesAnalysis]+++AzureHarmCategories = Literal["Hate", "SelfHarm", "Sexual", "Violence"]+++class AzureTextModerationOptionalParams(BaseModel):+ severity_threshold: Optional[int] = Field(+ default=None,+ description="Severity threshold for the Azure Content Safety Text Moderation guardrail across all categories",+ )+ severity_threshold_by_category: Optional[Dict[AzureHarmCategories, int]] = Field(+ default=None,+ description="Severity threshold by category for the Azure Content Safety Text Moderation guardrail. See list of categories - https://learn.microsoft.com/en-us/azure/ai-services/content-safety/concepts/harm-categories?tabs=warning",+ )++ categories: Optional[List[AzureHarmCategories]] = Field(+ default=None,+ description="Categories to scan for the Azure Content Safety Text Moderation guardrail. See list of categories - https://learn.microsoft.com/en-us/azure/ai-services/content-safety/concepts/harm-categories?tabs=warning",+ )+ blocklistNames: Optional[List[str]] = Field(+ default=None,+ description="Blocklist names to scan for the Azure Content Safety Text Moderation guardrail. Learn more - https://learn.microsoft.com/en-us/azure/ai-services/content-safety/quickstart-text",+ )+ haltOnBlocklistHit: Optional[bool] = Field(+ default=None,+ description="Whether to halt the request if a blocklist hit is detected",+ )+ outputType: Optional[Literal["FourSeverityLevels", "EightSeverityLevels"]] = Field(+ default=None,+ description="Output type for the Azure Content Safety Text Moderation guardrail. Learn more - https://learn.microsoft.com/en-us/azure/ai-services/content-safety/quickstart-text",+ )+++class AzureContentSafetyTextModerationConfigModel(+ AzureContentSafetyConfigModel,+ GuardrailConfigModel[AzureTextModerationOptionalParams],+):++ optional_params: AzureTextModerationOptionalParams = Field(+ description="Optional parameters for the Azure Content Safety Text Moderation guardrail",+ )diff --git a/litellm/types/proxy/guardrails/guardrail_hooks/azure/base.py b/litellm/types/proxy/guardrails/guardrail_hooks/azure/base.pynew file mode 100644index 00000000000..2f54bd3cc77--- /dev/null+++ b/litellm/types/proxy/guardrails/guardrail_hooks/azure/base.py@@ -0,0 +1,21 @@+from typing import Optional++from pydantic import BaseModel, Field+++class AzureContentSafetyConfigModel(BaseModel):+ """Configuration parameters for the Azure Content Safety Prompt Shield guardrail"""++ api_key: Optional[str] = Field(+ default=None,+ description="API key for the Azure Content Safety Prompt Shield guardrail",+ )++ api_base: Optional[str] = Field(+ default=None,+ description="Base URL for the Azure Content Safety Prompt Shield guardrail",+ )+ api_version: Optional[str] = Field(+ default="2024-09-01",+ description="API version for the Azure Content Safety Prompt Shield guardrail. Default is 2024-09-01",+ )diff --git a/litellm/types/proxy/guardrails/guardrail_hooks/base.py b/litellm/types/proxy/guardrails/guardrail_hooks/base.pynew file mode 100644index 00000000000..c346784edb1--- /dev/null+++ b/litellm/types/proxy/guardrails/guardrail_hooks/base.py@@ -0,0 +1,13 @@+from typing import Generic, TypeVar++from pydantic import BaseModel, Field++T = TypeVar("T", bound=BaseModel)+++class GuardrailConfigModel(BaseModel, Generic[T]):+ """Base model for guardrail configuration"""++ optional_params: T = Field(+ description="Optional parameters for the guardrail",+ )diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.jsonindex 7d21ec9a967..bc19668e6a1 100644--- a/model_prices_and_context_window.json+++ b/model_prices_and_context_window.json@@ -768,10 +768,10 @@"max_tokens": 100000,"max_input_tokens": 200000,"max_output_tokens": 100000,- "input_cost_per_token": 10e-06,- "output_cost_per_token": 40e-06,+ "input_cost_per_token": 1e-05,+ "output_cost_per_token": 4e-05,"input_cost_per_token_batches": 5e-06,- "output_cost_per_token_batches": 20e-06,+ "output_cost_per_token_batches": 2e-05,"cache_read_input_token_cost": 2.5e-06,"litellm_provider": "openai","mode": "responses",@@ -801,10 +801,10 @@"max_tokens": 100000,"max_input_tokens": 200000,"max_output_tokens": 100000,- "input_cost_per_token": 10e-06,- "output_cost_per_token": 40e-06,+ "input_cost_per_token": 1e-05,+ "output_cost_per_token": 4e-05,"input_cost_per_token_batches": 5e-06,- "output_cost_per_token_batches": 20e-06,+ "output_cost_per_token_batches": 2e-05,"cache_read_input_token_cost": 2.5e-06,"litellm_provider": "openai","mode": "responses",@@ -1012,7 +1012,7 @@"output_cost_per_token": 8e-06,"input_cost_per_token_batches": 1e-06,"output_cost_per_token_batches": 4e-06,- "cache_read_input_token_cost": 0.5e-06,+ "cache_read_input_token_cost": 5e-07,"litellm_provider": "openai","mode": "responses","supported_endpoints": [@@ -1045,7 +1045,7 @@"output_cost_per_token": 8e-06,"input_cost_per_token_batches": 1e-06,"output_cost_per_token_batches": 4e-06,- "cache_read_input_token_cost": 0.5e-06,+ "cache_read_input_token_cost": 5e-07,"litellm_provider": "openai","mode": "responses","supported_endpoints": [@@ -10962,8 +10962,7 @@"output_cost_per_token": 2.4e-05,"litellm_provider": "bedrock","mode": "chat",- "supports_function_calling": true,- "supports_tool_choice": true+ "supports_function_calling": true},"mistral.mistral-large-2407-v1:0": {"max_tokens": 8191,@@ -10984,8 +10983,7 @@"output_cost_per_token": 3e-06,"litellm_provider": "bedrock","mode": "chat",- "supports_function_calling": true,- "supports_tool_choice": true+ "supports_function_calling": true},"bedrock/us-west-2/mistral.mixtral-8x7b-instruct-v0:1": {"max_tokens": 8191,@@ -11055,8 +11053,7 @@"output_cost_per_token": 2.4e-05,"litellm_provider": "bedrock","mode": "chat",- "supports_function_calling": true,- "supports_tool_choice": true+ "supports_function_calling": true},"bedrock/us-west-2/mistral.mistral-large-2402-v1:0": {"max_tokens": 8191,@@ -11066,8 +11063,7 @@"output_cost_per_token": 2.4e-05,"litellm_provider": "bedrock","mode": "chat",- "supports_function_calling": true,- "supports_tool_choice": true+ "supports_function_calling": true},"bedrock/eu-west-3/mistral.mistral-large-2402-v1:0": {"max_tokens": 8191,@@ -11077,8 +11073,7 @@"output_cost_per_token": 3.12e-05,"litellm_provider": "bedrock","mode": "chat",- "supports_function_calling": true,- "supports_tool_choice": true+ "supports_function_calling": true},"amazon.nova-micro-v1:0": {"max_tokens": 10000,@@ -15773,7 +15768,7 @@},"elevenlabs/scribe_v1": {"mode": "audio_transcription",- "input_cost_per_second": 0.0000611,+ "input_cost_per_second": 6.11e-05,"output_cost_per_second": 0.0,"litellm_provider": "elevenlabs","supported_endpoints": [@@ -15788,7 +15783,7 @@},"elevenlabs/scribe_v1_experimental": {"mode": "audio_transcription",- "input_cost_per_second": 0.0000611,+ "input_cost_per_second": 6.11e-05,"output_cost_per_second": 0.0,"litellm_provider": "elevenlabs","supported_endpoints": [@@ -15801,4 +15796,4 @@"notes": "ElevenLabs Scribe v1 experimental - enhanced version of the main Scribe model"}}-}+}\ No newline at end of filediff --git a/test_script.py b/test_script.pyindex e4b4e2d0013..be44d11801f 100644--- a/test_script.py+++ b/test_script.py@@ -4,14 +4,20 @@ mistral_model_cost_map = json.load(open("model_prices_and_context_window.json"))for model, model_info in mistral_model_cost_map.items():if (- (model_info.get("litellm_provider") == "mistral")+ "bedrock" in model_info.get("litellm_provider")and model_info.get("mode") == "chat"- and ("codestral-mamba" not in model)+ and any(+ m in model+ for m in [+ "mistral.mistral-large-2402-v1:0",+ "mistral.mistral-small-2402-v1:0",+ ]+ )):"""Update all mistral models to supports_response_schema"""- model_info["supports_response_schema"] = True+ del model_info["supports_tool_choice"]print(f"Updated {model} to support response schema")json.dump(diff --git a/tests/test_litellm/proxy/guardrails/test_guardrail_endpoints.py b/tests/test_litellm/proxy/guardrails/test_guardrail_endpoints.pyindex 9e5acf84efe..c4d9f517db6 100644--- a/tests/test_litellm/proxy/guardrails/test_guardrail_endpoints.py+++ b/tests/test_litellm/proxy/guardrails/test_guardrail_endpoints.py@@ -170,3 +170,65 @@ async def test_get_guardrail_info_not_found(assert exc_info.value.status_code == 404assert "not found" in str(exc_info.value.detail)+++def test_get_provider_specific_params():+ """Test getting provider-specific parameters"""+ from litellm.proxy.guardrails.guardrail_endpoints import _get_fields_from_model+ from litellm.proxy.guardrails.guardrail_hooks.azure import (+ AzureContentSafetyTextModerationGuardrail,+ )++ fields = _get_fields_from_model(+ AzureContentSafetyTextModerationGuardrail.get_config_model()+ )+ print("FIELDS", fields)++ # Test that we get the expected nested structure+ assert isinstance(fields, dict)++ # Check that we have the expected top-level fields+ assert "api_key" in fields+ assert "api_base" in fields+ assert "api_version" in fields+ assert "optional_params" in fields++ # Check the structure of a simple field+ assert (+ fields["api_key"]["description"]+ == "API key for the Azure Content Safety Prompt Shield guardrail"+ )+ assert fields["api_key"]["required"] == False+ assert fields["api_key"]["type"] == "string" # Should be string, not None++ # Check the structure of the nested optional_params field+ assert fields["optional_params"]["type"] == "nested"+ assert fields["optional_params"]["required"] == True+ assert "fields" in fields["optional_params"]++ # Check nested fields within optional_params+ nested_fields = fields["optional_params"]["fields"]+ assert "severity_threshold" in nested_fields+ assert "severity_threshold_by_category" in nested_fields+ assert "categories" in nested_fields+ assert "blocklistNames" in nested_fields+ assert "haltOnBlocklistHit" in nested_fields+ assert "outputType" in nested_fields++ # Check structure of a nested field+ assert (+ nested_fields["severity_threshold"]["description"]+ == "Severity threshold for the Azure Content Safety Text Moderation guardrail across all categories"+ )+ assert nested_fields["severity_threshold"]["required"] == False+ assert (+ nested_fields["severity_threshold"]["type"] == "number"+ ) # Should be number, not None++ # Check other field types+ assert nested_fields["categories"]["type"] == "multiselect"+ assert nested_fields["blocklistNames"]["type"] == "array"+ assert nested_fields["haltOnBlocklistHit"]["type"] == "boolean"+ assert (+ nested_fields["outputType"]["type"] == "select"+ ) # Literal type should be selectdiff --git a/ui/litellm-dashboard/src/components/guardrails/README.md b/ui/litellm-dashboard/src/components/guardrails/README.mdnew file mode 100644index 00000000000..362a2f53480--- /dev/null+++ b/ui/litellm-dashboard/src/components/guardrails/README.md@@ -0,0 +1,126 @@+# Guardrail Configuration Components++This directory contains reusable React components for configuring various guardrail types in the LiteLLM dashboard.++## Azure Text Moderation Configuration++### Overview++The Azure Text Moderation configuration component allows users to configure Azure Content Safety settings for text moderation. It provides an intuitive interface for:++- **Category Selection**: Choose which content categories to monitor (Hate, Sexual, SelfHarm, Violence)+- **Global Severity Threshold**: Set a default severity level threshold for all categories+- **Per-Category Thresholds**: Override the global threshold for specific categories (advanced)++### Components++#### `AzureTextModerationConfiguration`++The main configuration component that renders the complete UI for Azure text moderation settings.++**Props:**+```typescript+interface AzureTextModerationConfigurationProps {+ categories: string[]; // Available categories+ selectedCategories: string[]; // Currently selected categories+ globalSeverityThreshold: number; // Global threshold (0, 2, 4, 6)+ categorySpecificThresholds: {[key: string]: number}; // Per-category overrides+ onCategorySelect: (category: string) => void; // Category selection handler+ onGlobalSeverityChange: (threshold: number) => void; // Global threshold handler+ onCategorySeverityChange: (category: string, threshold: number) => void; // Per-category handler+}+```++#### `AzureTextModerationExample`++A complete example showing how to integrate the configuration component with state management.++### Usage Example++```tsx+import React, { useState } from 'react';+import { AzureTextModerationConfiguration, AZURE_TEXT_MODERATION_CATEGORIES } from './guardrails';++const MyComponent = () => {+ const [selectedCategories, setSelectedCategories] = useState<string[]>(['Hate', 'Violence']);+ const [globalSeverityThreshold, setGlobalSeverityThreshold] = useState<number>(2);+ const [categorySpecificThresholds, setCategorySpecificThresholds] = useState<{[key: string]: number}>({});++ const handleCategorySelect = (category: string) => {+ setSelectedCategories(prev =>+ prev.includes(category)+ ? prev.filter(c => c !== category)+ : [...prev, category]+ );+ };++ const handleSave = () => {+ const config = {+ categories: selectedCategories,+ severity_threshold: globalSeverityThreshold,+ severity_threshold_by_category: categorySpecificThresholds,+ };+ // Save to backend...+ };++ return (+ <AzureTextModerationConfiguration+ categories={AZURE_TEXT_MODERATION_CATEGORIES.map(c => c.name)}+ selectedCategories={selectedCategories}+ globalSeverityThreshold={globalSeverityThreshold}+ categorySpecificThresholds={categorySpecificThresholds}+ onCategorySelect={handleCategorySelect}+ onGlobalSeverityChange={setGlobalSeverityThreshold}+ onCategorySeverityChange={(category, threshold) =>+ setCategorySpecificThresholds(prev => ({ ...prev, [category]: threshold }))+ }+ />+ );+};+```++### Severity Levels++The component supports Azure's severity levels:++- **Level 0 (Safe)**: Content is appropriate and safe+- **Level 2 (Low)**: Content may be inappropriate in some contexts+- **Level 4 (Medium)**: Content is inappropriate and should be filtered+- **Level 6 (High)**: Content is harmful and should be blocked++### Content Categories++Four predefined categories are supported:++1. **Hate**: Content that attacks or uses discriminatory language based on protected characteristics+2. **Sexual**: Content that describes sexual activity or other sexual content+3. **SelfHarm**: Content that promotes, encourages, or depicts acts of self-harm+4. **Violence**: Content that depicts death, violence, or physical injury++### Configuration Output++The component generates configuration objects compatible with the Azure Text Moderation guardrail:++```json+{+ "categories": ["Hate", "Violence"],+ "severity_threshold": 2,+ "severity_threshold_by_category": {+ "Hate": 4,+ "Violence": 2+ }+}+```++## PII Configuration++The existing PII configuration component provides similar functionality for configuring PII entity detection and actions (MASK/BLOCK).++### Files++- `azure_text_moderation_types.ts` - TypeScript interfaces and constants+- `azure_text_moderation_configuration.tsx` - Main configuration component+- `azure_text_moderation_example.tsx` - Usage example+- `pii_configuration.tsx` - PII configuration component+- `pii_components.tsx` - PII UI components+- `types.ts` - PII TypeScript interfaces\ No newline at end of filediff --git a/ui/litellm-dashboard/src/components/guardrails/add_guardrail_form.tsx b/ui/litellm-dashboard/src/components/guardrails/add_guardrail_form.tsxindex 93d97747c8d..2298d5f2af6 100644--- a/ui/litellm-dashboard/src/components/guardrails/add_guardrail_form.tsx+++ b/ui/litellm-dashboard/src/components/guardrails/add_guardrail_form.tsx@@ -6,6 +6,8 @@ import { GuardrailProviders, guardrail_provider_map, shouldRenderPIIConfigSettinimport { createGuardrailCall, getGuardrailUISettings, getGuardrailProviderSpecificParams } from '../networking';import PiiConfiguration from './pii_configuration';import GuardrailProviderFields from './guardrail_provider_fields';+import AzureTextModerationConfiguration from './azure_text_moderation_configuration';+import GuardrailOptionalParams from './guardrail_optional_params';const { Title, Text, Link } = Typography;const { Option } = Select;@@ -51,10 +53,13 @@ interface ProviderParam {default_value?: string;options?: string[];type?: string;+ fields?: { [key: string]: ProviderParam };+ dict_key_options?: string[];+ dict_value_type?: string;}interface ProviderParamsResponse {- [provider: string]: ProviderParam[];+ [provider: string]: { [key: string]: ProviderParam };}const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({@@ -71,6 +76,11 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({const [selectedActions, setSelectedActions] = useState<{[key: string]: string}>({});const [currentStep, setCurrentStep] = useState(0);const [providerParams, setProviderParams] = useState<ProviderParamsResponse | null>(null);++ // Azure Text Moderation state+ const [selectedCategories, setSelectedCategories] = useState<string[]>([]);+ const [globalSeverityThreshold, setGlobalSeverityThreshold] = useState<number>(2);+ const [categorySpecificThresholds, setCategorySpecificThresholds] = useState<{[key: string]: number}>({});// Fetch guardrail UI settings + provider params on mount / accessToken changeuseEffect(() => {@@ -107,6 +117,11 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({// Reset PII selections when changing providersetSelectedEntities([]);setSelectedActions({});++ // Reset Azure Text Moderation selections when changing provider+ setSelectedCategories([]);+ setGlobalSeverityThreshold(2);+ setCategorySpecificThresholds({});};const handleEntitySelect = (entity: string) => {@@ -126,6 +141,26 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({}));};+ // Azure Text Moderation handlers+ const handleCategorySelect = (category: string) => {+ setSelectedCategories(prev =>+ prev.includes(category)+ ? prev.filter(c => c !== category)+ : [...prev, category]+ );+ };++ const handleGlobalSeverityChange = (threshold: number) => {+ setGlobalSeverityThreshold(threshold);+ };++ const handleCategorySeverityChange = (category: string, threshold: number) => {+ setCategorySpecificThresholds(prev => ({+ ...prev,+ [category]: threshold+ }));+ };+const nextStep = async () => {try {// Validate current step fields@@ -142,6 +177,15 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({await form.validateFields(fieldsToValidate);}}++ // Validate configuration steps+ if (currentStep === 1) {+ if (shouldRenderPIIConfigSettings(selectedProvider) && selectedEntities.length === 0) {+ message.error('Please select at least one PII entity to continue');+ return;+ }+ }+setCurrentStep(currentStep + 1);} catch (error) {console.error("Form validation failed:", error);@@ -157,6 +201,9 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({setSelectedProvider(null);setSelectedEntities([]);setSelectedActions({});+ setSelectedCategories([]);+ setGlobalSeverityThreshold(2);+ setCategorySpecificThresholds({});setCurrentStep(0);};@@ -173,7 +220,8 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({// After validation, fetch *all* form values (including those from previous steps)const values = form.getFieldsValue(true);-++// Get the guardrail provider value from the mapconst guardrailProvider = guardrail_provider_map[values.provider];@@ -236,17 +284,40 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({* the selected provider and ONLY pass those recognised params.******************************/+ console.log("values: ", JSON.stringify(values));+// Use pre-fetched provider params to copy recognised paramsif (providerParams && selectedProvider) {const providerKey = guardrail_provider_map[selectedProvider]?.toLowerCase();- const providerSpecificParams = providerParams[providerKey] || [];+ const providerSpecificParams = providerParams[providerKey] || {};++ const allowedParams = new Set<string>();- const allowedParams = new Set<string>(- providerSpecificParams.map((p) => p.param)- );+ console.log("providerSpecificParams: ", JSON.stringify(providerSpecificParams));++ // Add root-level parameters (like api_key, api_base, api_version)+ Object.keys(providerSpecificParams).forEach(paramName => {+ if (paramName !== 'optional_params') {+ allowedParams.add(paramName);+ }+ });++ // Add nested parameters from optional_params.fields+ if (providerSpecificParams.optional_params &&+ providerSpecificParams.optional_params.fields) {+ Object.keys(providerSpecificParams.optional_params.fields).forEach(paramName => {+ allowedParams.add(paramName);+ });+ }+ console.log("allowedParams: ", allowedParams);allowedParams.forEach((paramName) => {- const paramValue = values[paramName];+ // Check for both direct parameter name and nested optional_params object+ let paramValue = values[paramName];+ if (paramValue === undefined || paramValue === null || paramValue === '') {+ paramValue = values.optional_params?.[paramName];+ }+if (paramValue !== undefined && paramValue !== null && paramValue !== '') {guardrailData.litellm_params[paramName] = paramValue;}@@ -436,6 +507,23 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({);};++ const renderOptionalParams = () => {+ if (!selectedProvider || !providerParams) return null;++ const providerKey = guardrail_provider_map[selectedProvider]?.toLowerCase();+ const providerFields = providerParams && providerParams[providerKey];++ if (!providerFields || !providerFields.optional_params) return null;++ return (+ <GuardrailOptionalParams+ optionalParams={providerFields.optional_params}+ parentFieldKey="optional_params"+ />+ );+ };+const renderStepContent = () => {switch (currentStep) {case 0:@@ -443,7 +531,8 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({case 1:if (shouldRenderPIIConfigSettings(selectedProvider)) {return renderPiiConfiguration();- }+ }+ return renderOptionalParams();default:return null;}@@ -460,14 +549,14 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({Previous</Button>)}- {currentStep < 1 && (+ {currentStep < 2 && (<ButtononClick={nextStep}>Next</Button>)}- {currentStep === 1 && (+ {currentStep === 2 && (<ButtononClick={handleSubmit}loading={loading}@@ -503,7 +592,10 @@ const AddGuardrailForm: React.FC<AddGuardrailFormProps> = ({><Steps current={currentStep} className="mb-6"><Step title="Basic Info" />- <Step title={selectedProvider === 'PresidioPII' ? "PII Configuration" : "Provider Configuration"} />+ <Step title={+ shouldRenderPIIConfigSettings(selectedProvider) ? "PII Configuration" :+ "Provider Configuration"+ } /></Steps>{renderStepContent()}diff --git a/ui/litellm-dashboard/src/components/guardrails/azure_text_moderation_configuration.tsx b/ui/litellm-dashboard/src/components/guardrails/azure_text_moderation_configuration.tsxnew file mode 100644index 00000000000..504c9e34698--- /dev/null+++ b/ui/litellm-dashboard/src/components/guardrails/azure_text_moderation_configuration.tsx@@ -0,0 +1,237 @@+import React, { useState } from 'react';+import { Typography, Badge, Card, Checkbox, Select, Slider, Tooltip, Divider, Row, Col } from 'antd';+import {+ AzureTextModerationConfigurationProps,+ AZURE_TEXT_MODERATION_CATEGORIES,+ SEVERITY_LEVELS+} from './azure_text_moderation_types';+import { InfoCircleOutlined, SafetyOutlined } from '@ant-design/icons';++const { Title, Text, Paragraph } = Typography;+const { Option } = Select;++/**+ * A reusable component for configuring Azure Text Moderation guardrail settings+ * Allows configuration of categories, global severity threshold, and per-category thresholds+ */+const AzureTextModerationConfiguration: React.FC<AzureTextModerationConfigurationProps> = ({+ selectedCategories,+ globalSeverityThreshold,+ categorySpecificThresholds,+ onCategorySelect,+ onGlobalSeverityChange,+ onCategorySeverityChange,+}) => {+ const [showAdvanced, setShowAdvanced] = useState(false);++ const getSeverityLabel = (value: number) => {+ const level = SEVERITY_LEVELS.find(l => l.value === value);+ return level ? level.label : `Level ${value}`;+ };++ const getSeverityColor = (value: number) => {+ if (value === 0) return '#52c41a'; // green+ if (value === 2) return '#faad14'; // orange+ if (value === 4) return '#fa8c16'; // dark orange+ return '#f5222d'; // red+ };++ const handleSelectAll = () => {+ AZURE_TEXT_MODERATION_CATEGORIES.forEach(category => {+ if (!selectedCategories.includes(category.name)) {+ onCategorySelect(category.name);+ }+ });+ };++ const handleUnselectAll = () => {+ selectedCategories.forEach(category => {+ onCategorySelect(category);+ });+ };++ return (+ <div className="azure-text-moderation-configuration">+ <div className="flex justify-between items-center mb-5">+ <div className="flex items-center">+ <SafetyOutlined className="text-blue-600 mr-2 text-lg" />+ <Title level={4} className="mb-0 font-semibold text-gray-800">Azure Text Moderation</Title>+ </div>+ <Badge+ count={selectedCategories.length}+ showZero+ style={{ backgroundColor: selectedCategories.length > 0 ? '#1890ff' : '#d9d9d9' }}+ overflowCount={999}+ >+ <Text className="text-gray-500">{selectedCategories.length} categories selected</Text>+ </Badge>+ </div>++ <Card className="mb-6">+ <div className="flex justify-between items-center mb-4">+ <Title level={5} className="mb-0">Content Categories</Title>+ <div className="space-x-2">+ <a onClick={handleSelectAll} className="text-blue-600 hover:text-blue-800 cursor-pointer">+ Select All+ </a>+ <span className="text-gray-300">|</span>+ <a+ onClick={handleUnselectAll}+ className="text-red-600 hover:text-red-800 cursor-pointer"+ style={{ display: selectedCategories.length > 0 ? 'inline' : 'none' }}+ >+ Unselect All+ </a>+ </div>+ </div>++ <Paragraph className="text-gray-600 mb-4">+ Select which content categories to monitor and filter+ </Paragraph>++ <Row gutter={[16, 16]}>+ {AZURE_TEXT_MODERATION_CATEGORIES.map(category => (+ <Col xs={24} sm={12} key={category.name}>+ <Card+ size="small"+ className={`cursor-pointer transition-all duration-200 ${+ selectedCategories.includes(category.name)+ ? 'border-blue-500 bg-blue-50 shadow-sm'+ : 'border-gray-200 hover:border-gray-300'+ }`}+ onClick={() => onCategorySelect(category.name)}+ >+ <div className="flex items-start">+ <Checkbox+ checked={selectedCategories.includes(category.name)}+ onChange={() => onCategorySelect(category.name)}+ className="mr-3 mt-1"+ />+ <div className="flex-1">+ <Text strong className="text-sm">{category.name}</Text>+ <br />+ <Text className="text-xs text-gray-600">{category.description}</Text>+ </div>+ </div>+ </Card>+ </Col>+ ))}+ </Row>+ </Card>++ <Card className="mb-6">+ <div className="flex items-center mb-4">+ <Title level={5} className="mb-0 mr-2">Global Severity Threshold</Title>+ <Tooltip title="Content with severity levels at or above this threshold will be flagged">+ <InfoCircleOutlined className="text-gray-400" />+ </Tooltip>+ </div>++ <Paragraph className="text-gray-600 mb-4">+ Set the minimum severity level that will trigger the guardrail for all selected categories+ </Paragraph>++ <div className="mb-4">+ <Row>+ <Col span={16}>+ <Slider+ min={0}+ max={6}+ step={2}+ value={globalSeverityThreshold}+ onChange={onGlobalSeverityChange}+ marks={{+ 0: { label: 'Safe', style: { color: '#52c41a' } },+ 2: { label: 'Low', style: { color: '#faad14' } },+ 4: { label: 'Medium', style: { color: '#fa8c16' } },+ 6: { label: 'High', style: { color: '#f5222d' } },+ }}+ tooltip={{+ formatter: (value) => getSeverityLabel(value || 0),+ }}+ />+ </Col>+ <Col span={8} className="pl-4">+ <div className="text-center">+ <div+ className="inline-block px-3 py-1 rounded-full text-white font-medium"+ style={{ backgroundColor: getSeverityColor(globalSeverityThreshold) }}+ >+ {getSeverityLabel(globalSeverityThreshold)}+ </div>+ </div>+ </Col>+ </Row>+ </div>+ </Card>++ <Card>+ <div className="flex justify-between items-center mb-4">+ <div className="flex items-center">+ <Title level={5} className="mb-0 mr-2">Per-Category Thresholds</Title>+ <Tooltip title="Override the global threshold for specific categories">+ <InfoCircleOutlined className="text-gray-400" />+ </Tooltip>+ </div>+ <a+ onClick={() => setShowAdvanced(!showAdvanced)}+ className="text-blue-600 hover:text-blue-800 cursor-pointer"+ >+ {showAdvanced ? 'Hide Advanced' : 'Show Advanced'}+ </a>+ </div>++ {showAdvanced && (+ <>+ <Paragraph className="text-gray-600 mb-4">+ Set custom severity thresholds for individual categories. Leave empty to use the global threshold.+ </Paragraph>++ {selectedCategories.length === 0 ? (+ <div className="text-center py-8 text-gray-500">+ Please select at least one category to configure per-category thresholds+ </div>+ ) : (+ <div className="space-y-4">+ {selectedCategories.map(category => (+ <div key={category}>+ <div className="flex justify-between items-center mb-2">+ <Text strong>{category}</Text>+ <Select+ placeholder="Use global threshold"+ style={{ width: 200 }}+ value={categorySpecificThresholds[category]}+ onChange={(value) => onCategorySeverityChange(category, value)}+ allowClear+ >+ {SEVERITY_LEVELS.map(level => (+ <Option key={level.value} value={level.value}>+ <div className="flex items-center justify-between">+ <span>{level.label}</span>+ <div+ className="w-3 h-3 rounded-full ml-2"+ style={{ backgroundColor: getSeverityColor(level.value) }}+ />+ </div>+ </Option>+ ))}+ </Select>+ </div>+ <Text className="text-xs text-gray-500">+ {AZURE_TEXT_MODERATION_CATEGORIES.find(c => c.name === category)?.description}+ </Text>+ {category !== selectedCategories[selectedCategories.length - 1] && (+ <Divider className="my-4" />+ )}+ </div>+ ))}+ </div>+ )}+ </>+ )}+ </Card>+ </div>+ );+};++export default AzureTextModerationConfiguration;\ No newline at end of filediff --git a/ui/litellm-dashboard/src/components/guardrails/azure_text_moderation_example.tsx b/ui/litellm-dashboard/src/components/guardrails/azure_text_moderation_example.tsxnew file mode 100644index 00000000000..648612b1e66--- /dev/null+++ b/ui/litellm-dashboard/src/components/guardrails/azure_text_moderation_example.tsx@@ -0,0 +1,92 @@+import React, { useState } from 'react';+import { Button, Space, Card, message } from 'antd';+import AzureTextModerationConfiguration from './azure_text_moderation_configuration';+import { AZURE_TEXT_MODERATION_CATEGORIES } from './azure_text_moderation_types';++/**+ * Example component showing how to use the AzureTextModerationConfiguration+ * This demonstrates the state management and event handling required+ */+const AzureTextModerationExample: React.FC = () => {+ const [selectedCategories, setSelectedCategories] = useState<string[]>(['Hate', 'Violence']);+ const [globalSeverityThreshold, setGlobalSeverityThreshold] = useState<number>(2);+ const [categorySpecificThresholds, setCategorySpecificThresholds] = useState<{[key: string]: number}>({+ 'Hate': 4,+ });++ const handleCategorySelect = (category: string) => {+ setSelectedCategories(prev =>+ prev.includes(category)+ ? prev.filter(c => c !== category)+ : [...prev, category]+ );+ };++ const handleGlobalSeverityChange = (threshold: number) => {+ setGlobalSeverityThreshold(threshold);+ };++ const handleCategorySeverityChange = (category: string, threshold: number) => {+ setCategorySpecificThresholds(prev => ({+ ...prev,+ [category]: threshold+ }));+ };++ const handleSave = () => {+ // Example of how to construct the configuration object+ const config = {+ categories: selectedCategories,+ severity_threshold: globalSeverityThreshold,+ severity_threshold_by_category: categorySpecificThresholds,+ };++ console.log('Azure Text Moderation Configuration:', config);+ message.success('Configuration saved successfully!');+ };++ const handleReset = () => {+ setSelectedCategories(['Hate', 'Violence']);+ setGlobalSeverityThreshold(2);+ setCategorySpecificThresholds({ 'Hate': 4 });+ message.info('Configuration reset to defaults');+ };++ return (+ <div style={{ maxWidth: 800, margin: '0 auto', padding: 20 }}>+ <Card title="Azure Text Moderation Configuration Example" className="mb-6">+ <AzureTextModerationConfiguration+ selectedCategories={selectedCategories}+ globalSeverityThreshold={globalSeverityThreshold}+ categorySpecificThresholds={categorySpecificThresholds}+ onCategorySelect={handleCategorySelect}+ onGlobalSeverityChange={handleGlobalSeverityChange}+ onCategorySeverityChange={handleCategorySeverityChange}+ />++ <div className="mt-6 pt-4 border-t">+ <Space>+ <Button type="primary" onClick={handleSave}>+ Save Configuration+ </Button>+ <Button onClick={handleReset}>+ Reset to Defaults+ </Button>+ </Space>+ </div>+ </Card>++ <Card title="Current Configuration" size="small">+ <pre style={{ fontSize: 12, backgroundColor: '#f5f5f5', padding: 12, borderRadius: 4 }}>+ {JSON.stringify({+ categories: selectedCategories,+ severity_threshold: globalSeverityThreshold,+ severity_threshold_by_category: categorySpecificThresholds,+ }, null, 2)}+ </pre>+ </Card>+ </div>+ );+};++export default AzureTextModerationExample;\ No newline at end of filediff --git a/ui/litellm-dashboard/src/components/guardrails/azure_text_moderation_types.ts b/ui/litellm-dashboard/src/components/guardrails/azure_text_moderation_types.tsnew file mode 100644index 00000000000..29017c454ce--- /dev/null+++ b/ui/litellm-dashboard/src/components/guardrails/azure_text_moderation_types.ts@@ -0,0 +1,77 @@+export interface AzureTextModerationCategory {+ name: string;+ description: string;+ enabled: boolean;+ severityThreshold?: number;+}++export interface AzureTextModerationConfigurationProps {+ selectedCategories: string[];+ globalSeverityThreshold: number;+ categorySpecificThresholds: { [key: string]: number };+ onCategorySelect: (category: string) => void;+ onGlobalSeverityChange: (threshold: number) => void;+ onCategorySeverityChange: (category: string, threshold: number) => void;+}++export interface AzureTextModerationGuardrail {+ guardrail_id: string;+ guardrail_name: string | null;+ litellm_params: {+ guardrail: string;+ mode: string;+ default_on: boolean;+ categories?: string[];+ severity_threshold?: number;+ severity_threshold_by_category?: { [key: string]: number };+ [key: string]: any;+ };+ guardrail_info: Record<string, any> | null;+ created_at?: string;+ updated_at?: string;+}++export const AZURE_TEXT_MODERATION_CATEGORIES = [+ {+ name: "Hate",+ description:+ "Content that attacks or uses discriminatory language based on protected characteristics",+ },+ {+ name: "Sexual",+ description:+ "Content that describes sexual activity or other sexual content",+ },+ {+ name: "SelfHarm",+ description:+ "Content that promotes, encourages, or depicts acts of self-harm",+ },+ {+ name: "Violence",+ description: "Content that depicts death, violence, or physical injury",+ },+];++export const SEVERITY_LEVELS = [+ {+ value: 0,+ label: "Level 0 - Safe",+ description: "Content is appropriate and safe",+ },+ {+ value: 2,+ label: "Level 2 - Low",+ description: "Content may be inappropriate in some contexts",+ },+ {+ value: 4,+ label: "Level 4 - Medium",+ description: "Content is inappropriate and should be filtered",+ },+ {+ value: 6,+ label: "Level 6 - High",+ description: "Content is harmful and should be blocked",+ },+];diff --git a/ui/litellm-dashboard/src/components/guardrails/guardrail_info_helpers.tsx b/ui/litellm-dashboard/src/components/guardrails/guardrail_info_helpers.tsxindex 1f9669813eb..62d1a573b79 100644--- a/ui/litellm-dashboard/src/components/guardrails/guardrail_info_helpers.tsx+++ b/ui/litellm-dashboard/src/components/guardrails/guardrail_info_helpers.tsx@@ -26,6 +26,16 @@ export const shouldRenderPIIConfigSettings = (provider: string | null) => {return providerEnum === GuardrailProviders.PresidioPII;};+// Decides if we should render the Azure Text Moderation config settings for a given provider+export const shouldRenderAzureTextModerationConfigSettings = (provider: string | null) => {+ if (!provider) {+ return false;+ }+ // cast provider to GuardrailProviders enum+ const providerEnum = GuardrailProviders[provider as keyof typeof GuardrailProviders];+ return providerEnum === GuardrailProviders.AzureContentSafetyTextModeration;+};+const asset_logos_folder = '../ui/assets/logos/';export const guardrailLogoMap: Record<string, string> = {diff --git a/ui/litellm-dashboard/src/components/guardrails/guardrail_optional_params.tsx b/ui/litellm-dashboard/src/components/guardrails/guardrail_optional_params.tsxnew file mode 100644index 00000000000..f795d5d6cb1--- /dev/null+++ b/ui/litellm-dashboard/src/components/guardrails/guardrail_optional_params.tsx@@ -0,0 +1,226 @@+import React from 'react';+import { Form, Select, Typography } from 'antd';+import { TextInput } from '@tremor/react';+import NumericalInput from '../shared/numerical_input';++const { Title } = Typography;++interface ProviderParam {+ param: string;+ description: string;+ required: boolean;+ default_value?: string;+ options?: string[];+ type?: string;+ fields?: { [key: string]: ProviderParam };+ dict_key_options?: string[];+ dict_value_type?: string;+}++interface GuardrailOptionalParamsProps {+ optionalParams: ProviderParam;+ parentFieldKey: string;+}++interface DictFieldProps {+ field: ProviderParam;+ fieldKey: string;+ fullFieldKey: string | string[];+}++const DictField: React.FC<DictFieldProps> = ({ field, fieldKey, fullFieldKey }) => {+ const [selectedEntries, setSelectedEntries] = React.useState<Array<{key: string, id: string}>>([]);+ const [availableKeys, setAvailableKeys] = React.useState<string[]>(field.dict_key_options || []);++ const addEntry = (selectedKey: string) => {+ if (!selectedKey) return;++ const newEntry = {+ key: selectedKey,+ id: `${selectedKey}_${Date.now()}`+ };++ setSelectedEntries([...selectedEntries, newEntry]);+ setAvailableKeys(availableKeys.filter(key => key !== selectedKey));+ };++ const removeEntry = (entryId: string, keyToRemove: string) => {+ setSelectedEntries(selectedEntries.filter(entry => entry.id !== entryId));+ setAvailableKeys([...availableKeys, keyToRemove].sort());+ };++ return (+ <div className="space-y-3">+ {/* Existing entries */}+ {selectedEntries.map((entry) => (+ <div key={entry.id} className="flex items-center space-x-3 p-3 border rounded-lg">+ <div className="w-24 font-medium text-sm">{entry.key}</div>+ <div className="flex-1">+ <Form.Item+ name={Array.isArray(fullFieldKey) ? [...fullFieldKey, entry.key] : [fullFieldKey, entry.key]}+ style={{ marginBottom: 0 }}+ >+ {field.dict_value_type === "number" ? (+ <NumericalInput+ step={1}+ width={200}+ placeholder={`Enter ${entry.key} value`}+ />+ ) : field.dict_value_type === "boolean" ? (+ <Select placeholder={`Select ${entry.key} value`}>+ <Select.Option value={true}>True</Select.Option>+ <Select.Option value={false}>False</Select.Option>+ </Select>+ ) : (+ <TextInput+ placeholder={`Enter ${entry.key} value`}+ type="text"+ />+ )}+ </Form.Item>+ </div>+ <button+ type="button"+ className="text-red-500 hover:text-red-700 text-sm"+ onClick={() => removeEntry(entry.id, entry.key)}+ >+ Remove+ </button>+ </div>+ ))}++ {/* Add new entry */}+ {availableKeys.length > 0 && (+ <div className="flex items-center space-x-3 mt-2">+ <Select+ placeholder="Select category to configure"+ style={{ width: 200 }}+ onSelect={(value: string | undefined) => value && addEntry(value)}+ value={undefined}+ >+ {availableKeys.map((key) => (+ <Select.Option key={key} value={key}>+ {key}+ </Select.Option>+ ))}+ </Select>+ <span className="text-sm text-gray-500">Select a category to add threshold configuration</span>+ </div>+ )}+ </div>+ );+};++const GuardrailOptionalParams: React.FC<GuardrailOptionalParamsProps> = ({+ optionalParams,+ parentFieldKey+}) => {+ const renderField = (fieldKey: string, field: ProviderParam) => {+ const fullFieldKey = `${parentFieldKey}.${fieldKey}`;++ // Handle dict fields separately since they manage their own Form.Items+ if (field.type === "dict" && field.dict_key_options) {+ return (+ <div key={fullFieldKey} className="mb-8 p-6 bg-gray-50 rounded-lg border border-gray-200">+ <div className="mb-4 font-medium text-gray-900 text-base">{fieldKey}</div>+ <p className="text-sm text-gray-600 mb-4">{field.description}</p>+ <DictField+ field={field}+ fieldKey={fieldKey}+ fullFieldKey={[parentFieldKey, fieldKey]}+ />+ </div>+ );+ }++ return (+ <div key={fullFieldKey} className="mb-8 p-6 bg-white rounded-lg border border-gray-200 shadow-sm">+ <Form.Item+ name={[parentFieldKey, fieldKey]}+ label={+ <div className="mb-2">+ <div className="font-medium text-gray-900 text-base">{fieldKey}</div>+ <p className="text-sm text-gray-600 mt-1">{field.description}</p>+ </div>+ }+ rules={field.required ? [{ required: true, message: `${fieldKey} is required` }] : undefined}+ className="mb-0"+ >+ {field.type === "select" && field.options ? (+ <Select+ placeholder={field.description}+ defaultValue={field.default_value}+ >+ {field.options.map((option) => (+ <Select.Option key={option} value={option}>+ {option}+ </Select.Option>+ ))}+ </Select>+ ) : field.type === "multiselect" && field.options ? (+ <Select+ mode="multiple"+ placeholder={field.description}+ defaultValue={field.default_value}+ >+ {field.options.map((option) => (+ <Select.Option key={option} value={option}>+ {option}+ </Select.Option>+ ))}+ </Select>+ ) : field.type === "bool" || field.type === "boolean" ? (+ <Select+ placeholder={field.description}+ defaultValue={field.default_value}+ >+ <Select.Option value="true">True</Select.Option>+ <Select.Option value="false">False</Select.Option>+ </Select>+ ) : field.type === "number" ? (+ <NumericalInput+ step={1}+ width={400}+ placeholder={field.description}+ />+ ) : fieldKey.includes("password") || fieldKey.includes("secret") || fieldKey.includes("key") ? (+ <TextInput+ placeholder={field.description}+ type="password"+ />+ ) : (+ <TextInput+ placeholder={field.description}+ type="text"+ />+ )}+ </Form.Item>+ </div>+ );+ };++ if (!optionalParams.fields || Object.keys(optionalParams.fields).length === 0) {+ return null;+ }++ return (+ <div className="guardrail-optional-params">+ <div className="mb-8 pb-4 border-b border-gray-100">+ <Title level={3} className="mb-2 font-semibold text-gray-900">+ Optional Parameters+ </Title>+ <p className="text-gray-600 text-sm">+ {optionalParams.description || 'Configure additional settings for this guardrail provider'}+ </p>+ </div>++ <div className="space-y-8">+ {Object.entries(optionalParams.fields).map(([fieldKey, field]) =>+ renderField(fieldKey, field)+ )}+ </div>+ </div>+ );+};++export default GuardrailOptionalParams;\ No newline at end of filediff --git a/ui/litellm-dashboard/src/components/guardrails/guardrail_provider_fields.tsx b/ui/litellm-dashboard/src/components/guardrails/guardrail_provider_fields.tsxindex a7758244f49..29631a85709 100644--- a/ui/litellm-dashboard/src/components/guardrails/guardrail_provider_fields.tsx+++ b/ui/litellm-dashboard/src/components/guardrails/guardrail_provider_fields.tsx@@ -3,6 +3,8 @@ import { Form, Select, Spin } from "antd";import { TextInput } from "@tremor/react";import { GuardrailProviders, guardrail_provider_map } from './guardrail_info_helpers';import { getGuardrailProviderSpecificParams } from "../networking";+import NumericalInput from "../shared/numerical_input";+import GuardrailOptionalParams from "./guardrail_optional_params";interface GuardrailProviderFieldsProps {selectedProvider: string | null;@@ -17,10 +19,13 @@ interface ProviderParam {default_value?: string;options?: string[];type?: string;+ fields?: { [key: string]: ProviderParam };+ dict_key_options?: string[];+ dict_value_type?: string;}interface ProviderParamsResponse {- [provider: string]: ProviderParam[];+ [provider: string]: { [key: string]: ProviderParam };}const GuardrailProviderFields: React.FC<GuardrailProviderFieldsProps> = ({@@ -88,19 +93,39 @@ const GuardrailProviderFields: React.FC<GuardrailProviderFieldsProps> = ({console.log("Provider key:", providerKey);console.log("Provider fields:", providerFields);- if (!providerFields || providerFields.length === 0) {+ if (!providerFields || Object.keys(providerFields).length === 0) {return <div>No configuration fields available for this provider.</div>;}- return (- <>- {providerFields.map((field) => (+ // Convert object to array of entries and render fields+ const renderFields = (fields: { [key: string]: ProviderParam }, parentKey = "") => {+ return Object.entries(fields).map(([fieldKey, field]) => {+ const fullFieldKey = parentKey ? `${parentKey}.${fieldKey}` : fieldKey;++ // Skip optional_params - they are handled in a separate step+ if (fieldKey === "optional_params" && field.type === "nested" && field.fields) {+ return null;+ }++ // Handle other nested fields (like azure/text_moderations optional_params)+ if (field.type === "nested" && field.fields) {+ return (+ <div key={fullFieldKey}>+ <div className="mb-2 font-medium">{fieldKey}</div>+ <div className="ml-4 border-l-2 border-gray-200 pl-4">+ {renderFields(field.fields, fullFieldKey)}+ </div>+ </div>+ );+ }++ return (<Form.Item- key={field.param}- name={field.param}- label={field.param}+ key={fullFieldKey}+ name={fullFieldKey}+ label={fieldKey}tooltip={field.description}- rules={field.required ? [{ required: true, message: `${field.param} is required` }] : undefined}+ rules={field.required ? [{ required: true, message: `${fieldKey} is required` }] : undefined}>{field.type === "select" && field.options ? (<Select@@ -113,15 +138,33 @@ const GuardrailProviderFields: React.FC<GuardrailProviderFieldsProps> = ({</Select.Option>))}</Select>- ) : field.type === "bool" ? (+ ) : field.type === "multiselect" && field.options ? (+ <Select+ mode="multiple"+ placeholder={field.description}+ defaultValue={field.default_value}+ >+ {field.options.map((option) => (+ <Select.Option key={option} value={option}>+ {option}+ </Select.Option>+ ))}+ </Select>+ ) : field.type === "bool" || field.type === "boolean" ? (<Selectplaceholder={field.description}defaultValue={field.default_value}>- <Select.Option value="True">True</Select.Option>- <Select.Option value="False">False</Select.Option>+ <Select.Option value="true">True</Select.Option>+ <Select.Option value="false">False</Select.Option></Select>- ) : field.param.includes("password") || field.param.includes("secret") ? (+ ) : field.type === "number" ? (+ <NumericalInput+ step={1}+ width={400}+ placeholder={field.description}+ />+ ) : fieldKey.includes("password") || fieldKey.includes("secret") || fieldKey.includes("key") ? (<TextInputplaceholder={field.description}type="password"@@ -133,7 +176,13 @@ const GuardrailProviderFields: React.FC<GuardrailProviderFieldsProps> = ({/>)}</Form.Item>- ))}+ );+ });+ };++ return (+ <>+ {renderFields(providerFields)}</>);};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.tsxindex 5ae3bb3024f..9327b2498a6 100644--- a/ui/litellm-dashboard/src/components/guardrails/guardrail_provider_specific_fields.tsx+++ b/ui/litellm-dashboard/src/components/guardrails/guardrail_provider_specific_fields.tsx@@ -1,69 +1,214 @@-import React from 'react';-import { Form, Tooltip } from 'antd';+import React, { useState, useEffect } from 'react';+import { Form, Select, Spin } from 'antd';import { TextInput } from '@tremor/react';-import { GuardrailProviders } from './guardrail_info_helpers';+import { GuardrailProviders, guardrail_provider_map } from './guardrail_info_helpers';+import { getGuardrailProviderSpecificParams } from '../networking';+import NumericalInput from '../shared/numerical_input';interface GuardrailProviderSpecificFieldsProps {selectedProvider: string;+ accessToken?: string | null;+ providerParams?: ProviderParamsResponse | null;}-interface FieldConfig {- key: string;- label: string;- placeholder?: string;- tooltip?: string;- required?: boolean;- type?: 'text' | 'password';+interface ProviderParam {+ param: string;+ description: string;+ required: boolean;+ default_value?: string;+ options?: string[];+ type?: string;+ fields?: { [key: string]: ProviderParam };+ dict_key_options?: string[];+ dict_value_type?: string;}-// 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'- }- ]-};+interface ProviderParamsResponse {+ [provider: string]: { [key: string]: ProviderParam };+}const GuardrailProviderSpecificFields: React.FC<GuardrailProviderSpecificFieldsProps> = ({- selectedProvider+ selectedProvider,+ accessToken,+ providerParams: providerParamsProp = null}) => {- // Get field configurations for the selected provider- const fieldConfigs = PROVIDER_FIELD_CONFIG[selectedProvider] || [];+ const [loading, setLoading] = useState(false);+ const [providerParams, setProviderParams] = useState<ProviderParamsResponse | null>(providerParamsProp);+ const [error, setError] = useState<string | null>(null);++ // Fetch provider-specific parameters when component mounts+ useEffect(() => {+ if (providerParamsProp) {+ setProviderParams(providerParamsProp);+ return;+ }++ const fetchProviderParams = async () => {+ if (!accessToken) return;++ setLoading(true);+ setError(null);++ try {+ const data = await getGuardrailProviderSpecificParams(accessToken);+ setProviderParams(data);+ } catch (error) {+ console.error("Error fetching provider params:", error);+ setError("Failed to load provider parameters");+ } finally {+ setLoading(false);+ }+ };++ if (!providerParamsProp) {+ fetchProviderParams();+ }+ }, [accessToken, providerParamsProp]);++ // If no provider is selected, don't render anything+ if (!selectedProvider) {+ return null;+ }++ // Show loading state+ if (loading) {+ return <Spin tip="Loading provider parameters..." />;+ }++ // Show error state+ if (error) {+ return <div className="text-red-500">{error}</div>;+ }++ // Get the provider key matching the selected provider+ const providerKey = guardrail_provider_map[selectedProvider]?.toLowerCase();++ // Get parameters for the selected provider+ const providerFields = providerParams && providerParams[providerKey];- if (fieldConfigs.length === 0) {+ if (!providerFields || Object.keys(providerFields).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}+ // Render fields function+ const renderFields = (fields: { [key: string]: ProviderParam }, parentKey = "") => {+ return Object.entries(fields).map(([fieldKey, field]) => {+ const fullFieldKey = parentKey ? `${parentKey}.${fieldKey}` : fieldKey;++++ // Handle nested fields+ if (field.type === "nested" && field.fields) {+ return (+ <div key={fullFieldKey}>+ <div className="mb-2 font-medium">{fieldKey}</div>+ <div className="ml-4 border-l-2 border-gray-200 pl-4">+ {renderFields(field.fields, fullFieldKey)}+ </div>+ </div>+ );+ }++ return (+ <Form.Item+ key={fullFieldKey}+ name={fullFieldKey}+ label={fieldKey}+ tooltip={field.description}+ rules={field.required ? [{ required: true, message: `${fieldKey} is required` }] : undefined}>- <TextInput- placeholder={field.placeholder}- type={field.type || 'text'}- />+ {field.type === "select" && field.options ? (+ <Select+ placeholder={field.description}+ defaultValue={field.default_value}+ >+ {field.options.map((option) => (+ <Select.Option key={option} value={option}>+ {option}+ </Select.Option>+ ))}+ </Select>+ ) : field.type === "multiselect" && field.options ? (+ <Select+ mode="multiple"+ placeholder={field.description}+ defaultValue={field.default_value}+ >+ {field.options.map((option) => (+ <Select.Option key={option} value={option}>+ {option}+ </Select.Option>+ ))}+ </Select>+ ) : field.type === "dict" && field.dict_key_options ? (+ <div className="space-y-3">+ <div className="text-sm text-gray-600 mb-3">+ {field.description}+ </div>++ {field.dict_key_options.map((key) => (+ <div key={key} className="flex items-center space-x-3">+ <div className="w-24 font-medium text-sm">{key}</div>+ <div className="flex-1">+ <Form.Item+ name={[fullFieldKey, key]}+ style={{ marginBottom: 0 }}+ >+ {field.dict_value_type === "number" ? (+ <NumericalInput+ step={1}+ width={200}+ placeholder={`Enter ${key} value`}+ />+ ) : field.dict_value_type === "boolean" ? (+ <Select placeholder={`Select ${key} value`}>+ <Select.Option value={true}>True</Select.Option>+ <Select.Option value={false}>False</Select.Option>+ </Select>+ ) : (+ <TextInput+ placeholder={`Enter ${key} value`}+ type="text"+ />+ )}+ </Form.Item>+ </div>+ </div>+ ))}+ </div>+ ) : field.type === "bool" || field.type === "boolean" ? (+ <Select+ placeholder={field.description}+ defaultValue={field.default_value}+ >+ <Select.Option value="true">True</Select.Option>+ <Select.Option value="false">False</Select.Option>+ </Select>+ ) : field.type === "number" ? (+ <NumericalInput+ step={1}+ width={400}+ placeholder={field.description}+ />+ ) : fieldKey.includes("password") || fieldKey.includes("secret") || fieldKey.includes("key") ? (+ <TextInput+ placeholder={field.description}+ type="password"+ />+ ) : (+ <TextInput+ placeholder={field.description}+ type="text"+ />+ )}</Form.Item>- ))}+ );+ });+ };++ return (+ <>+ {renderFields(providerFields)}</>);};diff --git a/ui/litellm-dashboard/src/components/guardrails/index.ts b/ui/litellm-dashboard/src/components/guardrails/index.tsnew file mode 100644index 00000000000..d6305bd8656--- /dev/null+++ b/ui/litellm-dashboard/src/components/guardrails/index.ts@@ -0,0 +1,9 @@+// PII Configuration exports+export { default as PiiConfiguration } from "./pii_configuration";+export * from "./pii_components";+export * from "./types";++// Azure Text Moderation Configuration exports+export { default as AzureTextModerationConfiguration } from "./azure_text_moderation_configuration";+export { default as AzureTextModerationExample } from "./azure_text_moderation_example";+export * from "./azure_text_moderation_types";