Add backend infrastructure for guardrails performance monitoring dashboard:
Database Schema:
- Add LiteLLM_DailyGuardrailMetrics table for daily aggregated metrics
- Track total_requests, success/intervened/failed/not_run counts per guardrail
- Store aggregated latency metrics in milliseconds
- Unique constraint on [guardrail_name, provider, mode, date, api_key]
Data Collection & Aggregation:
- Add DailyGuardrailMetricsTransaction type for queue transactions
- Implement guardrail metrics extraction from spend log metadata
- Add batch upsert logic with retry handling (60s commit interval)
- Process each guardrail separately with status-based counting
API Endpoints:
- GET /guardrail/metrics - List all guardrails with aggregated metrics
- GET /guardrail/{name}/metrics - Detail view with daily time-series
- GET /guardrail/{name}/logs - Request logs with status filtering
Type Definitions:
- Add Pydantic models for API request/response validation
- GuardrailSummary, GuardrailDetailMetrics, GuardrailLogsResponse
Key Features:
- Fail rate = (intervened_count / total_requests) * 100
- Avg latency measures guardrail execution overhead only
- Reuses LiteLLM_SpendLogs for per-request drill-down
- Follows existing daily spend tracking patterns
Testing Required:
- Run: poetry run prisma migrate dev --name add_guardrail_metrics
- Frontend implementation pending (Phase 5)
- See IMPLEMENTATION_STATUS.md for details
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
7.9 KiB
Guardrails Usage Dashboard - Implementation Status
Completed: Backend Implementation (Phases 1-4)
✅ Phase 1: Database Schema
- File:
litellm/proxy/schema.prisma - Added
LiteLLM_DailyGuardrailMetricstable with:- Unique constraint on
[guardrail_name, guardrail_provider, guardrail_mode, date, api_key] - Indexes on
date,guardrail_name,guardrail_provider,api_key - Fields for tracking total_requests, success/intervened/failed/not_run counts
- Aggregated latency metrics in milliseconds
- Unique constraint on
- Action Required: Run
poetry run prisma migrate dev --name add_guardrail_metricsto create the table
✅ Phase 2: Data Collection & Aggregation
-
File:
litellm/proxy/_types.py- Added
DailyGuardrailMetricsTransactionTypedDict
- Added
-
File:
litellm/proxy/db/db_spend_update_writer.py- Added
daily_guardrail_metrics_update_queueto__init__ - Implemented
add_spend_log_transaction_to_daily_guardrail_transaction():- Extracts guardrail_information from metadata
- Creates separate transaction per guardrail
- Calculates status counts and latency in milliseconds
- Implemented
update_daily_guardrail_metrics()static method:- Batch upserts to database with retry logic
- Increments counters on conflict
- Added guardrail transaction call to
update_database()flow - Added commit logic to
_commit_spend_updates_to_db_without_redis_buffer()
- Added
✅ Phase 3: Type Definitions
- File:
litellm/types/proxy/management_endpoints/guardrail_metrics.py- Created Pydantic models for:
GuardrailMetrics- Aggregated metricsGuardrailSummary- Table viewGuardrailMetricsResponse- List endpoint responseGuardrailDailyMetrics- Time-series dataGuardrailDetailMetrics- Detail view with daily metricsGuardrailLogEntry- Individual request logGuardrailLogsResponse- Logs endpoint response
- Created Pydantic models for:
✅ Phase 4: API Endpoints
-
File:
litellm/proxy/management_endpoints/guardrail_metrics_endpoints.py- Implemented 3 endpoints:
GET /guardrail/metrics- List guardrails with aggregated metrics- Query params: start_date, end_date, guardrail_name, provider, page, page_size
- Returns sorted by fail_rate descending
GET /guardrail/{guardrail_name}/metrics- Detail view metrics- Returns overview stats + daily time-series
GET /guardrail/{guardrail_name}/logs- Request logs- Query params: start_date, end_date, status_filter, page, page_size
- Filters LiteLLM_SpendLogs by guardrail_information
- Implemented 3 endpoints:
-
File:
litellm/proxy/proxy_server.py- Added import for
guardrail_metrics_router - Registered router with
app.include_router(guardrail_metrics_router)
- Added import for
🔲 Pending: Frontend Implementation (Phase 5)
TypeScript Types
- File to create:
ui/litellm-dashboard/src/components/GuardrailsPage/types.ts - Defines interfaces matching backend Pydantic models
Networking Functions
- File to update:
ui/litellm-dashboard/src/components/networking.tsx - Add API call functions:
guardrailMetricsCall()guardrailDetailMetricsCall()guardrailLogsCall()
Components
-
Table View:
ui/litellm-dashboard/src/components/GuardrailsPage/GuardrailsTableView.tsx- Displays list of guardrails with metrics
- Clickable rows navigate to detail view
-
Detail View:
ui/litellm-dashboard/src/components/GuardrailsPage/GuardrailDetailView.tsx- Metric cards (Requests, Fail Rate, Latency, Blocked)
- Tabs for Overview and Logs
- Area chart for fail rate trend
-
Logs Tab:
ui/litellm-dashboard/src/components/GuardrailsPage/GuardrailLogsTab.tsx- Filterable table (All, Blocked, Passed)
- Expandable rows for guardrail response details
Pages
-
Main Page:
ui/litellm-dashboard/src/app/(dashboard)/guardrails/page.tsx- Date range picker
- Renders GuardrailsTableView
-
Detail Page:
ui/litellm-dashboard/src/app/(dashboard)/guardrails/[name]/page.tsx- Back button to overview
- Date range picker
- Renders GuardrailDetailView
Testing & Verification
Backend Testing Steps
-
Run Prisma migration:
cd /Users/krrishdholakia/Documents/litellm-guardrails-dashboard poetry run prisma migrate dev --name add_guardrail_metrics --schema=litellm/proxy/schema.prisma -
Start the proxy server with guardrails configured
-
Send requests that trigger guardrails (both pass and fail cases)
-
Wait 60s for batch commit to database
-
Test API endpoints:
# List guardrails curl -X GET "http://localhost:4000/guardrail/metrics?start_date=2026-02-01&end_date=2026-02-19" \ -H "Authorization: Bearer <token>" # Get guardrail details curl -X GET "http://localhost:4000/guardrail/my-guardrail/metrics?start_date=2026-02-01&end_date=2026-02-19" \ -H "Authorization: Bearer <token>" # Get logs curl -X GET "http://localhost:4000/guardrail/my-guardrail/logs?start_date=2026-02-01&end_date=2026-02-19" \ -H "Authorization: Bearer <token>" -
Verify data in database:
SELECT * FROM "LiteLLM_DailyGuardrailMetrics" LIMIT 10;
Frontend Testing Steps (Once Implemented)
- Navigate to
/guardrailspage - Verify table loads with metrics
- Click guardrail row → navigate to detail page
- Verify Overview tab shows metrics and chart
- Switch to Logs tab → verify logs display
- Test status filter (All, Blocked, Passed)
- Test date range filtering
- Test pagination
Key Design Decisions
Fail Rate Calculation
- Formula:
(intervened_count / total_requests) * 100 - Only counts
guardrail_intervenedas failures (policy violations) - Excludes
guardrail_failed_to_respond(infrastructure errors)
Average Latency
- Formula:
total_latency_ms / total_requests - Measures guardrail execution overhead (not total request latency)
- Captured from
StandardLoggingGuardrailInformation.durationfield - Stored in milliseconds for better precision
Per-Request Logs
- No new table needed
- Existing
LiteLLM_SpendLogs.metadata.guardrail_informationused - Query optimized with date filtering and over-fetching strategy
Aggregation Strategy
- Daily aggregation reduces full table scans on large datasets
- Batch commits every 60s reduce database load
- Indexed queries for fast filtering
- Pagination limits memory usage
Files Modified
Backend
litellm/proxy/schema.prisma- Added tablelitellm/proxy/_types.py- Added transaction typelitellm/proxy/db/db_spend_update_writer.py- Data collection & commitlitellm/types/proxy/management_endpoints/guardrail_metrics.py- New filelitellm/proxy/management_endpoints/guardrail_metrics_endpoints.py- New filelitellm/proxy/proxy_server.py- Router registration
Frontend (Pending - 7 files)
ui/litellm-dashboard/src/components/GuardrailsPage/types.tsui/litellm-dashboard/src/components/networking.tsxui/litellm-dashboard/src/components/GuardrailsPage/GuardrailsTableView.tsxui/litellm-dashboard/src/components/GuardrailsPage/GuardrailDetailView.tsxui/litellm-dashboard/src/components/GuardrailsPage/GuardrailLogsTab.tsxui/litellm-dashboard/src/app/(dashboard)/guardrails/page.tsxui/litellm-dashboard/src/app/(dashboard)/guardrails/[name]/page.tsx
Next Steps
- Run Prisma Migration to create the database table
- Test Backend with curl requests after sending guardrail traffic
- Implement Frontend following Phase 5 specifications
- Run
make test-unitto ensure no regressions - Test Integration with high request volume (1000+ requests)
- Create Pull Request with proper tests and documentation
Notes
- Migration needs to be run in an environment with proper Prisma setup
- Some Pyright diagnostics appeared but are pre-existing in codebase
- Frontend implementation follows existing LiteLLM dashboard patterns (Tremor UI components)
- All backend code follows existing patterns from daily spend tracking