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
prelim changes for new Bedrock guardrail info view
=78cb8c71fda0
diff --git a/litellm/integrations/custom_guardrail.py b/litellm/integrations/custom_guardrail.pyindex e4d16160357..6b77557cd3d 100644--- a/litellm/integrations/custom_guardrail.py+++ b/litellm/integrations/custom_guardrail.py@@ -357,6 +357,7 @@ class CustomGuardrail(CustomLogger):end_time: Optional[float] = None,duration: Optional[float] = None,masked_entity_count: Optional[Dict[str, int]] = None,+ guardrail_provider: Optional[str] = None,) -> None:"""Builds `StandardLoggingGuardrailInformation` and adds it to the request metadata so it can be used for logging to DataDog, Langfuse, etc.@@ -367,6 +368,7 @@ class CustomGuardrail(CustomLogger):slg = StandardLoggingGuardrailInformation(guardrail_name=self.guardrail_name,+ guardrail_provider=guardrail_provider,guardrail_mode=(GuardrailMode(**self.event_hook.model_dump()) # type: ignoreif isinstance(self.event_hook, Mode)diff --git a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.pyindex dfb01a7cd0c..6dfde92e5c9 100644--- a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py+++ b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py@@ -111,6 +111,7 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):)self.guardrailIdentifier = guardrailIdentifierself.guardrailVersion = guardrailVersion+ self.guardrail_provider = "bedrock"# store kwargs as optional_paramsself.optional_params = kwargs@@ -372,6 +373,7 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):# Add guardrail information to request trace#########################################################self.add_standard_logging_guardrail_information_to_request_data(+ guardrail_provider=self.guardrail_provider,guardrail_json_response=response.json(),request_data=request_data or {},guardrail_status=self._get_bedrock_guardrail_response_status(diff --git a/litellm/proxy/guardrails/guardrail_hooks/presidio.py b/litellm/proxy/guardrails/guardrail_hooks/presidio.pyindex 3e40f33d167..8dbcf77a844 100644--- a/litellm/proxy/guardrails/guardrail_hooks/presidio.py+++ b/litellm/proxy/guardrails/guardrail_hooks/presidio.py@@ -76,6 +76,7 @@ class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):self.logging_only = Truekwargs["event_hook"] = GuardrailEventHooks.logging_onlysuper().__init__(**kwargs)+ self.guardrail_provider = "presidio"self.pii_tokens: dict = ({}) # mapping of PII token to original text - only used with Presidio `replace` operation@@ -369,6 +370,7 @@ class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):else:guardrail_json_response = exception_strself.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,diff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex fbf2bad98ba..a240b674580 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -2015,6 +2015,7 @@ class GuardrailMode(TypedDict, total=False):class StandardLoggingGuardrailInformation(TypedDict, total=False):guardrail_name: Optional[str]+ guardrail_provider: Optional[str]guardrail_mode: Optional[Union[GuardrailEventHooks, List[GuardrailEventHooks], GuardrailMode]]diff --git a/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer.tsx b/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer.tsxdeleted file mode 100644index a2909e28d4d..00000000000--- a/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer.tsx+++ /dev/null@@ -1,257 +0,0 @@-import React, { useState } from "react";--interface RecognitionMetadata {- recognizer_name: string;- recognizer_identifier: string;-}--interface GuardrailEntity {- end: number;- score: number;- start: number;- entity_type: string;- analysis_explanation: string | null;- recognition_metadata: RecognitionMetadata;-}--interface MaskedEntityCount {- [key: string]: number;-}--interface GuardrailInformation {- duration: number;- end_time: number;- start_time: number;- guardrail_mode: string;- guardrail_name: string;- guardrail_status: string;- guardrail_response: GuardrailEntity[];- masked_entity_count: MaskedEntityCount;-}--interface GuardrailViewerProps {- data: GuardrailInformation;-}--export function GuardrailViewer({ data }: GuardrailViewerProps) {- const [sectionExpanded, setSectionExpanded] = useState(true);- const [entityListExpanded, setEntityListExpanded] = useState(true);- const [expandedEntities, setExpandedEntities] = useState<Record<number, boolean>>({});-- if (!data) {- return null;- }-- // Calculate total masked entities- const totalMaskedEntities = data.masked_entity_count ?- Object.values(data.masked_entity_count).reduce((sum, count) => sum + count, 0) : 0;-- const formatTime = (timestamp: number): string => {- const date = new Date(timestamp * 1000);- return date.toLocaleString();- };-- const toggleEntity = (index: number) => {- setExpandedEntities(prev => ({- ...prev,- [index]: !prev[index]- }));- };-- const getScoreColor = (score: number): string => {- if (score >= 0.8) return "text-green-600";- return "text-yellow-600";- };-- return (- <div className="bg-white rounded-lg shadow mb-6">- <div- className="flex justify-between items-center p-4 border-b cursor-pointer hover:bg-gray-50"- onClick={() => setSectionExpanded(!sectionExpanded)}- >- <div className="flex items-center">- <svg- className={`w-5 h-5 mr-2 text-gray-600 transition-transform ${sectionExpanded ? '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>- <h3 className="text-lg font-medium">Guardrail Information</h3>- <span className={`ml-3 px-2 py-1 rounded-md text-xs font-medium inline-block ${- data.guardrail_status === "success"- ? 'bg-green-100 text-green-800'- : 'bg-red-100 text-red-800'- }`}>- {data.guardrail_status}- </span>- {totalMaskedEntities > 0 && (- <span className="ml-3 px-2 py-1 bg-blue-50 text-blue-700 rounded-md text-xs font-medium">- {totalMaskedEntities} masked {totalMaskedEntities === 1 ? 'entity' : 'entities'}- </span>- )}- </div>- <span className="text-sm text-gray-500">{sectionExpanded ? 'Click to collapse' : 'Click to expand'}</span>- </div>-- {sectionExpanded && (- <div className="p-4">- <div className="bg-white rounded-lg border p-4 mb-4">- <div className="grid 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">{data.guardrail_name}</span>- </div>- <div className="flex">- <span className="font-medium w-1/3">Mode:</span>- <span className="font-mono">{data.guardrail_mode}</span>- </div>- <div className="flex">- <span className="font-medium w-1/3">Status:</span>- <span className={`px-2 py-1 rounded-md text-xs font-medium inline-block ${- data.guardrail_status === "success"- ? 'bg-green-100 text-green-800'- : 'bg-red-100 text-red-800'- }`}>- {data.guardrail_status}- </span>- </div>- </div>- <div className="space-y-2">- <div className="flex">- <span className="font-medium w-1/3">Start Time:</span>- <span>{formatTime(data.start_time)}</span>- </div>- <div className="flex">- <span className="font-medium w-1/3">End Time:</span>- <span>{formatTime(data.end_time)}</span>- </div>- <div className="flex">- <span className="font-medium w-1/3">Duration:</span>- <span>{data.duration.toFixed(4)}s</span>- </div>- </div>- </div>-- {/* Masked Entity Summary */}- {data.masked_entity_count && Object.keys(data.masked_entity_count).length > 0 && (- <div className="mt-4 pt-4 border-t">- <h4 className="font-medium mb-2">Masked Entity Summary</h4>- <div className="flex flex-wrap gap-2">- {Object.entries(data.masked_entity_count).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>- )}- </div>-- {/* Detected Entities Section */}- {data.guardrail_response && data.guardrail_response.length > 0 && (- <div className="mt-4">- <div- className="flex items-center mb-2 cursor-pointer"- onClick={() => setEntityListExpanded(!entityListExpanded)}- >- <svg- className={`w-5 h-5 mr-2 transition-transform ${entityListExpanded ? '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>- <h4 className="font-medium">Detected Entities ({data.guardrail_response.length})</h4>- </div>-- {entityListExpanded && (- <div className="space-y-2">- {data.guardrail_response.map((entity, index) => {- const isExpanded = expandedEntities[index] || false;-- return (- <div key={index} 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={() => toggleEntity(index)}- >- <div className="flex items-center">- <svg- className={`w-5 h-5 mr-2 transition-transform ${isExpanded ? '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>- <span className="font-medium mr-2">{entity.entity_type}</span>- <span className={`font-mono ${getScoreColor(entity.score)}`}>- Score: {entity.score.toFixed(2)}- </span>- </div>- <span className="text-xs text-gray-500">- Position: {entity.start}-{entity.end}- </span>- </div>-- {isExpanded && (- <div className="p-3 border-t bg-white">- <div className="grid grid-cols-2 gap-4 mb-2">- <div className="space-y-2">- <div className="flex">- <span className="font-medium w-1/3">Entity Type:</span>- <span>{entity.entity_type}</span>- </div>- <div className="flex">- <span className="font-medium w-1/3">Position:</span>- <span>Characters {entity.start}-{entity.end}</span>- </div>- <div className="flex">- <span className="font-medium w-1/3">Confidence:</span>- <span className={getScoreColor(entity.score)}>- {entity.score.toFixed(2)}- </span>- </div>- </div>-- <div className="space-y-2">- {entity.recognition_metadata && (- <>- <div className="flex">- <span className="font-medium w-1/3">Recognizer:</span>- <span>{entity.recognition_metadata.recognizer_name}</span>- </div>- <div className="flex overflow-hidden">- <span className="font-medium w-1/3">Identifier:</span>- <span className="truncate text-xs font-mono">- {entity.recognition_metadata.recognizer_identifier}- </span>- </div>- </>- )}- {entity.analysis_explanation && (- <div className="flex">- <span className="font-medium w-1/3">Explanation:</span>- <span>{entity.analysis_explanation}</span>- </div>- )}- </div>- </div>- </div>- )}- </div>- );- })}- </div>- )}- </div>- )}- </div>- )}- </div>- );-}\ No newline at end of filediff --git a/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/BedrockGuardrailDetails.tsx b/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/BedrockGuardrailDetails.tsxnew file mode 100644index 00000000000..e7b041b93b4--- /dev/null+++ b/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/BedrockGuardrailDetails.tsx@@ -0,0 +1,508 @@+import React, { useState } from "react";++export type BedrockGuardrailAction = "NONE" | "GUARDRAIL_INTERVENED";++export interface BedrockGuardrailUsage {+ wordPolicyUnits?: number;+ topicPolicyUnits?: number;+ contentPolicyUnits?: number;+ contentPolicyImageUnits?: number;+ automatedReasoningPolicies?: number;+ automatedReasoningPolicyUnits?: number;+ contextualGroundingPolicyUnits?: number;+ sensitiveInformationPolicyUnits?: number;+ sensitiveInformationPolicyFreeUnits?: number;+}++export interface BedrockGuardrailCoverageDim {+ total?: number;+ guarded?: number;+}++export interface BedrockGuardrailCoverage {+ images?: BedrockGuardrailCoverageDim;+ textCharacters?: BedrockGuardrailCoverageDim;+}++export interface BedrockWordItem {+ action?: string; // e.g., "BLOCKED" or "ALLOWED"+ detected?: boolean;+ match?: string;+ type?: string; // present on managedWordLists entries+}++export interface BedrockContentFilter {+ type?: string; // e.g. "HATE", etc.+ action?: string; // "BLOCKED" | "NONE" (varies by config)+ detected?: boolean;+ filterStrength?: string; // e.g., "HIGH"/"MEDIUM"/"LOW"+ confidence?: string; // e.g., "HIGH"/"MEDIUM"/"LOW"+}++export interface BedrockContextualGroundingFilter {+ type?: string; // "GROUNDING" | "RELEVANCE"+ action?: string; // "BLOCKED" | ...+ detected?: boolean;+ score?: number; // model score+ threshold?: number; // configured threshold+}++export interface BedrockPiiEntity {+ type?: string; // e.g., "ADDRESS", "EMAIL", etc.+ match?: string; // the matched text (may be masked)+ detected?: boolean;+ action?: string; // "BLOCKED" | "ANONYMIZED" | ...+}++export interface BedrockRegexFinding {+ name?: string;+ regex?: string;+ match?: string;+ detected?: boolean;+ action?: string;+}++export interface BedrockTopic {+ name?: string; // topic list entry name+ type?: string; // "DENY" | "ALLOW" depending on list+ detected?: boolean;+ action?: string; // "BLOCKED" | "NONE"+}++export interface BedrockInvocationMetrics {+ usage?: BedrockGuardrailUsage;+ guardrailCoverage?: BedrockGuardrailCoverage;+ guardrailProcessingLatency?: number; // in ms+}++export interface BedrockAssessment {+ wordPolicy?: { customWords?: BedrockWordItem[]; managedWordLists?: BedrockWordItem[] };+ contentPolicy?: { filters?: BedrockContentFilter[] };+ topicPolicy?: { topics?: BedrockTopic[] };+ sensitiveInformationPolicy?: { piiEntities?: BedrockPiiEntity[]; regexes?: BedrockRegexFinding[] };+ contextualGroundingPolicy?: { filters?: BedrockContextualGroundingFilter[] };+ automatedReasoningPolicy?: { findings?: any[] };+ invocationMetrics?: BedrockInvocationMetrics;+}++export interface BedrockOutputContent {+ text?: string;+}++export interface BedrockGuardrailResponse {+ action?: BedrockGuardrailAction;+ actionReason?: string | null;+ outputs?: BedrockOutputContent[];+ output?: BedrockOutputContent[];+ usage?: BedrockGuardrailUsage;+ guardrailCoverage?: BedrockGuardrailCoverage;+ assessments?: BedrockAssessment[];+ blockedResponse?: string;+}++/** ====== UI helpers ====== */+type ChipTone = "green" | "red" | "blue" | "slate" | "amber";++const chip = (+ text: React.ReactNode,+ tone: ChipTone = "slate"+) => {+ const map: Record<ChipTone, 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>;+};++const boolPill = (b?: boolean) => (b ? chip("detected", "red") : chip("not detected", "slate"));++interface SectionProps {+ title: string;+ count?: number;+ defaultOpen?: boolean;+ right?: React.ReactNode;+ children?: React.ReactNode;+}++const Section: React.FC<SectionProps> = ({+ title,+ count,+ defaultOpen = true,+ right,+ 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>{right}</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 Divider: React.FC = () => <div className="my-3 border-t" />;++/** ====== Main component ====== */+export const BedrockGuardrailDetails: React.FC<{ response: BedrockGuardrailResponse }> = ({ response }) => {++ if (!response) return null;++ const outputs: BedrockOutputContent[] = (response.outputs ?? response.output ?? []) as BedrockOutputContent[];++ const actionTone: "green" | "red" = response.action === "GUARDRAIL_INTERVENED" ? "red" : "green";++ const coverageChips = (+ <div className="flex flex-wrap gap-2">+ {response.guardrailCoverage?.textCharacters && (+ chip(+ `text guarded ${response.guardrailCoverage.textCharacters.guarded ?? 0}/${response.guardrailCoverage.textCharacters.total ?? 0}`,+ "blue"+ )+ )}+ {response.guardrailCoverage?.images && (+ chip(+ `images guarded ${response.guardrailCoverage.images.guarded ?? 0}/${response.guardrailCoverage.images.total ?? 0}`,+ "blue"+ )+ )}+ </div>+ );++ const usagePills = response.usage && (+ <div className="flex flex-wrap gap-2">+ {Object.entries(response.usage).map(([k, v]) =>+ typeof v === "number" ? (+ <span key={k} className="px-2 py-1 bg-slate-100 text-slate-800 rounded-md text-xs font-medium">+ {k}: {v}+ </span>+ ) : null+ )}+ </div>+ );++ return (+ <div className="space-y-3">+ {/* Top summary card */}+ <div className="border rounded-lg p-4">+ <div className="grid grid-cols-2 gap-4">+ <div className="space-y-2">+ <KV label="Action:">+ {chip(response.action ?? "N/A", actionTone)}+ </KV>+ {response.actionReason && <KV label="Action Reason:">{response.actionReason}</KV>}+ {response.blockedResponse && (+ <KV label="Blocked Response:">+ <span className="italic">{response.blockedResponse}</span>+ </KV>+ )}+ </div>+ <div className="space-y-2">+ <KV label="Coverage:">{coverageChips}</KV>+ <KV label="Usage:">{usagePills}</KV>+ </div>+ </div>++ {/* Outputs */}+ {outputs.length > 0 && (+ <>+ <Divider />+ <h4 className="font-medium mb-2">Outputs</h4>+ <div className="space-y-2">+ {outputs.map((o, i) => (+ <div key={i} className="p-3 bg-gray-50 rounded-md">+ <div className="text-sm whitespace-pre-wrap">{o.text ?? <em>(non-text output)</em>}</div>+ </div>+ ))}+ </div>+ </>+ )}+ </div>++ {/* Assessments */}+ {response.assessments?.length ? (+ <div className="space-y-3">+ {response.assessments.map((assess, idx) => {+ const policyBadges = (+ <div className="flex flex-wrap gap-1">+ {assess.wordPolicy && chip("word", "slate")}+ {assess.contentPolicy && chip("content", "slate")}+ {assess.topicPolicy && chip("topic", "slate")}+ {assess.sensitiveInformationPolicy && chip("sensitive-info", "slate")}+ {assess.contextualGroundingPolicy && chip("contextual-grounding", "slate")}+ {assess.automatedReasoningPolicy && chip("automated-reasoning", "slate")}+ </div>+ );++ return (+ <Section+ key={idx}+ title={`Assessment #${idx + 1}`}+ defaultOpen+ right={+ <div className="flex items-center gap-3">+ {assess.invocationMetrics?.guardrailProcessingLatency != null &&+ chip(`${assess.invocationMetrics.guardrailProcessingLatency} ms`, "amber")}+ {policyBadges}+ </div>+ }+ >+ {/* Word policy */}+ {assess.wordPolicy && (+ <div className="mb-3">+ <h6 className="font-medium mb-2">Word Policy</h6>+ {(assess.wordPolicy.customWords?.length ?? 0) > 0 && (+ <Section title="Custom Words" defaultOpen>+ <div className="space-y-2">+ {assess.wordPolicy.customWords!.map((w, i) => (+ <div key={i} className="flex justify-between items-center p-2 bg-gray-50 rounded">+ <div className="flex items-center gap-2">+ {chip(w.action ?? "N/A", w.detected ? "red" : "slate")}+ <span className="font-mono text-sm break-all">{w.match}</span>+ </div>+ {boolPill(w.detected)}+ </div>+ ))}+ </div>+ </Section>+ )}+ {(assess.wordPolicy.managedWordLists?.length ?? 0) > 0 && (+ <Section title="Managed Word Lists" defaultOpen={false}>+ <div className="space-y-2">+ {assess.wordPolicy.managedWordLists!.map((w, i) => (+ <div key={i} className="flex justify-between items-center p-2 bg-gray-50 rounded">+ <div className="flex items-center gap-2">+ {chip(w.action ?? "N/A", w.detected ? "red" : "slate")}+ <span className="font-mono text-sm break-all">{w.match}</span>+ {w.type && chip(w.type, "slate")}+ </div>+ {boolPill(w.detected)}+ </div>+ ))}+ </div>+ </Section>+ )}+ </div>+ )}++ {/* Content policy */}+ {assess.contentPolicy?.filters?.length ? (+ <div className="mb-3">+ <h6 className="font-medium mb-2">Content Policy</h6>+ <div className="overflow-x-auto">+ <table className="min-w-full text-sm">+ <thead>+ <tr className="text-left text-gray-600">+ <th className="py-1 pr-4">Type</th>+ <th className="py-1 pr-4">Action</th>+ <th className="py-1 pr-4">Detected</th>+ <th className="py-1 pr-4">Strength</th>+ <th className="py-1 pr-4">Confidence</th>+ </tr>+ </thead>+ <tbody>+ {assess.contentPolicy.filters!.map((f, i) => (+ <tr key={i} className="border-t">+ <td className="py-1 pr-4">{f.type ?? "—"}</td>+ <td className="py-1 pr-4">{chip(f.action ?? "—", f.detected ? "red" : "slate")}</td>+ <td className="py-1 pr-4">{boolPill(f.detected)}</td>+ <td className="py-1 pr-4">{f.filterStrength ?? "—"}</td>+ <td className="py-1 pr-4">{f.confidence ?? "—"}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ ) : null}++ {/* Contextual grounding */}+ {assess.contextualGroundingPolicy?.filters?.length ? (+ <div className="mb-3">+ <h6 className="font-medium mb-2">Contextual Grounding</h6>+ <div className="overflow-x-auto">+ <table className="min-w-full text-sm">+ <thead>+ <tr className="text-left text-gray-600">+ <th className="py-1 pr-4">Type</th>+ <th className="py-1 pr-4">Action</th>+ <th className="py-1 pr-4">Detected</th>+ <th className="py-1 pr-4">Score</th>+ <th className="py-1 pr-4">Threshold</th>+ </tr>+ </thead>+ <tbody>+ {assess.contextualGroundingPolicy.filters!.map((f, i) => (+ <tr key={i} className="border-t">+ <td className="py-1 pr-4">{f.type ?? "—"}</td>+ <td className="py-1 pr-4">{chip(f.action ?? "—", f.detected ? "red" : "slate")}</td>+ <td className="py-1 pr-4">{boolPill(f.detected)}</td>+ <td className="py-1 pr-4">{f.score ?? "—"}</td>+ <td className="py-1 pr-4">{f.threshold ?? "—"}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ ) : null}++ {/* Sensitive Information */}+ {assess.sensitiveInformationPolicy && (+ <div className="mb-3">+ <h6 className="font-medium mb-2">Sensitive Information</h6>+ {(assess.sensitiveInformationPolicy.piiEntities?.length ?? 0) > 0 && (+ <Section title="PII Entities" defaultOpen>+ <div className="space-y-2">+ {assess.sensitiveInformationPolicy.piiEntities!.map((p, i) => (+ <div key={i} className="flex justify-between items-center p-2 bg-gray-50 rounded">+ <div className="flex items-center gap-2">+ {chip(p.action ?? "N/A", p.detected ? "red" : "slate")}+ {p.type && chip(p.type, "slate")}+ <span className="font-mono text-xs break-all">{p.match}</span>+ </div>+ {boolPill(p.detected)}+ </div>+ ))}+ </div>+ </Section>+ )}+ {(assess.sensitiveInformationPolicy.regexes?.length ?? 0) > 0 && (+ <Section title="Custom Regexes" defaultOpen={false}>+ <div className="space-y-2">+ {assess.sensitiveInformationPolicy.regexes!.map((r, i) => (+ <div key={i} className="flex flex-col sm:flex-row sm:items-center sm:justify-between p-2 bg-gray-50 rounded gap-1">+ <div className="flex items-center gap-2">+ {chip(r.action ?? "N/A", r.detected ? "red" : "slate")}+ <span className="font-medium">{r.name ?? "regex"}</span>+ <span className="font-mono text-xs break-all">{r.regex}</span>+ </div>+ <div className="flex items-center gap-2">+ {boolPill(r.detected)}+ {r.match && <span className="font-mono text-xs break-all">{r.match}</span>}+ </div>+ </div>+ ))}+ </div>+ </Section>+ )}+ </div>+ )}++ {/* Topic policy */}+ {assess.topicPolicy?.topics?.length ? (+ <div className="mb-3">+ <h6 className="font-medium mb-2">Topic Policy</h6>+ <div className="flex flex-wrap gap-2">+ {assess.topicPolicy.topics!.map((t, i) => (+ <div key={i} className="px-3 py-1.5 bg-gray-50 rounded-md text-xs">+ <div className="flex items-center gap-2">+ {chip(t.action ?? "N/A", t.detected ? "red" : "slate")}+ <span className="font-medium">{t.name ?? "topic"}</span>+ {t.type && chip(t.type, "slate")}+ {boolPill(t.detected)}+ </div>+ </div>+ ))}+ </div>+ </div>+ ) : null}++ {/* Invocation metrics */}+ {assess.invocationMetrics && (+ <Section title="Invocation Metrics" defaultOpen={false}>+ <div className="grid grid-cols-2 gap-4">+ <div className="space-y-2">+ <KV label="Latency (ms)">{assess.invocationMetrics.guardrailProcessingLatency ?? "—"}</KV>+ <KV label="Coverage:">+ <div className="flex flex-wrap gap-2">+ {assess.invocationMetrics.guardrailCoverage?.textCharacters &&+ chip(+ `text ${assess.invocationMetrics.guardrailCoverage.textCharacters.guarded ?? 0}/${+ assess.invocationMetrics.guardrailCoverage.textCharacters.total ?? 0+ }`,+ "blue"+ )}+ {assess.invocationMetrics.guardrailCoverage?.images &&+ chip(+ `images ${assess.invocationMetrics.guardrailCoverage.images.guarded ?? 0}/${+ assess.invocationMetrics.guardrailCoverage.images.total ?? 0+ }`,+ "blue"+ )}+ </div>+ </KV>+ </div>+ <div className="space-y-2">+ <KV label="Usage:">+ <div className="flex flex-wrap gap-2">+ {assess.invocationMetrics.usage &&+ Object.entries(assess.invocationMetrics.usage).map(([k, v]) =>+ typeof v === "number" ? (+ <span key={k} className="px-2 py-1 bg-slate-100 text-slate-800 rounded-md text-xs font-medium">+ {k}: {v}+ </span>+ ) : null+ )}+ </div>+ </KV>+ </div>+ </div>+ </Section>+ )}++ {/* Automated reasoning (fallback render) */}+ {assess.automatedReasoningPolicy?.findings?.length ? (+ <Section title="Automated Reasoning Findings" defaultOpen={false}>+ <div className="space-y-2">+ {assess.automatedReasoningPolicy.findings!.map((f, i) => (+ <pre key={i} className="bg-gray-50 rounded p-2 text-xs overflow-x-auto">+ {JSON.stringify(f, null, 2)}+ </pre>+ ))}+ </div>+ </Section>+ ) : null}+ </Section>+ );+ })}+ </div>+ ) : null}++ {/* Raw JSON (for debugging / completeness) */}+ <Section title="Raw Bedrock Guardrail Response" defaultOpen={false}>+ <pre className="bg-gray-50 rounded p-3 text-xs overflow-x-auto">{JSON.stringify(response, null, 2)}</pre>+ </Section>+ </div>+ );+};++export default BedrockGuardrailDetails;diff --git a/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsx b/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsxnew file mode 100644index 00000000000..96d1da91627--- /dev/null+++ b/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsx@@ -0,0 +1,163 @@+import React, { useState } from "react";+import PresidioDetectedEntities from "./PresidioDetectedEntities";+import BedrockGuardrailDetails, {+ BedrockGuardrailResponse,+} from "@/components/view_logs/GuardrailViewer/BedrockGuardrailDetails"++interface RecognitionMetadata {+ recognizer_name: string;+ recognizer_identifier: string;+}++interface GuardrailEntity {+ end: number;+ score: number;+ start: number;+ entity_type: string;+ analysis_explanation: string | null;+ recognition_metadata: RecognitionMetadata;+}++interface MaskedEntityCount {+ [key: string]: number;+}++interface GuardrailInformation {+ duration: number;+ end_time: number;+ start_time: number;+ guardrail_mode: string;+ guardrail_name: string;+ guardrail_status: string;+ guardrail_response: GuardrailEntity[] | BedrockGuardrailResponse;+ masked_entity_count: MaskedEntityCount;+ guardrail_provider?: string; // "presidio" | other providers+}++interface GuardrailViewerProps {+ data: GuardrailInformation;+}++const GuardrailViewer = ({ data }: GuardrailViewerProps) => {+ const [sectionExpanded, setSectionExpanded] = useState(true);++ // Default to presidio for backwards compatibility+ const guardrailProvider = data.guardrail_provider ?? "presidio";++ if (!data) {+ return null;+ }++ // Calculate total masked entities+ const totalMaskedEntities = data.masked_entity_count ?+ Object.values(data.masked_entity_count).reduce((sum, count) => sum + count, 0) : 0;++ const formatTime = (timestamp: number): string => {+ const date = new Date(timestamp * 1000);+ return date.toLocaleString();+ };++ return (+ <div className="bg-white rounded-lg shadow mb-6">+ <div+ className="flex justify-between items-center p-4 border-b cursor-pointer hover:bg-gray-50"+ onClick={() => setSectionExpanded(!sectionExpanded)}+ >+ <div className="flex items-center">+ <svg+ className={`w-5 h-5 mr-2 text-gray-600 transition-transform ${sectionExpanded ? '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>+ <h3 className="text-lg font-medium">Guardrail Information</h3>+ <span className={`ml-3 px-2 py-1 rounded-md text-xs font-medium inline-block ${+ data.guardrail_status === "success"+ ? 'bg-green-100 text-green-800'+ : 'bg-red-100 text-red-800'+ }`}>+ {data.guardrail_status}+ </span>+ {totalMaskedEntities > 0 && (+ <span className="ml-3 px-2 py-1 bg-blue-50 text-blue-700 rounded-md text-xs font-medium">+ {totalMaskedEntities} masked {totalMaskedEntities === 1 ? 'entity' : 'entities'}+ </span>+ )}+ </div>+ <span className="text-sm text-gray-500">{sectionExpanded ? 'Click to collapse' : 'Click to expand'}</span>+ </div>++ {sectionExpanded && (+ <div className="p-4">+ <div className="bg-white rounded-lg border p-4 mb-4">+ <div className="grid 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">{data.guardrail_name}</span>+ </div>+ <div className="flex">+ <span className="font-medium w-1/3">Mode:</span>+ <span className="font-mono">{data.guardrail_mode}</span>+ </div>+ <div className="flex">+ <span className="font-medium w-1/3">Status:</span>+ <span className={`px-2 py-1 rounded-md text-xs font-medium inline-block ${+ data.guardrail_status === "success"+ ? 'bg-green-100 text-green-800'+ : 'bg-red-100 text-red-800'+ }`}>+ {data.guardrail_status}+ </span>+ </div>+ </div>+ <div className="space-y-2">+ <div className="flex">+ <span className="font-medium w-1/3">Start Time:</span>+ <span>{formatTime(data.start_time)}</span>+ </div>+ <div className="flex">+ <span className="font-medium w-1/3">End Time:</span>+ <span>{formatTime(data.end_time)}</span>+ </div>+ <div className="flex">+ <span className="font-medium w-1/3">Duration:</span>+ <span>{data.duration.toFixed(4)}s</span>+ </div>+ </div>+ </div>++ {/* Masked Entity Summary */}+ {data.masked_entity_count && Object.keys(data.masked_entity_count).length > 0 && (+ <div className="mt-4 pt-4 border-t">+ <h4 className="font-medium mb-2">Masked Entity Summary</h4>+ <div className="flex flex-wrap gap-2">+ {Object.entries(data.masked_entity_count).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>+ )}+ </div>++ {/* Provider-specific Detected Entities */}+ {guardrailProvider === "presidio" && (data.guardrail_response as GuardrailEntity[])?.length > 0 && (+ <PresidioDetectedEntities entities={data.guardrail_response as GuardrailEntity[]} />+ )}++ {guardrailProvider === "bedrock" && data.guardrail_response && (+ <div className="mt-4">+ <BedrockGuardrailDetails response={data.guardrail_response as BedrockGuardrailResponse} />+ </div>+ )}+ </div>+ )}+ </div>+ );+}++export default GuardrailViewer;\ No newline at end of filediff --git a/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/PresidioDetectedEntities.tsx b/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/PresidioDetectedEntities.tsxnew file mode 100644index 00000000000..d03478a569e--- /dev/null+++ b/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/PresidioDetectedEntities.tsx@@ -0,0 +1,136 @@+import React, { useState } from "react";++interface RecognitionMetadata {+ recognizer_name: string;+ recognizer_identifier: string;+}++export interface GuardrailEntity {+ end: number;+ score: number;+ start: number;+ entity_type: string;+ analysis_explanation: string | null;+ recognition_metadata: RecognitionMetadata;+}++interface PresidioDetectedEntitiesProps {+ entities: GuardrailEntity[];+}++const getScoreColor = (score: number): string => {+ if (score >= 0.8) return "text-green-600";+ return "text-yellow-600";+};++const PresidioDetectedEntities = ({ entities }: PresidioDetectedEntitiesProps) => {+ const [entityListExpanded, setEntityListExpanded] = useState(true);+ const [expandedEntities, setExpandedEntities] = useState<Record<number, boolean>>({});++ const toggleEntity = (index: number) => {+ setExpandedEntities((prev) => ({+ ...prev,+ [index]: !prev[index],+ }));+ };++ if (!entities || entities.length === 0) return null;++ return (+ <div className="mt-4">+ <div+ className="flex items-center mb-2 cursor-pointer"+ onClick={() => setEntityListExpanded(!entityListExpanded)}+ >+ <svg+ className={`w-5 h-5 mr-2 transition-transform ${entityListExpanded ? "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>+ <h4 className="font-medium">Detected Entities ({entities.length})</h4>+ </div>++ {entityListExpanded && (+ <div className="space-y-2">+ {entities.map((entity, index) => {+ const isExpanded = expandedEntities[index] || false;++ return (+ <div key={index} 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={() => toggleEntity(index)}+ >+ <div className="flex items-center">+ <svg+ className={`w-5 h-5 mr-2 transition-transform ${isExpanded ? "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>+ <span className="font-medium mr-2">{entity.entity_type}</span>+ <span className={`font-mono ${getScoreColor(entity.score)}`}>+ Score: {entity.score.toFixed(2)}+ </span>+ </div>+ <span className="text-xs text-gray-500">Position: {entity.start}-{entity.end}</span>+ </div>++ {isExpanded && (+ <div className="p-3 border-t bg-white">+ <div className="grid grid-cols-2 gap-4 mb-2">+ <div className="space-y-2">+ <div className="flex">+ <span className="font-medium w-1/3">Entity Type:</span>+ <span>{entity.entity_type}</span>+ </div>+ <div className="flex">+ <span className="font-medium w-1/3">Position:</span>+ <span>Characters {entity.start}-{entity.end}</span>+ </div>+ <div className="flex">+ <span className="font-medium w-1/3">Confidence:</span>+ <span className={getScoreColor(entity.score)}>{entity.score.toFixed(2)}</span>+ </div>+ </div>++ <div className="space-y-2">+ {entity.recognition_metadata && (+ <>+ <div className="flex">+ <span className="font-medium w-1/3">Recognizer:</span>+ <span>{entity.recognition_metadata.recognizer_name}</span>+ </div>+ <div className="flex overflow-hidden">+ <span className="font-medium w-1/3">Identifier:</span>+ <span className="truncate text-xs font-mono">+ {entity.recognition_metadata.recognizer_identifier}+ </span>+ </div>+ </>+ )}+ {entity.analysis_explanation && (+ <div className="flex">+ <span className="font-medium w-1/3">Explanation:</span>+ <span>{entity.analysis_explanation}</span>+ </div>+ )}+ </div>+ </div>+ </div>+ )}+ </div>+ );+ })}+ </div>+ )}+ </div>+ );+}++export default PresidioDetectedEntities;diff --git a/ui/litellm-dashboard/src/components/view_logs/index.tsx b/ui/litellm-dashboard/src/components/view_logs/index.tsxindex 4552870ae9b..2a916db7f0f 100644--- a/ui/litellm-dashboard/src/components/view_logs/index.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/index.tsx@@ -17,7 +17,7 @@ import { KeyResponse, Team } from "../key_team_helpers/key_list"import KeyInfoView from "../templates/key_info_view"import { SessionView } from "./SessionView"import { VectorStoreViewer } from "./VectorStoreViewer"-import { GuardrailViewer } from "./GuardrailViewer"+import GuardrailViewer from "@/components/view_logs/GuardrailViewer/GuardrailViewer"import FilterComponent from "../molecules/filter"import { FilterOption } from "../molecules/filter"import { useLogFilterLogic } from "./log_filter_logic"