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: guardrail tracing UI - policy, detection method, match details (#21349)
Ishaan Jaff0f96b5a1b755
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 9d1c254d1a7..55746e5e527 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@@ -329,10 +329,10 @@ class ContentFilterGuardrail(CustomGuardrail):action if action else category_config_obj.default_action)- # Handle conditional categories (with identifier_words + inherit_from OR identifier_words + additional_block_words)- if category_config_obj.identifier_words and (- category_config_obj.inherit_from- or category_config_obj.additional_block_words+ # Handle conditional categories (with identifier_words + inherit_from)+ if (+ category_config_obj.identifier_words+ and category_config_obj.inherit_from):self._load_conditional_category(category_name,@@ -387,81 +387,64 @@ class ContentFilterGuardrail(CustomGuardrail):categories_dir: str,) -> None:"""- Load a conditional category that uses identifier_words + block_words.-- Supports two patterns:- 1. Inherit + additional: identifier_words + inherit_from + optional additional_block_words- 2. Standalone: identifier_words + additional_block_words (no inheritance)+ Load a conditional category that uses identifier_words + inherited block_words.Args:category_name: Name of the category- category_config_obj: CategoryConfig object with identifier_words and either inherit_from or additional_block_words+ category_config_obj: CategoryConfig object with identifier_words and inherit_fromcategory_action: Action to take when match is foundseverity_threshold: Minimum severity thresholdcategories_dir: Directory containing category files"""- block_words = []+ # Load the inherited category to get block wordsinherit_from = category_config_obj.inherit_from+ if not inherit_from:+ return- # Pattern 1: Load inherited category to get base block words- if inherit_from:- # Remove .json or .yaml extension if included- inherit_base = inherit_from.replace(".json", "").replace(".yaml", "")-- # Find the inherited category file- inherit_yaml_path = os.path.join(categories_dir, f"{inherit_base}.yaml")- inherit_json_path = os.path.join(categories_dir, f"{inherit_base}.json")-- if os.path.exists(inherit_yaml_path):- inherit_file_path = inherit_yaml_path- elif os.path.exists(inherit_json_path):- inherit_file_path = inherit_json_path- else:- verbose_proxy_logger.warning(- f"Category {category_name}: inherit_from '{inherit_from}' file not found at {categories_dir}"- )- verbose_proxy_logger.debug(- f"Tried paths: {inherit_yaml_path}, {inherit_json_path}"- )- return-- try:- # Load the inherited category- inherited_category = self._load_category_file(inherit_file_path)-- # Extract block words from inherited category that meet severity threshold- for keyword_data in inherited_category.keywords:- keyword = keyword_data["keyword"].lower()- severity = keyword_data["severity"]- if self._should_apply_severity(severity, severity_threshold):- block_words.append(keyword)- except Exception as e:- verbose_proxy_logger.error(- f"Error loading inherited category for {category_name}: {e}"- )- return+ # Remove .json or .yaml extension if included+ inherit_base = inherit_from.replace(".json", "").replace(".yaml", "")- # Pattern 2 or supplement to Pattern 1: Add additional block words- if category_config_obj.additional_block_words:- block_words.extend(category_config_obj.additional_block_words)+ # Find the inherited category file+ inherit_yaml_path = os.path.join(categories_dir, f"{inherit_base}.yaml")+ inherit_json_path = os.path.join(categories_dir, f"{inherit_base}.json")- # Ensure we have block words before storing- if not block_words:+ if os.path.exists(inherit_yaml_path):+ inherit_file_path = inherit_yaml_path+ elif os.path.exists(inherit_json_path):+ inherit_file_path = inherit_json_path+ else:verbose_proxy_logger.warning(- f"Category {category_name}: no block words found (check inherit_from or additional_block_words)"+ f"Category {category_name}: inherit_from '{inherit_from}' file not found at {categories_dir}"+ )+ verbose_proxy_logger.debug(+ f"Tried paths: {inherit_yaml_path}, {inherit_json_path}")return- # Store the conditional category configuration- self.conditional_categories[category_name] = {- "identifier_words": category_config_obj.identifier_words,- "block_words": block_words,- "action": category_action,- "severity": "high", # Combinations are always high severity- }+ try:+ # Load the inherited category+ inherited_category = self._load_category_file(inherit_file_path)++ # Extract block words from inherited category that meet severity threshold+ block_words = []+ for keyword_data in inherited_category.keywords:+ keyword = keyword_data["keyword"].lower()+ severity = keyword_data["severity"]+ if self._should_apply_severity(severity, severity_threshold):+ block_words.append(keyword)++ # Add additional block words specific to this category+ if category_config_obj.additional_block_words:+ block_words.extend(category_config_obj.additional_block_words)++ # Store the conditional category configuration+ self.conditional_categories[category_name] = {+ "identifier_words": category_config_obj.identifier_words,+ "block_words": block_words,+ "action": category_action,+ "severity": "high", # Combinations are always high severity+ }- # Log different messages based on pattern- if inherit_from and category_config_obj.additional_block_words:verbose_proxy_logger.info(f"Loaded conditional category {category_name}: "f"{len(category_config_obj.identifier_words)} identifiers + "@@ -469,17 +452,9 @@ class ContentFilterGuardrail(CustomGuardrail):f"({len(category_config_obj.additional_block_words)} additional + "f"{len(block_words) - len(category_config_obj.additional_block_words)} from {inherit_from})")- elif inherit_from:- verbose_proxy_logger.info(- f"Loaded conditional category {category_name}: "- f"{len(category_config_obj.identifier_words)} identifiers + "- f"{len(block_words)} block words (from {inherit_from})"- )- else:- verbose_proxy_logger.info(- f"Loaded conditional category {category_name}: "- f"{len(category_config_obj.identifier_words)} identifiers + "- f"{len(block_words)} block words (standalone)"+ except Exception as e:+ verbose_proxy_logger.error(+ f"Error loading inherited category for {category_name}: {e}")def _load_category_file(self, file_path: str) -> CategoryConfig:@@ -1398,6 +1373,41 @@ class ContentFilterGuardrail(CustomGuardrail):names = [cat.description or cat.category_name for cat in self.loaded_categories.values()]return ", ".join(names) if names else None+ def _compute_risk_score(+ self,+ detections: List[ContentFilterDetection],+ masked_entity_count: Dict[str, int],+ status: "GuardrailStatus",+ ) -> float:+ """+ Compute a risk score from 0-10 for this guardrail evaluation.++ Factors:+ - Match ratio: how many patterns matched vs total checked+ - Number of entities masked+ - Whether the guardrail blocked the request (max risk)+ """+ if status == "guardrail_intervened":+ return 10.0++ total_masked = sum(masked_entity_count.values()) if masked_entity_count else 0+ patterns_checked = self._get_patterns_checked_count()++ # Match ratio contribution (0-7 points)+ match_ratio = total_masked / patterns_checked if patterns_checked > 0 else 0.0+ ratio_score = match_ratio * 7.0++ # Detection count contribution (0-3 points, capped)+ detection_score = min(len(detections), 5) * 0.6++ score = ratio_score + detection_score++ # Floor: if anything matched, minimum risk is 2+ if total_masked > 0 and score < 2.0:+ score = 2.0++ return round(min(10.0, score), 1)+def _log_guardrail_information(self,request_data: dict,@@ -1444,6 +1454,7 @@ class ContentFilterGuardrail(CustomGuardrail):detection_method=self._get_detection_methods(detections) if detections else None,match_details=self._build_match_details(detections) if detections else None,patterns_checked=self._get_patterns_checked_count(),+ risk_score=self._compute_risk_score(detections, masked_entity_count, status),),)diff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex 5fbfd23b2db..5f8798c7712 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -2644,6 +2644,9 @@ class StandardLoggingGuardrailInformation(TypedDict, total=False):alert_recipients: Optional[List[str]]"""Email addresses that were notified"""+ risk_score: Optional[float]+ """Risk score 0-10 indicating how risky the request was (higher = riskier). Computed by the guardrail provider."""+class GuardrailTracingDetail(TypedDict, total=False):"""@@ -2661,6 +2664,7 @@ class GuardrailTracingDetail(TypedDict, total=False):match_details: Optional[List[dict]]patterns_checked: Optional[int]alert_recipients: Optional[List[str]]+ risk_score: Optional[float]StandardLoggingPayloadStatus = Literal["success", "failure"]diff --git a/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsx b/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsxindex 8f9869e4dd5..35828922012 100644--- a/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsx@@ -1,11 +1,13 @@-import React, { useState } from "react";-import { Tooltip, Collapse } from "antd";+import React, { useState, useMemo } from "react";+import { Tooltip } from "antd";import PresidioDetectedEntities from "./PresidioDetectedEntities";import BedrockGuardrailDetails, {BedrockGuardrailResponse,} from "@/components/view_logs/GuardrailViewer/BedrockGuardrailDetails";import ContentFilterDetails from "./ContentFilterDetails";+// ── Interfaces ──────────────────────────────────────────────────────────────+interface RecognitionMetadata {recognizer_name: string;recognizer_identifier: string;@@ -51,121 +53,159 @@ interface GuardrailInformation {match_details?: MatchDetail[];patterns_checked?: number;alert_recipients?: string[];+ risk_score?: number;}interface GuardrailViewerProps {data: GuardrailInformation | GuardrailInformation[];}-interface GuardrailDetailsProps {- entry: GuardrailInformation;- index: number;- total: number;-}+// ── Helpers ─────────────────────────────────────────────────────────────────-const formatTime = (timestamp: number) => {- const date = new Date(timestamp * 1000);- return date.toLocaleString();+const PROVIDERS_WITH_CUSTOM_RENDERERS = new Set([+ "presidio",+ "bedrock",+ "litellm_content_filter",+]);++const formatMode = (mode: string): string => {+ return mode.replace(/_/g, "-").toUpperCase();};-// Providers with custom renderers-const PROVIDERS_WITH_CUSTOM_RENDERERS = new Set(["presidio", "bedrock", "litellm_content_filter"]);+const formatDurationMs = (seconds: number): string => {+ const ms = Math.round(seconds * 1000);+ return `${ms}ms`;+};-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 getTotalMasked = (entry: GuardrailInformation): number => {+ return Object.values(entry.masked_entity_count || {}).reduce(+ (sum, count) => sum + (typeof count === "number" ? count : 0),+ 0,);};-const PolicyDetectionRow = ({ entry }: { entry: GuardrailInformation }) => {- const hasData = entry.policy_template || entry.detection_method || entry.confidence_score != null || entry.patterns_checked != null;- if (!hasData) return null;+const isEntrySuccess = (entry: GuardrailInformation): boolean => {+ return (entry.guardrail_status ?? "").toLowerCase() === "success";+};- return (- <div className="mt-4 pt-4 border-t">- <div className="flex flex-wrap gap-4">- {entry.policy_template && (- <div className="flex items-center gap-2">- <span className="font-medium text-sm">Policy:</span>- <span className="px-2 py-1 bg-purple-50 text-purple-700 rounded-md text-xs font-medium">- {entry.policy_template}- </span>- </div>- )}- {entry.detection_method && (- <div className="flex items-center gap-2">- <span className="font-medium text-sm">Detection:</span>- {entry.detection_method.split(",").map((method) => (- <span key={method} className="px-2 py-1 bg-slate-100 text-slate-700 rounded-md text-xs font-medium">- {method.trim()}- </span>- ))}- </div>- )}- {entry.confidence_score != null && (- <div className="flex items-center gap-2">- <span className="font-medium text-sm">Confidence:</span>- <span className={`px-2 py-1 rounded-md text-xs font-medium ${- entry.confidence_score >= 0.8 ? "bg-red-100 text-red-800" :- entry.confidence_score >= 0.5 ? "bg-amber-100 text-amber-800" :- "bg-green-100 text-green-800"- }`}>- {(entry.confidence_score * 100).toFixed(0)}%- </span>- </div>- )}- {entry.patterns_checked != null && (- <div className="flex items-center gap-2">- <span className="font-medium text-sm">Patterns checked:</span>- <span className="text-sm text-gray-600">{entry.patterns_checked}</span>- </div>- )}- </div>- </div>- );+const getRiskColor = (score: number): string => {+ if (score <= 3) return "text-green-600 bg-green-50 border-green-200";+ if (score <= 6) return "text-amber-600 bg-amber-50 border-amber-200";+ return "text-red-600 bg-red-50 border-red-200";};+const getRiskScore = (entry: GuardrailInformation): number | null => {+ if (!isEntrySuccess(entry)) return null;++ // Prefer backend-computed score+ if (entry.risk_score != null) return entry.risk_score;++ // Fallback: compute from available data+ const totalMasked = getTotalMasked(entry);+ const patternsChecked = entry.patterns_checked ?? 0;+ const confidence = entry.confidence_score ?? 0;++ if (patternsChecked === 0 && confidence === 0) return 0;++ const matchRatio = patternsChecked > 0 ? totalMasked / patternsChecked : 0;+ let score = matchRatio * 7 + confidence * 3;+ if (totalMasked > 0 && score < 2) score = 2;+ return Math.min(10, Math.round(score * 10) / 10);+};++const getDisplayName = (entry: GuardrailInformation): string => {+ return entry.policy_template || entry.guardrail_name;+};++// ── Icons (inline SVGs) ─────────────────────────────────────────────────────++const ShieldIcon = () => (+ <svg width="40" height="40" viewBox="0 0 40 40" fill="none">+ <circle cx="20" cy="20" r="20" fill="#EEF2FF" />+ <path+ d="M20 10l8 4v6c0 5.25-3.4 10.15-8 11.5C15.4 30.15 12 25.25 12 20v-6l8-4z"+ stroke="#6366F1"+ strokeWidth="1.5"+ fill="none"+ />+ <path+ d="M16 20l3 3 5-6"+ stroke="#6366F1"+ strokeWidth="1.5"+ strokeLinecap="round"+ strokeLinejoin="round"+ fill="none"+ />+ </svg>+);++const CheckCircleIcon = ({ className }: { className?: string }) => (+ <svg width="22" height="22" viewBox="0 0 22 22" fill="none" className={className}>+ <circle cx="11" cy="11" r="10" stroke="#16A34A" strokeWidth="1.5" fill="#F0FDF4" />+ <path d="M7 11l3 3 5-6" stroke="#16A34A" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />+ </svg>+);++const FailCircleIcon = ({ className }: { className?: string }) => (+ <svg width="22" height="22" viewBox="0 0 22 22" fill="none" className={className}>+ <circle cx="11" cy="11" r="10" stroke="#DC2626" strokeWidth="1.5" fill="#FEF2F2" />+ <path d="M8 8l6 6M14 8l-6 6" stroke="#DC2626" strokeWidth="1.5" strokeLinecap="round" />+ </svg>+);++const PlayCircleIcon = () => (+ <svg width="22" height="22" viewBox="0 0 22 22" fill="none">+ <circle cx="11" cy="11" r="10" stroke="#3B82F6" strokeWidth="1.5" fill="#EFF6FF" />+ <path d="M9 7.5l6 3.5-6 3.5V7.5z" fill="#3B82F6" />+ </svg>+);++const GrayDotIcon = () => (+ <svg width="22" height="22" viewBox="0 0 22 22" fill="none">+ <circle cx="11" cy="11" r="5" fill="#9CA3AF" />+ </svg>+);++const ChevronIcon = ({ expanded }: { expanded: boolean }) => (+ <svg+ width="20"+ height="20"+ viewBox="0 0 20 20"+ fill="none"+ className={`transition-transform ${expanded ? "rotate-180" : ""}`}+ >+ <path d="M6 8l4 4 4-4" stroke="#6B7280" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />+ </svg>+);++const DownloadIcon = () => (+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none">+ <path d="M8 2v8m0 0l-3-3m3 3l3-3M3 12h10" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />+ </svg>+);++const ExternalLinkIcon = () => (+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none" className="inline ml-1">+ <path d="M6 2H3a1 1 0 00-1 1v8a1 1 0 001 1h8a1 1 0 001-1V8M8 2h4m0 0v4m0-4L6.5 7.5" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round" />+ </svg>+);++// ── Sub-components ──────────────────────────────────────────────────────────+const MatchDetailsTable = ({ matchDetails }: { matchDetails: MatchDetail[] }) => {if (!matchDetails || matchDetails.length === 0) return null;return (- <div className="mt-4 pt-4 border-t">- <h5 className="font-medium mb-2">Match Details ({matchDetails.length})</h5>+ <div className="mt-3">+ <h5 className="text-sm font-medium mb-2 text-gray-700">Match Details ({matchDetails.length})</h5><div className="overflow-x-auto"><table className="w-full text-sm"><thead><tr className="border-b text-left text-gray-500">- <th className="pb-2 pr-4">Type</th>- <th className="pb-2 pr-4">Method</th>- <th className="pb-2 pr-4">Action</th>- <th className="pb-2">Detail</th>+ <th className="pb-2 pr-4 font-medium">Type</th>+ <th className="pb-2 pr-4 font-medium">Method</th>+ <th className="pb-2 pr-4 font-medium">Action</th>+ <th className="pb-2 font-medium">Detail</th></tr></thead><tbody>@@ -178,14 +218,17 @@ const MatchDetailsTable = ({ matchDetails }: { matchDetails: MatchDetail[] }) =></span></td><td className="py-2 pr-4">- <span className={`px-2 py-0.5 rounded text-xs font-medium ${- match.action_taken === "BLOCK" ? "bg-red-100 text-red-800" : "bg-blue-50 text-blue-700"- }`}>+ <span+ className={`px-2 py-0.5 rounded text-xs font-medium ${+ match.action_taken === "BLOCK" ? "bg-red-100 text-red-800" : "bg-blue-50 text-blue-700"+ }`}+ >{match.action_taken ?? "-"}</span></td><td className="py-2 font-mono text-xs text-gray-600 break-all">- {match.category ? `[${match.category}] ` : ""}{match.snippet ?? "-"}+ {match.category ? `[${match.category}] ` : ""}+ {match.snippet ?? "-"}</td></tr>))}@@ -196,35 +239,25 @@ const MatchDetailsTable = ({ matchDetails }: { matchDetails: MatchDetail[] }) =>);};-const ClassificationDetails = ({ classification }: { classification: Record<string, any> }) => {- if (!classification) return null;-+const GenericGuardrailResponse = ({ response }: { response: any }) => {+ const [showRaw, setShowRaw] = useState(false);return (- <div className="mt-4 pt-4 border-t">- <h5 className="font-medium mb-2">Classification</h5>- <div className="space-y-2 bg-gray-50 rounded-lg p-3">- {classification.category && (- <div className="flex">- <span className="font-medium w-1/3 text-sm">Category:</span>- <span className="text-sm">{classification.category}</span>- </div>- )}- {classification.article_reference && (- <div className="flex">- <span className="font-medium w-1/3 text-sm">Reference:</span>- <span className="text-sm font-mono">{classification.article_reference}</span>- </div>- )}- {classification.confidence != null && (- <div className="flex">- <span className="font-medium w-1/3 text-sm">Confidence:</span>- <span className="text-sm">{(classification.confidence * 100).toFixed(0)}%</span>+ <div className="mt-3">+ <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">+ <ChevronIcon expanded={showRaw} />+ <h5 className="font-medium text-sm ml-1">Raw Guardrail Response</h5></div>- )}- {classification.reason && (- <div className="flex">- <span className="font-medium w-1/3 text-sm">Reason:</span>- <span className="text-sm">{classification.reason}</span>+ </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>@@ -232,61 +265,162 @@ const ClassificationDetails = ({ classification }: { classification: Record<stri);};-const ExecutionTimeline = ({ entries }: { entries: GuardrailInformation[] }) => {- if (entries.length <= 1) return null;+// ── Timeline entry types ────────────────────────────────────────────────────++interface TimelineEntry {+ type: "request" | "guardrail" | "llm" | "response";+ label: string;+ offsetMs: number;+ status?: string;+ isSuccess?: boolean;+}++const RequestLifecycle = ({ entries }: { entries: GuardrailInformation[] }) => {+ const sorted = useMemo(+ () => [...entries].sort((a, b) => (a.start_time ?? 0) - (b.start_time ?? 0)),+ [entries],+ );- const sorted = [...entries].sort((a, b) => (a.start_time ?? 0) - (b.start_time ?? 0));+ const timeline = useMemo(() => {+ if (sorted.length === 0) return [];++ const baseTime = sorted[0].start_time;+ const items: TimelineEntry[] = [];++ // Request received+ items.push({ type: "request", label: "Request received", offsetMs: 0 });++ // Pre-call guardrails+ const preCalls = sorted.filter((e) => e.guardrail_mode === "pre_call");+ const postCalls = sorted.filter((e) => e.guardrail_mode === "post_call" || e.guardrail_mode === "logging_only");+ const duringCalls = sorted.filter((e) => e.guardrail_mode === "during_call");++ for (const e of preCalls) {+ const offsetMs = Math.round((e.end_time - baseTime) * 1000);+ items.push({+ type: "guardrail",+ label: `Pre-call guardrail: ${getDisplayName(e)}`,+ offsetMs,+ status: isEntrySuccess(e) ? "PASSED" : "FAILED",+ isSuccess: isEntrySuccess(e),+ });+ }++ // LLM call — infer from gap between pre-call end and post-call start+ const lastPreEnd = preCalls.length > 0 ? Math.max(...preCalls.map((e) => e.end_time)) : baseTime;+ const firstPostStart = postCalls.length > 0 ? Math.min(...postCalls.map((e) => e.start_time)) : undefined;+ const llmEndTime = firstPostStart ?? (lastPreEnd + 1);+ const llmOffsetMs = Math.round((llmEndTime - baseTime) * 1000);++ items.push({+ type: "llm",+ label: "LLM call",+ offsetMs: llmOffsetMs,+ });++ // During-call guardrails (rare)+ for (const e of duringCalls) {+ const offsetMs = Math.round((e.end_time - baseTime) * 1000);+ items.push({+ type: "guardrail",+ label: `During-call guardrail: ${getDisplayName(e)}`,+ offsetMs,+ status: isEntrySuccess(e) ? "PASSED" : "FAILED",+ isSuccess: isEntrySuccess(e),+ });+ }++ // Post-call guardrails+ for (const e of postCalls) {+ const offsetMs = Math.round((e.end_time - baseTime) * 1000);+ items.push({+ type: "guardrail",+ label: `Post-call guardrail: ${getDisplayName(e)}`,+ offsetMs,+ status: isEntrySuccess(e) ? "PASSED" : "FAILED",+ isSuccess: isEntrySuccess(e),+ });+ }++ // Response returned+ const maxEnd = Math.max(...sorted.map((e) => e.end_time));+ const responseOffsetMs = Math.round((maxEnd - baseTime) * 1000) + 1;+ items.push({ type: "response", label: "Response returned", offsetMs: responseOffsetMs });++ return items;+ }, [sorted]);return (- <div className="mb-4">- <h5 className="font-medium mb-3">Execution Timeline</h5>- <div className="relative pl-4 border-l-2 border-gray-200 space-y-3">- {sorted.map((e, idx) => {- const isSuccess = (e.guardrail_status ?? "").toLowerCase() === "success";- return (- <div key={idx} className="relative">- <div- className={`absolute -left-[calc(1rem+5px)] w-2.5 h-2.5 rounded-full mt-1.5 ${- isSuccess ? "bg-green-500" : "bg-red-500"- }`}- />+ <div>+ <h4 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-4">+ Request Lifecycle+ </h4>+ <div className="relative">+ {timeline.map((item, idx) => (+ <div key={idx} className="flex items-start gap-3 relative">+ {/* Vertical line */}+ <div className="flex flex-col items-center">+ <div className="flex-shrink-0">+ {item.type === "request" || item.type === "response" ? (+ <GrayDotIcon />+ ) : item.type === "llm" ? (+ <PlayCircleIcon />+ ) : item.isSuccess ? (+ <CheckCircleIcon />+ ) : (+ <FailCircleIcon />+ )}+ </div>+ {idx < timeline.length - 1 && (+ <div className="w-0.5 bg-gray-200 flex-grow" style={{ minHeight: "24px" }} />+ )}+ </div>++ {/* Content */}+ <div className="pb-4 flex-1 min-w-0"><div className="flex items-center gap-2 flex-wrap">- <span className="font-mono text-xs text-gray-500">- {e.duration?.toFixed(3)}s- </span>- <span className="text-sm font-medium">{e.guardrail_name}</span>- <span className="px-1.5 py-0.5 bg-gray-100 text-gray-600 rounded text-xs">- {e.guardrail_mode}- </span>- <span className={`px-1.5 py-0.5 rounded text-xs font-medium ${- isSuccess ? "bg-green-100 text-green-800" : "bg-red-100 text-red-800"- }`}>- {e.guardrail_status}+ <span+ className={`text-sm ${+ item.type === "llm" ? "text-blue-600 font-medium" : "text-gray-900"+ }`}+ >+ {item.label}</span>- {e.policy_template && (- <span className="px-1.5 py-0.5 bg-purple-50 text-purple-700 rounded text-xs">- {e.policy_template}+ {item.status && (+ <span+ className={`px-1.5 py-0.5 rounded text-[10px] font-bold uppercase ${+ item.isSuccess+ ? "bg-green-100 text-green-700"+ : "bg-red-100 text-red-700"+ }`}+ >+ {item.status}</span>)}+ <span className="text-xs text-gray-400 font-mono ml-auto flex-shrink-0">+ T+{item.offsetMs}ms+ </span></div></div>- );- })}+ </div>+ ))}</div></div>);};-const GuardrailDetails = ({ entry, index, total }: GuardrailDetailsProps) => {- const guardrailProvider = entry.guardrail_provider ?? "presidio";- const statusLabel = entry.guardrail_status ?? "unknown";- const isSuccess = statusLabel.toLowerCase() === "success";- const maskedEntityCount = entry.masked_entity_count || {};- const totalMaskedEntities = Object.values(maskedEntityCount).reduce(- (sum, count) => sum + (typeof count === "number" ? count : 0),- 0,- );+// ── Evaluation Card ─────────────────────────────────────────────────────────+const EvaluationCard = ({ entry }: { entry: GuardrailInformation }) => {+ const [expanded, setExpanded] = useState(false);+ const success = isEntrySuccess(entry);+ const totalMasked = getTotalMasked(entry);+ const displayName = getDisplayName(entry);+ const durationStr = formatDurationMs(entry.duration);+ const modeStr = formatMode(entry.guardrail_mode);+ const riskScore = getRiskScore(entry);++ const guardrailProvider = entry.guardrail_provider ?? "presidio";const guardrailResponse = entry.guardrail_response;const presidioEntities = Array.isArray(guardrailResponse) ? guardrailResponse : [];const bedrockResponse =@@ -297,201 +431,287 @@ const GuardrailDetails = ({ entry, index, total }: GuardrailDetailsProps) => {? (guardrailResponse as BedrockGuardrailResponse): undefined;+ // Match count string: "X/Y matched" or "X matched"+ const matchCountStr =+ entry.patterns_checked != null+ ? `${totalMasked}/${entry.patterns_checked} matched`+ : totalMasked > 0+ ? `${totalMasked} matched`+ : null;+return (- <div className="bg-white rounded-lg border border-gray-200 p-4">- {total > 1 && (- <div className="flex items-center justify-between mb-4">- <h4 className="text-base font-semibold">- Guardrail #{index + 1}- <span className="ml-2 font-mono text-sm text-gray-600">{entry.guardrail_name}</span>- </h4>- <span className="px-2 py-0.5 bg-gray-100 text-gray-600 rounded-md text-xs capitalize">- {guardrailProvider}- </span>+ <div className="border border-gray-200 rounded-lg bg-white">+ {/* Collapsed header row */}+ <div+ className="flex items-center gap-3 px-4 py-3 cursor-pointer hover:bg-gray-50 transition-colors"+ onClick={() => setExpanded(!expanded)}+ >+ {/* Status icon */}+ <div className="flex-shrink-0">+ {success ? <CheckCircleIcon /> : <FailCircleIcon />}</div>- )}- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">- <div className="space-y-2">- <div className="flex">- <span className="font-medium w-1/3">Guardrail Name:</span>- <span className="font-mono break-words">{entry.guardrail_name}</span>- </div>- {entry.guardrail_id && entry.guardrail_id !== entry.guardrail_name && (- <div className="flex">- <span className="font-medium w-1/3">Guardrail ID:</span>- <span className="font-mono break-words text-gray-600">{entry.guardrail_id}</span>- </div>+ {/* Name + badges */}+ <div className="flex items-center gap-2 flex-wrap flex-1 min-w-0">+ <span className="font-semibold text-gray-900 text-sm truncate">{displayName}</span>++ <span className="px-2 py-0.5 border border-blue-200 bg-blue-50 text-blue-700 rounded text-[11px] font-semibold uppercase flex-shrink-0">+ {modeStr}+ </span>++ <span+ className={`px-2 py-0.5 rounded text-[11px] font-semibold uppercase flex-shrink-0 ${+ success ? "bg-green-100 text-green-700 border border-green-200" : "bg-red-100 text-red-700 border border-red-200"+ }`}+ >+ {success ? "PASSED" : "FAILED"}+ </span>++ {matchCountStr && (+ <span+ className={`px-2 py-0.5 rounded text-[11px] font-medium flex-shrink-0 ${+ totalMasked === 0 ? "bg-green-50 text-green-700 border border-green-200" : "bg-amber-50 text-amber-700 border border-amber-200"+ }`}+ >+ {matchCountStr}+ </span>)}- <div className="flex">- <span className="font-medium w-1/3">Mode:</span>- <span className="font-mono break-words">{entry.guardrail_mode}</span>- </div>- <div className="flex">- <span className="font-medium w-1/3">Status:</span>- <Tooltip title={isSuccess ? null : "Guardrail failed to run."} placement="top" arrow destroyTooltipOnHide>- <span- className={`px-2 py-1 rounded-md text-xs font-medium inline-block ${- isSuccess ? "bg-green-100 text-green-800" : "bg-red-100 text-red-800 cursor-help"- }`}- >- {statusLabel}++ {entry.confidence_score != null && (+ <span className="px-2 py-0.5 bg-gray-100 text-gray-600 border border-gray-200 rounded text-[11px] font-medium flex-shrink-0">+ {(entry.confidence_score * 100).toFixed(0)}% conf+ </span>+ )}++ {riskScore != null && success && (+ <Tooltip title={`Risk score: ${riskScore}/10`}>+ <span className={`px-2 py-0.5 border rounded text-[11px] font-semibold flex-shrink-0 ${getRiskColor(riskScore)}`}>+ Risk {riskScore}/10</span></Tooltip>- </div>+ )}</div>- <div className="space-y-2">- <div className="flex">- <span className="font-medium w-1/3">Start Time:</span>- <span>{formatTime(entry.start_time)}</span>- </div>- <div className="flex">- <span className="font-medium w-1/3">End Time:</span>- <span>{formatTime(entry.end_time)}</span>- </div>- <div className="flex">- <span className="font-medium w-1/3">Duration:</span>- <span>{entry.duration.toFixed(4)}s</span>- </div>+ {/* Right side: duration + method + chevron */}+ <div className="flex items-center gap-3 flex-shrink-0">+ <span className="text-sm text-gray-500 font-mono">{durationStr}</span>+ {entry.detection_method && (+ <span className="px-2 py-0.5 bg-gray-100 text-gray-600 border border-gray-200 rounded text-[11px] font-medium">+ {entry.detection_method.split(",")[0].trim()}+ </span>+ )}+ <ChevronIcon expanded={expanded} /></div></div>- {/* Policy, detection method, confidence, patterns checked */}- <PolicyDetectionRow entry={entry} />-- {/* Classification details (LLM-judge) */}- {entry.classification && <ClassificationDetails classification={entry.classification} />}-- {/* Match details table */}- {entry.match_details && entry.match_details.length > 0 && (- <MatchDetailsTable matchDetails={entry.match_details} />- )}+ {/* Expanded details */}+ {expanded && (+ <div className="border-t border-gray-100 px-4 py-3">+ {/* View Policy Configuration link */}+ {entry.policy_template && (+ <div className="flex justify-end mb-3">+ <a+ href="/ui/policies"+ target="_blank"+ rel="noopener noreferrer"+ className="text-sm text-blue-600 hover:text-blue-800 font-medium"+ >+ View Policy Configuration+ <ExternalLinkIcon />+ </a>+ </div>+ )}- {totalMaskedEntities > 0 && (- <div className="mt-4 pt-4 border-t">- <h5 className="font-medium mb-2">Masked Entity Summary</h5>- <div className="flex flex-wrap gap-2">- {Object.entries(maskedEntityCount).map(([entityType, count]) => (- <span key={entityType} className="px-3 py-1.5 bg-blue-50 text-blue-700 rounded-md text-xs font-medium">- {entityType}: {count}- </span>- ))}- </div>- </div>- )}+ {/* Classification details for llm-judge */}+ {entry.classification && (+ <div className="mb-3 bg-gray-50 rounded-lg p-3 space-y-1">+ <h5 className="text-sm font-medium text-gray-700 mb-2">Classification</h5>+ {entry.classification.category && (+ <div className="flex text-sm">+ <span className="font-medium w-1/3 text-gray-500">Category:</span>+ <span>{entry.classification.category}</span>+ </div>+ )}+ {entry.classification.article_reference && (+ <div className="flex text-sm">+ <span className="font-medium w-1/3 text-gray-500">Reference:</span>+ <span className="font-mono">{entry.classification.article_reference}</span>+ </div>+ )}+ {entry.classification.confidence != null && (+ <div className="flex text-sm">+ <span className="font-medium w-1/3 text-gray-500">Confidence:</span>+ <span>{(entry.classification.confidence * 100).toFixed(0)}%</span>+ </div>+ )}+ {entry.classification.reason && (+ <div className="flex text-sm">+ <span className="font-medium w-1/3 text-gray-500">Reason:</span>+ <span>{entry.classification.reason}</span>+ </div>+ )}+ </div>+ )}- {guardrailProvider === "presidio" && presidioEntities.length > 0 && (- <div className="mt-4">- <PresidioDetectedEntities entities={presidioEntities} />- </div>- )}+ {/* Match details table */}+ {entry.match_details && entry.match_details.length > 0 && (+ <MatchDetailsTable matchDetails={entry.match_details} />+ )}- {guardrailProvider === "bedrock" && bedrockResponse && (- <div className="mt-4">- <BedrockGuardrailDetails response={bedrockResponse} />- </div>- )}+ {/* Masked entity summary */}+ {totalMasked > 0 && (+ <div className="mt-3">+ <h5 className="text-sm font-medium text-gray-700 mb-2">Masked Entities</h5>+ <div className="flex flex-wrap gap-2">+ {Object.entries(entry.masked_entity_count || {}).map(([entityType, count]) => (+ <span key={entityType} className="px-2 py-1 bg-blue-50 text-blue-700 rounded text-xs font-medium">+ {entityType}: {count}+ </span>+ ))}+ </div>+ </div>+ )}- {guardrailProvider === "litellm_content_filter" && guardrailResponse && (- <div className="mt-4">- <ContentFilterDetails response={guardrailResponse} />+ {/* Provider-specific details */}+ {guardrailProvider === "presidio" && presidioEntities.length > 0 && (+ <div className="mt-3">+ <PresidioDetectedEntities entities={presidioEntities} />+ </div>+ )}+ {guardrailProvider === "bedrock" && bedrockResponse && (+ <div className="mt-3">+ <BedrockGuardrailDetails response={bedrockResponse} />+ </div>+ )}+ {guardrailProvider === "litellm_content_filter" && guardrailResponse && (+ <div className="mt-3">+ <ContentFilterDetails response={guardrailResponse} />+ </div>+ )}+ {guardrailProvider &&+ !PROVIDERS_WITH_CUSTOM_RENDERERS.has(guardrailProvider) &&+ guardrailResponse && <GenericGuardrailResponse response={guardrailResponse} />}</div>)}-- {/* Generic fallback for unknown guardrail providers */}- {guardrailProvider &&- !PROVIDERS_WITH_CUSTOM_RENDERERS.has(guardrailProvider) &&- guardrailResponse && <GenericGuardrailResponse response={guardrailResponse} />}</div>);};+// ── Main Component ──────────────────────────────────────────────────────────+const GuardrailViewer = ({ data }: GuardrailViewerProps) => {- const guardrailEntries = Array.isArray(data)- ? data.filter((entry): entry is GuardrailInformation => Boolean(entry))- : data- ? [data]- : [];-- const primaryName =- guardrailEntries.length === 1 ? guardrailEntries[0].guardrail_name : `${guardrailEntries.length} guardrails`;- const statuses = Array.from(new Set(guardrailEntries.map((entry) => entry.guardrail_status)));- const allSucceeded = statuses.every((status) => (status ?? "").toLowerCase() === "success");- const aggregatedStatus = allSucceeded ? "success" : "failure";- const totalMaskedEntities = guardrailEntries.reduce((sum, entry) => {- return (- sum +- Object.values(entry.masked_entity_count || {}).reduce(- (acc, count) => acc + (typeof count === "number" ? count : 0),- 0,- )- );- }, 0);-- const policyTemplates = Array.from(- new Set(guardrailEntries.map((e) => e.policy_template).filter(Boolean))- );+ const guardrailEntries = useMemo(() => {+ return Array.isArray(data)+ ? data.filter((entry): entry is GuardrailInformation => Boolean(entry))+ : data+ ? [data]+ : [];+ }, [data]);++ const passedCount = guardrailEntries.filter(isEntrySuccess).length;+ const allPassed = passedCount === guardrailEntries.length;++ const totalOverheadMs = useMemo(() => {+ return Math.round(guardrailEntries.reduce((sum, e) => sum + (e.duration ?? 0), 0) * 1000);+ }, [guardrailEntries]);- const tooltipTitle = allSucceeded ? null : "Guardrail failed to run.";+ const policyTemplates = useMemo(() => {+ return Array.from(new Set(guardrailEntries.map((e) => e.policy_template).filter(Boolean)));+ }, [guardrailEntries]);if (guardrailEntries.length === 0) {return null;}+ const handleExport = () => {+ const blob = new Blob([JSON.stringify(guardrailEntries, null, 2)], {+ type: "application/json",+ });+ const url = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = url;+ a.download = `guardrail-compliance-log-${new Date().toISOString().slice(0, 10)}.json`;+ a.click();+ URL.revokeObjectURL(url);+ };+return (- <div className="bg-white rounded-lg shadow w-full max-w-full overflow-hidden mb-6">- <Collapse- defaultActiveKey={["1"]}- expandIconPosition="start"- items={[- {- key: "1",- label: (- <div className="flex items-center gap-2 flex-wrap">- <h3 className="text-lg font-medium text-gray-900">Guardrail Information</h3>+ <div className="bg-white rounded-xl border border-gray-200 shadow-sm w-full max-w-full overflow-hidden mb-6">+ {/* ── Header ─────────────────────────────────────────────── */}+ <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100">+ <div className="flex items-center gap-4">+ <ShieldIcon />+ <div>+ <h3 className="text-lg font-semibold text-gray-900">+ Guardrails & Policy Compliance+ </h3>+ <div className="flex items-center gap-2 mt-0.5">+ <span className="text-sm text-gray-500">+ {guardrailEntries.length} guardrail{guardrailEntries.length !== 1 ? "s" : ""} evaluated+ </span>+ <span className="text-gray-300">|</span>+ <span+ className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold ${+ allPassed+ ? "bg-green-50 text-green-700 border border-green-200"+ : "bg-red-50 text-red-700 border border-red-200"+ }`}+ >+ {allPassed ? (+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none">+ <path d="M3 6l2.5 2.5L9 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />+ </svg>+ ) : null}+ {passedCount} Passed+ </span>+ </div>+ </div>+ </div>- <Tooltip title={tooltipTitle} placement="top" arrow destroyTooltipOnHide>- <span- className={`px-2 py-1 rounded-md text-xs font-medium inline-block ${- allSucceeded ? "bg-green-100 text-green-800" : "bg-red-100 text-red-800 cursor-help"- }`}- >- {aggregatedStatus}- </span>- </Tooltip>+ <div className="flex items-center gap-6">+ <div className="text-right">+ <div className="text-sm font-medium text-gray-900">+ Total: {totalOverheadMs}ms overhead+ </div>+ {policyTemplates.length > 0 && (+ <div className="text-xs text-gray-500 mt-0.5">+ Policy: {policyTemplates.join(" / ")}+ </div>+ )}+ </div>- <span className="font-mono text-sm text-gray-600">{primaryName}</span>+ <button+ onClick={handleExport}+ className="inline-flex items-center gap-2 px-4 py-2 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 transition-colors"+ >+ <DownloadIcon />+ Export Compliance Log+ </button>+ </div>+ </div>- {totalMaskedEntities > 0 && (- <span className="px-2 py-1 bg-blue-50 text-blue-700 rounded-md text-xs font-medium">- {totalMaskedEntities} masked {totalMaskedEntities === 1 ? "entity" : "entities"}- </span>- )}+ {/* ── Body: two columns ──────────────────────────────────── */}+ <div className="flex">+ {/* Left column: Request Lifecycle */}+ <div className="w-[340px] flex-shrink-0 border-r border-gray-100 px-6 py-5">+ <RequestLifecycle entries={guardrailEntries} />+ </div>- {policyTemplates.map((pt) => (- <span key={pt} className="px-2 py-1 bg-purple-50 text-purple-700 rounded-md text-xs font-medium">- {pt}- </span>- ))}- </div>- ),- children: (- <div className="p-4 space-y-6">- <ExecutionTimeline entries={guardrailEntries} />- {guardrailEntries.map((entry, index) => (- <GuardrailDetails- key={`${entry.guardrail_name ?? "guardrail"}-${index}`}- entry={entry}- index={index}- total={guardrailEntries.length}- />- ))}- </div>- ),- },- ]}- />+ {/* Right column: Evaluation Details */}+ <div className="flex-1 px-6 py-5 min-w-0">+ <h4 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-4">+ Evaluation Details+ </h4>+ <div className="space-y-3">+ {guardrailEntries.map((entry, index) => (+ <EvaluationCard+ key={`${entry.guardrail_name ?? "guardrail"}-${index}`}+ entry={entry}+ />+ ))}+ </div>+ </div>+ </div></div>);};diff --git a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsxindex 9081219d5be..f0f4041531c 100644--- a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx@@ -66,6 +66,9 @@ export function LogDetailContent({ logEntry, onOpenSettings, isLoadingDetails =const hasGuardrailData = guardrailEntries.length > 0;const totalMaskedEntities = calculateTotalMaskedEntities(guardrailEntries);const primaryGuardrailLabel = getGuardrailLabel(guardrailEntries);+ const guardrailPolicyNames = Array.from(+ new Set(guardrailEntries.map((e: any) => e?.policy_template).filter(Boolean))+ ) as string[];// Vector store dataconst hasVectorStoreData = checkHasVectorStoreData(metadata);@@ -124,7 +127,7 @@ export function LogDetailContent({ logEntry, onOpenSettings, isLoadingDetails =)}{hasGuardrailData && (<Descriptions.Item label="Guardrail">- <GuardrailLabel label={primaryGuardrailLabel} maskedCount={totalMaskedEntities} />+ <GuardrailLabel label={primaryGuardrailLabel} maskedCount={totalMaskedEntities} policyNames={guardrailPolicyNames} /></Descriptions.Item>)}</Descriptions>@@ -164,7 +167,11 @@ export function LogDetailContent({ logEntry, onOpenSettings, isLoadingDetails =)}{/* Guardrail Data */}- {hasGuardrailData && <GuardrailViewer data={guardrailInfo} />}+ {hasGuardrailData && (+ <div id="guardrail-section">+ <GuardrailViewer data={guardrailInfo} />+ </div>+ )}{/* Vector Store Data */}{hasVectorStoreData && <VectorStoreViewer data={metadata.vector_store_request_metadata} />}@@ -218,15 +225,23 @@ function TagsSection({ tags }: { tags: Record<string, any> }) {);}-function GuardrailLabel({ label, maskedCount }: { label: string; maskedCount: number }) {+function GuardrailLabel({ label, maskedCount, policyNames }: { label: string; maskedCount: number; policyNames: string[] }) {+ const handleClick = () => {+ const el = document.getElementById("guardrail-section");+ if (el) el.scrollIntoView({ behavior: "smooth" });+ };+return (<Space size={SPACING_MEDIUM}>- <span>{label}</span>+ <a onClick={handleClick} style={{ cursor: "pointer" }}>{label}</a>{maskedCount > 0 && (<Tag color="blue">{maskedCount} masked</Tag>)}+ {policyNames.map((name) => (+ <Tag key={name} color="purple">{name}</Tag>+ ))}</Space>);}