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
[Feat] Guardrails - LiteLLM Content Filter, Allow Viewing/Editing Content Filter Settings (#16383)
Ishaan Jaff674d4b4cab4b
diff --git a/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py b/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.pyindex bad716643eb..644ecaf72ee 100644--- a/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py+++ b/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py@@ -84,20 +84,39 @@ class ContentFilterGuardrail(CustomGuardrail):self.pattern_redaction_format = pattern_redaction_format or self.PATTERN_REDACTION_FORMATself.keyword_redaction_tag = keyword_redaction_tag or self.KEYWORD_REDACTION_STR- # Compile regex patterns- self.compiled_patterns: List[Tuple[Pattern, str, ContentFilterAction]] = []+ # Normalize inputs: convert dicts to Pydantic models for consistent handling+ normalized_patterns: List[ContentFilterPattern] = []if patterns:for pattern_config in patterns:- self._add_pattern(pattern_config)+ if isinstance(pattern_config, dict):+ normalized_patterns.append(ContentFilterPattern(**pattern_config))+ else:+ normalized_patterns.append(pattern_config)- # Load blocked words- self.blocked_words: Dict[str, Tuple[ContentFilterAction, Optional[str]]] = {}+ normalized_blocked_words: List[BlockedWord] = []if blocked_words:for word in blocked_words:- self.blocked_words[word.keyword.lower()] = (- word.action,- word.description,- )+ if isinstance(word, dict):+ normalized_blocked_words.append(BlockedWord(**word))+ else:+ normalized_blocked_words.append(word)++ # Compile regex patterns+ self.compiled_patterns: List[Tuple[Pattern, str, ContentFilterAction]] = []+ for pattern_config in normalized_patterns:+ self._add_pattern(pattern_config)++ # Load blocked words - always initialize as dict+ self.blocked_words: Dict[str, Tuple[ContentFilterAction, Optional[str]]] = {}+ for word in normalized_blocked_words:+ self.blocked_words[word.keyword.lower()] = (word.action, word.description)++ # Defensive check: ensure blocked_words is a dict (not a list)+ if not isinstance(self.blocked_words, dict):+ verbose_proxy_logger.error(+ f"blocked_words is not a dict, got {type(self.blocked_words)}. Resetting to empty dict."+ )+ self.blocked_words = {}# Load blocked words from file if providedif blocked_words_file:@@ -208,6 +227,25 @@ class ContentFilterGuardrail(CustomGuardrail):Returns:Tuple of (keyword, action, description) if match found, None otherwise"""+ # Handle case where blocked_words might still be a list (old instances)+ if isinstance(self.blocked_words, list):+ verbose_proxy_logger.warning(+ "blocked_words is a list instead of dict. Re-initializing. "+ "This suggests an old guardrail instance is still in use. Please restart the server."+ )+ # Convert list to dict on-the-fly+ temp_dict: Dict[str, Tuple[ContentFilterAction, Optional[str]]] = {}+ for word in self.blocked_words:+ if isinstance(word, dict):+ temp_dict[word.get("keyword", "").lower()] = (+ word.get("action", ContentFilterAction.BLOCK),+ word.get("description")+ )+ self.blocked_words = temp_dict++ if not self.blocked_words:+ return None+text_lower = text.lower()for keyword, (action, description) in self.blocked_words.items():if keyword in text_lower:diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/content_filter/test_content_filter.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/content_filter/test_content_filter.pyindex 27530abd868..e756dd6bd5d 100644--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/content_filter/test_content_filter.py+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/content_filter/test_content_filter.py@@ -467,3 +467,54 @@ class TestContentFilterGuardrail:assert exc_info.value.status_code == 400assert "us_ssn" in str(exc_info.value.detail)+ def test_init_with_plain_dicts(self):+ """+ Test initialization with plain dicts (DB format).+ This ensures the guardrail can handle data loaded from the database+ without requiring Pydantic model conversion.+ """+ patterns = [+ {+ "pattern_type": "prebuilt",+ "pattern_name": "us_ssn",+ "action": "BLOCK",+ "name": "us_ssn",+ "pattern": None,+ },+ {+ "pattern_type": "prebuilt",+ "pattern_name": "email",+ "action": "MASK",+ "name": "email",+ "pattern": None,+ }+ ]++ blocked_words = [+ {+ "keyword": "langchain",+ "action": "BLOCK",+ "description": None,+ },+ {+ "keyword": "openai",+ "action": "MASK",+ "description": "Competitor name",+ }+ ]++ guardrail = ContentFilterGuardrail(+ guardrail_name="test-db-format",+ patterns=patterns,+ blocked_words=blocked_words,+ )++ assert guardrail.guardrail_name == "test-db-format"+ assert len(guardrail.compiled_patterns) == 2+ assert len(guardrail.blocked_words) == 2++ # Verify blocked_words are stored as dict+ assert "langchain" in guardrail.blocked_words+ assert guardrail.blocked_words["langchain"] == ("BLOCK", None)+ assert "openai" in guardrail.blocked_words+ assert guardrail.blocked_words["openai"] == ("MASK", "Competitor name")diff --git a/ui/litellm-dashboard/src/components/guardrails/content_filter/ContentFilterConfiguration.tsx b/ui/litellm-dashboard/src/components/guardrails/content_filter/ContentFilterConfiguration.tsxindex af9723564e3..168fefdfe64 100644--- a/ui/litellm-dashboard/src/components/guardrails/content_filter/ContentFilterConfiguration.tsx+++ b/ui/litellm-dashboard/src/components/guardrails/content_filter/ContentFilterConfiguration.tsx@@ -194,10 +194,10 @@ const ContentFilterConfiguration: React.FC<ContentFilterConfigurationProps> = ({><div style={{ marginBottom: 16 }}><Space>- <Button onClick={() => setPatternModalVisible(true)} icon={PlusOutlined}>+ <Button type="button" onClick={() => setPatternModalVisible(true)} icon={PlusOutlined}>Add prebuilt pattern</Button>- <Button onClick={() => setCustomPatternModalVisible(true)} variant="secondary" icon={PlusOutlined}>+ <Button type="button" onClick={() => setCustomPatternModalVisible(true)} variant="secondary" icon={PlusOutlined}>Add custom regex</Button></Space>@@ -226,11 +226,11 @@ const ContentFilterConfiguration: React.FC<ContentFilterConfigurationProps> = ({><div style={{ marginBottom: 16 }}><Space>- <Button onClick={() => setKeywordModalVisible(true)} icon={PlusOutlined}>+ <Button type="button" onClick={() => setKeywordModalVisible(true)} icon={PlusOutlined}>Add keyword</Button><Upload beforeUpload={handleFileUpload} accept=".yaml,.yml" showUploadList={false}>- <Button variant="secondary" icon={UploadOutlined} loading={uploadValidating}>+ <Button type="button" variant="secondary" icon={UploadOutlined} loading={uploadValidating}>Upload YAML file</Button></Upload>diff --git a/ui/litellm-dashboard/src/components/guardrails/content_filter/ContentFilterDisplay.tsx b/ui/litellm-dashboard/src/components/guardrails/content_filter/ContentFilterDisplay.tsxnew file mode 100644index 00000000000..0c1e12d8860--- /dev/null+++ b/ui/litellm-dashboard/src/components/guardrails/content_filter/ContentFilterDisplay.tsx@@ -0,0 +1,82 @@+import React from "react";+import { Card, Text, Badge } from "@tremor/react";+import PatternTable from "./PatternTable";+import KeywordTable from "./KeywordTable";++interface Pattern {+ id: string;+ type: "prebuilt" | "custom";+ name: string;+ display_name?: string;+ pattern?: string;+ action: "BLOCK" | "MASK";+}++interface BlockedWord {+ id: string;+ keyword: string;+ action: "BLOCK" | "MASK";+ description?: string;+}++interface ContentFilterDisplayProps {+ patterns: Pattern[];+ blockedWords: BlockedWord[];+ readOnly?: boolean;+ onPatternActionChange?: (id: string, action: "BLOCK" | "MASK") => void;+ onPatternRemove?: (id: string) => void;+ onBlockedWordUpdate?: (id: string, field: string, value: any) => void;+ onBlockedWordRemove?: (id: string) => void;+}++const ContentFilterDisplay: React.FC<ContentFilterDisplayProps> = ({+ patterns,+ blockedWords,+ readOnly = true,+ onPatternActionChange,+ onPatternRemove,+ onBlockedWordUpdate,+ onBlockedWordRemove,+}) => {+ if (patterns.length === 0 && blockedWords.length === 0) {+ return null;+ }++ // No-op handlers for read-only mode+ const noOp = () => {};++ return (+ <>+ {patterns.length > 0 && (+ <Card className="mt-6">+ <div className="flex justify-between items-center mb-4">+ <Text className="text-lg font-semibold">Pattern Detection</Text>+ <Badge color="blue">{patterns.length} patterns configured</Badge>+ </div>+ <PatternTable+ patterns={patterns}+ onActionChange={readOnly ? noOp : (onPatternActionChange || noOp)}+ onRemove={readOnly ? noOp : (onPatternRemove || noOp)}+ />+ </Card>+ )}++ {blockedWords.length > 0 && (+ <Card className="mt-6">+ <div className="flex justify-between items-center mb-4">+ <Text className="text-lg font-semibold">Blocked Keywords</Text>+ <Badge color="blue">{blockedWords.length} keywords configured</Badge>+ </div>+ <KeywordTable+ keywords={blockedWords}+ onActionChange={readOnly ? noOp : (onBlockedWordUpdate || noOp)}+ onRemove={readOnly ? noOp : (onBlockedWordRemove || noOp)}+ />+ </Card>+ )}+ </>+ );+};++export default ContentFilterDisplay;+diff --git a/ui/litellm-dashboard/src/components/guardrails/content_filter/ContentFilterManager.tsx b/ui/litellm-dashboard/src/components/guardrails/content_filter/ContentFilterManager.tsxnew file mode 100644index 00000000000..65a27388a22--- /dev/null+++ b/ui/litellm-dashboard/src/components/guardrails/content_filter/ContentFilterManager.tsx@@ -0,0 +1,159 @@+import React, { useState, useEffect } from "react";+import { Divider } from "antd";+import ContentFilterConfiguration from "./ContentFilterConfiguration";+import ContentFilterDisplay from "./ContentFilterDisplay";++interface Pattern {+ id: string;+ type: "prebuilt" | "custom";+ name: string;+ display_name?: string;+ pattern?: string;+ action: "BLOCK" | "MASK";+}++interface BlockedWord {+ id: string;+ keyword: string;+ action: "BLOCK" | "MASK";+ description?: string;+}++interface GuardrailSettings {+ content_filter_settings?: {+ prebuilt_patterns: Array<{+ name: string;+ display_name: string;+ category: string;+ description: string;+ }>;+ pattern_categories: string[];+ supported_actions: string[];+ };+}++interface ContentFilterManagerProps {+ guardrailData: any;+ guardrailSettings: GuardrailSettings | null;+ isEditing: boolean;+ accessToken: string | null;+ onDataChange?: (patterns: Pattern[], blockedWords: BlockedWord[]) => void;+}++const ContentFilterManager: React.FC<ContentFilterManagerProps> = ({+ guardrailData,+ guardrailSettings,+ isEditing,+ accessToken,+ onDataChange,+}) => {+ const [selectedPatterns, setSelectedPatterns] = useState<Pattern[]>([]);+ const [blockedWords, setBlockedWords] = useState<BlockedWord[]>([]);++ // Load data from guardrail on mount or when guardrailData changes+ useEffect(() => {+ if (guardrailData?.litellm_params?.patterns) {+ const patterns = guardrailData.litellm_params.patterns.map((p: any, index: number) => ({+ id: `pattern-${index}`,+ type: p.pattern_type === "prebuilt" ? "prebuilt" : "custom",+ name: p.pattern_name || p.name,+ display_name: p.display_name,+ pattern: p.pattern,+ action: p.action || "BLOCK",+ }));+ setSelectedPatterns(patterns);+ } else {+ setSelectedPatterns([]);+ }++ if (guardrailData?.litellm_params?.blocked_words) {+ const words = guardrailData.litellm_params.blocked_words.map((w: any, index: number) => ({+ id: `word-${index}`,+ keyword: w.keyword,+ action: w.action || "BLOCK",+ description: w.description,+ }));+ setBlockedWords(words);+ } else {+ setBlockedWords([]);+ }+ }, [guardrailData]);++ // Notify parent component when data changes+ useEffect(() => {+ if (onDataChange) {+ onDataChange(selectedPatterns, blockedWords);+ }+ }, [selectedPatterns, blockedWords, onDataChange]);++ // Check if this is a content filter guardrail+ if (guardrailData?.litellm_params?.guardrail !== "litellm_content_filter") {+ return null;+ }++ // Read-only display mode+ if (!isEditing) {+ return (+ <ContentFilterDisplay+ patterns={selectedPatterns}+ blockedWords={blockedWords}+ readOnly={true}+ />+ );+ }++ // Edit mode+ return (+ <>+ <Divider orientation="left">Content Filter Configuration</Divider>+ <div className="mb-6">+ {guardrailSettings && guardrailSettings.content_filter_settings && (+ <ContentFilterConfiguration+ prebuiltPatterns={guardrailSettings.content_filter_settings.prebuilt_patterns || []}+ categories={guardrailSettings.content_filter_settings.pattern_categories || []}+ selectedPatterns={selectedPatterns}+ blockedWords={blockedWords}+ onPatternAdd={(pattern) => setSelectedPatterns([...selectedPatterns, pattern])}+ onPatternRemove={(id) => setSelectedPatterns(selectedPatterns.filter((p) => p.id !== id))}+ onPatternActionChange={(id, action) =>+ setSelectedPatterns(selectedPatterns.map((p) => (p.id === id ? { ...p, action } : p)))+ }+ onBlockedWordAdd={(word) => setBlockedWords([...blockedWords, word])}+ onBlockedWordRemove={(id) => setBlockedWords(blockedWords.filter((w) => w.id !== id))}+ onBlockedWordUpdate={(id, field, value) =>+ setBlockedWords(blockedWords.map((w) => (w.id === id ? { ...w, [field]: value } : w)))+ }+ onFileUpload={(content: string) => {+ console.log("File uploaded:", content);+ }}+ accessToken={accessToken}+ />+ )}+ </div>+ </>+ );+};++export default ContentFilterManager;++// Helper function to format data for API+export const formatContentFilterDataForAPI = (+ patterns: Pattern[],+ blockedWords: BlockedWord[]+) => {+ return {+ patterns: patterns.map((p) => ({+ pattern_type: p.type === "prebuilt" ? "prebuilt" : "regex",+ pattern_name: p.type === "prebuilt" ? p.name : undefined,+ pattern: p.type === "custom" ? p.pattern : undefined,+ name: p.name,+ action: p.action,+ })),+ blocked_words: blockedWords.map((w) => ({+ keyword: w.keyword,+ action: w.action,+ description: w.description,+ })),+ };+};+diff --git a/ui/litellm-dashboard/src/components/guardrails/content_filter/KeywordTable.tsx b/ui/litellm-dashboard/src/components/guardrails/content_filter/KeywordTable.tsxindex 71dd6972a73..51f8e125bf5 100644--- a/ui/litellm-dashboard/src/components/guardrails/content_filter/KeywordTable.tsx+++ b/ui/litellm-dashboard/src/components/guardrails/content_filter/KeywordTable.tsx@@ -59,6 +59,7 @@ const KeywordTable: React.FC<KeywordTableProps> = ({width: 100,render: (_: any, record: BlockedWord) => (<Button+ type="button"variant="light"color="red"size="xs"diff --git a/ui/litellm-dashboard/src/components/guardrails/content_filter/PatternTable.tsx b/ui/litellm-dashboard/src/components/guardrails/content_filter/PatternTable.tsxindex a3c05801337..423a29c343d 100644--- a/ui/litellm-dashboard/src/components/guardrails/content_filter/PatternTable.tsx+++ b/ui/litellm-dashboard/src/components/guardrails/content_filter/PatternTable.tsx@@ -73,6 +73,7 @@ const PatternTable: React.FC<PatternTableProps> = ({width: 100,render: (_: any, record: Pattern) => (<Button+ type="button"variant="light"color="red"size="xs"diff --git a/ui/litellm-dashboard/src/components/guardrails/guardrail_info.tsx b/ui/litellm-dashboard/src/components/guardrails/guardrail_info.tsxindex d314cbc5ebe..6a84e542dd7 100644--- a/ui/litellm-dashboard/src/components/guardrails/guardrail_info.tsx+++ b/ui/litellm-dashboard/src/components/guardrails/guardrail_info.tsx@@ -21,10 +21,11 @@ import {getGuardrailUISettings,getGuardrailProviderSpecificParams,} from "@/components/networking";-import { getGuardrailLogoAndName, guardrail_provider_map } from "./guardrail_info_helpers";+import { getGuardrailLogoAndName, guardrail_provider_map, shouldRenderContentFilterConfigSettings } from "./guardrail_info_helpers";import PiiConfiguration from "./pii_configuration";import GuardrailProviderFields from "./guardrail_provider_fields";import GuardrailOptionalParams from "./guardrail_optional_params";+import ContentFilterManager, { formatContentFilterDataForAPI } from "./content_filter/ContentFilterManager";import { ArrowLeftIcon } from "@heroicons/react/outline";import { copyToClipboard as utilCopyToClipboard } from "@/utils/dataUtils";import { CheckIcon, CopyIcon } from "lucide-react";@@ -69,8 +70,24 @@ const GuardrailInfoView: React.FC<GuardrailInfoProps> = ({ guardrailId, onClose,entities: string[];}>;supported_modes: string[];+ content_filter_settings?: {+ prebuilt_patterns: Array<{+ name: string;+ display_name: string;+ category: string;+ description: string;+ }>;+ pattern_categories: string[];+ supported_actions: string[];+ };} | null>(null);const [copiedStates, setCopiedStates] = useState<Record<string, boolean>>({});++ // Content Filter data ref (managed by ContentFilterManager)+ const contentFilterDataRef = React.useRef<{ patterns: any[]; blockedWords: any[] }>({+ patterns: [],+ blockedWords: [],+ });const fetchGuardrailInfo = async () => {try {setLoading(true);@@ -212,6 +229,25 @@ const GuardrailInfoView: React.FC<GuardrailInfoProps> = ({ guardrailId, onClose,updateData.litellm_params.pii_entities_config = newPiiEntitiesConfig;}+ // Only add Content Filter patterns if there are changes+ if (guardrailData.litellm_params?.guardrail === "litellm_content_filter") {+ const originalPatterns = guardrailData.litellm_params?.patterns || [];+ const originalBlockedWords = guardrailData.litellm_params?.blocked_words || [];++ const formattedData = formatContentFilterDataForAPI(+ contentFilterDataRef.current.patterns,+ contentFilterDataRef.current.blockedWords+ );++ if (JSON.stringify(originalPatterns) !== JSON.stringify(formattedData.patterns)) {+ updateData.litellm_params.patterns = formattedData.patterns;+ }++ if (JSON.stringify(originalBlockedWords) !== JSON.stringify(formattedData.blocked_words)) {+ updateData.litellm_params.blocked_words = formattedData.blocked_words;+ }+ }+/******************************* Add provider-specific params (reusing logic from add_guardrail_form.tsx)* ----------------------------------@@ -443,6 +479,14 @@ const GuardrailInfoView: React.FC<GuardrailInfoProps> = ({ guardrailId, onClose,</div></Card>)}++ {/* Content Filter Configuration Display */}+ <ContentFilterManager+ guardrailData={guardrailData}+ guardrailSettings={guardrailSettings}+ isEditing={false}+ accessToken={accessToken}+ /></TabPanel>{/* Settings Panel (only for admins) */}@@ -512,6 +556,16 @@ const GuardrailInfoView: React.FC<GuardrailInfoProps> = ({ guardrailId, onClose,</>)}+ <ContentFilterManager+ guardrailData={guardrailData}+ guardrailSettings={guardrailSettings}+ isEditing={true}+ accessToken={accessToken}+ onDataChange={(patterns, blockedWords) => {+ contentFilterDataRef.current = { patterns, blockedWords };+ }}+ />+<Divider orientation="left">Provider Settings</Divider>{/* Provider-specific fields */}