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
Litellm dev 02 19 2026 p2 (#21871)
Krish Dholakia886f1a347274
diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260214124140_baseline_diff/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260214124140_baseline_diff/migration.sqldeleted file mode 100644index 2f725d83806..00000000000--- a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260214124140_baseline_diff/migration.sql+++ /dev/null@@ -1,2 +0,0 @@--- This is an empty migration.-diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260219181415_baseline_diff/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260219181415_baseline_diff/migration.sqlnew file mode 100644index 00000000000..dd95d9d84a3--- /dev/null+++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260219181415_baseline_diff/migration.sql@@ -0,0 +1,60 @@+-- CreateTable+CREATE TABLE "LiteLLM_DailyGuardrailMetrics" (+ "guardrail_id" TEXT NOT NULL,+ "date" TEXT NOT NULL,+ "requests_evaluated" BIGINT NOT NULL DEFAULT 0,+ "passed_count" BIGINT NOT NULL DEFAULT 0,+ "blocked_count" BIGINT NOT NULL DEFAULT 0,+ "flagged_count" BIGINT NOT NULL DEFAULT 0,+ "avg_score" DOUBLE PRECISION,+ "avg_latency_ms" DOUBLE PRECISION,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL,++ CONSTRAINT "LiteLLM_DailyGuardrailMetrics_pkey" PRIMARY KEY ("guardrail_id","date")+);++-- CreateTable+CREATE TABLE "LiteLLM_DailyPolicyMetrics" (+ "policy_id" TEXT NOT NULL,+ "date" TEXT NOT NULL,+ "requests_evaluated" BIGINT NOT NULL DEFAULT 0,+ "passed_count" BIGINT NOT NULL DEFAULT 0,+ "blocked_count" BIGINT NOT NULL DEFAULT 0,+ "flagged_count" BIGINT NOT NULL DEFAULT 0,+ "avg_score" DOUBLE PRECISION,+ "avg_latency_ms" DOUBLE PRECISION,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL,++ CONSTRAINT "LiteLLM_DailyPolicyMetrics_pkey" PRIMARY KEY ("policy_id","date")+);++-- CreateTable+CREATE TABLE "LiteLLM_SpendLogGuardrailIndex" (+ "request_id" TEXT NOT NULL,+ "guardrail_id" TEXT NOT NULL,+ "policy_id" TEXT,+ "start_time" TIMESTAMP(3) NOT NULL,++ CONSTRAINT "LiteLLM_SpendLogGuardrailIndex_pkey" PRIMARY KEY ("request_id","guardrail_id")+);++-- CreateIndex+CREATE INDEX "LiteLLM_DailyGuardrailMetrics_date_idx" ON "LiteLLM_DailyGuardrailMetrics"("date");++-- CreateIndex+CREATE INDEX "LiteLLM_DailyGuardrailMetrics_guardrail_id_idx" ON "LiteLLM_DailyGuardrailMetrics"("guardrail_id");++-- CreateIndex+CREATE INDEX "LiteLLM_DailyPolicyMetrics_date_idx" ON "LiteLLM_DailyPolicyMetrics"("date");++-- CreateIndex+CREATE INDEX "LiteLLM_DailyPolicyMetrics_policy_id_idx" ON "LiteLLM_DailyPolicyMetrics"("policy_id");++-- CreateIndex+CREATE INDEX "LiteLLM_SpendLogGuardrailIndex_guardrail_id_start_time_idx" ON "LiteLLM_SpendLogGuardrailIndex"("guardrail_id", "start_time");++-- CreateIndex+CREATE INDEX "LiteLLM_SpendLogGuardrailIndex_policy_id_start_time_idx" ON "LiteLLM_SpendLogGuardrailIndex"("policy_id", "start_time");+diff --git a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma b/litellm-proxy-extras/litellm_proxy_extras/schema.prismaindex 777e9c6b971..18a824d9b99 100644--- a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma+++ b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma@@ -213,53 +213,6 @@ model LiteLLM_DeletedTeamTable {@@index([created_at])}-// Audit table for deleted teams - preserves spend and team information for historical tracking-model LiteLLM_DeletedTeamTable {- id String @id @default(uuid())- team_id String // Original team_id- team_alias String?- organization_id String?- object_permission_id String?- admins String[]- members String[]- members_with_roles Json @default("{}")- metadata Json @default("{}")- max_budget Float?- soft_budget Float?- spend Float @default(0.0)- models String[]- max_parallel_requests Int?- tpm_limit BigInt?- rpm_limit BigInt?- budget_duration String?- budget_reset_at DateTime?- blocked Boolean @default(false)- model_spend Json @default("{}")- model_max_budget Json @default("{}")- router_settings Json? @default("{}")- team_member_permissions String[] @default([])- access_group_ids String[] @default([])- policies String[] @default([])- model_id Int? // id for LiteLLM_ModelTable -> stores team-level model aliases- allow_team_guardrail_config Boolean @default(false)-- // Original timestamps from team creation/updates- created_at DateTime? @map("created_at")- updated_at DateTime? @map("updated_at")-- // Deletion metadata- deleted_at DateTime @default(now()) @map("deleted_at")- deleted_by String? @map("deleted_by") // User who deleted the team- deleted_by_api_key String? @map("deleted_by_api_key") // API key hash that performed the deletion- litellm_changed_by String? @map("litellm_changed_by") // From litellm-changed-by header if provided-- @@index([team_id])- @@index([deleted_at])- @@index([organization_id])- @@index([team_alias])- @@index([created_at])-}-// Track spend, rate limit, budget Usersmodel LiteLLM_UserTable {user_id String @id@@ -912,6 +865,54 @@ model LiteLLM_GuardrailsTable {updated_at DateTime @updatedAt}+// Daily guardrail metrics for usage dashboard (one row per guardrail per day)+model LiteLLM_DailyGuardrailMetrics {+ guardrail_id String // logical id; may not FK if guardrail from config+ date String // YYYY-MM-DD+ requests_evaluated BigInt @default(0)+ passed_count BigInt @default(0)+ blocked_count BigInt @default(0)+ flagged_count BigInt @default(0)+ avg_score Float?+ avg_latency_ms Float?+ created_at DateTime @default(now())+ updated_at DateTime @updatedAt++ @@id([guardrail_id, date])+ @@index([date])+ @@index([guardrail_id])+}++// Daily policy metrics for usage dashboard (one row per policy per day)+model LiteLLM_DailyPolicyMetrics {+ policy_id String+ date String // YYYY-MM-DD+ requests_evaluated BigInt @default(0)+ passed_count BigInt @default(0)+ blocked_count BigInt @default(0)+ flagged_count BigInt @default(0)+ avg_score Float?+ avg_latency_ms Float?+ created_at DateTime @default(now())+ updated_at DateTime @updatedAt++ @@id([policy_id, date])+ @@index([date])+ @@index([policy_id])+}++// Index for fast "last N logs for guardrail/policy" from SpendLogs+model LiteLLM_SpendLogGuardrailIndex {+ request_id String+ guardrail_id String+ policy_id String? // set when run as part of a policy pipeline+ start_time DateTime++ @@id([request_id, guardrail_id])+ @@index([guardrail_id, start_time])+ @@index([policy_id, start_time])+}+// Prompt table for storing prompt configurationsmodel LiteLLM_PromptTable {id String @id @default(uuid())diff --git a/litellm/integrations/custom_guardrail.py b/litellm/integrations/custom_guardrail.pyindex 4a1e3e41e96..bf330944ef8 100644--- a/litellm/integrations/custom_guardrail.py+++ b/litellm/integrations/custom_guardrail.py@@ -587,9 +587,10 @@ class CustomGuardrail(CustomLogger):elif "litellm_metadata" in request_data:_append_guardrail_info(request_data["litellm_metadata"])else:- verbose_logger.warning(- "unable to log guardrail information. No metadata found in request_data"- )+ # Ensure guardrail info is always logged (e.g. proxy may not have set+ # metadata yet). Attach to "metadata" so spend log / standard logging see it.+ request_data["metadata"] = {}+ _append_guardrail_info(request_data["metadata"])async def apply_guardrail(self,diff --git a/litellm/proxy/guardrails/guardrail_endpoints.py b/litellm/proxy/guardrails/guardrail_endpoints.pyindex e14782fa1f8..c083c60cb4c 100644--- a/litellm/proxy/guardrails/guardrail_endpoints.py+++ b/litellm/proxy/guardrails/guardrail_endpoints.py@@ -14,21 +14,27 @@ from litellm.integrations.custom_guardrail import CustomGuardrailfrom litellm.proxy._types import UserAPIKeyAuthfrom litellm.proxy.auth.user_api_key_auth import user_api_key_authfrom litellm.proxy.guardrails.guardrail_registry import GuardrailRegistry-from litellm.types.guardrails import (PII_ENTITY_CATEGORIES_MAP,- ApplyGuardrailRequest,- ApplyGuardrailResponse,- BaseLitellmParams,- BedrockGuardrailConfigModel, Guardrail,- GuardrailEventHooks,- GuardrailInfoResponse,- GuardrailUIAddGuardrailSettings,- LakeraV2GuardrailConfigModel,- ListGuardrailsResponse, LitellmParams,- PatchGuardrailRequest, PiiAction,- PiiEntityType,- PresidioPresidioConfigModelUserInterface,- SupportedGuardrailIntegrations,- ToolPermissionGuardrailConfigModel)+from litellm.proxy.guardrails.usage_endpoints import router as guardrails_usage_router+from litellm.types.guardrails import (+ PII_ENTITY_CATEGORIES_MAP,+ ApplyGuardrailRequest,+ ApplyGuardrailResponse,+ BaseLitellmParams,+ BedrockGuardrailConfigModel,+ Guardrail,+ GuardrailEventHooks,+ GuardrailInfoResponse,+ GuardrailUIAddGuardrailSettings,+ LakeraV2GuardrailConfigModel,+ ListGuardrailsResponse,+ LitellmParams,+ PatchGuardrailRequest,+ PiiAction,+ PiiEntityType,+ PresidioPresidioConfigModelUserInterface,+ SupportedGuardrailIntegrations,+ ToolPermissionGuardrailConfigModel,+)#### GUARDRAILS ENDPOINTS ####@@ -147,8 +153,7 @@ async def list_guardrails_v2():```"""from litellm.litellm_core_utils.litellm_logging import _get_masked_values- from litellm.proxy.guardrails.guardrail_registry import \- IN_MEMORY_GUARDRAIL_HANDLER+ from litellm.proxy.guardrails.guardrail_registry import IN_MEMORY_GUARDRAIL_HANDLERfrom litellm.proxy.proxy_server import prisma_clientif prisma_client is None:@@ -288,8 +293,7 @@ async def create_guardrail(request: CreateGuardrailRequest):}```"""- from litellm.proxy.guardrails.guardrail_registry import \- IN_MEMORY_GUARDRAIL_HANDLER+ from litellm.proxy.guardrails.guardrail_registry import IN_MEMORY_GUARDRAIL_HANDLERfrom litellm.proxy.proxy_server import prisma_clientif prisma_client is None:@@ -378,8 +382,7 @@ async def update_guardrail(guardrail_id: str, request: UpdateGuardrailRequest):}```"""- from litellm.proxy.guardrails.guardrail_registry import \- IN_MEMORY_GUARDRAIL_HANDLER+ from litellm.proxy.guardrails.guardrail_registry import IN_MEMORY_GUARDRAIL_HANDLERfrom litellm.proxy.proxy_server import prisma_clientif prisma_client is None:@@ -447,8 +450,7 @@ async def delete_guardrail(guardrail_id: str):}```"""- from litellm.proxy.guardrails.guardrail_registry import \- IN_MEMORY_GUARDRAIL_HANDLER+ from litellm.proxy.guardrails.guardrail_registry import IN_MEMORY_GUARDRAIL_HANDLERfrom litellm.proxy.proxy_server import prisma_clientif prisma_client is None:@@ -541,8 +543,7 @@ async def patch_guardrail(guardrail_id: str, request: PatchGuardrailRequest):}```"""- from litellm.proxy.guardrails.guardrail_registry import \- IN_MEMORY_GUARDRAIL_HANDLER+ from litellm.proxy.guardrails.guardrail_registry import IN_MEMORY_GUARDRAIL_HANDLERfrom litellm.proxy.proxy_server import prisma_clientif prisma_client is None:@@ -664,8 +665,7 @@ async def get_guardrail_info(guardrail_id: str):"""from litellm.litellm_core_utils.litellm_logging import _get_masked_values- from litellm.proxy.guardrails.guardrail_registry import \- IN_MEMORY_GUARDRAIL_HANDLER+ from litellm.proxy.guardrails.guardrail_registry import IN_MEMORY_GUARDRAIL_HANDLERfrom litellm.proxy.proxy_server import prisma_clientfrom litellm.types.guardrails import GUARDRAIL_DEFINITION_LOCATION@@ -740,8 +740,10 @@ async def get_guardrail_ui_settings():- Content filter settings (patterns and categories)"""from litellm.proxy.guardrails.guardrail_hooks.litellm_content_filter.patterns import (- PATTERN_CATEGORIES, get_available_content_categories,- get_pattern_metadata)+ PATTERN_CATEGORIES,+ get_available_content_categories,+ get_pattern_metadata,+ )# Convert the PII_ENTITY_CATEGORIES_MAP to the format expected by the UIcategory_maps = []@@ -1313,8 +1315,7 @@ async def get_provider_specific_params():}### get the config model for the guardrail - go through the registry and get the config model for the guardrail- from litellm.proxy.guardrails.guardrail_registry import \- guardrail_class_registry+ from litellm.proxy.guardrails.guardrail_registry import guardrail_class_registryfor guardrail_name, guardrail_class in guardrail_class_registry.items():guardrail_config_model = guardrail_class.get_config_model()@@ -1442,8 +1443,9 @@ async def test_custom_code_guardrail(request: TestCustomCodeGuardrailRequest):import concurrent.futuresimport re- from litellm.proxy.guardrails.guardrail_hooks.custom_code.primitives import \- get_custom_code_primitives+ from litellm.proxy.guardrails.guardrail_hooks.custom_code.primitives import (+ get_custom_code_primitives,+ )# Security validation patternsFORBIDDEN_PATTERNS = [@@ -1633,3 +1635,7 @@ async def apply_guardrail()except Exception as e:raise handle_exception_on_proxy(e)+++# Usage (dashboard) endpoints: overview, detail, logs+router.include_router(guardrails_usage_router)diff --git a/litellm/proxy/guardrails/usage_endpoints.py b/litellm/proxy/guardrails/usage_endpoints.pynew file mode 100644index 00000000000..16a6f1a2cc5--- /dev/null+++ b/litellm/proxy/guardrails/usage_endpoints.py@@ -0,0 +1,587 @@+"""+Guardrails and policies usage endpoints for the dashboard.+GET /guardrails/usage/overview, /guardrails/usage/detail/:id, /guardrails/usage/logs+"""++import json+from datetime import datetime, timedelta, timezone+from typing import Any, Dict, List, Optional++from fastapi import APIRouter, Depends, Query+from pydantic import BaseModel++from litellm.proxy._types import UserAPIKeyAuth+from litellm.proxy.auth.user_api_key_auth import user_api_key_auth++router = APIRouter()+++# --- Response models ---+++class UsageOverviewRow(BaseModel):+ id: str+ name: str+ type: str+ provider: str+ requestsEvaluated: int+ failRate: float+ avgScore: Optional[float]+ avgLatency: Optional[float]+ status: str # healthy | warning | critical+ trend: str # up | down | stable+++class UsageOverviewResponse(BaseModel):+ rows: List[UsageOverviewRow]+ chart: List[Dict[str, Any]] # [{ date, passed, blocked }]+ totalRequests: int+ totalBlocked: int+ passRate: float+++class UsageDetailResponse(BaseModel):+ guardrail_id: str+ guardrail_name: str+ type: str+ provider: str+ requestsEvaluated: int+ failRate: float+ avgScore: Optional[float]+ avgLatency: Optional[float]+ status: str+ trend: str+ description: Optional[str]+ time_series: List[Dict[str, Any]]+++class UsageLogEntry(BaseModel):+ id: str+ timestamp: str+ action: str # blocked | passed | flagged+ score: Optional[float]+ latency_ms: Optional[float]+ model: Optional[str]+ input_snippet: Optional[str]+ output_snippet: Optional[str]+ reason: Optional[str]+++class UsageLogsResponse(BaseModel):+ logs: List[UsageLogEntry]+ total: int+ page: int+ page_size: int+++def _status_from_fail_rate(fail_rate: float) -> str:+ if fail_rate > 15:+ return "critical"+ if fail_rate > 5:+ return "warning"+ return "healthy"+++def _trend_from_comparison(current_fail: float, previous_fail: float) -> str:+ if previous_fail <= 0:+ return "stable"+ diff = current_fail - previous_fail+ if diff > 0.5:+ return "up"+ if diff < -0.5:+ return "down"+ return "stable"+++def _aggregate_daily_metrics(metrics: Any, id_attr: str) -> Dict[str, Dict[str, Any]]:+ agg: Dict[str, Dict[str, Any]] = {}+ for m in metrics:+ gid = getattr(m, id_attr)+ if gid not in agg:+ agg[gid] = {"requests": 0, "passed": 0, "blocked": 0, "flagged": 0}+ agg[gid]["requests"] += int(m.requests_evaluated or 0)+ agg[gid]["passed"] += int(m.passed_count or 0)+ agg[gid]["blocked"] += int(m.blocked_count or 0)+ agg[gid]["flagged"] += int(m.flagged_count or 0)+ return agg+++def _prev_fail_rates(+ metrics_prev: Any, id_attr: str+) -> Dict[str, float]:+ prev_agg_raw: Dict[str, Dict[str, int]] = {}+ for m in metrics_prev:+ gid = getattr(m, id_attr)+ r, b = int(m.requests_evaluated or 0), int(m.blocked_count or 0)+ if gid not in prev_agg_raw:+ prev_agg_raw[gid] = {"req": 0, "blocked": 0}+ prev_agg_raw[gid]["req"] += r+ prev_agg_raw[gid]["blocked"] += b+ return {+ gid: (100.0 * v["blocked"] / v["req"]) if v["req"] else 0.0+ for gid, v in prev_agg_raw.items()+ }+++def _chart_from_metrics(metrics: Any) -> List[Dict[str, Any]]:+ chart_by_date: Dict[str, Dict[str, int]] = {}+ for m in metrics:+ d = m.date+ if d not in chart_by_date:+ chart_by_date[d] = {"passed": 0, "blocked": 0}+ chart_by_date[d]["passed"] += int(m.passed_count or 0)+ chart_by_date[d]["blocked"] += int(m.blocked_count or 0)+ return [+ {"date": d, "passed": v["passed"], "blocked": v["blocked"]}+ for d, v in sorted(chart_by_date.items())+ ]+++def _guardrail_overview_rows(+ guardrails: Any,+ agg: Dict[str, Dict[str, Any]],+ prev_agg: Dict[str, float],+) -> List[UsageOverviewRow]:+ rows: List[UsageOverviewRow] = []+ for g in guardrails:+ gid = g.guardrail_id+ a = agg.get(gid, {"requests": 0, "passed": 0, "blocked": 0, "flagged": 0})+ req, blocked = a["requests"], a["blocked"]+ fail_rate = (100.0 * blocked / req) if req else 0.0+ litellm_params = (+ (g.litellm_params or {}) if isinstance(g.litellm_params, dict) else {}+ )+ provider = str(litellm_params.get("guardrail", "Unknown"))+ guardrail_info = (+ (g.guardrail_info or {}) if isinstance(g.guardrail_info, dict) else {}+ )+ gtype = str(guardrail_info.get("type", "Guardrail"))+ prev_fail = (+ prev_agg.get(gid, 0.0)+ if isinstance(prev_agg.get(gid), (int, float))+ else 0.0+ )+ trend = _trend_from_comparison(fail_rate, prev_fail)+ rows.append(+ UsageOverviewRow(+ id=gid,+ name=g.guardrail_name or gid,+ type=gtype,+ provider=provider,+ requestsEvaluated=req,+ failRate=round(fail_rate, 1),+ avgScore=None,+ avgLatency=None,+ status=_status_from_fail_rate(fail_rate),+ trend=trend,+ )+ )+ return rows+++def _policy_overview_rows(+ policies: Any,+ agg: Dict[str, Dict[str, Any]],+ prev_agg: Dict[str, float],+) -> List[UsageOverviewRow]:+ rows: List[UsageOverviewRow] = []+ for p in policies:+ pid = p.policy_id+ a = agg.get(pid, {"requests": 0, "passed": 0, "blocked": 0, "flagged": 0})+ req, blocked = a["requests"], a["blocked"]+ fail_rate = (100.0 * blocked / req) if req else 0.0+ trend = _trend_from_comparison(fail_rate, prev_agg.get(pid, 0.0))+ rows.append(+ UsageOverviewRow(+ id=pid,+ name=p.policy_name or pid,+ type="Policy",+ provider="LiteLLM",+ requestsEvaluated=req,+ failRate=round(fail_rate, 1),+ avgScore=None,+ avgLatency=None,+ status=_status_from_fail_rate(fail_rate),+ trend=trend,+ )+ )+ return rows+++ "/guardrails/usage/overview",+ tags=["Guardrails"],+ dependencies=[Depends(user_api_key_auth)],+ response_model=UsageOverviewResponse,+)+async def guardrails_usage_overview(+ start_date: Optional[str] = Query(None, description="YYYY-MM-DD"),+ end_date: Optional[str] = Query(None, description="YYYY-MM-DD"),+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """Return guardrail performance overview for the dashboard."""+ from litellm.proxy.proxy_server import prisma_client++ if prisma_client is None:+ return UsageOverviewResponse(+ rows=[], chart=[], totalRequests=0, totalBlocked=0, passRate=100.0+ )++ now = datetime.now(timezone.utc)+ end = end_date or now.strftime("%Y-%m-%d")+ start = start_date or (now - timedelta(days=7)).strftime("%Y-%m-%d")++ try:+ # Guardrails from DB+ guardrails = await prisma_client.db.litellm_guardrailstable.find_many()++ # Daily metrics in range+ metrics = await prisma_client.db.litellm_dailyguardrailmetrics.find_many(+ where={"date": {"gte": start, "lte": end}}+ )++ # Previous period for trend+ start_prev = (+ datetime.strptime(start, "%Y-%m-%d") - timedelta(days=7)+ ).strftime("%Y-%m-%d")+ metrics_prev = await prisma_client.db.litellm_dailyguardrailmetrics.find_many(+ where={"date": {"gte": start_prev, "lt": start}}+ )++ agg = _aggregate_daily_metrics(metrics, "guardrail_id")+ prev_agg = _prev_fail_rates(metrics_prev, "guardrail_id")+ chart = _chart_from_metrics(metrics)+ total_requests = sum(a["requests"] for a in agg.values())+ total_blocked = sum(a["blocked"] for a in agg.values())+ pass_rate = (+ (100.0 * (total_requests - total_blocked) / total_requests)+ if total_requests+ else 100.0+ )+ rows = _guardrail_overview_rows(guardrails, agg, prev_agg)+ return UsageOverviewResponse(+ rows=rows,+ chart=chart,+ totalRequests=total_requests,+ totalBlocked=total_blocked,+ passRate=round(pass_rate, 1),+ )+ except Exception as e:+ from litellm.proxy.utils import handle_exception_on_proxy++ raise handle_exception_on_proxy(e)+++ "/guardrails/usage/detail/{guardrail_id}",+ tags=["Guardrails"],+ dependencies=[Depends(user_api_key_auth)],+ response_model=UsageDetailResponse,+)+async def guardrails_usage_detail(+ guardrail_id: str,+ start_date: Optional[str] = Query(None),+ end_date: Optional[str] = Query(None),+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """Return single guardrail usage metrics and time series."""+ from litellm.proxy.proxy_server import prisma_client++ if prisma_client is None:+ from fastapi import HTTPException++ raise HTTPException(status_code=500, detail="Prisma client not initialized")++ now = datetime.now(timezone.utc)+ end = end_date or now.strftime("%Y-%m-%d")+ start = start_date or (now - timedelta(days=7)).strftime("%Y-%m-%d")++ guardrail = await prisma_client.db.litellm_guardrailstable.find_unique(+ where={"guardrail_id": guardrail_id}+ )+ if not guardrail:+ from fastapi import HTTPException++ raise HTTPException(status_code=404, detail="Guardrail not found")++ metrics = await prisma_client.db.litellm_dailyguardrailmetrics.find_many(+ where={"guardrail_id": guardrail_id, "date": {"gte": start, "lte": end}}+ )+ metrics_prev = await prisma_client.db.litellm_dailyguardrailmetrics.find_many(+ where={"guardrail_id": guardrail_id, "date": {"lt": start}}+ )++ requests = sum(int(m.requests_evaluated or 0) for m in metrics)+ blocked = sum(int(m.blocked_count or 0) for m in metrics)+ fail_rate = (100.0 * blocked / requests) if requests else 0.0++ prev_blocked = sum(int(m.blocked_count or 0) for m in metrics_prev)+ prev_req = sum(int(m.requests_evaluated or 0) for m in metrics_prev)+ prev_fail = (100.0 * prev_blocked / prev_req) if prev_req else 0.0+ trend = _trend_from_comparison(fail_rate, prev_fail)++ time_series = [+ {+ "date": m.date,+ "passed": int(m.passed_count or 0),+ "blocked": int(m.blocked_count or 0),+ "score": None,+ }+ for m in sorted(metrics, key=lambda x: x.date)+ ]+ litellm_params = (+ (guardrail.litellm_params or {})+ if isinstance(guardrail.litellm_params, dict)+ else {}+ )+ guardrail_info = (+ (guardrail.guardrail_info or {})+ if isinstance(guardrail.guardrail_info, dict)+ else {}+ )++ return UsageDetailResponse(+ guardrail_id=guardrail_id,+ guardrail_name=guardrail.guardrail_name or guardrail_id,+ type=str(guardrail_info.get("type", "Guardrail")),+ provider=str(litellm_params.get("guardrail", "Unknown")),+ requestsEvaluated=requests,+ failRate=round(fail_rate, 1),+ avgScore=None,+ avgLatency=None,+ status=_status_from_fail_rate(fail_rate),+ trend=trend,+ description=guardrail_info.get("description"),+ time_series=time_series,+ )+++def _build_usage_logs_where(+ guardrail_id: Optional[str],+ policy_id: Optional[str],+ start_date: Optional[str],+ end_date: Optional[str],+) -> Dict[str, Any]:+ where: Dict[str, Any] = {}+ if guardrail_id:+ where["guardrail_id"] = guardrail_id+ if policy_id:+ where["policy_id"] = policy_id+ if start_date or end_date:+ st_filter: Dict[str, Any] = {}+ if start_date:+ sd = start_date.replace("Z", "+00:00").strip()+ if "T" not in sd:+ sd += "T00:00:00+00:00"+ st_filter["gte"] = datetime.fromisoformat(sd)+ if end_date:+ ed = end_date.replace("Z", "+00:00").strip()+ if "T" not in ed:+ ed += "T23:59:59+00:00"+ st_filter["lte"] = datetime.fromisoformat(ed)+ where["start_time"] = st_filter+ return where+++def _usage_log_entry_from_row(+ r: Any, sl: Any, action_filter: Optional[str]+) -> Optional[UsageLogEntry]:+ meta = sl.metadata+ if isinstance(meta, str):+ try:+ meta = json.loads(meta)+ except Exception:+ meta = {}+ guardrail_info_list = (meta or {}).get("guardrail_information") or []+ entry_for_guardrail = None+ for gi in guardrail_info_list:+ if (gi.get("guardrail_id") or gi.get("guardrail_name")) == r.guardrail_id:+ entry_for_guardrail = gi+ break+ action_val = "passed"+ score_val = None+ latency_val = None+ reason_val = None+ if entry_for_guardrail:+ st = (entry_for_guardrail.get("guardrail_status") or "").lower()+ if "intervened" in st or "block" in st:+ action_val = "blocked"+ elif "fail" in st or "error" in st:+ action_val = "flagged"+ duration = entry_for_guardrail.get("duration")+ if duration is not None:+ latency_val = round(float(duration) * 1000, 0)+ score_val = entry_for_guardrail.get("confidence_score") or entry_for_guardrail.get(+ "risk_score"+ )+ if score_val is not None:+ score_val = round(float(score_val), 2)+ resp = entry_for_guardrail.get("guardrail_response")+ if isinstance(resp, str):+ reason_val = resp[:500]+ elif isinstance(resp, dict):+ reason_val = str(resp)[:500]+ if action_filter and action_val != action_filter:+ return None+ ts = (+ sl.startTime.isoformat()+ if hasattr(sl.startTime, "isoformat")+ else str(sl.startTime)+ )+ return UsageLogEntry(+ id=r.request_id,+ timestamp=ts,+ action=action_val,+ score=score_val,+ latency_ms=latency_val,+ model=sl.model,+ input_snippet=_snippet(sl.messages),+ output_snippet=_snippet(sl.response),+ reason=reason_val,+ )+++def _snippet(text: Any, max_len: int = 200) -> Optional[str]:+ if text is None:+ return None+ if isinstance(text, str):+ s = text+ elif isinstance(text, list):+ parts = []+ for item in text:+ if isinstance(item, dict) and "content" in item:+ c = item["content"]+ parts.append(c if isinstance(c, str) else str(c))+ else:+ parts.append(str(item))+ s = " ".join(parts)+ else:+ s = str(text)+ return (s[:max_len] + "...") if len(s) > max_len else s+++ "/guardrails/usage/logs",+ tags=["Guardrails"],+ dependencies=[Depends(user_api_key_auth)],+ response_model=UsageLogsResponse,+)+async def guardrails_usage_logs(+ guardrail_id: Optional[str] = Query(None),+ policy_id: Optional[str] = Query(None),+ page: int = Query(1, ge=1),+ page_size: int = Query(50, ge=1, le=100),+ action: Optional[str] = Query(None),+ start_date: Optional[str] = Query(None),+ end_date: Optional[str] = Query(None),+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """Return paginated run logs for a guardrail (or policy) from SpendLogs via index."""+ from litellm.proxy.proxy_server import prisma_client++ if prisma_client is None:+ return UsageLogsResponse(logs=[], total=0, page=page, page_size=page_size)++ if not guardrail_id and not policy_id:+ return UsageLogsResponse(logs=[], total=0, page=page, page_size=page_size)++ try:+ where = _build_usage_logs_where(+ guardrail_id, policy_id, start_date, end_date+ )+ index_rows = await prisma_client.db.litellm_spendlogguardrailindex.find_many(+ where=where,+ order={"start_time": "desc"},+ skip=(page - 1) * page_size,+ take=page_size + 1,+ )+ total = await prisma_client.db.litellm_spendlogguardrailindex.count(where=where)+ request_ids = [r.request_id for r in index_rows[:page_size]]+ if not request_ids:+ return UsageLogsResponse(+ logs=[], total=total, page=page, page_size=page_size+ )+ spend_logs = await prisma_client.db.litellm_spendlogs.find_many(+ where={"request_id": {"in": request_ids}}+ )+ log_by_id = {s.request_id: s for s in spend_logs}+ logs_out: List[UsageLogEntry] = []+ for r in index_rows[:page_size]:+ sl = log_by_id.get(r.request_id)+ if not sl:+ continue+ entry = _usage_log_entry_from_row(r, sl, action)+ if entry is not None:+ logs_out.append(entry)+ return UsageLogsResponse(+ logs=logs_out, total=total, page=page, page_size=page_size+ )+ except Exception as e:+ from litellm.proxy.utils import handle_exception_on_proxy++ raise handle_exception_on_proxy(e)+++# --- Policy usage (same shape as guardrails; policy metrics populated when policy_run is in metadata) ---+++ "/policies/usage/overview",+ tags=["Policies"],+ dependencies=[Depends(user_api_key_auth)],+ response_model=UsageOverviewResponse,+)+async def policies_usage_overview(+ start_date: Optional[str] = Query(None, description="YYYY-MM-DD"),+ end_date: Optional[str] = Query(None, description="YYYY-MM-DD"),+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """Return policy performance overview for the dashboard."""+ from litellm.proxy.proxy_server import prisma_client++ if prisma_client is None:+ return UsageOverviewResponse(+ rows=[], chart=[], totalRequests=0, totalBlocked=0, passRate=100.0+ )++ now = datetime.now(timezone.utc)+ end = end_date or now.strftime("%Y-%m-%d")+ start = start_date or (now - timedelta(days=7)).strftime("%Y-%m-%d")++ try:+ policies = await prisma_client.db.litellm_policytable.find_many()+ metrics = await prisma_client.db.litellm_dailypolicymetrics.find_many(+ where={"date": {"gte": start, "lte": end}}+ )+ metrics_prev = await prisma_client.db.litellm_dailypolicymetrics.find_many(+ where={+ "date": {+ "gte": (+ datetime.strptime(start, "%Y-%m-%d") - timedelta(days=7)+ ).strftime("%Y-%m-%d"),+ "lt": start,+ }+ }+ )+ agg = _aggregate_daily_metrics(metrics, "policy_id")+ prev_agg = _prev_fail_rates(metrics_prev, "policy_id")+ chart = _chart_from_metrics(metrics)+ total_requests = sum(a["requests"] for a in agg.values())+ total_blocked = sum(a["blocked"] for a in agg.values())+ pass_rate = (+ (100.0 * (total_requests - total_blocked) / total_requests)+ if total_requests+ else 100.0+ )+ rows = _policy_overview_rows(policies, agg, prev_agg)+ return UsageOverviewResponse(+ rows=rows,+ chart=chart,+ totalRequests=total_requests,+ totalBlocked=total_blocked,+ passRate=round(pass_rate, 1),+ )+ except Exception as e:+ from litellm.proxy.utils import handle_exception_on_proxy++ raise handle_exception_on_proxy(e)diff --git a/litellm/proxy/guardrails/usage_tracking.py b/litellm/proxy/guardrails/usage_tracking.pynew file mode 100644index 00000000000..248f3a19875--- /dev/null+++ b/litellm/proxy/guardrails/usage_tracking.py@@ -0,0 +1,170 @@+"""+Track guardrail and policy usage for the dashboard: upsert daily metrics and+insert into SpendLogGuardrailIndex when spend logs are written.+"""++import json+from collections import defaultdict+from datetime import datetime, timezone+from typing import Any, Dict, List, Optional++from litellm._logging import verbose_proxy_logger+from litellm.proxy.utils import PrismaClient+++def _guardrail_status_to_action(status: Optional[str]) -> str:+ """Map StandardLogging guardrail_status to blocked/passed/flagged."""+ if not status:+ return "passed"+ s = (status or "").lower()+ if "intervened" in s or "block" in s:+ return "blocked"+ if "fail" in s or "error" in s:+ return "flagged"+ return "passed"+++def _parse_guardrail_info_from_payload(payload: Dict[str, Any]) -> List[Dict[str, Any]]:+ """Extract guardrail_information from spend log payload metadata."""+ meta = payload.get("metadata")+ if not meta:+ return []+ if isinstance(meta, str):+ try:+ meta = json.loads(meta)+ except (json.JSONDecodeError, TypeError):+ return []+ if not isinstance(meta, dict):+ return []+ info = meta.get("guardrail_information") or meta.get(+ "standard_logging_guardrail_information"+ )+ if not isinstance(info, list):+ return []+ return info+++def _date_str(dt: datetime) -> str:+ """YYYY-MM-DD in UTC."""+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=timezone.utc)+ return dt.astimezone(timezone.utc).strftime("%Y-%m-%d")+++async def process_spend_logs_guardrail_usage(+ prisma_client: PrismaClient,+ logs_to_process: List[Dict[str, Any]],+) -> None:+ """+ After spend logs are written: update DailyGuardrailMetrics and insert+ SpendLogGuardrailIndex rows from guardrail_information in each payload.+ """+ if not logs_to_process:+ return+ # Aggregate daily metrics by (guardrail_id, date). Latency/score metrics dropped.+ daily_guardrail: Dict[tuple, Dict[str, Any]] = defaultdict(+ lambda: {+ "requests_evaluated": 0,+ "passed_count": 0,+ "blocked_count": 0,+ "flagged_count": 0,+ }+ )+ index_rows: List[Dict[str, Any]] = []++ for payload in logs_to_process:+ request_id = payload.get("request_id")+ start_time = payload.get("startTime")+ if not request_id or not start_time:+ continue+ if isinstance(start_time, str):+ try:+ start_time = datetime.fromisoformat(start_time.replace("Z", "+00:00"))+ except (ValueError, TypeError):+ continue+ date_key = _date_str(start_time)++ for entry in _parse_guardrail_info_from_payload(payload):+ guardrail_id = entry.get("guardrail_id") or entry.get("guardrail_name") or ""+ if not guardrail_id:+ continue+ key = (guardrail_id, date_key)+ daily_guardrail[key]["requests_evaluated"] += 1+ action = _guardrail_status_to_action(entry.get("guardrail_status"))+ if action == "passed":+ daily_guardrail[key]["passed_count"] += 1+ elif action == "blocked":+ daily_guardrail[key]["blocked_count"] += 1+ else:+ daily_guardrail[key]["flagged_count"] += 1+ policy_id = entry.get("policy_id")+ index_rows.append({+ "request_id": request_id,+ "guardrail_id": guardrail_id,+ "policy_id": policy_id,+ "start_time": start_time,+ })++ if not daily_guardrail and not index_rows:+ return++ try:+ # Insert index rows (skip duplicates by request_id + guardrail_id)+ if index_rows:+ index_data = []+ for r in index_rows:+ st = r["start_time"]+ if isinstance(st, str):+ try:+ st = datetime.fromisoformat(st.replace("Z", "+00:00"))+ except (ValueError, TypeError):+ continue+ index_data.append({+ "request_id": r["request_id"],+ "guardrail_id": r["guardrail_id"],+ "policy_id": r.get("policy_id"),+ "start_time": st,+ })+ try:+ await prisma_client.db.litellm_spendlogguardrailindex.create_many(+ data=index_data,+ skip_duplicates=True,+ )+ except Exception as e:+ verbose_proxy_logger.debug(+ "Guardrail usage tracking: index create_many skipped: %s", e+ )++ # Upsert daily guardrail metrics (counts only; latency/score dropped)+ for (guardrail_id, date_key), agg in daily_guardrail.items():+ n = int(agg["requests_evaluated"])+ if n == 0:+ continue+ await prisma_client.db.litellm_dailyguardrailmetrics.upsert(+ where={+ "guardrail_id_date": {+ "guardrail_id": guardrail_id,+ "date": date_key,+ }+ },+ data={+ "create": {+ "guardrail_id": guardrail_id,+ "date": date_key,+ "requests_evaluated": n,+ "passed_count": int(agg["passed_count"]),+ "blocked_count": int(agg["blocked_count"]),+ "flagged_count": int(agg["flagged_count"]),+ },+ "update": {+ "requests_evaluated": {"increment": n},+ "passed_count": {"increment": int(agg["passed_count"])},+ "blocked_count": {"increment": int(agg["blocked_count"])},+ "flagged_count": {"increment": int(agg["flagged_count"])},+ },+ },+ )+ except Exception as e:+ verbose_proxy_logger.warning(+ "Guardrail usage tracking failed (non-fatal): %s", e+ )diff --git a/litellm/proxy/schema.prisma b/litellm/proxy/schema.prismaindex 4128ab5f23e..18a824d9b99 100644--- a/litellm/proxy/schema.prisma+++ b/litellm/proxy/schema.prisma@@ -273,7 +273,6 @@ model LiteLLM_MCPServerTable {alias String?description String?url String?- spec_path String?transport String @default("sse")auth_type String?credentials Json? @default("{}")@@ -866,6 +865,54 @@ model LiteLLM_GuardrailsTable {updated_at DateTime @updatedAt}+// Daily guardrail metrics for usage dashboard (one row per guardrail per day)+model LiteLLM_DailyGuardrailMetrics {+ guardrail_id String // logical id; may not FK if guardrail from config+ date String // YYYY-MM-DD+ requests_evaluated BigInt @default(0)+ passed_count BigInt @default(0)+ blocked_count BigInt @default(0)+ flagged_count BigInt @default(0)+ avg_score Float?+ avg_latency_ms Float?+ created_at DateTime @default(now())+ updated_at DateTime @updatedAt++ @@id([guardrail_id, date])+ @@index([date])+ @@index([guardrail_id])+}++// Daily policy metrics for usage dashboard (one row per policy per day)+model LiteLLM_DailyPolicyMetrics {+ policy_id String+ date String // YYYY-MM-DD+ requests_evaluated BigInt @default(0)+ passed_count BigInt @default(0)+ blocked_count BigInt @default(0)+ flagged_count BigInt @default(0)+ avg_score Float?+ avg_latency_ms Float?+ created_at DateTime @default(now())+ updated_at DateTime @updatedAt++ @@id([policy_id, date])+ @@index([date])+ @@index([policy_id])+}++// Index for fast "last N logs for guardrail/policy" from SpendLogs+model LiteLLM_SpendLogGuardrailIndex {+ request_id String+ guardrail_id String+ policy_id String? // set when run as part of a policy pipeline+ start_time DateTime++ @@id([request_id, guardrail_id])+ @@index([guardrail_id, start_time])+ @@index([policy_id, start_time])+}+// Prompt table for storing prompt configurationsmodel LiteLLM_PromptTable {id String @id @default(uuid())diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex bbc549782d0..1edb7b1b530 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -25,31 +25,23 @@ from typing import ()from litellm import _custom_logger_compatible_callbacks_literal-from litellm.constants import DEFAULT_MODEL_CREATED_AT_TIME, MAX_TEAM_LIST_LIMIT-from litellm.proxy._types import (- DB_CONNECTION_ERROR_TYPES,- CommonProxyErrors,- ProxyErrorTypes,- ProxyException,- SpendLogsMetadata,- SpendLogsPayload,-)+from litellm.constants import (DEFAULT_MODEL_CREATED_AT_TIME,+ MAX_TEAM_LIST_LIMIT)+from litellm.proxy._types import (DB_CONNECTION_ERROR_TYPES, CommonProxyErrors,+ ProxyErrorTypes, ProxyException,+ SpendLogsMetadata, SpendLogsPayload)from litellm.types.guardrails import GuardrailEventHooksfrom litellm.types.utils import CallTypes, CallTypesLiteraltry:- from litellm_enterprise.enterprise_callbacks.send_emails.base_email import (- BaseEmailLogger,- )- from litellm_enterprise.enterprise_callbacks.send_emails.resend_email import (- ResendEmailLogger,- )- from litellm_enterprise.enterprise_callbacks.send_emails.sendgrid_email import (- SendGridEmailLogger,- )- from litellm_enterprise.enterprise_callbacks.send_emails.smtp_email import (- SMTPEmailLogger,- )+ from litellm_enterprise.enterprise_callbacks.send_emails.base_email import \+ BaseEmailLogger+ from litellm_enterprise.enterprise_callbacks.send_emails.resend_email import \+ ResendEmailLogger+ from litellm_enterprise.enterprise_callbacks.send_emails.sendgrid_email import \+ SendGridEmailLogger+ from litellm_enterprise.enterprise_callbacks.send_emails.smtp_email import \+ SMTPEmailLoggerexcept ImportError:BaseEmailLogger = None # type: ignoreSendGridEmailLogger = None # type: ignore@@ -68,70 +60,56 @@ from fastapi import HTTPException, statusimport litellmimport litellm.litellm_core_utilsimport litellm.litellm_core_utils.litellm_logging-from litellm import (- EmbeddingResponse,- ImageResponse,- ModelResponse,- ModelResponseStream,- Router,-)+from litellm import (EmbeddingResponse, ImageResponse, ModelResponse,+ ModelResponseStream, Router)from litellm._logging import verbose_proxy_loggerfrom litellm._service_logger import ServiceLogging, ServiceTypesfrom litellm.caching.caching import DualCache, RedisCachefrom litellm.caching.dual_cache import LimitedSizeOrderedDictfrom litellm.exceptions import RejectedRequestError-from litellm.integrations.custom_guardrail import (- CustomGuardrail,- ModifyResponseException,-)+from litellm.integrations.custom_guardrail import (CustomGuardrail,+ ModifyResponseException)from litellm.integrations.custom_logger import CustomLoggerfrom litellm.integrations.SlackAlerting.slack_alerting import SlackAlerting-from litellm.integrations.SlackAlerting.utils import _add_langfuse_trace_id_to_alert+from litellm.integrations.SlackAlerting.utils import \+ _add_langfuse_trace_id_to_alertfrom litellm.litellm_core_utils.litellm_logging import Loggingfrom litellm.litellm_core_utils.safe_json_dumps import safe_dumpsfrom litellm.litellm_core_utils.safe_json_loads import safe_json_loadsfrom litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler-from litellm.proxy._types import (- AlertType,- CallInfo,- LiteLLM_VerificationTokenView,- Member,- UserAPIKeyAuth,-)+from litellm.proxy._types import (AlertType, CallInfo,+ LiteLLM_VerificationTokenView, Member,+ UserAPIKeyAuth)from litellm.proxy.auth.route_checks import RouteChecks-from litellm.proxy.db.create_views import (- create_missing_views,- should_create_missing_views,-)+from litellm.proxy.db.create_views import (create_missing_views,+ should_create_missing_views)from litellm.proxy.db.db_spend_update_writer import DBSpendUpdateWriterfrom litellm.proxy.db.exception_handler import PrismaDBExceptionHandlerfrom litellm.proxy.db.log_db_metrics import log_db_metricsfrom litellm.proxy.db.prisma_client import PrismaWrapper-from litellm.proxy.guardrails.guardrail_hooks.unified_guardrail.unified_guardrail import (- UnifiedLLMGuardrails,-)+from litellm.proxy.guardrails.guardrail_hooks.unified_guardrail.unified_guardrail import \+ UnifiedLLMGuardrailsfrom litellm.proxy.hooks import PROXY_HOOKS, get_proxy_hookfrom litellm.proxy.hooks.cache_control_check import _PROXY_CacheControlCheckfrom litellm.proxy.hooks.max_budget_limiter import _PROXY_MaxBudgetLimiter-from litellm.proxy.hooks.parallel_request_limiter import (- _PROXY_MaxParallelRequestsHandler,-)+from litellm.proxy.hooks.parallel_request_limiter import \+ _PROXY_MaxParallelRequestsHandlerfrom litellm.proxy.litellm_pre_call_utils import LiteLLMProxyRequestSetupfrom litellm.proxy.policy_engine.pipeline_executor import PipelineExecutorfrom litellm.secret_managers.main import str_to_boolfrom litellm.types.integrations.slack_alerting import DEFAULT_ALERT_TYPES-from litellm.types.mcp import (- MCPDuringCallResponseObject,- MCPPreCallRequestObject,- MCPPreCallResponseObject,-)-from litellm.types.proxy.policy_engine.pipeline_types import PipelineExecutionResult+from litellm.types.mcp import (MCPDuringCallResponseObject,+ MCPPreCallRequestObject,+ MCPPreCallResponseObject)+from litellm.types.proxy.policy_engine.pipeline_types import \+ PipelineExecutionResultfrom litellm.types.utils import LLMResponseTypes, LoggedLiteLLMParamsif TYPE_CHECKING:from opentelemetry.trace import Span as _Span- from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+ from litellm.litellm_core_utils.litellm_logging import \+ Logging as LiteLLMLoggingObjSpan = Union[_Span, Any]else:@@ -1070,10 +1048,9 @@ class ProxyLogging:"""Process prompt template if applicable."""from litellm.proxy.prompts.prompt_endpoints import (- construct_versioned_prompt_id,- get_latest_version_prompt_id,- )- from litellm.proxy.prompts.prompt_registry import IN_MEMORY_PROMPT_REGISTRY+ construct_versioned_prompt_id, get_latest_version_prompt_id)+ from litellm.proxy.prompts.prompt_registry import \+ IN_MEMORY_PROMPT_REGISTRYfrom litellm.utils import get_non_default_completion_paramsif prompt_version is None:@@ -1123,9 +1100,8 @@ class ProxyLogging:def _process_guardrail_metadata(self, data: dict) -> None:"""Process guardrails from metadata and add to applied_guardrails."""- from litellm.proxy.common_utils.callback_utils import (- add_guardrail_to_applied_guardrails_header,- )+ from litellm.proxy.common_utils.callback_utils import \+ add_guardrail_to_applied_guardrails_headermetadata_standard = data.get("metadata") or {}metadata_litellm = data.get("litellm_metadata") or {}@@ -2022,7 +1998,8 @@ class ProxyLogging:if isinstance(response, (ModelResponse, ModelResponseStream)):response_str = litellm.get_response_string(response_obj=response)elif isinstance(response, dict) and self.is_a2a_streaming_response(response):- from litellm.llms.a2a.common_utils import extract_text_from_a2a_response+ from litellm.llms.a2a.common_utils import \+ extract_text_from_a2a_responseresponse_str = extract_text_from_a2a_response(response)if response_str is not None:@@ -2031,7 +2008,8 @@ class ProxyLogging:_callback: Optional[CustomLogger] = Noneif isinstance(callback, CustomGuardrail):# Main - V2 Guardrails implementation- from litellm.types.guardrails import GuardrailEventHooks+ from litellm.types.guardrails import \+ GuardrailEventHooks## CHECK FOR MODEL-LEVEL GUARDRAILSmodified_data = _check_and_merge_model_level_guardrails(@@ -4166,20 +4144,24 @@ class ProxyUpdateSpend:prisma_client: PrismaClient,db_writer_client: Optional[AsyncHTTPHandler],proxy_logging_obj: ProxyLogging,+ logs_to_process: Optional[List[Dict[str, Any]]] = None,):BATCH_SIZE = 1000 # Preferred size of each batch to write to the databaseMAX_LOGS_PER_INTERVAL = (10000 # Maximum number of logs to flush in a single interval)- # Atomically read and remove logs to process (protected by lock)- async with prisma_client._spend_log_transactions_lock:- logs_to_process = prisma_client.spend_log_transactions[- :MAX_LOGS_PER_INTERVAL- ]- # Remove the logs we're about to process- prisma_client.spend_log_transactions = prisma_client.spend_log_transactions[- len(logs_to_process) :- ]+ popped_batch = False+ if logs_to_process is None:+ # Atomically read and remove logs to process (protected by lock)+ async with prisma_client._spend_log_transactions_lock:+ logs_to_process = prisma_client.spend_log_transactions[+ :MAX_LOGS_PER_INTERVAL+ ]+ # Remove the logs we're about to process+ prisma_client.spend_log_transactions = prisma_client.spend_log_transactions[+ len(logs_to_process) :+ ]+ popped_batch = Truestart_time = time.time()try:for i in range(n_retry_times + 1):@@ -4239,8 +4221,9 @@ class ProxyUpdateSpend:e=e, start_time=start_time, proxy_logging_obj=proxy_logging_obj)finally:- # Clean up logs_to_process after all processing is complete- del logs_to_process+ # Clean up logs_to_process only if we popped it (caller-owned otherwise)+ if popped_batch:+ del logs_to_process@staticmethoddef disable_spend_updates() -> bool:@@ -4306,24 +4289,47 @@ async def update_spend_logs_job(Job to process spend_log_transactions queue.This job is triggered based on queue size rather than time.- Processes spend log transactions when the queue reaches a threshold.+ Pops the batch once, writes spend logs, then runs guardrail usage tracking."""n_retry_times = 3+ MAX_LOGS_PER_INTERVAL = 10000- # Check queue size with lock protection+ # Atomically pop batch from queueasync with prisma_client._spend_log_transactions_lock:queue_size = len(prisma_client.spend_log_transactions)-if queue_size == 0:return+ async with prisma_client._spend_log_transactions_lock:+ logs_to_process = prisma_client.spend_log_transactions[+ :MAX_LOGS_PER_INTERVAL+ ]+ prisma_client.spend_log_transactions = prisma_client.spend_log_transactions[+ len(logs_to_process) :+ ]+await ProxyUpdateSpend.update_spend_logs(n_retry_times=n_retry_times,prisma_client=prisma_client,proxy_logging_obj=proxy_logging_obj,db_writer_client=db_writer_client,+ logs_to_process=logs_to_process,)+ # Guardrail/policy usage tracking (same batch, outside spend-logs update)+ try:+ from litellm.proxy.guardrails.usage_tracking import \+ process_spend_logs_guardrail_usage+ await process_spend_logs_guardrail_usage(+ prisma_client=prisma_client,+ logs_to_process=logs_to_process,+ )+ except Exception as guardrail_tracking_err:+ verbose_proxy_logger.debug(+ "Guardrail usage tracking failed (non-fatal): %s",+ guardrail_tracking_err,+ )+async def _monitor_spend_logs_queue(prisma_client: PrismaClient,@@ -4339,10 +4345,8 @@ async def _monitor_spend_logs_queue(db_writer_client: Optional HTTP handler for external spend logs endpointproxy_logging_obj: Proxy logging object"""- from litellm.constants import (- SPEND_LOG_QUEUE_POLL_INTERVAL,- SPEND_LOG_QUEUE_SIZE_THRESHOLD,- )+ from litellm.constants import (SPEND_LOG_QUEUE_POLL_INTERVAL,+ SPEND_LOG_QUEUE_SIZE_THRESHOLD)threshold = SPEND_LOG_QUEUE_SIZE_THRESHOLDbase_interval = SPEND_LOG_QUEUE_POLL_INTERVAL@@ -4863,12 +4867,11 @@ async def get_available_models_for_user(List of model names available to the user"""from litellm.proxy.auth.auth_checks import get_team_object- from litellm.proxy.auth.model_checks import (- get_complete_model_list,- get_key_models,- get_team_models,- )- from litellm.proxy.management_endpoints.team_endpoints import validate_membership+ from litellm.proxy.auth.model_checks import (get_complete_model_list,+ get_key_models,+ get_team_models)+ from litellm.proxy.management_endpoints.team_endpoints import \+ validate_membership# Get proxy model list and access groupsif llm_router is None:diff --git a/schema.prisma b/schema.prismaindex 4128ab5f23e..3ef88e18b0d 100644--- a/schema.prisma+++ b/schema.prisma@@ -866,6 +866,54 @@ model LiteLLM_GuardrailsTable {updated_at DateTime @updatedAt}+// Daily guardrail metrics for usage dashboard (one row per guardrail per day)+model LiteLLM_DailyGuardrailMetrics {+ guardrail_id String // logical id; may not FK if guardrail from config+ date String // YYYY-MM-DD+ requests_evaluated BigInt @default(0)+ passed_count BigInt @default(0)+ blocked_count BigInt @default(0)+ flagged_count BigInt @default(0)+ avg_score Float?+ avg_latency_ms Float?+ created_at DateTime @default(now())+ updated_at DateTime @updatedAt++ @@id([guardrail_id, date])+ @@index([date])+ @@index([guardrail_id])+}++// Daily policy metrics for usage dashboard (one row per policy per day)+model LiteLLM_DailyPolicyMetrics {+ policy_id String+ date String // YYYY-MM-DD+ requests_evaluated BigInt @default(0)+ passed_count BigInt @default(0)+ blocked_count BigInt @default(0)+ flagged_count BigInt @default(0)+ avg_score Float?+ avg_latency_ms Float?+ created_at DateTime @default(now())+ updated_at DateTime @updatedAt++ @@id([policy_id, date])+ @@index([date])+ @@index([policy_id])+}++// Index for fast "last N logs for guardrail/policy" from SpendLogs+model LiteLLM_SpendLogGuardrailIndex {+ request_id String+ guardrail_id String+ policy_id String? // set when run as part of a policy pipeline+ start_time DateTime++ @@id([request_id, guardrail_id])+ @@index([guardrail_id, start_time])+ @@index([policy_id, start_time])+}+// Prompt table for storing prompt configurationsmodel LiteLLM_PromptTable {id String @id @default(uuid())diff --git a/ui/litellm-dashboard/src/app/page.tsx b/ui/litellm-dashboard/src/app/page.tsxindex ae3bd76e3cf..fb749d7afb0 100644--- a/ui/litellm-dashboard/src/app/page.tsx+++ b/ui/litellm-dashboard/src/app/page.tsx@@ -13,6 +13,7 @@ import { fetchTeams } from "@/components/common_components/fetch_teams";import LoadingScreen from "@/components/common_components/LoadingScreen";import { CostTrackingSettings } from "@/components/CostTrackingSettings";import GeneralSettings from "@/components/general_settings";+import GuardrailsMonitorView from "@/components/GuardrailsMonitor/GuardrailsMonitorView";import GuardrailsPanel from "@/components/guardrails";import PoliciesPanel from "@/components/policies";import { Team } from "@/components/key_team_helpers/key_list";@@ -547,6 +548,8 @@ function CreateKeyPageContent() {<AccessGroupsPage />) : page == "vector-stores" ? (<VectorStoreManagement accessToken={accessToken} userRole={userRole} userID={userID} />+ ) : page == "guardrails-monitor" ? (+ <GuardrailsMonitorView accessToken={accessToken} />) : page == "new_usage" ? (<NewUsagePageteams={(teams as Team[]) ?? []}diff --git a/ui/litellm-dashboard/src/components/GuardrailsMonitor/EvaluationSettingsModal.tsx b/ui/litellm-dashboard/src/components/GuardrailsMonitor/EvaluationSettingsModal.tsxnew file mode 100644index 00000000000..f502d2a8a30--- /dev/null+++ b/ui/litellm-dashboard/src/components/GuardrailsMonitor/EvaluationSettingsModal.tsx@@ -0,0 +1,157 @@+import { CloseOutlined, PlayCircleOutlined } from "@ant-design/icons";+import { Button, Modal, Select, Input } from "antd";+import React, { useEffect, useState } from "react";+import { fetchAvailableModels, type ModelGroup } from "@/components/playground/llm_calls/fetch_models";++const DEFAULT_PROMPT = `Evaluate whether this guardrail's decision was correct.+Analyze the user input, the guardrail action taken, and determine if it was appropriate.++Consider:+— Was the user's intent genuinely harmful or policy-violating?+— Was the guardrail's action (block / flag / pass) appropriate?+— Could this be a false positive or false negative?++Return a structured verdict with confidence and justification.`;++const DEFAULT_SCHEMA = `{+ "verdict": "correct" | "false_positive" | "false_negative",+ "confidence": 0.0,+ "justification": "string",+ "risk_category": "string",+ "suggested_action": "keep" | "adjust threshold" | "add allowlist"+}+`;++export interface EvaluationSettingsModalProps {+ open: boolean;+ onClose: () => void;+ guardrailName?: string;+ accessToken: string | null;+ onRunEvaluation?: (settings: { prompt: string; schema: string; model: string }) => void;+}++export function EvaluationSettingsModal({+ open,+ onClose,+ guardrailName,+ accessToken,+ onRunEvaluation,+}: EvaluationSettingsModalProps) {+ const [prompt, setPrompt] = useState(DEFAULT_PROMPT);+ const [schema, setSchema] = useState(DEFAULT_SCHEMA);+ const [model, setModel] = useState<string | null>(null);+ const [modelOptions, setModelOptions] = useState<ModelGroup[]>([]);+ const [loadingModels, setLoadingModels] = useState(false);++ useEffect(() => {+ if (!open || !accessToken) {+ setModelOptions([]);+ return;+ }+ let cancelled = false;+ setLoadingModels(true);+ fetchAvailableModels(accessToken)+ .then((list) => {+ if (!cancelled) setModelOptions(list);+ })+ .catch(() => {+ if (!cancelled) setModelOptions([]);+ })+ .finally(() => {+ if (!cancelled) setLoadingModels(false);+ });+ return () => {+ cancelled = true;+ };+ }, [open, accessToken]);++ const handleResetPrompt = () => setPrompt(DEFAULT_PROMPT);+ const handleRun = () => {+ if (model) {+ onRunEvaluation?.({ prompt, schema, model });+ onClose();+ }+ };++ const modelSelectOptions = modelOptions.map((m) => ({+ value: m.model_group,+ label: m.model_group,+ }));++ return (+ <Modal+ title="Evaluation Settings"+ open={open}+ onCancel={onClose}+ width={640}+ footer={null}+ closeIcon={<CloseOutlined />}+ destroyOnClose+ >+ <p className="text-sm text-gray-500 mb-4">+ {guardrailName+ ? `Configure AI evaluation for ${guardrailName}`+ : "Configure AI evaluation for re-running on logs"}+ </p>++ <div className="space-y-4">+ <div>+ <div className="flex items-center justify-between mb-1.5">+ <label className="text-sm font-medium text-gray-700">Evaluation Prompt</label>+ <button+ type="button"+ onClick={handleResetPrompt}+ className="text-xs text-indigo-600 hover:text-indigo-700"+ >+ Reset to default+ </button>+ </div>+ <Input.TextArea+ value={prompt}+ onChange={(e) => setPrompt(e.target.value)}+ rows={6}+ className="font-mono text-sm"+ />+ <p className="text-xs text-gray-400 mt-1">+ System prompt sent to the evaluation model. Output is structured via response_format.+ </p>+ </div>++ <div>+ <label className="block text-sm font-medium text-gray-700 mb-1.5">+ Response Schema+ </label>+ <p className="text-xs text-gray-400 mb-1">response_format: json_schema</p>+ <Input.TextArea+ value={schema}+ onChange={(e) => setSchema(e.target.value)}+ rows={6}+ className="font-mono text-sm"+ />+ </div>++ <div>+ <label className="block text-sm font-medium text-gray-700 mb-1.5">Model</label>+ <Select+ placeholder={loadingModels ? "Loading models…" : "Select a model"}+ value={model ?? undefined}+ onChange={setModel}+ options={modelSelectOptions}+ style={{ width: "100%" }}+ showSearch+ optionFilterProp="label"+ loading={loadingModels}+ notFoundContent={!accessToken ? "Sign in to see models" : "No models available"}+ />+ </div>+ </div>++ <div className="flex items-center justify-end gap-2 mt-6 pt-4 border-t border-gray-100">+ <Button onClick={onClose}>Cancel</Button>+ <Button type="primary" icon={<PlayCircleOutlined />} onClick={handleRun} disabled={!model}>+ Run Evaluation+ </Button>+ </div>+ </Modal>+ );+}diff --git a/ui/litellm-dashboard/src/components/GuardrailsMonitor/GuardrailConfig.tsx b/ui/litellm-dashboard/src/components/GuardrailsMonitor/GuardrailConfig.tsxnew file mode 100644index 00000000000..3d0aa51b48b--- /dev/null+++ b/ui/litellm-dashboard/src/components/GuardrailsMonitor/GuardrailConfig.tsx@@ -0,0 +1,217 @@+import {+ CheckCircleOutlined,+ CodeOutlined,+ PlayCircleOutlined,+ RollbackOutlined,+ SaveOutlined,+} from "@ant-design/icons";+import { Button, Input, Select, Switch } from "antd";+import React, { useState } from "react";++interface GuardrailConfigProps {+ guardrailName: string;+ guardrailType: string;+ provider: string;+}++const versions = [+ { id: "v3", label: "v3 (current)", date: "2026-02-18", author: "[email protected]", changes: "Adjusted sensitivity for medical terms" },+ { id: "v2", label: "v2", date: "2026-02-10", author: "[email protected]", changes: "Added custom categories list" },+ { id: "v1", label: "v1", date: "2026-01-28", author: "[email protected]", changes: "Initial configuration" },+];++export function GuardrailConfig({+ guardrailName,+ guardrailType,+ provider,+}: GuardrailConfigProps) {+ const [action, setAction] = useState("block");+ const [enabled, setEnabled] = useState(true);+ const [customCode, setCustomCode] = useState("");+ const [useCustomCode, setUseCustomCode] = useState(false);+ const [rerunStatus, setRerunStatus] = useState<"idle" | "running" | "success" | "error">("idle");+ const [version, setVersion] = useState("v3");+ const [showVersionHistory, setShowVersionHistory] = useState(false);++ const handleRerun = () => {+ setRerunStatus("running");+ setTimeout(() => {+ setRerunStatus("success");+ setTimeout(() => setRerunStatus("idle"), 3000);+ }, 2000);+ };++ return (+ <div className="space-y-6">+ {/* Version Bar */}+ <div className="bg-white border border-gray-200 rounded-lg p-4">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-3">+ <span className="text-sm font-medium text-gray-700">Version:</span>+ <Select+ value={version}+ onChange={setVersion}+ options={versions.map((v) => ({ value: v.id, label: v.label }))}+ style={{ width: 140 }}+ />+ <Button type="link" size="small" onClick={() => setShowVersionHistory(!showVersionHistory)}>+ {showVersionHistory ? "Hide history" : "View history"}+ </Button>+ </div>+ <div className="flex items-center gap-2">+ <Button icon={<RollbackOutlined />}>Revert</Button>+ <Button type="primary" icon={<SaveOutlined />}>+ Save as v{parseInt(version.replace("v", ""), 10) + 1}+ </Button>+ </div>+ </div>++ {showVersionHistory && (+ <div className="mt-4 border-t border-gray-100 pt-4 space-y-2">+ {versions.map((v) => (+ <div+ key={v.id}+ className={`flex items-center justify-between p-2.5 rounded-md text-sm ${+ v.id === version ? "bg-blue-50 border border-blue-200" : "bg-gray-50"+ }`}+ >+ <div className="flex items-center gap-3">+ <span className={`font-mono text-xs font-medium ${v.id === version ? "text-blue-600" : "text-gray-500"}`}>+ {v.id}+ </span>+ <span className="text-gray-700">{v.changes}</span>+ </div>+ <div className="flex items-center gap-3 text-xs text-gray-500">+ <span>{v.author}</span>+ <span>{v.date}</span>+ </div>+ </div>+ ))}+ </div>+ )}+ </div>++ {/* Parameters */}+ <div className="bg-white border border-gray-200 rounded-lg p-6">+ <h3 className="text-base font-semibold text-gray-900 mb-1">Parameters</h3>+ <p className="text-xs text-gray-500 mb-5">Configure {guardrailName} behavior</p>++ <div className="grid grid-cols-1 md:grid-cols-2 gap-6">+ <div>+ <label className="block text-sm font-medium text-gray-700 mb-1.5">Action on Failure</label>+ <Select+ value={action}+ onChange={setAction}+ style={{ width: "100%" }}+ options={[+ { value: "block", label: "Block Request" },+ { value: "flag", label: "Flag for Review" },+ { value: "log", label: "Log Only" },+ { value: "fallback", label: "Use Fallback Response" },+ ]}+ />+ </div>++ <div>+ <label className="block text-sm font-medium text-gray-700 mb-1.5">Provider</label>+ <Select+ style={{ width: "100%" }}+ defaultValue={provider}+ options={[+ { value: "bedrock", label: "AWS Bedrock Guardrails" },+ { value: "google", label: "Google Cloud AI Safety" },+ { value: "litellm", label: "LiteLLM Built-in" },+ { value: "custom", label: "Custom Code" },+ ]}+ />+ </div>++ <div>+ <label className="block text-sm font-medium text-gray-700 mb-1.5">Guardrail Type</label>+ <Select+ style={{ width: "100%" }}+ defaultValue={guardrailType}+ options={[+ { value: "Content Safety", label: "Content Safety" },+ { value: "PII", label: "PII Detection" },+ { value: "Topic", label: "Topic Restriction" },+ { value: "prompt_injection", label: "Prompt Injection" },+ { value: "custom", label: "Custom" },+ ]}+ />+ </div>++ <div className="md:col-span-2">+ <label className="block text-sm font-medium text-gray-700 mb-1.5">Categories (comma-separated)</label>+ <Input defaultValue="violence, hate_speech, sexual_content, self_harm, illegal_activity" />+ </div>++ <div className="md:col-span-2 flex items-center gap-3">+ <Switch checked={enabled} onChange={setEnabled} />+ <span className="text-sm text-gray-700">Guardrail enabled in production</span>+ </div>+ </div>+ </div>++ {/* Custom Code Override */}+ <div className="bg-white border border-gray-200 rounded-lg p-6">+ <div className="flex items-center justify-between mb-4">+ <div>+ <h3 className="text-base font-semibold text-gray-900 flex items-center gap-2">+ <CodeOutlined className="text-gray-500" />+ Custom Code Override+ </h3>+ <p className="text-xs text-gray-500 mt-0.5">+ Replace the built-in guardrail with custom evaluation code+ </p>+ </div>+ <Switch checked={useCustomCode} onChange={setUseCustomCode} />+ </div>++ {useCustomCode && (+ <Input.TextArea+ value={customCode}+ onChange={(e) => setCustomCode(e.target.value)}+ placeholder={`async def evaluate(input_text: str, context: dict) -> dict:+ # Return {"score": 0.0-1.0, "passed": bool, "reason": str}+ # Example:+ if "banned_word" in input_text.lower():+ return {"score": 0.1, "passed": False, "reason": "Banned word detected"}+ return {"score": 0.9, "passed": True, "reason": "No violations"}`}+ rows={10}+ className="font-mono text-sm"+ />+ )}+ </div>++ {/* Re-run on Failing Logs */}+ <div className="bg-white border border-gray-200 rounded-lg p-6">+ <h3 className="text-base font-semibold text-gray-900 mb-1">Test Configuration</h3>+ <p className="text-xs text-gray-500 mb-4">+ Re-run this guardrail on recent failing logs to validate your changes+ </p>++ <div className="flex items-center gap-3">+ <Button+ type="primary"+ icon={rerunStatus === "running" ? undefined : <PlayCircleOutlined />}+ loading={rerunStatus === "running"}+ onClick={handleRerun}+ >+ {rerunStatus === "running" ? "Running on 10 samples..." : "Re-run on failing logs"}+ </Button>++ {rerunStatus === "success" && (+ <span className="text-sm text-green-600 flex items-center gap-2">+ <CheckCircleOutlined /> 7/10 would now pass with new config+ </span>+ )}++ {rerunStatus === "error" && (+ <span className="text-sm text-red-600">Error running tests</span>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/ui/litellm-dashboard/src/components/GuardrailsMonitor/GuardrailDetail.tsx b/ui/litellm-dashboard/src/components/GuardrailsMonitor/GuardrailDetail.tsxnew file mode 100644index 00000000000..9724050276d--- /dev/null+++ b/ui/litellm-dashboard/src/components/GuardrailsMonitor/GuardrailDetail.tsx@@ -0,0 +1,301 @@+import {+ ArrowLeftOutlined,+ BellOutlined,+ PlayCircleOutlined,+ SafetyOutlined,+ SettingOutlined,+ WarningOutlined,+} from "@ant-design/icons";+import { useQuery } from "@tanstack/react-query";+import { Card, Col, Grid, Title } from "@tremor/react";+import { Button, Spin, Tabs } from "antd";+import React, { useMemo, useState } from "react";+import {+ formatDate,+ getGuardrailsUsageDetail,+ getGuardrailsUsageLogs,+} from "@/components/networking";+import { EvaluationSettingsModal } from "./EvaluationSettingsModal";+import { LogViewer } from "./LogViewer";+import { MetricCard } from "./MetricCard";+import type { LogEntry } from "./mockData";++interface GuardrailDetailProps {+ guardrailId: string;+ onBack: () => void;+ accessToken?: string | null;+}++const statusColors: Record<+ string,+ { bg: string; text: string; dot: string }+> = {+ healthy: { bg: "bg-green-50", text: "text-green-700", dot: "bg-green-500" },+ warning: { bg: "bg-amber-50", text: "text-amber-700", dot: "bg-amber-500" },+ critical: { bg: "bg-red-50", text: "text-red-700", dot: "bg-red-500" },+};++const defaultEnd = new Date();+const defaultStart = new Date();+defaultStart.setDate(defaultStart.getDate() - 7);++export function GuardrailDetail({+ guardrailId,+ onBack,+ accessToken = null,+}: GuardrailDetailProps) {+ const [activeTab, setActiveTab] = useState("overview");+ const [evaluationModalOpen, setEvaluationModalOpen] = useState(false);+ const [startDate] = useState(() => formatDate(defaultStart));+ const [endDate] = useState(() => formatDate(defaultEnd));+ const [logsPage, setLogsPage] = useState(1);+ const logsPageSize = 50;++ const { data: detailData, isLoading: detailLoading, error: detailError } = useQuery({+ queryKey: ["guardrails-usage-detail", guardrailId, startDate, endDate],+ queryFn: () => getGuardrailsUsageDetail(accessToken!, guardrailId, startDate, endDate),+ enabled: !!accessToken && !!guardrailId,+ });+ const { data: logsData, isLoading: logsLoading } = useQuery({+ queryKey: ["guardrails-usage-logs", guardrailId, logsPage, logsPageSize],+ queryFn: () =>+ getGuardrailsUsageLogs(accessToken!, {+ guardrailId,+ page: logsPage,+ pageSize: logsPageSize,+ startDate,+ endDate,+ }),+ enabled: !!accessToken && !!guardrailId,+ });++ const logs: LogEntry[] = useMemo(() => {+ const list = logsData?.logs ?? [];+ return list.map((l: Record<string, unknown>) => ({+ id: l.id as string,+ timestamp: l.timestamp as string,+ action: l.action as "blocked" | "passed" | "flagged",+ score: l.score as number | undefined,+ model: l.model as string | undefined,+ input_snippet: l.input_snippet as string | undefined,+ output_snippet: l.output_snippet as string | undefined,+ reason: l.reason as string | undefined,+ }));+ }, [logsData?.logs]);++ const data = detailData+ ? {+ name: detailData.guardrail_name,+ description: detailData.description ?? "",+ status: detailData.status,+ provider: detailData.provider,+ type: detailData.type,+ requestsEvaluated: detailData.requestsEvaluated,+ failRate: detailData.failRate,+ avgScore: detailData.avgScore,+ avgLatency: detailData.avgLatency,+ }+ : {+ name: guardrailId,+ description: "",+ status: "healthy",+ provider: "—",+ type: "—",+ requestsEvaluated: 0,+ failRate: 0,+ avgScore: undefined as number | undefined,+ avgLatency: undefined as number | undefined,+ };+ const statusStyle = statusColors[data.status] ?? statusColors.healthy;++ if (detailLoading && !detailData) {+ return (+ <div className="flex items-center justify-center py-12">+ <Spin size="large" />+ </div>+ );+ }+ if (detailError && !detailData) {+ return (+ <div>+ <Button type="link" icon={<ArrowLeftOutlined />} onClick={onBack} className="pl-0 mb-4">+ Back to Overview+ </Button>+ <p className="text-red-600">Failed to load guardrail details.</p>+ </div>+ );+ }++ return (+ <div>+ <div className="mb-6">+ <Button+ type="link"+ icon={<ArrowLeftOutlined />}+ onClick={onBack}+ className="pl-0 mb-4"+ >+ Back to Overview+ </Button>++ <div className="flex items-start justify-between">+ <div>+ <div className="flex items-center gap-3 mb-1">+ <SafetyOutlined className="text-xl text-gray-400" />+ <h1 className="text-xl font-semibold text-gray-900">{data.name}</h1>+ <span+ className={`inline-flex items-center gap-1.5 px-2.5 py-0.5 text-xs font-medium rounded-full ${statusStyle.bg} ${statusStyle.text}`}+ >+ <span className={`w-1.5 h-1.5 rounded-full ${statusStyle.dot}`} />+ {data.status.charAt(0).toUpperCase() + data.status.slice(1)}+ </span>+ </div>+ <p className="text-sm text-gray-500 ml-8">{data.description}</p>+ </div>+ <div className="flex items-center gap-2">+ <span className="inline-flex items-center px-2.5 py-1 text-xs font-medium rounded-md bg-indigo-50 text-indigo-700 border border-indigo-200">+ {data.provider}+ </span>+ <Button type="default" icon={<PlayCircleOutlined />} title="Coming soon">+ Re-run AI+ </Button>+ <Button+ type="default"+ icon={<SettingOutlined />}+ onClick={() => setEvaluationModalOpen(true)}+ title="Evaluation settings"+ />+ <Button+ type="default"+ icon={<BellOutlined />}+ title="Coming soon"+ className="opacity-75"+ >+ Notify+ </Button>+ </div>+ </div>+ </div>++ <Tabs+ activeKey={activeTab}+ onChange={setActiveTab}+ items={[+ { key: "overview", label: "Overview" },+ { key: "logs", label: "Logs" },+ ]}+ />++ {activeTab === "overview" && (+ <div className="space-y-6 mt-4">+ <Grid numItems={2} numItemsMd={5} className="gap-4">+ <Col>+ <MetricCard label="Requests Evaluated" value={data.requestsEvaluated.toLocaleString()} />+ </Col>+ <Col>+ <MetricCard+ label="Fail Rate"+ value={`${data.failRate}%`}+ valueColor={+ data.failRate > 15 ? "text-red-600" : data.failRate > 5 ? "text-amber-600" : "text-green-600"+ }+ subtitle={`${Math.round((data.requestsEvaluated * data.failRate) / 100).toLocaleString()} blocked`}+ icon={data.failRate > 15 ? <WarningOutlined className="text-red-400" /> : undefined}+ />+ </Col>+ <Col>+ <MetricCard+ label="Avg. latency added"+ value={+ data.avgLatency != null ? `${Math.round(data.avgLatency)}ms` : "—"+ }+ valueColor={+ data.avgLatency != null+ ? data.avgLatency > 150+ ? "text-red-600"+ : data.avgLatency > 50+ ? "text-amber-600"+ : "text-green-600"+ : "text-gray-500"+ }+ subtitle={data.avgLatency != null ? "Per request (avg)" : "No data"}+ />+ </Col>+ </Grid>++ <Card className="bg-white border border-gray-200 rounded-lg p-6">+ <Title className="text-base font-semibold text-gray-900 mb-1">+ Root Cause Analysis+ </Title>+ <p className="text-xs text-gray-500 mb-4">Common patterns in failing requests</p>+ <div className="space-y-3">+ <div className="flex items-start gap-3 p-3 bg-red-50 rounded-lg border border-red-100">+ <WarningOutlined className="text-red-500 mt-0.5 flex-shrink-0" />+ <div>+ <p className="text-sm font-medium text-red-800">+ High sensitivity to medical terminology+ </p>+ <p className="text-xs text-red-600 mt-0.5">+ 34% of blocked requests contain common medical terms (e.g., "symptoms",+ "treatment", "medication") that are benign in context.+ Consider adding an allowlist or relaxing sensitivity for these categories.+ </p>+ </div>+ </div>+ <div className="flex items-start gap-3 p-3 bg-amber-50 rounded-lg border border-amber-100">+ <WarningOutlined className="text-amber-500 mt-0.5 flex-shrink-0" />+ <div>+ <p className="text-sm font-medium text-amber-800">+ False positives on educational content+ </p>+ <p className="text-xs text-amber-600 mt-0.5">+ 22% of blocked requests are educational queries about safety topics. The guardrail+ is flagging the topic itself rather than harmful intent.+ </p>+ </div>+ </div>+ <div className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg border border-gray-200">+ <WarningOutlined className="text-gray-400 mt-0.5 flex-shrink-0" />+ <div>+ <p className="text-sm font-medium text-gray-800">+ Sensitivity may be too aggressive+ </p>+ <p className="text-xs text-gray-600 mt-0.5">+ Many blocked requests may be false positives. Consider relaxing sensitivity or+ adding allowlisted patterns to reduce blocks by ~40% while maintaining safety.+ </p>+ </div>+ </div>+ </div>+ </Card>++ <LogViewer+ guardrailName={data.name}+ filterAction="blocked"+ logs={logs}+ logsLoading={logsLoading}+ totalLogs={logsData?.total ?? 0}+ />+ </div>+ )}++ {activeTab === "logs" && (+ <div className="mt-4">+ <LogViewer+ guardrailName={data.name}+ logs={logs}+ logsLoading={logsLoading}+ totalLogs={logsData?.total ?? 0}+ />+ </div>+ )}++ <EvaluationSettingsModal+ open={evaluationModalOpen}+ onClose={() => setEvaluationModalOpen(false)}+ guardrailName={data.name}+ accessToken={accessToken}+ />+ </div>+ );+}diff --git a/ui/litellm-dashboard/src/components/GuardrailsMonitor/GuardrailsMonitorView.test.tsx b/ui/litellm-dashboard/src/components/GuardrailsMonitor/GuardrailsMonitorView.test.tsxnew file mode 100644index 00000000000..be2bc7f3e48--- /dev/null+++ b/ui/litellm-dashboard/src/components/GuardrailsMonitor/GuardrailsMonitorView.test.tsx@@ -0,0 +1,62 @@+import { render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { describe, expect, it, vi } from "vitest";+import GuardrailsMonitorView from "./GuardrailsMonitorView";+import * as networking from "@/components/networking";++vi.mock("@/components/networking", () => ({+ getGuardrailsUsageOverview: vi.fn(),+ getPoliciesUsageOverview: vi.fn(),+ formatDate: vi.fn((d: Date) => d.toISOString().slice(0, 10)),+}));++const mockGetGuardrailsUsageOverview = vi.mocked(networking.getGuardrailsUsageOverview);+const mockGetPoliciesUsageOverview = vi.mocked(networking.getPoliciesUsageOverview);++function wrapper({ children }: { children: React.ReactNode }) {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ },+ });+ return (+ <QueryClientProvider client={queryClient}>+ {children}+ </QueryClientProvider>+ );+}++describe("GuardrailsMonitorView", () => {+ it("should render overview and fetch guardrails and policies usage when accessToken is provided", async () => {+ mockGetGuardrailsUsageOverview.mockResolvedValue({+ rows: [],+ chart: [],+ totalRequests: 0,+ totalBlocked: 0,+ passRate: 100,+ });+ mockGetPoliciesUsageOverview.mockResolvedValue({+ rows: [],+ chart: [],+ totalRequests: 0,+ totalBlocked: 0,+ passRate: 100,+ });++ render(+ <GuardrailsMonitorView accessToken="test-token" />,+ { wrapper }+ );++ expect(await screen.findByRole("heading", { name: /Guardrails Monitor/i })).toBeDefined();+ await waitFor(() => {+ expect(mockGetGuardrailsUsageOverview).toHaveBeenCalled();+ expect(mockGetPoliciesUsageOverview).toHaveBeenCalled();+ });+ });++ it("should render without crashing when accessToken is null", async () => {+ render(<GuardrailsMonitorView accessToken={null} />, { wrapper });+ expect(await screen.findByRole("heading", { name: /Guardrails Monitor/i })).toBeDefined();+ });+});diff --git a/ui/litellm-dashboard/src/components/GuardrailsMonitor/GuardrailsMonitorView.tsx b/ui/litellm-dashboard/src/components/GuardrailsMonitor/GuardrailsMonitorView.tsxnew file mode 100644index 00000000000..7cc2074e468--- /dev/null+++ b/ui/litellm-dashboard/src/components/GuardrailsMonitor/GuardrailsMonitorView.tsx@@ -0,0 +1,37 @@+import React, { useState } from "react";+import { GuardrailsOverview } from "./GuardrailsOverview";+import { GuardrailDetail } from "./GuardrailDetail";++type View =+ | { type: "overview" }+ | { type: "detail"; guardrailId: string };++interface GuardrailsMonitorViewProps {+ accessToken?: string | null;+}++export default function GuardrailsMonitorView({ accessToken = null }: GuardrailsMonitorViewProps) {+ const [view, setView] = useState<View>({ type: "overview" });++ const handleSelectGuardrail = (id: string) => {+ setView({ type: "detail", guardrailId: id });+ };++ const handleBack = () => {+ setView({ type: "overview" });+ };++ return (+ <div className="p-6 w-full min-w-0 flex-1">+ {view.type === "overview" ? (+ <GuardrailsOverview accessToken={accessToken} onSelectGuardrail={handleSelectGuardrail} />+ ) : (+ <GuardrailDetail+ guardrailId={view.guardrailId}+ onBack={handleBack}+ accessToken={accessToken}+ />+ )}+ </div>+ );+}diff --git a/ui/litellm-dashboard/src/components/GuardrailsMonitor/GuardrailsOverview.tsx b/ui/litellm-dashboard/src/components/GuardrailsMonitor/GuardrailsOverview.tsxnew file mode 100644index 00000000000..6aef6a9e0ad--- /dev/null+++ b/ui/litellm-dashboard/src/components/GuardrailsMonitor/GuardrailsOverview.tsx@@ -0,0 +1,395 @@+import {+ DownloadOutlined,+ FileTextOutlined,+ PlayCircleOutlined,+ RiseOutlined,+ SafetyOutlined,+ SettingOutlined,+ WarningOutlined,+} from "@ant-design/icons";+import { useQuery } from "@tanstack/react-query";+import { Card, Col, Grid, Title } from "@tremor/react";+import { Button, Spin, Table } from "antd";+import type { ColumnsType } from "antd/es/table";+import React, { useEffect, useMemo, useState } from "react";+import {+ getGuardrailsUsageOverview,+ getPoliciesUsageOverview,+} from "@/components/networking";+import { formatDate } from "@/components/networking";+import { type PerformanceRow } from "./mockData";+import { EvaluationSettingsModal } from "./EvaluationSettingsModal";+import { MetricCard } from "./MetricCard";+import { ScoreChart } from "./ScoreChart";++interface GuardrailsOverviewProps {+ accessToken?: string | null;+ onSelectGuardrail: (id: string) => void;+}++type ViewMode = "guardrails" | "policies";+type SortKey =+ | "failRate"+ | "requestsEvaluated"+ | "avgLatency"+ | "falsePositiveRate"+ | "falseNegativeRate";++const providerColors: Record<string, string> = {+ Bedrock: "bg-orange-100 text-orange-700 border-orange-200",+ "Google Cloud": "bg-sky-100 text-sky-700 border-sky-200",+ LiteLLM: "bg-indigo-100 text-indigo-700 border-indigo-200",+ Custom: "bg-gray-100 text-gray-600 border-gray-200",+};++function computeMetricsFromRows(data: PerformanceRow[]) {+ const totalRequests = data.reduce((sum, r) => sum + r.requestsEvaluated, 0);+ const totalBlocked = data.reduce(+ (sum, r) => sum + Math.round((r.requestsEvaluated * r.failRate) / 100),+ 0+ );+ const passRate =+ totalRequests > 0 ? ((1 - totalBlocked / totalRequests) * 100).toFixed(1) : "0";+ const withLat = data.filter((r) => r.avgLatency != null);+ const avgLatency =+ withLat.length > 0+ ? Math.round(withLat.reduce((sum, r) => sum + (r.avgLatency ?? 0), 0) / withLat.length)+ : 0;+ return { totalRequests, totalBlocked, passRate, avgLatency, count: data.length };+}++type RerunState = "idle" | "running" | "done";++const defaultEnd = new Date();+const defaultStart = new Date();+defaultStart.setDate(defaultStart.getDate() - 7);++export function GuardrailsOverview({+ accessToken = null,+ onSelectGuardrail,+}: GuardrailsOverviewProps) {+ const [viewMode, setViewMode] = useState<ViewMode>("guardrails");+ const [sortBy, setSortBy] = useState<SortKey>("failRate");+ const [sortDir, setSortDir] = useState<"asc" | "desc">("desc");+ const [rerunState, setRerunState] = useState<RerunState>("idle");+ const [evaluationModalOpen, setEvaluationModalOpen] = useState(false);+ const [startDate, setStartDate] = useState<string>(() => formatDate(defaultStart));+ const [endDate, setEndDate] = useState<string>(() => formatDate(defaultEnd));++ const { data: guardrailsData, isLoading: guardrailsLoading, error: guardrailsError } = useQuery({+ queryKey: ["guardrails-usage-overview", startDate, endDate],+ queryFn: () => getGuardrailsUsageOverview(accessToken!, startDate, endDate),+ enabled: !!accessToken,+ });+ const { data: policiesData, isLoading: policiesLoading, error: policiesError } = useQuery({+ queryKey: ["policies-usage-overview", startDate, endDate],+ queryFn: () => getPoliciesUsageOverview(accessToken!, startDate, endDate),+ enabled: !!accessToken,+ });++ useEffect(() => {+ if (rerunState !== "done") return;+ const t = setTimeout(() => setRerunState("idle"), 4000);+ return () => clearTimeout(t);+ }, [rerunState]);++ const activeData: PerformanceRow[] = viewMode === "guardrails"+ ? (guardrailsData?.rows ?? [])+ : (policiesData?.rows ?? []);+ const metrics = useMemo(() => {+ if (viewMode === "guardrails" && guardrailsData) {+ return {+ totalRequests: guardrailsData.totalRequests ?? 0,+ totalBlocked: guardrailsData.totalBlocked ?? 0,+ passRate: String(guardrailsData.passRate ?? 0),+ avgLatency: activeData.length ? Math.round(activeData.reduce((s, r) => s + (r.avgLatency ?? 0), 0) / activeData.length) : 0,+ count: activeData.length,+ };+ }+ if (viewMode === "policies" && policiesData) {+ return {+ totalRequests: policiesData.totalRequests ?? 0,+ totalBlocked: policiesData.totalBlocked ?? 0,+ passRate: String(policiesData.passRate ?? 0),+ avgLatency: activeData.length ? Math.round(activeData.reduce((s, r) => s + (r.avgLatency ?? 0), 0) / activeData.length) : 0,+ count: activeData.length,+ };+ }+ return computeMetricsFromRows(activeData);+ }, [viewMode, guardrailsData, policiesData, activeData]);+ const chartData = viewMode === "guardrails" ? guardrailsData?.chart : policiesData?.chart;+ const sorted = useMemo(() => {+ return [...activeData].sort((a, b) => {+ const mult = sortDir === "desc" ? -1 : 1;+ const aVal = a[sortBy] ?? 0;+ const bVal = b[sortBy] ?? 0;+ return (Number(aVal) - Number(bVal)) * mult;+ });+ }, [activeData, sortBy, sortDir]);+ const isLoading = viewMode === "guardrails" ? guardrailsLoading : policiesLoading;+ const error = viewMode === "guardrails" ? guardrailsError : policiesError;++ const isGuardrails = viewMode === "guardrails";++ const columns: ColumnsType<PerformanceRow> = [+ {+ title: isGuardrails ? "Guardrail" : "Policy",+ dataIndex: "name",+ key: "name",+ render: (name: string, row) => (+ <button+ type="button"+ className="text-sm font-medium text-gray-900 hover:text-indigo-600 text-left"+ onClick={() => onSelectGuardrail(row.id)}+ >+ {name}+ </button>+ ),+ },+ {+ title: "Provider",+ dataIndex: "provider",+ key: "provider",+ render: (provider: string) => (+ <span+ className={`inline-flex items-center px-2 py-0.5 text-xs font-medium rounded border ${+ providerColors[provider] ?? providerColors.Custom+ }`}+ >+ {provider}+ </span>+ ),+ },+ {+ title: "Requests",+ dataIndex: "requestsEvaluated",+ key: "requestsEvaluated",+ align: "right",+ sorter: true,+ sortOrder: sortBy === "requestsEvaluated" ? (sortDir === "desc" ? "descend" : "ascend") : null,+ render: (v: number) => v.toLocaleString(),+ },+ {+ title: "Fail Rate",+ dataIndex: "failRate",+ key: "failRate",+ align: "right",+ sorter: true,+ sortOrder: sortBy === "failRate" ? (sortDir === "desc" ? "descend" : "ascend") : null,+ render: (v: number, row) => (+ <span+ className={+ v > 15 ? "text-red-600" : v > 5 ? "text-amber-600" : "text-green-600"+ }+ >+ {v}%+ {row.trend === "up" && <span className="ml-1 text-xs text-red-400">↑</span>}+ {row.trend === "down" && <span className="ml-1 text-xs text-green-400">↓</span>}+ </span>+ ),+ },+ {+ title: "Avg. latency added",+ dataIndex: "avgLatency",+ key: "avgLatency",+ align: "right",+ sorter: true,+ sortOrder: sortBy === "avgLatency" ? (sortDir === "desc" ? "descend" : "ascend") : null,+ render: (v?: number) => (+ <span+ className={+ v == null ? "text-gray-400" : v > 150 ? "text-red-600" : v > 50 ? "text-amber-600" : "text-green-600"+ }+ >+ {v != null ? `${v}ms` : "—"}+ </span>+ ),+ },+ {+ title: "Status",+ dataIndex: "status",+ key: "status",+ align: "center",+ render: (status: string) => (+ <span className="inline-flex items-center gap-1.5">+ <span+ className={`w-2 h-2 rounded-full ${+ status === "healthy"+ ? "bg-green-500"+ : status === "warning"+ ? "bg-amber-500"+ : "bg-red-500"+ }`}+ />+ <span className="text-xs text-gray-600 capitalize">{status}</span>+ </span>+ ),+ },+ ];++ const sortableKeys: SortKey[] = ["failRate", "requestsEvaluated", "avgLatency"];+ const handleTableChange = (_pagination: unknown, _filters: unknown, sorter: unknown) => {+ const s = sorter as { field?: keyof PerformanceRow; order?: string };+ if (s?.field && sortableKeys.includes(s.field as SortKey)) {+ setSortBy(s.field as SortKey);+ setSortDir(s.order === "ascend" ? "asc" : "desc");+ }+ };++ const handleRerun = () => {+ if (rerunState !== "idle") return;+ setRerunState("running");+ setTimeout(() => setRerunState("done"), 2500);+ };++ return (+ <div>+ <div className="flex items-start justify-between mb-5">+ <div>+ <div className="flex items-center gap-2 mb-1">+ <SafetyOutlined className="text-lg text-indigo-500" />+ <h1 className="text-xl font-semibold text-gray-900">Guardrails Monitor</h1>+ </div>+ <p className="text-sm text-gray-500">+ {isGuardrails+ ? "Monitor guardrail performance across all requests"+ : "Monitor policy enforcement across all requests"}+ </p>+ </div>+ <div className="flex items-center gap-3">+ <span className="text-sm text-gray-600 bg-white border border-gray-200 rounded-md px-3 py-2">+ {startDate} – {endDate}+ </span>+ <Button type="default" icon={<DownloadOutlined />} title="Coming soon">+ Export Data+ </Button>+ </div>+ </div>++ <div className="flex items-center gap-1 p-1 bg-gray-100 rounded-lg w-fit mb-6">+ <button+ type="button"+ onClick={() => {+ setViewMode("guardrails");+ setSortBy("failRate");+ setSortDir("desc");+ }}+ className={`inline-flex items-center gap-1.5 px-3.5 py-1.5 text-sm font-medium rounded-md transition-colors ${+ isGuardrails ? "bg-white text-gray-900 shadow-sm" : "text-gray-500 hover:text-gray-700"+ }`}+ >+ <SafetyOutlined /> Guardrail Performance+ </button>+ <button+ type="button"+ onClick={() => {+ setViewMode("policies");+ setSortBy("failRate");+ setSortDir("desc");+ }}+ className={`inline-flex items-center gap-1.5 px-3.5 py-1.5 text-sm font-medium rounded-md transition-colors ${+ !isGuardrails ? "bg-white text-gray-900 shadow-sm" : "text-gray-500 hover:text-gray-700"+ }`}+ >+ <FileTextOutlined /> Policy Performance+ </button>+ </div>++ <Grid numItems={2} numItemsLg={5} className="gap-4 mb-6 items-stretch">+ <Col className="flex flex-col">+ <MetricCard label="Total Requests Evaluated" value={metrics.totalRequests.toLocaleString()} />+ </Col>+ <Col className="flex flex-col">+ <MetricCard+ label="Blocked Requests"+ value={metrics.totalBlocked.toLocaleString()}+ valueColor="text-red-600"+ icon={<WarningOutlined className="text-red-400" />}+ />+ </Col>+ <Col className="flex flex-col">+ <MetricCard+ label="Pass Rate"+ value={`${metrics.passRate}%`}+ valueColor="text-green-600"+ icon={<RiseOutlined className="text-green-400" />}+ />+ </Col>+ <Col className="flex flex-col">+ <MetricCard+ label="Avg. latency added"+ value={`${metrics.avgLatency}ms`}+ valueColor={+ metrics.avgLatency > 150+ ? "text-red-600"+ : metrics.avgLatency > 50+ ? "text-amber-600"+ : "text-green-600"+ }+ />+ </Col>+ <Col className="flex flex-col">+ <MetricCard+ label={isGuardrails ? "Active Guardrails" : "Active Policies"}+ value={metrics.count}+ />+ </Col>+ </Grid>++ <div className="mb-6">+ <ScoreChart data={chartData} />+ </div>++ <Card className="bg-white border border-gray-200 rounded-lg">+ {(isLoading || error) && (+ <div className="px-6 py-4 border-b border-gray-200 flex items-center gap-2">+ {isLoading && <Spin size="small" />}+ {error && <span className="text-sm text-red-600">Failed to load data. Try again.</span>}+ </div>+ )}+ <div className="px-6 py-4 border-b border-gray-200 flex items-start justify-between gap-4">+ <div>+ <Title className="text-base font-semibold text-gray-900">+ {isGuardrails ? "Guardrail Performance" : "Policy Performance"}+ </Title>+ <p className="text-xs text-gray-500 mt-0.5">+ {isGuardrails+ ? "Click a guardrail to view details, logs, and configuration"+ : "Click a policy to view details, logs, and configuration"}+ </p>+ </div>+ <div className="flex items-center gap-2">+ <Button+ type="default"+ icon={<SettingOutlined />}+ onClick={() => setEvaluationModalOpen(true)}+ title="Evaluation settings"+ />+ <Button type="default" icon={<PlayCircleOutlined />} title="Coming soon">+ Re-run AI on last 100 logs+ </Button>+ </div>+ </div>+ <Table+ columns={columns}+ dataSource={sorted}+ rowKey="id"+ pagination={false}+ loading={isLoading}+ onChange={handleTableChange}+ locale={activeData.length === 0 && !isLoading ? { emptyText: "No data for this period" } : undefined}+ onRow={(row) => ({+ onClick: () => onSelectGuardrail(row.id),+ style: { cursor: "pointer" },+ })}+ />+ </Card>++ <EvaluationSettingsModal+ open={evaluationModalOpen}+ onClose={() => setEvaluationModalOpen(false)}+ accessToken={accessToken}+ />+ </div>+ );+}diff --git a/ui/litellm-dashboard/src/components/GuardrailsMonitor/LogViewer.tsx b/ui/litellm-dashboard/src/components/GuardrailsMonitor/LogViewer.tsxnew file mode 100644index 00000000000..f4af5f122e1--- /dev/null+++ b/ui/litellm-dashboard/src/components/GuardrailsMonitor/LogViewer.tsx@@ -0,0 +1,219 @@+import {+ CheckCircleOutlined,+ CloseOutlined,+ CopyOutlined,+ DownOutlined,+ WarningOutlined,+} from "@ant-design/icons";+import { Button, Spin } from "antd";+import React, { useState } from "react";+import type { LogEntry } from "./mockData";++const actionConfig: Record<+ "blocked" | "passed" | "flagged",+ { icon: React.ElementType; color: string; bg: string; border: string; label: string }+> = {+ blocked: {+ icon: CloseOutlined,+ color: "text-red-600",+ bg: "bg-red-50",+ border: "border-red-200",+ label: "Blocked",+ },+ passed: {+ icon: CheckCircleOutlined,+ color: "text-green-600",+ bg: "bg-green-50",+ border: "border-green-200",+ label: "Passed",+ },+ flagged: {+ icon: WarningOutlined,+ color: "text-amber-600",+ bg: "bg-amber-50",+ border: "border-amber-200",+ label: "Flagged",+ },+};++interface LogViewerProps {+ guardrailName?: string;+ filterAction?: "all" | "blocked" | "passed" | "flagged";+ logs?: LogEntry[];+ logsLoading?: boolean;+ totalLogs?: number;+}++export function LogViewer({+ guardrailName,+ filterAction = "all",+ logs = [],+ logsLoading = false,+ totalLogs,+}: LogViewerProps) {+ const [sampleSize, setSampleSize] = useState(10);+ const [expandedLog, setExpandedLog] = useState<string | null>(null);+ const [activeFilter, setActiveFilter] = useState<string>(filterAction);++ const filteredLogs = logs.filter(+ (log) => activeFilter === "all" || log.action === activeFilter+ );+ const displayLogs = filteredLogs.slice(0, sampleSize);+ const total = totalLogs ?? logs.length;+ const sampleSizes = [10, 50, 100];+ const filters: Array<"all" | "blocked" | "flagged" | "passed"> = [+ "all",+ "blocked",+ "flagged",+ "passed",+ ];++ return (+ <div className="bg-white border border-gray-200 rounded-lg">+ <div className="p-4 border-b border-gray-200">+ <div className="flex items-center justify-between flex-wrap gap-3">+ <div>+ <h3 className="text-base font-semibold text-gray-900">+ {guardrailName ? `Logs — ${guardrailName}` : "Request Logs"}+ </h3>+ <p className="text-xs text-gray-500 mt-0.5">+ {logsLoading+ ? "Loading…"+ : logs.length > 0+ ? `Showing ${displayLogs.length} of ${total} entries`+ : "No logs for this period. Select a guardrail and date range."}+ </p>+ </div>+ {logs.length > 0 && (+ <div className="flex items-center gap-4">+ <div className="flex items-center gap-1">+ {filters.map((f) => (+ <Button+ key={f}+ type={activeFilter === f ? "primary" : "default"}+ size="small"+ onClick={() => setActiveFilter(f)}+ >+ {f.charAt(0).toUpperCase() + f.slice(1)}+ </Button>+ ))}+ </div>+ <div className="h-4 w-px bg-gray-200" />+ <div className="flex items-center gap-1">+ <span className="text-xs text-gray-500 mr-1">Sample:</span>+ {sampleSizes.map((size) => (+ <Button+ key={size}+ type={sampleSize === size ? "primary" : "default"}+ size="small"+ onClick={() => setSampleSize(size)}+ >+ {size}+ </Button>+ ))}+ </div>+ </div>+ )}+ </div>+ </div>++ {logsLoading && (+ <div className="flex items-center justify-center py-12">+ <Spin />+ </div>+ )}+ {!logsLoading && displayLogs.length === 0 && (+ <div className="py-12 text-center text-sm text-gray-500">+ No logs to display. Adjust filters or date range.+ </div>+ )}+ {!logsLoading && displayLogs.length > 0 && (+ <div className="divide-y divide-gray-100">+ {displayLogs.map((log) => {+ const config = actionConfig[log.action];+ const ActionIcon = config.icon;+ const isExpanded = expandedLog === log.id;+ return (+ <div key={log.id}>+ <button+ type="button"+ onClick={() => setExpandedLog(isExpanded ? null : log.id)}+ className="w-full text-left px-4 py-3 hover:bg-gray-50 transition-colors flex items-start gap-3"+ >+ <ActionIcon+ className={`w-4 h-4 mt-0.5 flex-shrink-0 ${config.color}`}+ />+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 mb-1 flex-wrap">+ <span+ className={`inline-flex items-center px-2 py-0.5 text-xs font-medium rounded border ${config.bg} ${config.color} ${config.border}`}+ >+ {config.label}+ </span>+ <span className="text-xs text-gray-400">{log.timestamp}</span>+ <span className="text-xs text-gray-400">·</span>+ {log.model && (+ <span className="text-xs text-gray-500">{log.model}</span>+ )}+ </div>+ <p className="text-sm text-gray-800 truncate">+ {log.input_snippet ?? log.input ?? "—"}+ </p>+ </div>+ <span+ className={`flex-shrink-0 mt-1 transition-transform ${+ isExpanded ? "rotate-180" : ""+ }`}+ >+ <DownOutlined className="w-4 h-4 text-gray-400" />+ </span>+ </button>++ {isExpanded && (+ <div className="px-4 pb-4 pl-11">+ <div className="bg-gray-50 rounded-lg p-4 space-y-3 text-sm">+ <div>+ <div className="flex items-center justify-between mb-1">+ <span className="text-xs font-medium text-gray-500 uppercase tracking-wide">+ Input+ </span>+ <Button+ type="text"+ size="small"+ icon={<CopyOutlined />}+ aria-label="Copy input"+ />+ </div>+ <p className="text-gray-800 font-mono text-xs bg-white rounded border border-gray-200 p-3">+ {log.input_snippet ?? log.input ?? "—"}+ </p>+ </div>+ <div>+ <span className="text-xs font-medium text-gray-500 uppercase tracking-wide">+ Output+ </span>+ <p className="text-gray-800 font-mono text-xs bg-white rounded border border-gray-200 p-3 mt-1">+ {log.output_snippet ?? log.output ?? "—"}+ </p>+ </div>+ {(log.reason ?? log.score != null) && (+ <div>+ <span className="text-xs font-medium text-gray-500 uppercase tracking-wide">+ Reason+ </span>+ <p className="text-gray-700 text-xs mt-1">+ {log.reason ?? (log.score != null ? `Score: ${log.score}` : "—")}+ </p>+ </div>+ )}+ </div>+ </div>+ )}+ </div>+ );+ })}+ </div>+ )}+ </div>+ );+}diff --git a/ui/litellm-dashboard/src/components/GuardrailsMonitor/MetricCard.tsx b/ui/litellm-dashboard/src/components/GuardrailsMonitor/MetricCard.tsxnew file mode 100644index 00000000000..4a11efe72ab--- /dev/null+++ b/ui/litellm-dashboard/src/components/GuardrailsMonitor/MetricCard.tsx@@ -0,0 +1,30 @@+import React, { type ReactNode } from "react";++interface MetricCardProps {+ label: string;+ value: string | number;+ valueColor?: string;+ icon?: ReactNode;+ subtitle?: string;+}++export function MetricCard({+ label,+ value,+ valueColor = "text-gray-900",+ icon,+ subtitle,+}: MetricCardProps) {+ return (+ <div className="h-full bg-white border border-gray-200 rounded-lg p-5 flex flex-col">+ <div className="flex items-center justify-between mb-1">+ <span className="text-sm font-medium text-gray-600">{label}</span>+ {icon && <span className="text-gray-400">{icon}</span>}+ </div>+ <div className={`text-3xl font-semibold ${valueColor} tracking-tight`}>+ {value}+ </div>+ {subtitle && <p className="text-xs text-gray-500 mt-1">{subtitle}</p>}+ </div>+ );+}diff --git a/ui/litellm-dashboard/src/components/GuardrailsMonitor/ScoreChart.tsx b/ui/litellm-dashboard/src/components/GuardrailsMonitor/ScoreChart.tsxnew file mode 100644index 00000000000..e4803747d4f--- /dev/null+++ b/ui/litellm-dashboard/src/components/GuardrailsMonitor/ScoreChart.tsx@@ -0,0 +1,39 @@+import { BarChart, Card, Title } from "@tremor/react";+import React from "react";++/**+ * Overview chart: Request Outcomes Over Time (passed vs blocked).+ * Uses Tremor BarChart with stacked data. Data from usage/overview API (chart array).+ */+interface ScoreChartProps {+ data?: Array<{ date: string; passed: number; blocked: number }>;+}++export function ScoreChart({ data }: ScoreChartProps) {+ const chartData = data && data.length > 0 ? data : [];+ return (+ <Card className="bg-white border border-gray-200">+ <Title className="text-base font-semibold text-gray-900 mb-4">+ Request Outcomes Over Time+ </Title>+ <div className="h-80 min-h-[280px]">+ {chartData.length > 0 ? (+ <BarChart+ data={chartData}+ index="date"+ categories={["passed", "blocked"]}+ colors={["green", "red"]}+ valueFormatter={(v) => v.toLocaleString()}+ yAxisWidth={48}+ showLegend={true}+ stack={true}+ />+ ) : (+ <div className="flex items-center justify-center h-full text-sm text-gray-500">+ No chart data for this period+ </div>+ )}+ </div>+ </Card>+ );+}diff --git a/ui/litellm-dashboard/src/components/GuardrailsMonitor/mockData.ts b/ui/litellm-dashboard/src/components/GuardrailsMonitor/mockData.tsnew file mode 100644index 00000000000..7d99ebe7c44--- /dev/null+++ b/ui/litellm-dashboard/src/components/GuardrailsMonitor/mockData.ts@@ -0,0 +1,50 @@+/**+ * Types for Guardrails Monitor dashboard (data from usage API).+ */++export interface PerformanceRow {+ id: string;+ name: string;+ type: string;+ provider: string;+ requestsEvaluated: number;+ failRate: number;+ avgScore?: number;+ avgLatency?: number;+ p95Latency?: number;+ falsePositiveRate?: number;+ falseNegativeRate?: number;+ status: "healthy" | "warning" | "critical";+ trend: "up" | "down" | "stable";+}++export interface GuardrailDetailRecord {+ name: string;+ type: string;+ provider: string;+ requestsEvaluated: number;+ failRate: number;+ avgScore?: number;+ avgLatency?: number;+ p95Latency?: number;+ falsePositiveRate?: number;+ falsePositiveCount?: number;+ falseNegativeRate?: number;+ falseNegativeCount?: number;+ status: string;+ description: string;+}++export interface LogEntry {+ id: string;+ timestamp: string;+ input?: string;+ output?: string;+ input_snippet?: string;+ output_snippet?: string;+ score?: number;+ action: "blocked" | "passed" | "flagged";+ model?: string;+ reason?: string;+ latency_ms?: number;+}diff --git a/ui/litellm-dashboard/src/components/leftnav.tsx b/ui/litellm-dashboard/src/components/leftnav.tsxindex 150be88de21..da3ca2a8bae 100644--- a/ui/litellm-dashboard/src/components/leftnav.tsx+++ b/ui/litellm-dashboard/src/components/leftnav.tsx@@ -154,6 +154,13 @@ const menuGroups: MenuGroup[] = [label: "Logs",icon: <LineChartOutlined />,},+ {+ key: "guardrails-monitor",+ page: "guardrails-monitor",+ label: "Guardrails Monitor",+ icon: <SafetyOutlined />,+ roles: [...all_admin_roles, ...internalUserRoles],+ },],},{diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsxindex a16afe9c8a2..87b9ae98e11 100644--- a/ui/litellm-dashboard/src/components/networking.tsx+++ b/ui/litellm-dashboard/src/components/networking.tsx@@ -5408,6 +5408,128 @@ export const getGuardrailsList = async (accessToken: string) => {}};+// Guardrails / Policies usage (dashboard)+export const getGuardrailsUsageOverview = async (+ accessToken: string,+ startDate?: string,+ endDate?: string+) => {+ try {+ let url = proxyBaseUrl ? `${proxyBaseUrl}/guardrails/usage/overview` : `/guardrails/usage/overview`;+ const params = new URLSearchParams();+ if (startDate) params.append("start_date", startDate);+ if (endDate) params.append("end_date", endDate);+ if (params.toString()) url += `?${params.toString()}`;+ const response = await fetch(url, {+ method: "GET",+ headers: {+ [globalLitellmHeaderName]: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ });+ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(deriveErrorMessage(errorData));+ }+ return response.json();+ } catch (error) {+ console.error("Failed to get guardrails usage overview:", error);+ throw error;+ }+};++export const getGuardrailsUsageDetail = async (+ accessToken: string,+ guardrailId: string,+ startDate?: string,+ endDate?: string+) => {+ try {+ let url = proxyBaseUrl ? `${proxyBaseUrl}/guardrails/usage/detail/${encodeURIComponent(guardrailId)}` : `/guardrails/usage/detail/${encodeURIComponent(guardrailId)}`;+ const params = new URLSearchParams();+ if (startDate) params.append("start_date", startDate);+ if (endDate) params.append("end_date", endDate);+ if (params.toString()) url += `?${params.toString()}`;+ const response = await fetch(url, {+ method: "GET",+ headers: {+ [globalLitellmHeaderName]: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ });+ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(deriveErrorMessage(errorData));+ }+ return response.json();+ } catch (error) {+ console.error("Failed to get guardrails usage detail:", error);+ throw error;+ }+};++export const getGuardrailsUsageLogs = async (+ accessToken: string,+ options: { guardrailId?: string; policyId?: string; page?: number; pageSize?: number; action?: string; startDate?: string; endDate?: string }+) => {+ try {+ let url = proxyBaseUrl ? `${proxyBaseUrl}/guardrails/usage/logs` : `/guardrails/usage/logs`;+ const params = new URLSearchParams();+ if (options.guardrailId) params.append("guardrail_id", options.guardrailId);+ if (options.policyId) params.append("policy_id", options.policyId);+ if (options.page != null) params.append("page", String(options.page));+ if (options.pageSize != null) params.append("page_size", String(options.pageSize));+ if (options.action) params.append("action", options.action);+ if (options.startDate) params.append("start_date", options.startDate);+ if (options.endDate) params.append("end_date", options.endDate);+ if (params.toString()) url += `?${params.toString()}`;+ const response = await fetch(url, {+ method: "GET",+ headers: {+ [globalLitellmHeaderName]: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ });+ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(deriveErrorMessage(errorData));+ }+ return response.json();+ } catch (error) {+ console.error("Failed to get guardrails usage logs:", error);+ throw error;+ }+};++export const getPoliciesUsageOverview = async (+ accessToken: string,+ startDate?: string,+ endDate?: string+) => {+ try {+ let url = proxyBaseUrl ? `${proxyBaseUrl}/policies/usage/overview` : `/policies/usage/overview`;+ const params = new URLSearchParams();+ if (startDate) params.append("start_date", startDate);+ if (endDate) params.append("end_date", endDate);+ if (params.toString()) url += `?${params.toString()}`;+ const response = await fetch(url, {+ method: "GET",+ headers: {+ [globalLitellmHeaderName]: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ });+ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(deriveErrorMessage(errorData));+ }+ return response.json();+ } catch (error) {+ console.error("Failed to get policies usage overview:", error);+ throw error;+ }+};+// ─────────────────────────────────────────────────────────────────────────────// Policy CRUD API Calls// ─────────────────────────────────────────────────────────────────────────────diff --git a/ui/litellm-dashboard/src/components/page_metadata.ts b/ui/litellm-dashboard/src/components/page_metadata.tsindex 54fbfd791bf..69fcf1bd39a 100644--- a/ui/litellm-dashboard/src/components/page_metadata.ts+++ b/ui/litellm-dashboard/src/components/page_metadata.ts@@ -16,6 +16,7 @@ export const pageDescriptions: Record<string, string> = {"vector-stores": "Manage vector databases for embeddings",new_usage: "View usage analytics and metrics",logs: "Access request and response logs",+ "guardrails-monitor": "Monitor guardrail and policy performance and view logs",users: "Manage internal user accounts and permissions",teams: "Create and manage teams for access control",organizations: "Manage organizations and their members",diff --git a/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsx b/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsxindex 12abf9c3c6d..49ea447720c 100644--- a/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsx@@ -77,8 +77,10 @@ const PROVIDERS_WITH_CUSTOM_RENDERERS = new Set(["litellm_content_filter",]);-const formatMode = (mode: string): string => {- return mode.replace(/_/g, "-").toUpperCase();+const formatMode = (mode: unknown): string => {+ if (mode == null) return "—";+ const s = typeof mode === "string" ? mode : String(mode);+ return s.replace(/_/g, "-").toUpperCase();};const formatDurationMs = (seconds: number): string => {