Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

Litellm content filter logs page (#18335)

Ishaan Jaff268ed11a0189
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.py
index 83eb57158d7..a04e438f481 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
@@ -8,6 +8,7 @@ to detect and block/mask sensitive content.
import asyncio
import os
import re
+from datetime import datetime
from typing import (
TYPE_CHECKING,
Any,
@@ -33,7 +34,8 @@ from litellm.types.utils import ModelResponseStream
if TYPE_CHECKING:
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
- from litellm.types.utils import GenericGuardrailAPIInputs
+ from litellm.types.utils import GenericGuardrailAPIInputs, GuardrailStatus
+
from litellm.types.guardrails import (
BlockedWord,
ContentFilterAction,
@@ -42,8 +44,13 @@ from litellm.types.guardrails import (
Mode,
)
from litellm.types.proxy.guardrails.guardrail_hooks.litellm_content_filter import (
+ BlockedWordDetection,
+ CategoryKeywordDetection,
ContentFilterCategoryConfig,
+ ContentFilterDetection,
+ PatternDetection,
)
+
from .patterns import get_compiled_pattern
@@ -508,7 +515,9 @@ class ContentFilterGuardrail(CustomGuardrail):
return (keyword, action, description)
return None
- def _filter_single_text(self, text: str) -> str:
+ def _filter_single_text(
+ self, text: str, detections: Optional[List[ContentFilterDetection]] = None
+ ) -> str:
"""
Apply all content filtering checks to a single text.
@@ -519,6 +528,7 @@ class ContentFilterGuardrail(CustomGuardrail):
Args:
text: Text to filter
+ detections: Optional list to append detection information
Returns:
Filtered text (with masking applied if action is MASK)
@@ -535,6 +545,15 @@ class ContentFilterGuardrail(CustomGuardrail):
category_keyword_match = self._check_category_keywords(text, all_exceptions)
if category_keyword_match:
keyword, category_name, severity, action = category_keyword_match
+ if detections is not None:
+ category_detection: CategoryKeywordDetection = {
+ "type": "category_keyword",
+ "category": category_name,
+ "keyword": keyword,
+ "severity": severity,
+ "action": action.value,
+ }
+ detections.append(category_detection)
if action == ContentFilterAction.BLOCK:
error_msg = (
f"Content blocked: {category_name} category keyword '{keyword}' detected "
@@ -568,6 +587,15 @@ class ContentFilterGuardrail(CustomGuardrail):
if not match:
continue
+ if detections is not None:
+ # Don't log matched_text to avoid exposing sensitive content (emails, credit cards, etc.)
+ pattern_detection: PatternDetection = {
+ "type": "pattern",
+ "pattern_name": pattern_name,
+ "action": action.value,
+ }
+ detections.append(pattern_detection)
+
if action == ContentFilterAction.BLOCK:
error_msg = f"Content blocked: {pattern_name} pattern detected"
verbose_proxy_logger.warning(error_msg)
@@ -596,6 +624,15 @@ class ContentFilterGuardrail(CustomGuardrail):
f"Blocked word '{keyword}' found with action {action}"
)
+ if detections is not None:
+ blocked_word_detection: BlockedWordDetection = {
+ "type": "blocked_word",
+ "keyword": keyword,
+ "action": action.value,
+ "description": description,
+ }
+ detections.append(blocked_word_detection)
+
if action == ContentFilterAction.BLOCK:
error_msg = f"Content blocked: keyword '{keyword}' detected"
if description:
@@ -639,6 +676,143 @@ class ContentFilterGuardrail(CustomGuardrail):
)
return redaction_tag
+ async def _process_images(
+ self, images: List[str], detections: List[ContentFilterDetection]
+ ) -> None:
+ """
+ Process images by describing them and applying content filtering.
+
+ Args:
+ images: List of image URLs
+ detections: List to append detection information
+ """
+ if not (images and self.image_model and self.llm_router):
+ return
+
+ tasks = []
+ for image in images:
+ task = self.llm_router.acompletion(
+ model=self.image_model,
+ messages=[
+ {
+ "role": "system",
+ "content": "Describe the image in detail.",
+ },
+ {
+ "role": "user",
+ "content": [
+ {"type": "image_url", "image_url": {"url": image}},
+ ],
+ },
+ ],
+ stream=False,
+ )
+ tasks.append(task)
+
+ responses = await asyncio.gather(*tasks)
+ descriptions = []
+ for response in responses:
+ choice = response.choices[0]
+ message = getattr(choice, "message", None)
+ if message and getattr(message, "content", None):
+ image_description = message.content
+ verbose_proxy_logger.debug(f"Image description: {image_description}")
+ descriptions.append(image_description)
+ else:
+ verbose_proxy_logger.warning("No image description found")
+
+ # Apply content filtering to image descriptions
+ verbose_proxy_logger.debug(
+ f"ContentFilterGuardrail: Applying guardrail to {len(descriptions)} image description(s)"
+ )
+ for description in descriptions:
+ # This will raise HTTPException if BLOCK action is triggered
+ try:
+ self._filter_single_text(description, detections=detections)
+ except HTTPException as e:
+ # e.detail can be a string or dict
+ if isinstance(e.detail, dict) and "error" in e.detail:
+ detail_dict = cast(Dict[str, Any], e.detail)
+ detail_dict["error"] = (
+ detail_dict["error"] + " (Image description): " + description
+ )
+ elif isinstance(e.detail, str):
+ e.detail = e.detail + " (Image description): " + description
+ else:
+ e.detail = "Content blocked: Image description detected" + description
+ raise e
+
+ def _count_masked_entities(
+ self, detections: List[ContentFilterDetection], masked_entity_count: Dict[str, int]
+ ) -> None:
+ """
+ Count masked entities by type from detections.
+
+ Args:
+ detections: List of detection dictionaries
+ masked_entity_count: Dictionary to update with counts
+ """
+ for detection in detections:
+ if detection["action"] == ContentFilterAction.MASK.value:
+ detection_type = detection["type"]
+ if detection_type == "pattern":
+ pattern_detection = cast(PatternDetection, detection)
+ pattern_name = pattern_detection["pattern_name"]
+ masked_entity_count[pattern_name] = (
+ masked_entity_count.get(pattern_name, 0) + 1
+ )
+ elif detection_type == "blocked_word":
+ entity_type = "blocked_word"
+ masked_entity_count[entity_type] = (
+ masked_entity_count.get(entity_type, 0) + 1
+ )
+ elif detection_type == "category_keyword":
+ category_detection = cast(CategoryKeywordDetection, detection)
+ category = category_detection["category"]
+ masked_entity_count[category] = (
+ masked_entity_count.get(category, 0) + 1
+ )
+
+ def _log_guardrail_information(
+ self,
+ request_data: dict,
+ detections: List[ContentFilterDetection],
+ status: "GuardrailStatus",
+ start_time: datetime,
+ masked_entity_count: Dict[str, int],
+ exception_str: str,
+ ) -> None:
+ """
+ Log guardrail information to request_data metadata.
+
+ Args:
+ request_data: Request data dictionary
+ detections: List of detection dictionaries
+ status: Guardrail status
+ start_time: Start time of guardrail execution
+ masked_entity_count: Count of masked entities by type
+ exception_str: Exception string if guardrail failed
+ """
+ # Convert TypedDict detections to regular dicts for JSON serialization
+ guardrail_json_response: Union[Exception, str, dict, List[dict]] = [
+ dict(detection) for detection in detections
+ ]
+ if status != "success":
+ guardrail_json_response = exception_str if exception_str else [
+ dict(detection) for detection in detections
+ ]
+
+ self.add_standard_logging_guardrail_information_to_request_data(
+ guardrail_provider=self.guardrail_provider,
+ guardrail_json_response=guardrail_json_response,
+ request_data=request_data,
+ guardrail_status=status,
+ start_time=start_time.timestamp(),
+ end_time=datetime.now().timestamp(),
+ duration=(datetime.now() - start_time).total_seconds(),
+ masked_entity_count=masked_entity_count,
+ )
+
async def apply_guardrail(
self,
inputs: "GenericGuardrailAPIInputs",
@@ -664,81 +838,57 @@ class ContentFilterGuardrail(CustomGuardrail):
Raises:
HTTPException: If sensitive content is detected and action is BLOCK
"""
- texts = inputs.get("texts", [])
- images = inputs.get("images", [])
- if images and self.image_model and self.llm_router:
- tasks = []
- for image in images:
- task = self.llm_router.acompletion(
- model=self.image_model,
- messages=[
- {
- "role": "system",
- "content": "Describe the image in detail.",
- },
- {
- "role": "user",
- "content": [
- {"type": "image_url", "image_url": {"url": image}},
- ],
- },
- ],
- stream=False,
- )
- tasks.append(task)
-
- responses = await asyncio.gather(*tasks)
- descriptions = []
- for response in responses:
- choice = response.choices[0]
- message = getattr(choice, "message", None)
- if message and getattr(message, "content", None):
- image_description = message.content
- verbose_proxy_logger.debug(
- f"Image description: {image_description}"
- )
- descriptions.append(image_description)
- else:
- verbose_proxy_logger.warning("No image description found")
+ from litellm.types.utils import GuardrailStatus
+
+ start_time = datetime.now()
+ detections: List[ContentFilterDetection] = []
+ masked_entity_count: Dict[str, int] = {}
+ status: GuardrailStatus = "success"
+ exception_str: str = ""
+
+ try:
+ texts = inputs.get("texts", [])
+ images = inputs.get("images", [])
+
+ # Process images if present
+ await self._process_images(images, detections)
- # Apply content filtering to image descriptions
+ # Process texts
verbose_proxy_logger.debug(
- f"ContentFilterGuardrail: Applying guardrail to {len(descriptions)} image description(s)"
+ f"ContentFilterGuardrail: Applying guardrail to {len(texts)} text(s)"
)
- for description in descriptions:
- # This will raise HTTPException if BLOCK action is triggered
- try:
- self._filter_single_text(description)
- except HTTPException as e:
- # e.detail can be a string or dict
- if isinstance(e.detail, dict) and "error" in e.detail:
- detail_dict = cast(Dict[str, Any], e.detail)
- detail_dict["error"] = (
- detail_dict["error"]
- + " (Image description): "
- + description
- )
- elif isinstance(e.detail, str):
- e.detail = e.detail + " (Image description): " + description
- else:
- e.detail = (
- "Content blocked: Image description detected" + description
- )
- raise e
- verbose_proxy_logger.debug(
- f"ContentFilterGuardrail: Applying guardrail to {len(texts)} text(s)"
- )
- processed_texts = []
- for text in texts:
- filtered_text = self._filter_single_text(text)
- processed_texts.append(filtered_text)
+ processed_texts = []
+ for text in texts:
+ filtered_text = self._filter_single_text(text, detections=detections)
+ processed_texts.append(filtered_text)
- verbose_proxy_logger.debug(
- "ContentFilterGuardrail: Guardrail applied successfully"
- )
- inputs["texts"] = processed_texts
- return inputs
+ verbose_proxy_logger.debug(
+ "ContentFilterGuardrail: Guardrail applied successfully"
+ )
+ inputs["texts"] = processed_texts
+
+ # Count masked entities by type
+ self._count_masked_entities(detections, masked_entity_count)
+
+ return inputs
+ except HTTPException:
+ status = "guardrail_intervened"
+ raise
+ except Exception as e:
+ status = "guardrail_failed_to_respond"
+ exception_str = str(e)
+ raise e
+ finally:
+ # Log guardrail information
+ self._log_guardrail_information(
+ request_data=request_data,
+ detections=detections,
+ status=status,
+ start_time=start_time,
+ masked_entity_count=masked_entity_count,
+ exception_str=exception_str,
+ )
async def async_post_call_streaming_iterator_hook(
self,
diff --git a/litellm/types/proxy/guardrails/guardrail_hooks/litellm_content_filter.py b/litellm/types/proxy/guardrails/guardrail_hooks/litellm_content_filter.py
index b5e36334ede..686f30f3b58 100644
--- a/litellm/types/proxy/guardrails/guardrail_hooks/litellm_content_filter.py
+++ b/litellm/types/proxy/guardrails/guardrail_hooks/litellm_content_filter.py
@@ -1,4 +1,5 @@
-from typing import List, Literal, Optional
+from enum import Enum
+from typing import List, Literal, Optional, TypedDict, Union
from pydantic import Field
@@ -6,6 +7,39 @@ from litellm.types.llms.base import BaseLiteLLMOpenAIResponseObject
from litellm.types.proxy.guardrails.guardrail_hooks.base import GuardrailConfigModel
+# Detection type enum
+class DetectionType(str, Enum):
+ PATTERN = "pattern"
+ BLOCKED_WORD = "blocked_word"
+ CATEGORY_KEYWORD = "category_keyword"
+
+
+# Typed detection dictionaries
+class PatternDetection(TypedDict):
+ type: Literal["pattern"]
+ pattern_name: str
+ # Note: matched_text is intentionally excluded to avoid logging sensitive content
+ action: str # ContentFilterAction.value
+
+
+class BlockedWordDetection(TypedDict):
+ type: Literal["blocked_word"]
+ keyword: str
+ action: str # ContentFilterAction.value
+ description: Optional[str]
+
+
+class CategoryKeywordDetection(TypedDict):
+ type: Literal["category_keyword"]
+ category: str
+ keyword: str
+ severity: str
+ action: str # ContentFilterAction.value
+
+
+ContentFilterDetection = Union[PatternDetection, BlockedWordDetection, CategoryKeywordDetection]
+
+
class ContentFilterCategoryConfig(BaseLiteLLMOpenAIResponseObject):
"""
category: "harmful_self_harm"
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.py
index 3e82c8ed0af..474d2a30036 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
@@ -761,3 +761,153 @@ class TestContentFilterGuardrail:
assert "Key1" not in result[0]
assert "Key2" not in result[0]
assert result[0].count("[CUSTOM_KEY_REDACTED]") == 3
+
+ @pytest.mark.asyncio
+ async def test_apply_guardrail_logs_guardrail_information(self):
+ """
+ Test that apply_guardrail calls add_standard_logging_guardrail_information_to_request_data
+ with correct detection information, excluding sensitive content.
+ """
+ patterns = [
+ ContentFilterPattern(
+ pattern_type="prebuilt",
+ pattern_name="email",
+ action=ContentFilterAction.MASK,
+ ),
+ ]
+
+ blocked_words = [
+ BlockedWord(
+ keyword="confidential",
+ action=ContentFilterAction.MASK,
+ description="Test keyword",
+ ),
+ ]
+
+ guardrail = ContentFilterGuardrail(
+ guardrail_name="test-logging",
+ patterns=patterns,
+ blocked_words=blocked_words,
+ )
+
+ request_data = {
+ "messages": [{"role": "user", "content": "Test"}],
+ "model": "gpt-4o",
+ "metadata": {},
+ }
+
+ # Apply guardrail with content that triggers detections
+ # Email will be masked, blocked word will be masked
+ result = await guardrail.apply_guardrail(
+ inputs={"texts": ["Contact me at [email protected] for confidential info"]},
+ request_data=request_data,
+ input_type="request",
+ )
+
+ # Verify guardrail information was added to metadata
+ assert "metadata" in request_data
+ assert "standard_logging_guardrail_information" in request_data["metadata"]
+
+ guardrail_info_list = request_data["metadata"]["standard_logging_guardrail_information"]
+ assert isinstance(guardrail_info_list, list)
+ assert len(guardrail_info_list) == 1
+
+ guardrail_info = guardrail_info_list[0]
+
+ # Verify basic fields
+ assert guardrail_info["guardrail_name"] == "test-logging"
+ assert guardrail_info["guardrail_provider"] == "litellm_content_filter"
+ assert guardrail_info["guardrail_status"] == "success"
+ assert "start_time" in guardrail_info
+ assert "end_time" in guardrail_info
+ assert "duration" in guardrail_info
+ assert guardrail_info["duration"] > 0
+ assert guardrail_info["start_time"] < guardrail_info["end_time"]
+
+ # Verify detections are logged
+ assert "guardrail_response" in guardrail_info
+ detections = guardrail_info["guardrail_response"]
+ assert isinstance(detections, list)
+ assert len(detections) >= 2 # At least email pattern and blocked word
+
+ # Verify pattern detection structure (without sensitive content)
+ pattern_detections = [d for d in detections if d.get("type") == "pattern"]
+ assert len(pattern_detections) > 0
+ for detection in pattern_detections:
+ assert detection["type"] == "pattern"
+ assert "pattern_name" in detection
+ assert detection["pattern_name"] == "email"
+ assert "action" in detection
+ assert detection["action"] == "MASK"
+ # Verify sensitive content (matched_text) is NOT included
+ assert "matched_text" not in detection, "Sensitive content should not be logged"
+
+ # Verify blocked word detection structure
+ blocked_word_detections = [d for d in detections if d.get("type") == "blocked_word"]
+ assert len(blocked_word_detections) > 0
+ for detection in blocked_word_detections:
+ assert detection["type"] == "blocked_word"
+ assert "keyword" in detection
+ assert detection["keyword"] == "confidential" # Config keyword, not user content
+ assert "action" in detection
+ assert detection["action"] == "MASK"
+ assert "description" in detection
+ assert detection["description"] == "Test keyword"
+
+ # Verify masked entity count
+ assert "masked_entity_count" in guardrail_info
+ masked_count = guardrail_info["masked_entity_count"]
+ assert isinstance(masked_count, dict)
+ # Should have counts for masked entities
+ assert len(masked_count) > 0
+
+ @pytest.mark.asyncio
+ async def test_apply_guardrail_logs_blocked_status(self):
+ """
+ Test that apply_guardrail logs guardrail_intervened status when content is blocked.
+ """
+ patterns = [
+ ContentFilterPattern(
+ pattern_type="prebuilt",
+ pattern_name="us_ssn",
+ action=ContentFilterAction.BLOCK,
+ ),
+ ]
+
+ guardrail = ContentFilterGuardrail(
+ guardrail_name="test-block-logging",
+ patterns=patterns,
+ )
+
+ request_data = {
+ "messages": [{"role": "user", "content": "Test"}],
+ "model": "gpt-4o",
+ "metadata": {},
+ }
+
+ # Apply guardrail with content that triggers BLOCK
+ with pytest.raises(HTTPException):
+ await guardrail.apply_guardrail(
+ inputs={"texts": ["My SSN is 123-45-6789"]},
+ request_data=request_data,
+ input_type="request",
+ )
+
+ # Verify guardrail information was added even when blocked
+ assert "metadata" in request_data
+ assert "standard_logging_guardrail_information" in request_data["metadata"]
+
+ guardrail_info_list = request_data["metadata"]["standard_logging_guardrail_information"]
+ assert len(guardrail_info_list) == 1
+
+ guardrail_info = guardrail_info_list[0]
+ assert guardrail_info["guardrail_status"] == "guardrail_intervened"
+ assert guardrail_info["guardrail_name"] == "test-block-logging"
+
+ # Verify detection is logged (even though request was blocked)
+ detections = guardrail_info.get("guardrail_response", [])
+ if isinstance(detections, list) and len(detections) > 0:
+ # If detections are logged, verify they don't contain sensitive content
+ for detection in detections:
+ if detection.get("type") == "pattern":
+ assert "matched_text" not in detection, "Sensitive content should not be logged"
diff --git a/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/ContentFilterDetails.tsx b/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/ContentFilterDetails.tsx
new file mode 100644
index 00000000000..766c267676a
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/ContentFilterDetails.tsx
@@ -0,0 +1,224 @@
+import React, { useState } from "react";
+
+export interface ContentFilterDetection {
+ type: "pattern" | "blocked_word" | "category_keyword";
+ pattern_name?: string;
+ // matched_text is intentionally excluded to avoid exposing sensitive content
+ keyword?: string;
+ category?: string;
+ severity?: string;
+ action: "BLOCK" | "MASK";
+ description?: string;
+}
+
+interface ContentFilterDetailsProps {
+ response: ContentFilterDetection[] | string | null | undefined;
+}
+
+const chip = (text: React.ReactNode, tone: "green" | "red" | "blue" | "slate" | "amber" = "slate") => {
+ const map: Record<string, string> = {
+ green: "bg-green-100 text-green-800",
+ red: "bg-red-100 text-red-800",
+ blue: "bg-blue-50 text-blue-700",
+ slate: "bg-slate-100 text-slate-800",
+ amber: "bg-amber-100 text-amber-800",
+ };
+ return <span className={`px-2 py-1 rounded-md text-xs font-medium inline-block ${map[tone]}`}>{text}</span>;
+};
+
+interface SectionProps {
+ title: string;
+ count?: number;
+ defaultOpen?: boolean;
+ children?: React.ReactNode;
+}
+
+const Section: React.FC<SectionProps> = ({ title, count, defaultOpen = true, children }) => {
+ const [open, setOpen] = useState(defaultOpen);
+ return (
+ <div className="border rounded-lg overflow-hidden">
+ <div
+ className="flex items-center justify-between p-3 bg-gray-50 cursor-pointer hover:bg-gray-100"
+ onClick={() => setOpen((v) => !v)}
+ >
+ <div className="flex items-center">
+ <svg
+ className={`w-5 h-5 mr-2 transition-transform ${open ? "transform rotate-90" : ""}`}
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
+ </svg>
+ <h5 className="font-medium">
+ {title} {typeof count === "number" && <span className="text-gray-500 font-normal">({count})</span>}
+ </h5>
+ </div>
+ </div>
+ {open && <div className="p-3 border-t bg-white">{children}</div>}
+ </div>
+ );
+};
+
+interface KVProps {
+ label: string;
+ children?: React.ReactNode;
+ mono?: boolean;
+}
+
+const KV: React.FC<KVProps> = ({ label, children, mono }) => (
+ <div className="flex">
+ <span className="font-medium w-1/3">{label}</span>
+ <span className={mono ? "font-mono text-sm break-all" : ""}>{children}</span>
+ </div>
+);
+
+const ContentFilterDetails: React.FC<ContentFilterDetailsProps> = ({ response }) => {
+ // Handle case where response is a string (error message) or null
+ if (!response || typeof response === "string") {
+ if (typeof response === "string" && response) {
+ return (
+ <div className="bg-white rounded-lg border border-red-200 p-4">
+ <div className="text-red-800">
+ <h5 className="font-medium mb-2">Error</h5>
+ <p className="text-sm">{response}</p>
+ </div>
+ </div>
+ );
+ }
+ return null;
+ }
+
+ // Ensure response is an array
+ const detections: ContentFilterDetection[] = Array.isArray(response) ? response : [];
+
+ if (detections.length === 0) {
+ return (
+ <div className="bg-white rounded-lg border border-gray-200 p-4">
+ <div className="text-gray-600 text-sm">No detections found</div>
+ </div>
+ );
+ }
+
+ // Group detections by type
+ const patterns = detections.filter((d) => d.type === "pattern");
+ const blockedWords = detections.filter((d) => d.type === "blocked_word");
+ const categoryKeywords = detections.filter((d) => d.type === "category_keyword");
+
+ // Count actions
+ const blockedCount = detections.filter((d) => d.action === "BLOCK").length;
+ const maskedCount = detections.filter((d) => d.action === "MASK").length;
+
+ // Summary stats
+ const totalDetections = detections.length;
+
+ return (
+ <div className="space-y-3">
+ {/* Summary Section */}
+ <div className="bg-white rounded-lg border border-gray-200 p-4">
+ <div className="grid grid-cols-2 gap-4">
+ <div className="space-y-2">
+ <KV label="Total Detections:">
+ <span className="font-semibold">{totalDetections}</span>
+ </KV>
+ <KV label="Actions:">
+ <div className="flex flex-wrap gap-2">
+ {blockedCount > 0 && chip(`${blockedCount} blocked`, "red")}
+ {maskedCount > 0 && chip(`${maskedCount} masked`, "blue")}
+ {blockedCount === 0 && maskedCount === 0 && chip("passed", "green")}
+ </div>
+ </KV>
+ </div>
+ <div className="space-y-2">
+ <KV label="By Type:">
+ <div className="flex flex-wrap gap-2">
+ {patterns.length > 0 && chip(`${patterns.length} patterns`, "slate")}
+ {blockedWords.length > 0 && chip(`${blockedWords.length} keywords`, "slate")}
+ {categoryKeywords.length > 0 && chip(`${categoryKeywords.length} categories`, "slate")}
+ </div>
+ </KV>
+ </div>
+ </div>
+ </div>
+
+ {/* Patterns Section */}
+ {patterns.length > 0 && (
+ <Section title="Patterns Matched" count={patterns.length} defaultOpen={true}>
+ <div className="space-y-2">
+ {patterns.map((detection, idx) => (
+ <div key={idx} className="p-3 bg-gray-50 rounded-md">
+ <div className="grid grid-cols-2 gap-4">
+ <div className="space-y-1">
+ <KV label="Pattern:">{detection.pattern_name || "unknown"}</KV>
+ </div>
+ <div className="space-y-1">
+ <KV label="Action:">{chip(detection.action, detection.action === "BLOCK" ? "red" : "blue")}</KV>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </Section>
+ )}
+
+ {/* Blocked Words Section */}
+ {blockedWords.length > 0 && (
+ <Section title="Blocked Words Detected" count={blockedWords.length} defaultOpen={true}>
+ <div className="space-y-2">
+ {blockedWords.map((detection, idx) => (
+ <div key={idx} className="p-3 bg-gray-50 rounded-md">
+ <div className="grid grid-cols-2 gap-4">
+ <div className="space-y-1">
+ <KV label="Keyword:" mono>
+ {detection.keyword || "unknown"}
+ </KV>
+ {detection.description && <KV label="Description:">{detection.description}</KV>}
+ </div>
+ <div className="space-y-1">
+ <KV label="Action:">{chip(detection.action, detection.action === "BLOCK" ? "red" : "blue")}</KV>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </Section>
+ )}
+
+ {/* Category Keywords Section */}
+ {categoryKeywords.length > 0 && (
+ <Section title="Category Keywords Detected" count={categoryKeywords.length} defaultOpen={true}>
+ <div className="space-y-2">
+ {categoryKeywords.map((detection, idx) => (
+ <div key={idx} className="p-3 bg-gray-50 rounded-md">
+ <div className="grid grid-cols-2 gap-4">
+ <div className="space-y-1">
+ <KV label="Category:">{detection.category || "unknown"}</KV>
+ <KV label="Keyword:" mono>
+ {detection.keyword || "unknown"}
+ </KV>
+ {detection.severity && (
+ <KV label="Severity:">
+ {chip(detection.severity, detection.severity === "high" ? "red" : detection.severity === "medium" ? "amber" : "slate")}
+ </KV>
+ )}
+ </div>
+ <div className="space-y-1">
+ <KV label="Action:">{chip(detection.action, detection.action === "BLOCK" ? "red" : "blue")}</KV>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </Section>
+ )}
+
+ {/* Raw JSON (for debugging) */}
+ <Section title="Raw Detection Data" defaultOpen={false}>
+ <pre className="bg-gray-50 rounded p-3 text-xs overflow-x-auto">{JSON.stringify(detections, null, 2)}</pre>
+ </Section>
+ </div>
+ );
+};
+
+export default ContentFilterDetails;
+
diff --git a/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsx b/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsx
index 36eecd6684a..b25545200cd 100644
--- a/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsx
+++ b/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsx
@@ -4,6 +4,7 @@ import PresidioDetectedEntities from "./PresidioDetectedEntities";
import BedrockGuardrailDetails, {
BedrockGuardrailResponse,
} from "@/components/view_logs/GuardrailViewer/BedrockGuardrailDetails";
+import ContentFilterDetails from "./ContentFilterDetails";
interface RecognitionMetadata {
recognizer_name: string;
@@ -30,9 +31,9 @@ interface GuardrailInformation {
guardrail_mode: string;
guardrail_name: string;
guardrail_status: string;
- guardrail_response: GuardrailEntity[] | BedrockGuardrailResponse;
+ guardrail_response: GuardrailEntity[] | BedrockGuardrailResponse | any;
masked_entity_count: MaskedEntityCount;
- guardrail_provider?: string; // "presidio" | other providers
+ guardrail_provider?: string; // "presidio" | "bedrock" | "litellm_content_filter" | other providers
}
interface GuardrailViewerProps {
@@ -50,6 +51,42 @@ const formatTime = (timestamp: number) => {
return date.toLocaleString();
};
+// Providers with custom renderers
+const PROVIDERS_WITH_CUSTOM_RENDERERS = new Set(["presidio", "bedrock", "litellm_content_filter"]);
+
+const GenericGuardrailResponse = ({ response }: { response: any }) => {
+ const [showRaw, setShowRaw] = useState(false);
+ return (
+ <div className="mt-4">
+ <div className="border rounded-lg overflow-hidden">
+ <div
+ className="flex items-center justify-between p-3 bg-gray-50 cursor-pointer hover:bg-gray-100"
+ onClick={() => setShowRaw(!showRaw)}
+ >
+ <div className="flex items-center">
+ <svg
+ className={`w-5 h-5 mr-2 transition-transform ${showRaw ? "transform rotate-90" : ""}`}
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
+ </svg>
+ <h5 className="font-medium">Raw Guardrail Response</h5>
+ </div>
+ </div>
+ {showRaw && (
+ <div className="p-3 border-t bg-white">
+ <pre className="bg-gray-50 rounded p-3 text-xs overflow-x-auto">
+ {JSON.stringify(response, null, 2)}
+ </pre>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
+
const GuardrailDetails = ({ entry, index, total }: GuardrailDetailsProps) => {
const guardrailProvider = entry.guardrail_provider ?? "presidio";
const statusLabel = entry.guardrail_status ?? "unknown";
@@ -148,6 +185,17 @@ const GuardrailDetails = ({ entry, index, total }: GuardrailDetailsProps) => {
<BedrockGuardrailDetails response={bedrockResponse} />
</div>
)}
+
+ {guardrailProvider === "litellm_content_filter" && guardrailResponse && (
+ <div className="mt-4">
+ <ContentFilterDetails response={guardrailResponse} />
+ </div>
+ )}
+
+ {/* Generic fallback for unknown guardrail providers */}
+ {guardrailProvider &&
+ !PROVIDERS_WITH_CUSTOM_RENDERERS.has(guardrailProvider) &&
+ guardrailResponse && <GenericGuardrailResponse response={guardrailResponse} />}
</div>
);
};