Skip to content

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

fix: add missing OpenAI chat completion params to OPENAI_CHAT_COMPLETION_PARAMS (#21360)

shin-bot-litellmb609f5841b03
diff --git a/.github/workflows/test_server_root_path.yml b/.github/workflows/test_server_root_path.yml
new file mode 100644
index 00000000000..bc559817503
--- /dev/null
+++ b/.github/workflows/test_server_root_path.yml
@@ -0,0 +1,96 @@
+name: Test Proxy SERVER_ROOT_PATH Routing
+permissions:
+ contents: read
+
+on:
+ pull_request:
+ branches: [main]
+
+jobs:
+ test-server-root-path:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+
+ strategy:
+ matrix:
+ root_path: ["/api/v1", "/llmproxy"]
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v3
+
+ - name: Build Docker image
+ uses: docker/build-push-action@v5
+ with:
+ context: .
+ file: ./docker/Dockerfile.database
+ tags: litellm-test:${{ github.sha }}
+ load: true
+ cache-from: type=gha
+ cache-to: type=gha,mode=max
+
+ - name: Start LiteLLM container with SERVER_ROOT_PATH
+ run: |
+ docker run -d \
+ --name litellm-test \
+ -p 4000:4000 \
+ -e SERVER_ROOT_PATH="${{ matrix.root_path }}" \
+ -e LITELLM_MASTER_KEY="sk-1234" \
+ litellm-test:${{ github.sha }} \
+ --detailed_debug
+
+ - name: Wait for container to be healthy
+ run: |
+ echo "Waiting for LiteLLM to start..."
+ max_attempts=30
+ attempt=0
+
+ while [ $attempt -lt $max_attempts ]; do
+ if docker logs litellm-test 2>&1 | grep -q "Uvicorn running"; then
+ echo "LiteLLM started successfully"
+ break
+ fi
+ attempt=$((attempt + 1))
+ echo "Attempt $attempt/$max_attempts - waiting for server to start..."
+ sleep 2
+ done
+
+ if [ $attempt -eq $max_attempts ]; then
+ echo "Server failed to start within timeout"
+ docker logs litellm-test
+ exit 1
+ fi
+
+ sleep 5
+
+ - name: Show container logs
+ if: always()
+ run: docker logs litellm-test
+
+ - name: Test UI endpoint with root path
+ run: |
+ ROOT_PATH="${{ matrix.root_path }}"
+ echo "Testing UI at: http://localhost:4000${ROOT_PATH}/ui/"
+
+ for i in 1 2 3; do
+ content=$(curl -sL --max-time 5 -H "Authorization: Bearer sk-1234" "http://localhost:4000${ROOT_PATH}/ui/")
+ if echo "$content" | grep -q -E "(html|<!DOCTYPE|<head|<body)"; then
+ echo "UI page contains valid HTML content"
+ exit 0
+ fi
+ echo "Attempt $i/3 - no valid HTML, retrying in 5s..."
+ sleep 5
+ done
+ echo "UI page does not contain expected HTML content"
+ echo "Response: $content"
+ docker logs litellm-test
+ exit 1
+
+ - name: Cleanup
+ if: always()
+ run: |
+ docker stop litellm-test || true
+ docker rm litellm-test || true
diff --git a/docs/my-website/blog/claude_code_beta_headers/index.md b/docs/my-website/blog/claude_code_beta_headers/index.md
index 138a85a60c5..b5ec14e209a 100644
--- a/docs/my-website/blog/claude_code_beta_headers/index.md
+++ b/docs/my-website/blog/claude_code_beta_headers/index.md
@@ -1,6 +1,6 @@
---
-slug: claude_code_beta_headers
-title: "Claude Code - Managing Anthropic Beta Headers"
+slug: claude-code-beta-headers-incident
+title: "Incident Report: Invalid beta headers with Claude Code"
date: 2026-02-16T10:00:00
authors:
- name: Sameer Kankute
@@ -15,260 +15,161 @@ authors:
title: "CEO, LiteLLM"
url: https://www.linkedin.com/in/krish-d/
image_url: https://pbs.twimg.com/profile_images/1298587542745358340/DZv3Oj-h_400x400.jpg
-description: "How to manage and configure Anthropic beta headers with Claude Code in LiteLLM: filtering, mapping, and dynamic updates across providers."
-tags: [anthropic, claude, beta headers, configuration, liteLLM]
+tags: [incident-report, anthropic, stability]
hide_table_of_contents: false
-
---
-import Image from '@theme/IdealImage';
-
-When using Claude Code with LiteLLM and non-Anthropic providers (Bedrock, Azure AI, Vertex AI), you need to ensure that only supported beta headers are sent to each provider. This guide explains how to add support for new beta headers or fix invalid beta header errors.
-
-## What Are Beta Headers?
-
-Anthropic uses beta headers to enable experimental features in Claude. When you use Claude Code, it may send beta headers like:
-
-```
-anthropic-beta: prompt-caching-scope-2026-01-05,advanced-tool-use-2025-11-20
-```
-
-However, not all providers support all Anthropic beta features. LiteLLM uses `anthropic_beta_headers_config.json` to manage which beta headers are supported by each provider.
-## Common Error Message
+**Date:** February 13, 2026
+**Duration:** ~3 hours
+**Severity:** High
+**Status:** Resolved
-```bash
-Error: The model returned the following errors: invalid beta flag
-```
-
-## How LiteLLM Handles Beta Headers
-
-LiteLLM uses a strict validation approach with a configuration file:
-
-```
-litellm/litellm/anthropic_beta_headers_config.json
-```
+## Summary
-This JSON file contains a **mapping** of beta headers for each provider:
-- **Keys**: Input beta header names (from Anthropic)
-- **Values**: Provider-specific header names (or `null` if unsupported)
-- **Validation**: Only headers present in the mapping with non-null values are forwarded
-
-This enforces stricter validation than just filtering unsupported headers - headers must be explicitly defined to be allowed.
-
-## Adding Support for a New Beta Header
-
-When Anthropic releases a new beta feature, you need to add it to the configuration file for each provider.
-
-### Step 1: Add the New Beta Header
-
-Open `anthropic_beta_headers_config.json` and add the new header to each provider's mapping:
-
-```json title="anthropic_beta_headers_config.json"
-{
- "description": "Mapping of Anthropic beta headers for each provider. Keys are input header names, values are provider-specific header names (or null if unsupported). Only headers present in mapping keys with non-null values can be forwarded.",
- "anthropic": {
- "advanced-tool-use-2025-11-20": "advanced-tool-use-2025-11-20",
- "new-feature-2026-03-01": "new-feature-2026-03-01",
- ...
- },
- "azure_ai": {
- "advanced-tool-use-2025-11-20": "advanced-tool-use-2025-11-20",
- "new-feature-2026-03-01": "new-feature-2026-03-01",
- ...
- },
- "bedrock_converse": {
- "advanced-tool-use-2025-11-20": "tool-search-tool-2025-10-19",
- "new-feature-2026-03-01": null,
- ...
- },
- "bedrock": {
- "advanced-tool-use-2025-11-20": "tool-search-tool-2025-10-19",
- "new-feature-2026-03-01": null,
- ...
- },
- "vertex_ai": {
- "advanced-tool-use-2025-11-20": "tool-search-tool-2025-10-19",
- "new-feature-2026-03-01": null,
- ...
- }
-}
-```
-
-**Key Points:**
-- **Supported headers**: Set the value to the provider-specific header name (often the same as the key)
-- **Unsupported headers**: Set the value to `null`
-- **Header transformations**: Some providers use different header names (e.g., Bedrock maps `advanced-tool-use-2025-11-20` to `tool-search-tool-2025-10-19`)
-- **Alphabetical order**: Keep headers sorted alphabetically for maintainability
-
-### Step 2: Reload Configuration (No Restart Required!)
-
-**Option 1: Dynamic Reload Without Restart**
-
-Instead of restarting your application, you can dynamically reload the beta headers configuration using environment variables and API endpoints:
-
-```bash
-# Set environment variable to fetch from remote URL (Do this if you want to point it to some other URL)
-export LITELLM_ANTHROPIC_BETA_HEADERS_URL="https://raw.githubusercontent.com/BerriAI/litellm/main/litellm/anthropic_beta_headers_config.json"
-
-# Manually trigger reload via API (no restart needed!)
-curl -X POST "https://your-proxy-url/reload/anthropic_beta_headers" \
- -H "Authorization: Bearer YOUR_ADMIN_TOKEN"
-```
-
-**Option 2: Schedule Automatic Reloads**
-
-Set up automatic reloading to always stay up-to-date with the latest beta headers:
-
-```bash
-# Reload configuration every 24 hours
-curl -X POST "https://your-proxy-url/schedule/anthropic_beta_headers_reload?hours=24" \
- -H "Authorization: Bearer YOUR_ADMIN_TOKEN"
-```
-
-**Option 3: Traditional Restart**
-
-If you prefer the traditional approach, restart your LiteLLM proxy or application:
-
-```bash
-# If using LiteLLM proxy
-litellm --config config.yaml
-
-# If using Python SDK
-# Just restart your Python application
-```
+Claude Code began sending unsupported Anthropic beta headers to non-Anthropic providers (Bedrock, Azure AI, Vertex AI), causing `invalid beta flag` errors. LiteLLM was forwarding all beta headers without provider-specific validation. Users experienced request failures when routing Claude Code requests through LiteLLM to these providers.
-:::tip Zero-Downtime Updates
-With dynamic reloading, you can fix invalid beta header errors **without restarting your service**! This is especially useful in production environments where downtime is costly.
+- **LLM calls to Anthropic:** No impact.
+- **LLM calls to Bedrock/Azure/Vertex:** Failed with `invalid beta flag` errors when unsupported headers were present.
+- **Cost tracking and routing:** No impact.
-See [Auto Sync Anthropic Beta Headers](../proxy/sync_anthropic_beta_headers.md) for complete documentation.
-:::
+{/* truncate */}
-## Fixing Invalid Beta Header Errors
+---
-If you encounter an "invalid beta flag" error, it means a beta header is being sent that the provider doesn't support.
+## Background
-### Step 1: Identify the Problematic Header
+Anthropic uses beta headers to enable experimental features in Claude. When Claude Code makes API requests, it includes headers like `anthropic-beta: prompt-caching-scope-2026-01-05,advanced-tool-use-2025-11-20`. However, not all providers support all Anthropic beta features.
-Check your logs to see which header is causing the issue:
+Before this incident, LiteLLM forwarded all beta headers to all providers without validation:
-```bash
-Error: The model returned the following errors: invalid beta flag: new-feature-2026-03-01
-```
+```mermaid
+sequenceDiagram
+ participant CC as Claude Code
+ participant LP as LiteLLM (old behavior)
+ participant Provider as Provider (Bedrock/Azure/Vertex)
-### Step 2: Update the Config
+ CC->>LP: Request with beta headers
+ Note over CC,LP: anthropic-beta: header1,header2,header3
-Set the header value to `null` for that provider:
+ LP->>Provider: Forward ALL headers (no validation)
+ Note over LP,Provider: anthropic-beta: header1,header2,header3
-```json title="anthropic_beta_headers_config.json"
-{
- "bedrock_converse": {
- "new-feature-2026-03-01": null
- }
-}
+ Provider-->>LP: ❌ Error: invalid beta flag
+ LP-->>CC: Request fails
```
-### Step 3: Restart and Test
-
-Restart your application and verify the header is now filtered out.
-
-## Contributing a Fix to LiteLLM
+Requests succeeded for Anthropic (native support) but failed for other providers when Claude Code sent headers those providers didn't support.
-Help the community by contributing your fix!
-
-### What to Include in Your PR
-
-1. **Update the config file**: Add the new beta header to `litellm/anthropic_beta_headers_config.json`
-2. **Test your changes**: Verify the header is correctly filtered/mapped for each provider
-3. **Documentation**: Include provider documentation links showing which headers are supported
-
-### Example PR Description
-
-```markdown
-## Add support for new-feature-2026-03-01 beta header
+---
-### Changes
-- Added `new-feature-2026-03-01` to anthropic_beta_headers_config.json
-- Set to `null` for bedrock_converse (unsupported)
-- Set to header name for anthropic, azure_ai (supported)
+## Root cause
-### Testing
-Tested with:
-- ✅ Anthropic: Header passed through correctly
-- ✅ Azure AI: Header passed through correctly
-- ✅ Bedrock Converse: Header filtered out (returns error without fix)
+LiteLLM lacked provider-specific beta header validation. When Claude Code introduced new beta features or sent headers that specific providers didn't support, those headers were blindly forwarded, causing provider API errors.
-### References
-- Anthropic docs: [link]
-- AWS Bedrock docs: [link]
-```
+---
+## Remediation
-## How Beta Header Filtering Works
+| # | Action | Status | Code |
+|---|---|---|---|
+| 1 | Create `anthropic_beta_headers_config.json` with provider-specific mappings | ✅ Done | [`anthropic_beta_headers_config.json`](https://github.com/BerriAI/litellm/blob/main/litellm/anthropic_beta_headers_config.json) |
+| 2 | Implement strict validation: headers must be explicitly mapped to be forwarded | ✅ Done | [`litellm_logging.py`](https://github.com/BerriAI/litellm/blob/main/litellm/litellm_core_utils/litellm_logging.py) |
+| 3 | Add `/reload/anthropic_beta_headers` endpoint for dynamic config updates | ✅ Done | Proxy management endpoints |
+| 4 | Add `/schedule/anthropic_beta_headers_reload` for automatic periodic updates | ✅ Done | Proxy management endpoints |
+| 5 | Support `LITELLM_ANTHROPIC_BETA_HEADERS_URL` for custom config sources | ✅ Done | Environment configuration |
+| 6 | Support `LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS` for air-gapped deployments | ✅ Done | Environment configuration |
-When you make a request through LiteLLM:
+Now LiteLLM validates and transforms headers per-provider:
```mermaid
sequenceDiagram
participant CC as Claude Code
- participant LP as LiteLLM
+ participant LP as LiteLLM (new behavior)
participant Config as Beta Headers Config
- participant Provider as Provider (Bedrock/Azure/etc)
+ participant Provider as Provider (Bedrock/Azure/Vertex)
CC->>LP: Request with beta headers
Note over CC,LP: anthropic-beta: header1,header2,header3
-
+
LP->>Config: Load header mapping for provider
Config-->>LP: Returns mapping (header→value or null)
-
+
Note over LP: Validate & Transform:<br/>1. Check if header exists in mapping<br/>2. Filter out null values<br/>3. Map to provider-specific names
-
+
LP->>Provider: Request with filtered & mapped headers
Note over LP,Provider: anthropic-beta: mapped-header2<br/>(header1, header3 filtered out)
-
- Provider-->>LP: Success response
+
+ Provider-->>LP: ✅ Success response
LP-->>CC: Response
```
-### Filtering Rules
+---
-1. **Header must exist in mapping**: Unknown headers are filtered out
-2. **Header must have non-null value**: Headers with `null` values are filtered out
-3. **Header transformation**: Headers are mapped to provider-specific names (e.g., `advanced-tool-use-2025-11-20` → `tool-search-tool-2025-10-19` for Bedrock)
+## Dynamic configuration updates
-### Example
+A key improvement is zero-downtime configuration updates. When Anthropic releases new beta features, users can update their configuration without restarting:
-Request with headers:
-```
-anthropic-beta: advanced-tool-use-2025-11-20,computer-use-2025-01-24,unknown-header
+```bash
+# Manually trigger reload (no restart needed)
+curl -X POST "https://your-proxy-url/reload/anthropic_beta_headers" \
+ -H "Authorization: Bearer YOUR_ADMIN_TOKEN"
+
+# Or schedule automatic reloads every 24 hours
+curl -X POST "https://your-proxy-url/schedule/anthropic_beta_headers_reload?hours=24" \
+ -H "Authorization: Bearer YOUR_ADMIN_TOKEN"
```
-For Bedrock Converse:
-- ✅ `computer-use-2025-01-24` → `computer-use-2025-01-24` (supported, passed through)
-- ❌ `advanced-tool-use-2025-11-20` → filtered out (null value in config)
-- ❌ `unknown-header` → filtered out (not in config)
+This prevents future incidents where Claude Code introduces new headers before LiteLLM configuration is updated.
-Result sent to Bedrock:
-```
-anthropic-beta: computer-use-2025-01-24
+---
+
+## Configuration format
+
+The `anthropic_beta_headers_config.json` file maps input headers to provider-specific output headers:
+
+```json
+{
+ "description": "Mapping of Anthropic beta headers for each provider.",
+ "anthropic": {
+ "advanced-tool-use-2025-11-20": "advanced-tool-use-2025-11-20",
+ "computer-use-2025-01-24": "computer-use-2025-01-24"
+ },
+ "bedrock_converse": {
+ "advanced-tool-use-2025-11-20": null,
+ "computer-use-2025-01-24": "computer-use-2025-01-24"
+ },
+ "azure_ai": {
+ "advanced-tool-use-2025-11-20": "advanced-tool-use-2025-11-20",
+ "computer-use-2025-01-24": "computer-use-2025-01-24"
+ }
+}
```
-## Dynamic Configuration Management (No Restart Required!)
+**Validation rules:**
+1. Headers must exist in the mapping for the target provider
+2. Headers with `null` values are filtered out (unsupported)
+3. Header names can be transformed per-provider (e.g., Bedrock uses different names for some features)
-### Environment Variables
+---
-Control how LiteLLM loads the beta headers configuration:
+## Resolution steps for users
-| Variable | Description | Default |
-|----------|-------------|---------|
-| `LITELLM_ANTHROPIC_BETA_HEADERS_URL` | URL to fetch config from | GitHub main branch |
-| `LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS` | Set to `True` to use local config only | `False` |
+For users still experiencing issues, update to the latest LiteLLM version if < v1.81.11-nightly:
-**Example: Use Custom Config URL**
```bash
-export LITELLM_ANTHROPIC_BETA_HEADERS_URL="https://your-company.com/custom-beta-headers.json"
+pip install --upgrade litellm
```
-**Example: Use Local Config Only (No Remote Fetching)**
+Or manually reload the configuration without restarting:
+
```bash
-export LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS=True
+curl -X POST "https://your-proxy-url/reload/anthropic_beta_headers" \
+ -H "Authorization: Bearer YOUR_ADMIN_TOKEN"
```
+
+---
+
+## Related documentation
+
+- [Managing Anthropic Beta Headers](../proxy/sync_anthropic_beta_headers.md) - Complete configuration guide
+- [`anthropic_beta_headers_config.json`](https://github.com/BerriAI/litellm/blob/main/litellm/anthropic_beta_headers_config.json) - Current configuration file
diff --git a/docs/my-website/docs/proxy/config_settings.md b/docs/my-website/docs/proxy/config_settings.md
index 5e3f56c4206..775cdf6876a 100644
--- a/docs/my-website/docs/proxy/config_settings.md
+++ b/docs/my-website/docs/proxy/config_settings.md
@@ -450,6 +450,7 @@ router_settings:
| BATCH_STATUS_POLL_INTERVAL_SECONDS | Interval in seconds for polling batch status. Default is 3600 (1 hour)
| BATCH_STATUS_POLL_MAX_ATTEMPTS | Maximum number of attempts for polling batch status. Default is 24 (for 24 hours)
| BEDROCK_MAX_POLICY_SIZE | Maximum size for Bedrock policy. Default is 75
+| BEDROCK_MIN_THINKING_BUDGET_TOKENS | Minimum thinking budget in tokens for Bedrock reasoning models. Bedrock returns a 400 error if budget_tokens is below this value. Requests with lower values are clamped to this minimum. Default is 1024
| BERRISPEND_ACCOUNT_ID | Account ID for BerriSpend service
| BRAINTRUST_API_KEY | API key for Braintrust integration
| BRAINTRUST_API_BASE | Base URL for Braintrust API. Default is https://api.braintrustdata.com/v1
diff --git a/litellm/constants.py b/litellm/constants.py
index 7c21111d313..458f48cb0b6 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -577,6 +577,10 @@ OPENAI_CHAT_COMPLETION_PARAMS = [
"web_search_options",
"service_tier",
"store",
+ "prompt_cache_key",
+ "prompt_cache_retention",
+ "safety_identifier",
+ "verbosity",
]
OPENAI_TRANSCRIPTION_PARAMS = [
diff --git a/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py b/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py
index 9d1c254d1a7..55746e5e527 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py
@@ -329,10 +329,10 @@ class ContentFilterGuardrail(CustomGuardrail):
action if action else category_config_obj.default_action
)
- # Handle conditional categories (with identifier_words + inherit_from OR identifier_words + additional_block_words)
- if category_config_obj.identifier_words and (
- category_config_obj.inherit_from
- or category_config_obj.additional_block_words
+ # Handle conditional categories (with identifier_words + inherit_from)
+ if (
+ category_config_obj.identifier_words
+ and category_config_obj.inherit_from
):
self._load_conditional_category(
category_name,
@@ -387,81 +387,64 @@ class ContentFilterGuardrail(CustomGuardrail):
categories_dir: str,
) -> None:
"""
- Load a conditional category that uses identifier_words + block_words.
-
- Supports two patterns:
- 1. Inherit + additional: identifier_words + inherit_from + optional additional_block_words
- 2. Standalone: identifier_words + additional_block_words (no inheritance)
+ Load a conditional category that uses identifier_words + inherited block_words.
Args:
category_name: Name of the category
- category_config_obj: CategoryConfig object with identifier_words and either inherit_from or additional_block_words
+ category_config_obj: CategoryConfig object with identifier_words and inherit_from
category_action: Action to take when match is found
severity_threshold: Minimum severity threshold
categories_dir: Directory containing category files
"""
- block_words = []
+ # Load the inherited category to get block words
inherit_from = category_config_obj.inherit_from
+ if not inherit_from:
+ return
- # Pattern 1: Load inherited category to get base block words
- if inherit_from:
- # Remove .json or .yaml extension if included
- inherit_base = inherit_from.replace(".json", "").replace(".yaml", "")
-
- # Find the inherited category file
- inherit_yaml_path = os.path.join(categories_dir, f"{inherit_base}.yaml")
- inherit_json_path = os.path.join(categories_dir, f"{inherit_base}.json")
-
- if os.path.exists(inherit_yaml_path):
- inherit_file_path = inherit_yaml_path
- elif os.path.exists(inherit_json_path):
- inherit_file_path = inherit_json_path
- else:
- verbose_proxy_logger.warning(
- f"Category {category_name}: inherit_from '{inherit_from}' file not found at {categories_dir}"
- )
- verbose_proxy_logger.debug(
- f"Tried paths: {inherit_yaml_path}, {inherit_json_path}"
- )
- return
-
- try:
- # Load the inherited category
- inherited_category = self._load_category_file(inherit_file_path)
-
- # Extract block words from inherited category that meet severity threshold
- for keyword_data in inherited_category.keywords:
- keyword = keyword_data["keyword"].lower()
- severity = keyword_data["severity"]
- if self._should_apply_severity(severity, severity_threshold):
- block_words.append(keyword)
- except Exception as e:
- verbose_proxy_logger.error(
- f"Error loading inherited category for {category_name}: {e}"
- )
- return
+ # Remove .json or .yaml extension if included
+ inherit_base = inherit_from.replace(".json", "").replace(".yaml", "")
- # Pattern 2 or supplement to Pattern 1: Add additional block words
- if category_config_obj.additional_block_words:
- block_words.extend(category_config_obj.additional_block_words)
+ # Find the inherited category file
+ inherit_yaml_path = os.path.join(categories_dir, f"{inherit_base}.yaml")
+ inherit_json_path = os.path.join(categories_dir, f"{inherit_base}.json")
- # Ensure we have block words before storing
- if not block_words:
+ if os.path.exists(inherit_yaml_path):
+ inherit_file_path = inherit_yaml_path
+ elif os.path.exists(inherit_json_path):
+ inherit_file_path = inherit_json_path
+ else:
verbose_proxy_logger.warning(
- f"Category {category_name}: no block words found (check inherit_from or additional_block_words)"
+ f"Category {category_name}: inherit_from '{inherit_from}' file not found at {categories_dir}"
+ )
+ verbose_proxy_logger.debug(
+ f"Tried paths: {inherit_yaml_path}, {inherit_json_path}"
)
return
- # Store the conditional category configuration
- self.conditional_categories[category_name] = {
- "identifier_words": category_config_obj.identifier_words,
- "block_words": block_words,
- "action": category_action,
- "severity": "high", # Combinations are always high severity
- }
+ try:
+ # Load the inherited category
+ inherited_category = self._load_category_file(inherit_file_path)
+
+ # Extract block words from inherited category that meet severity threshold
+ block_words = []
+ for keyword_data in inherited_category.keywords:
+ keyword = keyword_data["keyword"].lower()
+ severity = keyword_data["severity"]
+ if self._should_apply_severity(severity, severity_threshold):
+ block_words.append(keyword)
+
+ # Add additional block words specific to this category
+ if category_config_obj.additional_block_words:
+ block_words.extend(category_config_obj.additional_block_words)
+
+ # Store the conditional category configuration
+ self.conditional_categories[category_name] = {
+ "identifier_words": category_config_obj.identifier_words,
+ "block_words": block_words,
+ "action": category_action,
+ "severity": "high", # Combinations are always high severity
+ }
- # Log different messages based on pattern
- if inherit_from and category_config_obj.additional_block_words:
verbose_proxy_logger.info(
f"Loaded conditional category {category_name}: "
f"{len(category_config_obj.identifier_words)} identifiers + "
@@ -469,17 +452,9 @@ class ContentFilterGuardrail(CustomGuardrail):
f"({len(category_config_obj.additional_block_words)} additional + "
f"{len(block_words) - len(category_config_obj.additional_block_words)} from {inherit_from})"
)
- elif inherit_from:
- verbose_proxy_logger.info(
- f"Loaded conditional category {category_name}: "
- f"{len(category_config_obj.identifier_words)} identifiers + "
- f"{len(block_words)} block words (from {inherit_from})"
- )
- else:
- verbose_proxy_logger.info(
- f"Loaded conditional category {category_name}: "
- f"{len(category_config_obj.identifier_words)} identifiers + "
- f"{len(block_words)} block words (standalone)"
+ except Exception as e:
+ verbose_proxy_logger.error(
+ f"Error loading inherited category for {category_name}: {e}"
)
def _load_category_file(self, file_path: str) -> CategoryConfig:
@@ -1398,6 +1373,41 @@ class ContentFilterGuardrail(CustomGuardrail):
names = [cat.description or cat.category_name for cat in self.loaded_categories.values()]
return ", ".join(names) if names else None
+ def _compute_risk_score(
+ self,
+ detections: List[ContentFilterDetection],
+ masked_entity_count: Dict[str, int],
+ status: "GuardrailStatus",
+ ) -> float:
+ """
+ Compute a risk score from 0-10 for this guardrail evaluation.
+
+ Factors:
+ - Match ratio: how many patterns matched vs total checked
+ - Number of entities masked
+ - Whether the guardrail blocked the request (max risk)
+ """
+ if status == "guardrail_intervened":
+ return 10.0
+
+ total_masked = sum(masked_entity_count.values()) if masked_entity_count else 0
+ patterns_checked = self._get_patterns_checked_count()
+
+ # Match ratio contribution (0-7 points)
+ match_ratio = total_masked / patterns_checked if patterns_checked > 0 else 0.0
+ ratio_score = match_ratio * 7.0
+
+ # Detection count contribution (0-3 points, capped)
+ detection_score = min(len(detections), 5) * 0.6
+
+ score = ratio_score + detection_score
+
+ # Floor: if anything matched, minimum risk is 2
+ if total_masked > 0 and score < 2.0:
+ score = 2.0
+
+ return round(min(10.0, score), 1)
+
def _log_guardrail_information(
self,
request_data: dict,
@@ -1444,6 +1454,7 @@ class ContentFilterGuardrail(CustomGuardrail):
detection_method=self._get_detection_methods(detections) if detections else None,
match_details=self._build_match_details(detections) if detections else None,
patterns_checked=self._get_patterns_checked_count(),
+ risk_score=self._compute_risk_score(detections, masked_entity_count, status),
),
)
diff --git a/litellm/proxy/management_endpoints/internal_user_endpoints.py b/litellm/proxy/management_endpoints/internal_user_endpoints.py
index c0285407855..57b6453ac43 100644
--- a/litellm/proxy/management_endpoints/internal_user_endpoints.py
+++ b/litellm/proxy/management_endpoints/internal_user_endpoints.py
@@ -1911,6 +1911,10 @@ async def get_user_daily_activity(
default=None,
description="Filter by specific API key",
),
+ user_id: Optional[str] = fastapi.Query(
+ default=None,
+ description="Filter by specific user ID. Admins can filter by any user or omit for global view. Non-admins must provide their own user_id.",
+ ),
page: int = fastapi.Query(
default=1, description="Page number for pagination", ge=1
),
@@ -1955,9 +1959,21 @@ async def get_user_daily_activity(
)
try:
- entity_id: Optional[str] = None
- if not _user_has_admin_view(user_api_key_dict):
- entity_id = user_api_key_dict.user_id
+ is_admin = _user_has_admin_view(user_api_key_dict)
+
+ if is_admin:
+ entity_id = user_id # None means global view, otherwise filter by user
+ else:
+ if user_id is None:
+ user_id = user_api_key_dict.user_id
+ if user_id != user_api_key_dict.user_id:
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail={
+ "error": "Non-admin users can only view their own spend data."
+ },
+ )
+ entity_id = user_id
return await get_daily_activity(
prisma_client=prisma_client,
@@ -1974,6 +1990,8 @@ async def get_user_daily_activity(
timezone_offset_minutes=timezone,
)
+ except HTTPException:
+ raise
except Exception as e:
verbose_proxy_logger.exception(
"/spend/daily/analytics: Exception occured - {}".format(str(e))
@@ -2008,6 +2026,10 @@ async def get_user_daily_activity_aggregated(
default=None,
description="Filter by specific API key",
),
+ user_id: Optional[str] = fastapi.Query(
+ default=None,
+ description="Filter by specific user ID. Admins can filter by any user or omit for global view. Non-admins must provide their own user_id.",
+ ),
timezone: Optional[int] = fastapi.Query(
default=None,
description="Timezone offset in minutes from UTC (e.g., 480 for PST). "
@@ -2034,9 +2056,21 @@ async def get_user_daily_activity_aggregated(
)
try:
- entity_id: Optional[str] = None
- if not _user_has_admin_view(user_api_key_dict):
- entity_id = user_api_key_dict.user_id
+ is_admin = _user_has_admin_view(user_api_key_dict)
+
+ if is_admin:
+ entity_id = user_id # None means global view, otherwise filter by user
+ else:
+ if user_id is None:
+ user_id = user_api_key_dict.user_id
+ if user_id != user_api_key_dict.user_id:
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail={
+ "error": "Non-admin users can only view their own spend data."
+ },
+ )
+ entity_id = user_id
return await get_daily_activity_aggregated(
prisma_client=prisma_client,
@@ -2051,6 +2085,8 @@ async def get_user_daily_activity_aggregated(
timezone_offset_minutes=timezone,
)
+ except HTTPException:
+ raise
except Exception as e:
verbose_proxy_logger.exception(
"/user/daily/activity/aggregated: Exception occured - {}".format(str(e))
diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py
index 9dcc25e7a87..21459a1b802 100644
--- a/litellm/proxy/management_endpoints/key_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py
@@ -3277,6 +3277,14 @@ async def _execute_virtual_key_regeneration(
update_data.update(non_default_values)
update_data = prisma_client.jsonify_object(data=update_data)
+ # If grace period set, insert deprecated key so old key remains valid
+ await _insert_deprecated_key(
+ prisma_client=prisma_client,
+ old_token_hash=hashed_api_key,
+ new_token_hash=new_token_hash,
+ grace_period=data.grace_period if data else None,
+ )
+
updated_token = await prisma_client.db.litellm_verificationtoken.update(
where={"token": hashed_api_key},
data=update_data, # type: ignore
@@ -3474,58 +3482,6 @@ async def regenerate_key_fn( # noqa: PLR0915
)
verbose_proxy_logger.debug("key_in_db: %s", _key_in_db)
- new_token = get_new_token(data=data)
-
- new_token_hash = hash_token(new_token)
- new_token_key_name = f"sk-...{new_token[-4:]}"
-
- # Prepare the update data
- update_data = {
- "token": new_token_hash,
- "key_name": new_token_key_name,
- }
-
- non_default_values = {}
- if data is not None:
- # Update with any provided parameters from GenerateKeyRequest
- non_default_values = await prepare_key_update_data(
- data=data, existing_key_row=_key_in_db
- )
- verbose_proxy_logger.debug("non_default_values: %s", non_default_values)
-
- update_data.update(non_default_values)
- update_data = prisma_client.jsonify_object(data=update_data)
-
- # If grace period set, insert deprecated key so old key remains valid
- await _insert_deprecated_key(
- prisma_client=prisma_client,
- old_token_hash=hashed_api_key,
- new_token_hash=new_token_hash,
- grace_period=data.grace_period if data else None,
- )
-
- # Update the token in the database
- updated_token = await prisma_client.db.litellm_verificationtoken.update(
- where={"token": hashed_api_key},
- data=update_data, # type: ignore
- )
-
- updated_token_dict = {}
- if updated_token is not None:
- updated_token_dict = dict(updated_token)
-
- updated_token_dict["key"] = new_token
- updated_token_dict["token_id"] = updated_token_dict.pop("token")
-
- ### 3. remove existing key entry from cache
- ######################################################################
-
- if hashed_api_key or key:
- await _delete_cache_key_object(
- hashed_token=hash_token(key),
- user_api_key_cache=user_api_key_cache,
- proxy_logging_obj=proxy_logging_obj,
- )
# Normalize litellm_changed_by: if it's a Header object or not a string, convert to None
if litellm_changed_by is not None and not isinstance(litellm_changed_by, str):
litellm_changed_by = None
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index 5fbfd23b2db..5f8798c7712 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -2644,6 +2644,9 @@ class StandardLoggingGuardrailInformation(TypedDict, total=False):
alert_recipients: Optional[List[str]]
"""Email addresses that were notified"""
+ risk_score: Optional[float]
+ """Risk score 0-10 indicating how risky the request was (higher = riskier). Computed by the guardrail provider."""
+
class GuardrailTracingDetail(TypedDict, total=False):
"""
@@ -2661,6 +2664,7 @@ class GuardrailTracingDetail(TypedDict, total=False):
match_details: Optional[List[dict]]
patterns_checked: Optional[int]
alert_recipients: Optional[List[str]]
+ risk_score: Optional[float]
StandardLoggingPayloadStatus = Literal["success", "failure"]
diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json
index 9ea9f39b1db..41acb5c8101 100644
--- a/model_prices_and_context_window.json
+++ b/model_prices_and_context_window.json
@@ -17112,6 +17112,19 @@
"supports_parallel_function_calling": true,
"supports_vision": true
},
+ "github_copilot/claude-opus-4.6-fast": {
+ "litellm_provider": "github_copilot",
+ "max_input_tokens": 128000,
+ "max_output_tokens": 16000,
+ "max_tokens": 16000,
+ "mode": "chat",
+ "supported_endpoints": [
+ "/v1/chat/completions"
+ ],
+ "supports_function_calling": true,
+ "supports_parallel_function_calling": true,
+ "supports_vision": true
+ },
"github_copilot/claude-opus-41": {
"litellm_provider": "github_copilot",
"max_input_tokens": 80000,
@@ -17363,6 +17376,20 @@
"supports_response_schema": true,
"supports_vision": true
},
+ "github_copilot/gpt-5.3-codex": {
+ "litellm_provider": "github_copilot",
+ "max_input_tokens": 128000,
+ "max_output_tokens": 128000,
+ "max_tokens": 128000,
+ "mode": "responses",
+ "supported_endpoints": [
+ "/v1/responses"
+ ],
+ "supports_function_calling": true,
+ "supports_parallel_function_calling": true,
+ "supports_response_schema": true,
+ "supports_vision": true
+ },
"github_copilot/text-embedding-3-small": {
"litellm_provider": "github_copilot",
"max_input_tokens": 8191,
diff --git a/pyproject.toml b/pyproject.toml
index 68b38fb5ff8..4deb61836b3 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "litellm"
-version = "1.81.12"
+version = "1.81.13"
description = "Library to easily interface with LLM API providers"
authors = ["BerriAI"]
license = "MIT"
@@ -182,7 +182,7 @@ requires = ["poetry-core", "wheel"]
build-backend = "poetry.core.masonry.api"
[tool.commitizen]
-version = "1.81.12"
+version = "1.81.13"
version_files = [
"pyproject.toml:^version"
]
diff --git a/tests/llm_responses_api_testing/base_responses_api.py b/tests/llm_responses_api_testing/base_responses_api.py
index 0850f742231..f38ce67cede 100644
--- a/tests/llm_responses_api_testing/base_responses_api.py
+++ b/tests/llm_responses_api_testing/base_responses_api.py
@@ -74,7 +74,7 @@ def validate_responses_api_response(response, final_chunk: bool = False):
"top_p": (int, float, type(None)),
"max_output_tokens": (int, type(None)),
"previous_response_id": (str, type(None)),
- "reasoning": dict,
+ "reasoning": (dict, type(None)),
"status": str,
"text": dict,
"truncation": (str, type(None)),
diff --git a/tests/test_litellm/containers/test_container_integration.py b/tests/test_litellm/containers/test_container_integration.py
index b2f52fcea97..177996abd99 100644
--- a/tests/test_litellm/containers/test_container_integration.py
+++ b/tests/test_litellm/containers/test_container_integration.py
@@ -385,6 +385,15 @@ class TestContainerIntegration:
@pytest.mark.parametrize("provider", ["openai"])
def test_provider_support(self, provider):
"""Test that the container API works with supported providers."""
+ import importlib
+ import litellm.containers.main as containers_main_module
+
+ # Reload the module to ensure it has a fresh reference to base_llm_http_handler
+ # after conftest reloads litellm (same pattern as test_error_handling_integration)
+ importlib.reload(containers_main_module)
+
+ from litellm.containers.main import create_container as create_container_fresh
+
mock_response = ContainerObject(
id="cntr_provider_test",
object="container",
@@ -398,7 +407,7 @@ class TestContainerIntegration:
with patch('litellm.containers.main.base_llm_http_handler') as mock_handler:
mock_handler.container_create_handler.return_value = mock_response
- response = create_container(
+ response = create_container_fresh(
name="Provider Test Container",
custom_llm_provider=provider
)
diff --git a/tests/test_litellm/llms/meta_llama/test_meta_llama_chat_transformation.py b/tests/test_litellm/llms/meta_llama/test_meta_llama_chat_transformation.py
index fa605154bb0..7b974aba35c 100644
--- a/tests/test_litellm/llms/meta_llama/test_meta_llama_chat_transformation.py
+++ b/tests/test_litellm/llms/meta_llama/test_meta_llama_chat_transformation.py
@@ -1,6 +1,5 @@
import os
import sys
-from unittest.mock import AsyncMock, patch
import pytest
@@ -47,67 +46,26 @@ def test_map_openai_params():
assert "response_format" in result
-async def test_llama_api_streaming_no_307_error():
- """Test that streaming works without 307 redirect errors due to follow_redirects=True"""
-
- # Mock the httpx client to simulate a successful streaming response
- with patch(
- "litellm.llms.custom_httpx.http_handler.get_async_httpx_client"
- ) as mock_get_client:
- # Create a mock client
- mock_client = AsyncMock()
- mock_get_client.return_value = mock_client
-
- # Mock a successful streaming response (not a 307 redirect)
- mock_response = AsyncMock()
- mock_response.status_code = 200
- mock_response.headers = {"content-type": "text/plain; charset=utf-8"}
-
- # Mock streaming data that would come from a successful request
- async def mock_aiter_lines():
- yield 'data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1234567890,"model":"meta_llama/Llama-4-Maverick-17B-128E-Instruct-FP8","choices":[{"index":0,"delta":{"role":"assistant","content":"Hello"},"finish_reason":null}]}'
- yield 'data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1234567890,"model":"meta_llama/Llama-4-Maverick-17B-128E-Instruct-FP8","choices":[{"index":0,"delta":{"content":" there"},"finish_reason":null}]}'
- yield 'data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1234567890,"model":"meta_llama/Llama-4-Maverick-17B-128E-Instruct-FP8","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}'
- yield "data: [DONE]"
-
- mock_response.aiter_lines.return_value = mock_aiter_lines()
- mock_client.stream.return_value.__aenter__.return_value = mock_response
-
- # Test the streaming completion
- try:
- response = await litellm.acompletion(
- model="meta_llama/Llama-4-Maverick-17B-128E-Instruct-FP8",
- messages=[{"role": "user", "content": "Tell me about yourself"}],
- stream=True,
- temperature=0.0,
- )
-
- # Verify we get a CustomStreamWrapper (streaming response)
- from litellm.utils import CustomStreamWrapper
-
- assert isinstance(response, CustomStreamWrapper)
-
- # Verify the HTTP client was called with follow_redirects=True
- mock_client.stream.assert_called_once()
- call_kwargs = mock_client.stream.call_args[1]
- assert (
- call_kwargs.get("follow_redirects") is True
- ), "follow_redirects should be True to prevent 307 errors"
-
- # Verify the response status is 200 (not 307)
- assert (
- mock_response.status_code == 200
- ), "Should get 200 response, not 307 redirect"
-
- except Exception as e:
- # If there's an exception, make sure it's not a 307 error
- error_str = str(e)
- assert (
- "307" not in error_str
- ), f"Should not get 307 redirect error: {error_str}"
-
- # Still verify that follow_redirects was set correctly
- if mock_client.stream.called:
- call_kwargs = mock_client.stream.call_args[1]
- assert call_kwargs.get("follow_redirects") is True
+def test_llama_api_streaming_no_307_error():
+ """
+ Test that the OpenAI-compatible httpx clients use follow_redirects=True.
+
+ meta_llama routes through the OpenAI SDK path (BaseOpenAILLM), so the
+ follow_redirects setting on that SDK's underlying httpx client is what
+ actually prevents 307 redirect errors for LLaMA API streaming.
+ """
+ from litellm.llms.openai.common_utils import BaseOpenAILLM
+
+ # Verify the async httpx client has follow_redirects enabled
+ async_client = BaseOpenAILLM._get_async_http_client()
+ assert async_client is not None
+ assert (
+ async_client.follow_redirects is True
+ ), "Async httpx client should set follow_redirects=True to prevent 307 errors"
+
+ # Verify the sync httpx client has follow_redirects enabled
+ sync_client = BaseOpenAILLM._get_sync_http_client()
+ assert sync_client is not None
+ assert (
+ sync_client.follow_redirects is True
+ ), "Sync httpx client should set follow_redirects=True to prevent 307 errors"
diff --git a/tests/test_litellm/llms/publicai/test_publicai_chat_transformation.py b/tests/test_litellm/llms/publicai/test_publicai_chat_transformation.py
index f6e5e05fe51..cd530cd3b40 100644
--- a/tests/test_litellm/llms/publicai/test_publicai_chat_transformation.py
+++ b/tests/test_litellm/llms/publicai/test_publicai_chat_transformation.py
@@ -7,6 +7,7 @@ PublicAI is an OpenAI-compatible provider with minor customizations.
import os
import sys
+from unittest.mock import patch
sys.path.insert(
0, os.path.abspath("../../../../..")
@@ -51,9 +52,13 @@ class TestPublicAIConfig:
assert result["Authorization"] == f"Bearer {api_key}"
assert result["Content-Type"] == "application/json"
- def test_get_supported_openai_params(self, config):
+ @patch("litellm.utils.supports_function_calling", return_value=True)
+ def test_get_supported_openai_params(self, mock_supports_fc, config):
"""
- Test that get_supported_openai_params returns correct params
+ Test that get_supported_openai_params returns correct params.
+ We mock supports_function_calling because the test model name
+ 'swiss-ai-apertus' is not in the model registry; this test validates
+ config behaviour, not registry lookups.
"""
supported_params = config.get_supported_openai_params(model="swiss-ai-apertus")
@@ -66,9 +71,12 @@ class TestPublicAIConfig:
# Note: JSON-based configs inherit from OpenAIGPTConfig which includes functions
# This is expected behavior for JSON-based providers
- def test_map_openai_params_includes_functions(self, config):
+ @patch("litellm.utils.supports_function_calling", return_value=True)
+ def test_map_openai_params_includes_functions(self, mock_supports_fc, config):
"""
- Test that functions parameter is mapped (JSON-based configs don't exclude functions)
+ Test that functions parameter is mapped (JSON-based configs don't exclude functions).
+ We mock supports_function_calling because the test model name
+ 'swiss-ai-apertus' is not in the model registry.
"""
non_default_params = {
"functions": [{"name": "test_function", "description": "Test function"}],
diff --git a/tests/test_litellm/llms/vertex_ai/rerank/test_vertex_ai_rerank_transformation.py b/tests/test_litellm/llms/vertex_ai/rerank/test_vertex_ai_rerank_transformation.py
index fbf5239797f..5e29f927b67 100644
--- a/tests/test_litellm/llms/vertex_ai/rerank/test_vertex_ai_rerank_transformation.py
+++ b/tests/test_litellm/llms/vertex_ai/rerank/test_vertex_ai_rerank_transformation.py
@@ -22,6 +22,8 @@ class TestVertexAIRerankTransform:
"GOOGLE_APPLICATION_CREDENTIALS",
"GOOGLE_CLOUD_PROJECT",
"VERTEXAI_PROJECT",
+ "VERTEXAI_CREDENTIALS",
+ "VERTEX_AI_CREDENTIALS",
"VERTEX_PROJECT",
"VERTEX_LOCATION",
"VERTEX_AI_PROJECT",
@@ -471,16 +473,20 @@ class TestVertexAIRerankTransform:
}
assert headers == expected_headers
- @patch('litellm.llms.vertex_ai.rerank.transformation.VertexAIRerankConfig._ensure_access_token')
def test_validate_environment_preserves_optional_params_for_get_complete_url(
self,
- mock_ensure_access_token,
):
"""
Validate that calling validate_environment does not remove vertex-specific
parameters needed later by get_complete_url.
+
+ Uses instance-level mocking to avoid class-reference issues caused by
+ importlib.reload(litellm) in conftest.py.
"""
- mock_ensure_access_token.return_value = ("test-access-token", "project-from-token")
+ mock_ensure_access_token = MagicMock(
+ return_value=("test-access-token", "project-from-token")
+ )
+ self.config._ensure_access_token = mock_ensure_access_token
optional_params = {
"vertex_credentials": "path/to/credentials.json",
diff --git a/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py
index 919af96f760..9a417f3566c 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py
@@ -1167,4 +1167,136 @@ def test_generate_request_base_validator():
# Test with None
req = GenerateRequestBase(max_budget=None)
- assert req.max_budget is None
\ No newline at end of file
+ assert req.max_budget is None
+
+
+async def test_get_user_daily_activity_non_admin_cannot_view_other_users(monkeypatch):
+ """
+ Test that non-admin users cannot view another user's daily activity data.
+ The endpoint should raise 403 when user_id does not match the caller's own user_id.
+ Also verifies that omitting user_id defaults to the caller's own user_id.
+ """
+ from unittest.mock import AsyncMock, MagicMock, patch
+
+ from fastapi import HTTPException
+
+ from litellm.proxy.management_endpoints.internal_user_endpoints import (
+ get_user_daily_activity,
+ )
+
+ # Mock the prisma client so the DB-not-connected check passes
+ mock_prisma_client = MagicMock()
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.prisma_client", mock_prisma_client
+ )
+
+ # Non-admin caller
+ non_admin_key_dict = UserAPIKeyAuth(
+ user_id="regular-user-123",
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ )
+
+ # Case 1: Non-admin tries to view a different user's data — should get 403
+ with pytest.raises(HTTPException) as exc_info:
+ await get_user_daily_activity(
+ start_date="2025-01-01",
+ end_date="2025-01-31",
+ model=None,
+ api_key=None,
+ user_id="other-user-456",
+ page=1,
+ page_size=50,
+ timezone=None,
+ user_api_key_dict=non_admin_key_dict,
+ )
+
+ assert exc_info.value.status_code == 403
+ assert "Non-admin users can only view their own spend data" in str(
+ exc_info.value.detail
+ )
+
+ # Case 2: Non-admin omits user_id — should default to their own user_id
+ mock_response = MagicMock()
+ with patch(
+ "litellm.proxy.management_endpoints.internal_user_endpoints.get_daily_activity",
+ new_callable=AsyncMock,
+ return_value=mock_response,
+ ) as mock_get_daily:
+ result = await get_user_daily_activity(
+ start_date="2025-01-01",
+ end_date="2025-01-31",
+ model=None,
+ api_key=None,
+ user_id=None,
+ page=1,
+ page_size=50,
+ timezone=None,
+ user_api_key_dict=non_admin_key_dict,
+ )
+
+ # Verify it called get_daily_activity with the caller's own user_id
+ mock_get_daily.assert_called_once()
+ call_kwargs = mock_get_daily.call_args
+ assert call_kwargs.kwargs["entity_id"] == "regular-user-123"
+
+
+async def test_get_user_daily_activity_aggregated_admin_global_view(monkeypatch):
+ """
+ Test that admin users can call the aggregated endpoint without a user_id
+ to get a global view. Also verifies that the correct arguments are forwarded
+ to the underlying get_daily_activity_aggregated helper.
+ """
+ from unittest.mock import AsyncMock, MagicMock
+
+ from litellm.proxy.management_endpoints.internal_user_endpoints import (
+ get_user_daily_activity_aggregated,
+ )
+
+ # Mock the prisma client
+ mock_prisma_client = MagicMock()
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.prisma_client", mock_prisma_client
+ )
+
+ # Mock the downstream helper so we don't need a real DB
+ mock_response = MagicMock()
+ mock_get_daily_agg = AsyncMock(return_value=mock_response)
+ monkeypatch.setattr(
+ "litellm.proxy.management_endpoints.internal_user_endpoints.get_daily_activity_aggregated",
+ mock_get_daily_agg,
+ )
+
+ # Admin caller
+ admin_key_dict = UserAPIKeyAuth(
+ user_id="admin-user-001",
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ )
+
+ # Admin calls without user_id → global view (entity_id=None)
+ result = await get_user_daily_activity_aggregated(
+ start_date="2025-02-01",
+ end_date="2025-02-28",
+ model="gpt-4",
+ api_key=None,
+ user_id=None,
+ timezone=480,
+ user_api_key_dict=admin_key_dict,
+ )
+
+ assert result is mock_response
+
+ # Verify the helper was called with the right parameters
+ mock_get_daily_agg.assert_called_once_with(
+ prisma_client=mock_prisma_client,
+ table_name="litellm_dailyuserspend",
+ entity_id_field="user_id",
+ entity_id=None, # global view: no user_id filter
+ entity_metadata_field=None,
+ start_date="2025-02-01",
+ end_date="2025-02-28",
+ model="gpt-4",
+ api_key=None,
+ timezone_offset_minutes=480,
+ )
\ No newline at end of file
diff --git a/tests/test_litellm/proxy/test_proxy_cli.py b/tests/test_litellm/proxy/test_proxy_cli.py
index be91800732b..a18c2dba032 100644
--- a/tests/test_litellm/proxy/test_proxy_cli.py
+++ b/tests/test_litellm/proxy/test_proxy_cli.py
@@ -446,8 +446,24 @@ class TestProxyInitializationHelpers:
mock_proxy_config_instance.get_config = mock_get_config
mock_proxy_config.return_value = mock_proxy_config_instance
- # Ensure DATABASE_URL is not set in the environment
- with patch.dict(os.environ, {"DATABASE_URL": ""}, clear=True):
+ mock_proxy_server_module = MagicMock(app=mock_app)
+
+ # Only remove DATABASE_URL and DIRECT_URL to prevent the database setup
+ # code path from running. Do NOT use clear=True as it removes PATH, HOME,
+ # etc., which causes imports inside run_server to break in CI (the real
+ # litellm.proxy.proxy_server import at line 820 of proxy_cli.py has heavy
+ # side effects that fail without a proper environment).
+ env_overrides = {
+ "DATABASE_URL": "",
+ "DIRECT_URL": "",
+ "IAM_TOKEN_DB_AUTH": "",
+ "USE_AWS_KMS": "",
+ }
+ with patch.dict(os.environ, env_overrides):
+ # Remove DATABASE_URL entirely so the DB setup block is skipped
+ os.environ.pop("DATABASE_URL", None)
+ os.environ.pop("DIRECT_URL", None)
+
with patch.dict(
"sys.modules",
{
@@ -456,7 +472,11 @@ class TestProxyInitializationHelpers:
ProxyConfig=mock_proxy_config,
KeyManagementSettings=mock_key_mgmt,
save_worker_config=mock_save_worker_config,
- )
+ ),
+ # Also mock litellm.proxy.proxy_server to prevent the real
+ # import at line 820 of proxy_cli.py which has heavy side
+ # effects (FastAPI app init, logging setup, etc.)
+ "litellm.proxy.proxy_server": mock_proxy_server_module,
},
), patch(
"litellm.proxy.proxy_cli.ProxyInitializationHelpers._get_default_unvicorn_init_args"
@@ -470,7 +490,10 @@ class TestProxyInitializationHelpers:
# Test with no config parameter (config=None)
result = runner.invoke(run_server, ["--local"])
- assert result.exit_code == 0
+ assert result.exit_code == 0, (
+ f"run_server failed with exit_code={result.exit_code}, "
+ f"output={result.output}, exception={result.exception}"
+ )
# Verify that uvicorn.run was called
mock_uvicorn_run.assert_called_once()
@@ -481,7 +504,10 @@ class TestProxyInitializationHelpers:
# Test with explicit --config None (should behave the same)
result = runner.invoke(run_server, ["--local", "--config", "None"])
- assert result.exit_code == 0
+ assert result.exit_code == 0, (
+ f"run_server failed with exit_code={result.exit_code}, "
+ f"output={result.output}, exception={result.exception}"
+ )
# Verify that uvicorn.run was called again
mock_uvicorn_run.assert_called_once()
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/hooks/users/useUsers.test.ts b/ui/litellm-dashboard/src/app/(dashboard)/hooks/users/useUsers.test.ts
new file mode 100644
index 00000000000..b0a96eff0e7
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/(dashboard)/hooks/users/useUsers.test.ts
@@ -0,0 +1,339 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import React, { ReactNode } from "react";
+import { useInfiniteUsers } from "./useUsers";
+import { userListCall } from "@/components/networking";
+import type { UserListResponse } from "@/components/networking";
+
+vi.mock("@/components/networking", () => ({
+ userListCall: vi.fn(),
+}));
+
+vi.mock("../common/queryKeysFactory", () => ({
+ createQueryKeys: vi.fn((resource: string) => ({
+ all: [resource],
+ lists: () => [resource, "list"],
+ list: (params?: any) => [resource, "list", { params }],
+ details: () => [resource, "detail"],
+ detail: (uid: string) => [resource, "detail", uid],
+ })),
+}));
+
+const mockUseAuthorized = vi.fn();
+vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({
+ default: () => mockUseAuthorized(),
+}));
+
+const DEFAULT_AUTH = {
+ accessToken: "test-access-token",
+ userId: "test-user-id",
+ userRole: "Admin",
+ token: "test-token",
+ userEmail: "[email protected]",
+ premiumUser: false,
+ disabledPersonalKeyCreation: null,
+ showSSOBanner: false,
+};
+
+const buildUserListResponse = (
+ page: number,
+ totalPages: number,
+ userCount = 2,
+): UserListResponse => ({
+ page,
+ page_size: 50,
+ total: totalPages * userCount,
+ total_pages: totalPages,
+ users: Array.from({ length: userCount }, (_, i) => ({
+ user_id: `user-${page}-${i}`,
+ user_email: `user-${page}-${i}@example.com`,
+ user_alias: null,
+ user_role: "Internal User",
+ spend: 0,
+ max_budget: null,
+ key_count: 0,
+ created_at: "2024-01-01T00:00:00Z",
+ updated_at: "2024-01-01T00:00:00Z",
+ sso_user_id: null,
+ budget_duration: null,
+ })),
+});
+
+describe("useInfiniteUsers", () => {
+ let queryClient: QueryClient;
+
+ beforeEach(() => {
+ queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ },
+ },
+ });
+ vi.clearAllMocks();
+ mockUseAuthorized.mockReturnValue(DEFAULT_AUTH);
+ });
+
+ const wrapper = ({ children }: { children: ReactNode }) =>
+ React.createElement(QueryClientProvider, { client: queryClient }, children);
+
+ it("should return paginated user data when query is successful", async () => {
+ const mockResponse = buildUserListResponse(1, 2);
+ (userListCall as any).mockResolvedValue(mockResponse);
+
+ const { result } = renderHook(() => useInfiniteUsers(), { wrapper });
+
+ await waitFor(() => {
+ expect(result.current.isSuccess).toBe(true);
+ });
+
+ expect(result.current.data?.pages).toHaveLength(1);
+ expect(result.current.data?.pages[0]).toEqual(mockResponse);
+ expect(userListCall).toHaveBeenCalledWith(
+ "test-access-token",
+ null,
+ 1,
+ 50,
+ null,
+ );
+ });
+
+ it("should use the default page size of 50", async () => {
+ const mockResponse = buildUserListResponse(1, 1);
+ (userListCall as any).mockResolvedValue(mockResponse);
+
+ const { result } = renderHook(() => useInfiniteUsers(), { wrapper });
+
+ await waitFor(() => {
+ expect(result.current.isSuccess).toBe(true);
+ });
+
+ expect(userListCall).toHaveBeenCalledWith(
+ "test-access-token",
+ null,
+ 1,
+ 50,
+ null,
+ );
+ });
+
+ it("should use a custom page size when provided", async () => {
+ const customPageSize = 25;
+ const mockResponse = buildUserListResponse(1, 1, 5);
+ (userListCall as any).mockResolvedValue(mockResponse);
+
+ const { result } = renderHook(() => useInfiniteUsers(customPageSize), {
+ wrapper,
+ });
+
+ await waitFor(() => {
+ expect(result.current.isSuccess).toBe(true);
+ });
+
+ expect(userListCall).toHaveBeenCalledWith(
+ "test-access-token",
+ null,
+ 1,
+ customPageSize,
+ null,
+ );
+ });
+
+ it("should pass searchEmail to userListCall when provided", async () => {
+ const searchEmail = "[email protected]";
+ const mockResponse = buildUserListResponse(1, 1, 1);
+ (userListCall as any).mockResolvedValue(mockResponse);
+
+ const { result } = renderHook(() => useInfiniteUsers(50, searchEmail), {
+ wrapper,
+ });
+
+ await waitFor(() => {
+ expect(result.current.isSuccess).toBe(true);
+ });
+
+ expect(userListCall).toHaveBeenCalledWith(
+ "test-access-token",
+ null,
+ 1,
+ 50,
+ searchEmail,
+ );
+ });
+
+ it("should pass null for searchEmail when not provided", async () => {
+ const mockResponse = buildUserListResponse(1, 1);
+ (userListCall as any).mockResolvedValue(mockResponse);
+
+ const { result } = renderHook(() => useInfiniteUsers(50, undefined), {
+ wrapper,
+ });
+
+ await waitFor(() => {
+ expect(result.current.isSuccess).toBe(true);
+ });
+
+ expect(userListCall).toHaveBeenCalledWith(
+ "test-access-token",
+ null,
+ 1,
+ 50,
+ null,
+ );
+ });
+
+ it("should fetch the next page when more pages are available", async () => {
+ const page1 = buildUserListResponse(1, 3);
+ const page2 = buildUserListResponse(2, 3);
+ let callCount = 0;
+ (userListCall as any).mockImplementation(async () => {
+ callCount++;
+ return callCount === 1 ? page1 : page2;
+ });
+
+ const { result } = renderHook(() => useInfiniteUsers(), { wrapper });
+
+ await waitFor(() => {
+ expect(result.current.isSuccess).toBe(true);
+ });
+
+ expect(result.current.hasNextPage).toBe(true);
+
+ result.current.fetchNextPage();
+
+ await waitFor(() => {
+ expect(result.current.isFetchingNextPage).toBe(false);
+ expect(result.current.data?.pages).toHaveLength(2);
+ });
+
+ expect(result.current.data?.pages[1]).toEqual(page2);
+ expect(userListCall).toHaveBeenCalledTimes(2);
+ expect(userListCall).toHaveBeenLastCalledWith(
+ "test-access-token",
+ null,
+ 2,
+ 50,
+ null,
+ );
+ });
+
+ it("should not have a next page when on the last page", async () => {
+ const lastPage = buildUserListResponse(2, 2);
+ (userListCall as any).mockResolvedValue(lastPage);
+
+ const { result } = renderHook(() => useInfiniteUsers(), { wrapper });
+
+ await waitFor(() => {
+ expect(result.current.isSuccess).toBe(true);
+ });
+
+ expect(result.current.hasNextPage).toBe(false);
+ });
+
+ it("should not execute query when accessToken is missing", async () => {
+ mockUseAuthorized.mockReturnValue({
+ ...DEFAULT_AUTH,
+ accessToken: null,
+ });
+
+ const { result } = renderHook(() => useInfiniteUsers(), { wrapper });
+
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.data).toBeUndefined();
+ expect(result.current.isFetched).toBe(false);
+ expect(userListCall).not.toHaveBeenCalled();
+ });
+
+ it("should not execute query when userRole is not an admin role", async () => {
+ mockUseAuthorized.mockReturnValue({
+ ...DEFAULT_AUTH,
+ userRole: "Internal User",
+ });
+
+ const { result } = renderHook(() => useInfiniteUsers(), { wrapper });
+
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.data).toBeUndefined();
+ expect(result.current.isFetched).toBe(false);
+ expect(userListCall).not.toHaveBeenCalled();
+ });
+
+ it("should not execute query when both accessToken and userRole are invalid", async () => {
+ mockUseAuthorized.mockReturnValue({
+ ...DEFAULT_AUTH,
+ accessToken: null,
+ userRole: "App User",
+ });
+
+ const { result } = renderHook(() => useInfiniteUsers(), { wrapper });
+
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.data).toBeUndefined();
+ expect(result.current.isFetched).toBe(false);
+ expect(userListCall).not.toHaveBeenCalled();
+ });
+
+ it("should execute query for each admin role", async () => {
+ const adminRoles = [
+ "Admin",
+ "Admin Viewer",
+ "proxy_admin",
+ "proxy_admin_viewer",
+ "org_admin",
+ ];
+
+ for (const role of adminRoles) {
+ vi.clearAllMocks();
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const mockResponse = buildUserListResponse(1, 1);
+ (userListCall as any).mockResolvedValue(mockResponse);
+ mockUseAuthorized.mockReturnValue({ ...DEFAULT_AUTH, userRole: role });
+
+ const { result } = renderHook(() => useInfiniteUsers(), { wrapper });
+
+ await waitFor(() => {
+ expect(result.current.isSuccess).toBe(true);
+ });
+
+ expect(userListCall).toHaveBeenCalledTimes(1);
+ }
+ });
+
+ it("should handle error when userListCall fails", async () => {
+ const testError = new Error("Failed to fetch users");
+ (userListCall as any).mockRejectedValue(testError);
+
+ const { result } = renderHook(() => useInfiniteUsers(), { wrapper });
+
+ await waitFor(() => {
+ expect(result.current.isError).toBe(true);
+ });
+
+ expect(result.current.error).toEqual(testError);
+ expect(result.current.data).toBeUndefined();
+ });
+
+ it("should pass empty string searchEmail as null", async () => {
+ const mockResponse = buildUserListResponse(1, 1);
+ (userListCall as any).mockResolvedValue(mockResponse);
+
+ const { result } = renderHook(() => useInfiniteUsers(50, ""), {
+ wrapper,
+ });
+
+ await waitFor(() => {
+ expect(result.current.isSuccess).toBe(true);
+ });
+
+ expect(userListCall).toHaveBeenCalledWith(
+ "test-access-token",
+ null,
+ 1,
+ 50,
+ null,
+ );
+ });
+});
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/hooks/users/useUsers.ts b/ui/litellm-dashboard/src/app/(dashboard)/hooks/users/useUsers.ts
new file mode 100644
index 00000000000..cb30299f46f
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/(dashboard)/hooks/users/useUsers.ts
@@ -0,0 +1,41 @@
+import { userListCall, UserListResponse } from "@/components/networking";
+import { useInfiniteQuery } from "@tanstack/react-query";
+import { createQueryKeys } from "../common/queryKeysFactory";
+import { all_admin_roles } from "@/utils/roles";
+import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";
+
+const infiniteUsersKeys = createQueryKeys("infiniteUsers");
+
+const DEFAULT_PAGE_SIZE = 50;
+
+export const useInfiniteUsers = (
+ pageSize: number = DEFAULT_PAGE_SIZE,
+ searchEmail?: string,
+) => {
+ const { accessToken, userRole } = useAuthorized();
+ return useInfiniteQuery<UserListResponse>({
+ queryKey: infiniteUsersKeys.list({
+ filters: {
+ pageSize,
+ ...(searchEmail && { searchEmail }),
+ },
+ }),
+ queryFn: async ({ pageParam }) => {
+ return await userListCall(
+ accessToken!,
+ null, // userIDs
+ pageParam as number, // page
+ pageSize, // page_size
+ searchEmail || null, // userEmail
+ );
+ },
+ initialPageParam: 1,
+ getNextPageParam: (lastPage) => {
+ if (lastPage.page < lastPage.total_pages) {
+ return lastPage.page + 1;
+ }
+ return undefined;
+ },
+ enabled: Boolean(accessToken) && all_admin_roles.includes(userRole!),
+ });
+};
diff --git a/ui/litellm-dashboard/src/components/UsagePage/components/UsagePageView.test.tsx b/ui/litellm-dashboard/src/components/UsagePage/components/UsagePageView.test.tsx
index 1a344d3dd95..5f5ffe83baa 100644
--- a/ui/litellm-dashboard/src/components/UsagePage/components/UsagePageView.test.tsx
+++ b/ui/litellm-dashboard/src/components/UsagePage/components/UsagePageView.test.tsx
@@ -2,6 +2,7 @@ import { useAgents } from "@/app/(dashboard)/hooks/agents/useAgents";
import { useCustomers } from "@/app/(dashboard)/hooks/customers/useCustomers";
import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";
import { useCurrentUser } from "@/app/(dashboard)/hooks/users/useCurrentUser";
+import { useInfiniteUsers } from "@/app/(dashboard)/hooks/users/useUsers";
import { act, fireEvent, screen, waitFor } from "@testing-library/react";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { renderWithProviders } from "../../../../tests/test-utils";
@@ -116,6 +117,10 @@ vi.mock("@/app/(dashboard)/hooks/users/useCurrentUser", () => ({
useCurrentUser: vi.fn(),
}));
+vi.mock("@/app/(dashboard)/hooks/users/useUsers", () => ({
+ useInfiniteUsers: vi.fn(),
+}));
+
vi.mock("antd", async (importOriginal) => {
const React = await import("react");
const actual = await importOriginal<typeof import("antd")>();
@@ -223,6 +228,10 @@ vi.mock("@ant-design/icons", async () => {
return React.createElement("span");
}
+ function LoadingOutlined(props: any) {
+ return React.createElement("span", { "data-testid": "loading-icon", ...props });
+ }
+
return {
GlobalOutlined: Icon,
BankOutlined: Icon,
@@ -235,6 +244,8 @@ vi.mock("@ant-design/icons", async () => {
ClockCircleOutlined: Icon,
CalendarOutlined: Icon,
InfoCircleOutlined: Icon,
+ UserOutlined: Icon,
+ LoadingOutlined,
};
});
@@ -320,11 +331,13 @@ vi.mock("@tremor/react", async () => {
describe("UsagePage", () => {
const mockUserDailyActivityAggregatedCall = vi.mocked(networking.userDailyActivityAggregatedCall);
+ const mockUserDailyActivityCall = vi.mocked(networking.userDailyActivityCall);
const mockTagListCall = vi.mocked(networking.tagListCall);
const mockUseCustomers = vi.mocked(useCustomers);
const mockUseAgents = vi.mocked(useAgents);
const mockUseAuthorized = vi.mocked(useAuthorized);
const mockUseCurrentUser = vi.mocked(useCurrentUser);
+ const mockUseInfiniteUsers = vi.mocked(useInfiniteUsers);
const mockSpendData = {
results: [
@@ -487,6 +500,8 @@ describe("UsagePage", () => {
beforeEach(() => {
mockUseAuthorized.mockReturnValue({
+ isLoading: false,
+ isAuthorized: true,
token: "mock-token",
accessToken: "test-token",
userId: "user-123",
@@ -505,8 +520,30 @@ describe("UsagePage", () => {
error: null,
} as any);
mockUserDailyActivityAggregatedCall.mockClear();
+ mockUserDailyActivityCall.mockClear();
mockTagListCall.mockClear();
mockUserDailyActivityAggregatedCall.mockResolvedValue(mockSpendData);
+ mockUseInfiniteUsers.mockReturnValue({
+ data: {
+ pages: [
+ {
+ users: [
+ { user_id: "user-001", user_alias: "Alice", user_email: "[email protected]" },
+ { user_id: "user-002", user_alias: null, user_email: "[email protected]" },
+ { user_id: "user-003", user_alias: null, user_email: null },
+ ],
+ page: 1,
+ total_pages: 1,
+ total_count: 3,
+ },
+ ],
+ pageParams: [1],
+ },
+ fetchNextPage: vi.fn(),
+ hasNextPage: false,
+ isFetchingNextPage: false,
+ isLoading: false,
+ } as any);
mockTagListCall.mockResolvedValue({});
mockUseCustomers.mockReturnValue({
data: [],
@@ -661,4 +698,434 @@ describe("UsagePage", () => {
expect(entityUsageElements.length).toBeGreaterThan(0);
});
});
+
+ describe("admin user selector", () => {
+ it("should render user selector for admin users in global view", async () => {
+ renderWithProviders(<UsagePage {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();
+ });
+
+ // Admin should see the user selector select element with the placeholder attribute
+ const userSelects = screen.getAllByRole("combobox");
+ const userSelect = userSelects.find(
+ (el) => el.getAttribute("placeholder") === "All Users (Global View)",
+ );
+ expect(userSelect).toBeDefined();
+ });
+
+ it("should format user options with alias when available", async () => {
+ renderWithProviders(<UsagePage {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();
+ });
+
+ // User with alias should show "alias (id)"
+ expect(screen.getByText("Alice (user-001)")).toBeInTheDocument();
+ // User without alias but with email should show "email (id)"
+ expect(screen.getByText("[email protected] (user-002)")).toBeInTheDocument();
+ // User with neither alias nor email should show just the id
+ expect(screen.getByText("user-003")).toBeInTheDocument();
+ });
+
+ it("should call useInfiniteUsers with debounced search", async () => {
+ renderWithProviders(<UsagePage {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();
+ });
+
+ // useInfiniteUsers should be called with default page size
+ expect(mockUseInfiniteUsers).toHaveBeenCalledWith(50, undefined);
+ });
+
+ it("should deduplicate users across pages", async () => {
+ mockUseInfiniteUsers.mockReturnValue({
+ data: {
+ pages: [
+ {
+ users: [
+ { user_id: "user-dup", user_alias: "DupUser", user_email: null },
+ ],
+ page: 1,
+ total_pages: 2,
+ total_count: 2,
+ },
+ {
+ users: [
+ { user_id: "user-dup", user_alias: "DupUser", user_email: null },
+ { user_id: "user-unique", user_alias: "UniqueUser", user_email: null },
+ ],
+ page: 2,
+ total_pages: 2,
+ total_count: 2,
+ },
+ ],
+ pageParams: [1, 2],
+ },
+ fetchNextPage: vi.fn(),
+ hasNextPage: false,
+ isFetchingNextPage: false,
+ isLoading: false,
+ } as any);
+
+ renderWithProviders(<UsagePage {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();
+ });
+
+ // Duplicate user should appear only once
+ const dupElements = screen.getAllByText("DupUser (user-dup)");
+ expect(dupElements).toHaveLength(1);
+ // Unique user should also appear
+ expect(screen.getByText("UniqueUser (user-unique)")).toBeInTheDocument();
+ });
+
+ it("should pass selected userId to aggregated call", async () => {
+ renderWithProviders(<UsagePage {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();
+ });
+
+ // Initially called with null (global view for admin)
+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalledWith(
+ "test-token",
+ expect.any(Date),
+ expect.any(Date),
+ null,
+ );
+ });
+ });
+
+ describe("non-admin user behavior", () => {
+ it("should not render user selector for non-admin users", async () => {
+ mockUseAuthorized.mockReturnValue({
+ isLoading: false,
+ isAuthorized: true,
+ token: "mock-token",
+ accessToken: "test-token",
+ userId: "user-123",
+ userEmail: "[email protected]",
+ userRole: "Internal User",
+ premiumUser: false,
+ disabledPersonalKeyCreation: false,
+ showSSOBanner: false,
+ });
+
+ renderWithProviders(<UsagePage {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();
+ });
+
+ // Non-admin should not see the user selector
+ const userSelects = screen.getAllByRole("combobox");
+ const userSelect = userSelects.find(
+ (el) => el.getAttribute("placeholder") === "All Users (Global View)",
+ );
+ expect(userSelect).toBeUndefined();
+ });
+
+ it("should always pass own userId for non-admin users", async () => {
+ mockUseAuthorized.mockReturnValue({
+ isLoading: false,
+ isAuthorized: true,
+ token: "mock-token",
+ accessToken: "test-token",
+ userId: "user-123",
+ userEmail: "[email protected]",
+ userRole: "Internal User",
+ premiumUser: false,
+ disabledPersonalKeyCreation: false,
+ showSSOBanner: false,
+ });
+
+ renderWithProviders(<UsagePage {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalledWith(
+ "test-token",
+ expect.any(Date),
+ expect.any(Date),
+ "user-123",
+ );
+ });
+ });
+ });
+
+ describe("aggregated endpoint fallback", () => {
+ it("should fall back to paginated calls when aggregated endpoint fails", async () => {
+ mockUserDailyActivityAggregatedCall.mockRejectedValue(new Error("Aggregated endpoint not available"));
+ mockUserDailyActivityCall.mockResolvedValue({
+ ...mockSpendData,
+ metadata: {
+ ...mockSpendData.metadata,
+ total_pages: 1,
+ page: 1,
+ },
+ });
+
+ renderWithProviders(<UsagePage {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();
+ expect(mockUserDailyActivityCall).toHaveBeenCalled();
+ });
+
+ // Should still render the data from the paginated fallback
+ expect(screen.getByText("1,500")).toBeInTheDocument();
+ });
+
+ it("should aggregate multiple pages when paginated endpoint has more than 1 page", async () => {
+ mockUserDailyActivityAggregatedCall.mockRejectedValue(new Error("Not available"));
+
+ const page1Data = {
+ results: [mockSpendData.results[0]],
+ metadata: {
+ total_spend: 60,
+ total_api_requests: 700,
+ total_successful_requests: 680,
+ total_failed_requests: 20,
+ total_tokens: 35000,
+ total_pages: 2,
+ page: 1,
+ },
+ };
+
+ const page2Data = {
+ results: [
+ {
+ ...mockSpendData.results[0],
+ date: "2025-01-02",
+ },
+ ],
+ metadata: {
+ total_spend: 65.75,
+ total_api_requests: 800,
+ total_successful_requests: 770,
+ total_failed_requests: 30,
+ total_tokens: 40000,
+ total_pages: 2,
+ page: 2,
+ },
+ };
+
+ mockUserDailyActivityCall
+ .mockResolvedValueOnce(page1Data)
+ .mockResolvedValueOnce(page2Data);
+
+ renderWithProviders(<UsagePage {...defaultProps} />);
+
+ await waitFor(() => {
+ // Both pages should have been fetched
+ expect(mockUserDailyActivityCall).toHaveBeenCalledTimes(2);
+ });
+
+ // Verify first page call
+ expect(mockUserDailyActivityCall).toHaveBeenCalledWith(
+ "test-token",
+ expect.any(Date),
+ expect.any(Date),
+ 1,
+ null,
+ );
+
+ // Verify second page call
+ expect(mockUserDailyActivityCall).toHaveBeenCalledWith(
+ "test-token",
+ expect.any(Date),
+ expect.any(Date),
+ 2,
+ null,
+ );
+ });
+ });
+
+ describe("MCP Server Activity tab", () => {
+ it("should render MCP Server Activity tab", async () => {
+ renderWithProviders(<UsagePage {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();
+ });
+
+ // The tab list should contain MCP Server Activity
+ expect(screen.getByText("MCP Server Activity")).toBeInTheDocument();
+ });
+ });
+
+ describe("User Agent Activity view", () => {
+ it("should render User Agent Activity component when view is selected", async () => {
+ renderWithProviders(<UsagePage {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();
+ });
+
+ const usageSelect = screen.getByTestId("usage-view-select");
+ act(() => {
+ fireEvent.change(usageSelect, { target: { value: "user-agent-activity" } });
+ });
+
+ await waitFor(() => {
+ // "User Agent Activity" appears both in the select option and in the rendered component
+ const elements = screen.getAllByText("User Agent Activity");
+ expect(elements.length).toBeGreaterThanOrEqual(2);
+ });
+ });
+ });
+
+ describe("Export Data button", () => {
+ it("should render Export Data button in global view for admin", async () => {
+ renderWithProviders(<UsagePage {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();
+ });
+
+ expect(screen.getByText("Export Data")).toBeInTheDocument();
+ });
+ });
+
+ describe("model view toggle", () => {
+ it("should show Public Model Name view by default", async () => {
+ renderWithProviders(<UsagePage {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();
+ });
+
+ // Default should be "groups" view showing "Top Public Model Names"
+ expect(screen.getByText("Top Public Model Names")).toBeInTheDocument();
+ expect(screen.getByText("Public Model Name")).toBeInTheDocument();
+ expect(screen.getByText("Litellm Model Name")).toBeInTheDocument();
+ });
+
+ it("should switch to Litellm Model Name view on toggle click", async () => {
+ renderWithProviders(<UsagePage {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();
+ });
+
+ // Click the "Litellm Model Name" toggle
+ const litellmToggle = screen.getByText("Litellm Model Name");
+ act(() => {
+ fireEvent.click(litellmToggle);
+ });
+
+ // Title should change to "Top Litellm Models"
+ await waitFor(() => {
+ expect(screen.getByText("Top Litellm Models")).toBeInTheDocument();
+ });
+ });
+
+ it("should switch back to Public Model Name view", async () => {
+ renderWithProviders(<UsagePage {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();
+ });
+
+ // Switch to individual first
+ const litellmToggle = screen.getByText("Litellm Model Name");
+ act(() => {
+ fireEvent.click(litellmToggle);
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText("Top Litellm Models")).toBeInTheDocument();
+ });
+
+ // Switch back to groups
+ const publicToggle = screen.getByText("Public Model Name");
+ act(() => {
+ fireEvent.click(publicToggle);
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText("Top Public Model Names")).toBeInTheDocument();
+ });
+ });
+ });
+
+ describe("customer usage banner", () => {
+ it("should show and be dismissible in customer view", async () => {
+ mockUseCustomers.mockReturnValue({
+ data: mockCustomers,
+ isLoading: false,
+ error: null,
+ } as any);
+
+ renderWithProviders(<UsagePage {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();
+ });
+
+ const usageSelect = screen.getByTestId("usage-view-select");
+ act(() => {
+ fireEvent.change(usageSelect, { target: { value: "customer" } });
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText("Customer usage is a new feature.")).toBeInTheDocument();
+ });
+
+ // Click the close button
+ const closeButton = screen.getByLabelText("Close");
+ act(() => {
+ fireEvent.click(closeButton);
+ });
+
+ await waitFor(() => {
+ expect(screen.queryByText("Customer usage is a new feature.")).not.toBeInTheDocument();
+ });
+ });
+ });
+
+ describe("agent usage banner", () => {
+ it("should show agent usage banner with A2A info", async () => {
+ mockUseAgents.mockReturnValue({
+ data: { agents: mockAgents },
+ isLoading: false,
+ error: null,
+ } as any);
+
+ renderWithProviders(<UsagePage {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();
+ });
+
+ const usageSelect = screen.getByTestId("usage-view-select");
+ act(() => {
+ fireEvent.change(usageSelect, { target: { value: "agent" } });
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText("Agent usage (A2A) is a new feature.")).toBeInTheDocument();
+ });
+ });
+ });
+
+ describe("tab navigation in global view", () => {
+ it("should render all expected tabs", async () => {
+ renderWithProviders(<UsagePage {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();
+ });
+
+ expect(screen.getByText("Cost")).toBeInTheDocument();
+ expect(screen.getByText("Model Activity")).toBeInTheDocument();
+ expect(screen.getByText("Key Activity")).toBeInTheDocument();
+ expect(screen.getByText("MCP Server Activity")).toBeInTheDocument();
+ expect(screen.getByText("Endpoint Activity")).toBeInTheDocument();
+ });
+ });
});
diff --git a/ui/litellm-dashboard/src/components/UsagePage/components/UsagePageView.tsx b/ui/litellm-dashboard/src/components/UsagePage/components/UsagePageView.tsx
index 688ee73767f..f81da6e2455 100644
--- a/ui/litellm-dashboard/src/components/UsagePage/components/UsagePageView.tsx
+++ b/ui/litellm-dashboard/src/components/UsagePage/components/UsagePageView.tsx
@@ -6,7 +6,7 @@
* Works at 1m+ spend logs, by querying an aggregate table instead.
*/
-import { InfoCircleOutlined } from "@ant-design/icons";
+import { InfoCircleOutlined, LoadingOutlined, UserOutlined } from "@ant-design/icons";
import {
BarChart,
Card,
@@ -21,13 +21,15 @@ import {
Text,
Title
} from "@tremor/react";
-import { Alert, Segmented, Tooltip } from "antd";
-import React, { useCallback, useEffect, useMemo, useState } from "react";
+import { Alert, Segmented, Select, Tooltip } from "antd";
+import { useDebouncedState } from "@tanstack/react-pacer/debouncer";
+import React, { useCallback, useEffect, useMemo, useState, type UIEvent } from "react";
import { useAgents } from "@/app/(dashboard)/hooks/agents/useAgents";
import { useCustomers } from "@/app/(dashboard)/hooks/customers/useCustomers";
import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";
import { useCurrentUser } from "@/app/(dashboard)/hooks/users/useCurrentUser";
+import { useInfiniteUsers } from "@/app/(dashboard)/hooks/users/useUsers";
import { formatNumberWithCommas } from "@/utils/dataUtils";
import { Button } from "@tremor/react";
import { all_admin_roles } from "../../../utils/roles";
@@ -81,6 +83,62 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {
const { data: currentUser } = useCurrentUser();
console.log(`currentUser: ${JSON.stringify(currentUser)}`);
console.log(`currentUser max budget: ${currentUser?.max_budget}`);
+ const isAdmin = all_admin_roles.includes(userRole || "");
+
+ // Debounced search for user selector
+ const [userSearchInput, setUserSearchInput] = useState("");
+ const [debouncedUserSearch, setDebouncedUserSearch] = useDebouncedState("", {
+ wait: 300,
+ });
+
+ const {
+ data: usersInfiniteData,
+ fetchNextPage: fetchNextUsersPage,
+ hasNextPage: hasNextUsersPage,
+ isFetchingNextPage: isFetchingNextUsersPage,
+ isLoading: isLoadingUsers,
+ } = useInfiniteUsers(50, debouncedUserSearch || undefined);
+
+ const userOptions = useMemo(() => {
+ if (!usersInfiniteData?.pages) return [];
+ const seen = new Set<string>();
+ const result: { value: string; label: string }[] = [];
+ for (const page of usersInfiniteData.pages) {
+ for (const user of page.users) {
+ if (seen.has(user.user_id)) continue;
+ seen.add(user.user_id);
+ result.push({
+ value: user.user_id,
+ label: user.user_alias
+ ? `${user.user_alias} (${user.user_id})`
+ : user.user_email
+ ? `${user.user_email} (${user.user_id})`
+ : user.user_id,
+ });
+ }
+ }
+ return result;
+ }, [usersInfiniteData]);
+
+ const handleUserSearchChange = (value: string) => {
+ setUserSearchInput(value);
+ setDebouncedUserSearch(value);
+ };
+
+ const handleUserPopupScroll = (e: UIEvent<HTMLDivElement>) => {
+ const target = e.currentTarget;
+ const scrollRatio =
+ (target.scrollTop + target.clientHeight) / target.scrollHeight;
+ if (scrollRatio >= 0.8 && hasNextUsersPage && !isFetchingNextUsersPage) {
+ fetchNextUsersPage();
+ }
+ };
+
+ // For admins: null means global view (all users), a string means filter by that user
+ // For non-admins: always set to their own user ID
+ const [selectedUserId, setSelectedUserId] = useState<string | null>(
+ isAdmin ? null : (userID || null)
+ );
const [modelViewType, setModelViewType] = useState<"groups" | "individual">("groups");
const [isCloudZeroModalOpen, setIsCloudZeroModalOpen] = useState(false);
const [isGlobalExportModalOpen, setIsGlobalExportModalOpen] = useState(false);
@@ -107,6 +165,13 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {
getAllTags();
}, [accessToken]);
+ // Sync selectedUserId when auth state settles (isAdmin/userID may be null on initial render)
+ useEffect(() => {
+ if (!isAdmin && userID) {
+ setSelectedUserId(userID);
+ }
+ }, [isAdmin, userID]);
+
// Derived states from userSpendData
const totalSpend = userSpendData.metadata?.total_spend || 0;
@@ -301,6 +366,9 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {
const fetchUserSpendData = useCallback(async () => {
if (!accessToken || !dateValue.from || !dateValue.to) return;
+ // For non-admins, always pass their own user_id
+ const effectiveUserId = isAdmin ? selectedUserId : (userID || null);
+
setLoading(true);
// Create new Date objects to avoid mutating the original dates
@@ -310,14 +378,14 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {
try {
// Prefer aggregated endpoint to avoid many page requests
try {
- const aggregated = await userDailyActivityAggregatedCall(accessToken, startTime, endTime);
+ const aggregated = await userDailyActivityAggregatedCall(accessToken, startTime, endTime, effectiveUserId);
setUserSpendData(aggregated);
return;
} catch (e) {
// Fallback to paginated calls if aggregated endpoint is unavailable
}
- const firstPageData = await userDailyActivityCall(accessToken, startTime, endTime);
+ const firstPageData = await userDailyActivityCall(accessToken, startTime, endTime, 1, effectiveUserId);
if (firstPageData.metadata.total_pages <= 1) {
setUserSpendData(firstPageData);
@@ -328,7 +396,7 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {
const aggregatedMetadata = { ...firstPageData.metadata };
for (let page = 2; page <= firstPageData.metadata.total_pages; page++) {
- const pageData = await userDailyActivityCall(accessToken, startTime, endTime, page);
+ const pageData = await userDailyActivityCall(accessToken, startTime, endTime, page, effectiveUserId);
allResults.push(...pageData.results);
if (pageData.metadata) {
aggregatedMetadata.total_spend += pageData.metadata.total_spend || 0;
@@ -349,7 +417,7 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {
setLoading(false);
setIsDateChanging(false);
}
- }, [accessToken, dateValue.from, dateValue.to]);
+ }, [accessToken, dateValue.from, dateValue.to, selectedUserId, isAdmin, userID]);
// Super responsive date change handler
const handleDateChange = useCallback((newValue: DateRangePickerValue) => {
@@ -423,12 +491,13 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {
<UsageViewSelect
value={usageView}
onChange={(value) => setUsageView(value)}
- isAdmin={all_admin_roles.includes(userRole || "")}
+ isAdmin={isAdmin}
/>
<AdvancedDatePicker value={dateValue} onValueChange={handleDateChange} />
</div>
{/* Your Usage Panel */}
{usageView === "global" && (
+ <>
<TabGroup>
<div className="flex justify-between items-center">
<TabList variant="solid" className="mt-1">
@@ -460,24 +529,61 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {
<Grid numItems={2} className="gap-2 w-full">
{/* Total Spend Card */}
<Col numColSpan={2}>
- <Text className="text-tremor-default text-tremor-content dark:text-dark-tremor-content mb-2 mt-2 text-lg">
- Project Spend{" "}
- {dateValue.from && dateValue.to && (
- <>
- {dateValue.from.toLocaleDateString("en-US", {
- month: "short",
- day: "numeric",
- year: dateValue.from.getFullYear() !== dateValue.to.getFullYear() ? "numeric" : undefined,
- })}
- {" - "}
- {dateValue.to.toLocaleDateString("en-US", {
- month: "short",
- day: "numeric",
- year: "numeric",
- })}
- </>
+ <div className="flex items-center gap-4 mt-2 mb-2">
+ <Text className="text-tremor-default text-tremor-content dark:text-dark-tremor-content text-lg">
+ Project Spend{" "}
+ {dateValue.from && dateValue.to && (
+ <>
+ {dateValue.from.toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ year: dateValue.from.getFullYear() !== dateValue.to.getFullYear() ? "numeric" : undefined,
+ })}
+ {" - "}
+ {dateValue.to.toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ })}
+ </>
+ )}
+ </Text>
+ {isAdmin && (
+ <div className="flex items-center gap-2">
+ <UserOutlined style={{ fontSize: "14px", color: "#6b7280" }} />
+ <Select
+ showSearch
+ allowClear
+ style={{ width: 300 }}
+ placeholder="All Users (Global View)"
+ value={selectedUserId}
+ onChange={(value) => setSelectedUserId(value ?? null)}
+ filterOption={false}
+ onSearch={handleUserSearchChange}
+ searchValue={userSearchInput}
+ onPopupScroll={handleUserPopupScroll}
+ loading={isLoadingUsers}
+ notFoundContent={isLoadingUsers ? <LoadingOutlined spin /> : "No users found"}
+ options={userOptions}
+ popupRender={(menu) => (
+ <>
+ {menu}
+ {isFetchingNextUsersPage && (
+ <div style={{ textAlign: "center", padding: 8 }}>
+ <LoadingOutlined spin />
+ </div>
+ )}
+ </>
+ )}
+ />
+ {selectedUserId && (
+ <span className="text-xs text-gray-500">
+ Filtering by user
+ </span>
+ )}
+ </div>
)}
- </Text>
+ </div>
<ViewUserSpend
userSpend={totalSpend}
@@ -694,6 +800,7 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {
</TabPanel>
</TabPanels>
</TabGroup>
+ </>
)}
{/* Organization Usage Panel */}
diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsx
index 885a62fab54..35e713a94c1 100644
--- a/ui/litellm-dashboard/src/components/networking.tsx
+++ b/ui/litellm-dashboard/src/components/networking.tsx
@@ -1726,7 +1726,7 @@ const fetchDailyActivity = async ({
}
};
-export const userDailyActivityCall = async (accessToken: string, startTime: Date, endTime: Date, page: number = 1) => {
+export const userDailyActivityCall = async (accessToken: string, startTime: Date, endTime: Date, page: number = 1, userId: string | null = null) => {
/**
* Get daily user activity on proxy
*/
@@ -1736,6 +1736,9 @@ export const userDailyActivityCall = async (accessToken: string, startTime: Date
startTime,
endTime,
page,
+ extraQueryParams: {
+ user_id: userId,
+ },
});
};
@@ -3405,7 +3408,7 @@ export interface User {
[key: string]: string; // Include any other potential keys in the dictionary
}
-export const userDailyActivityAggregatedCall = async (accessToken: string, startTime: Date, endTime: Date) => {
+export const userDailyActivityAggregatedCall = async (accessToken: string, startTime: Date, endTime: Date, userId: string | null = null) => {
/**
* Get aggregated daily user activity (no pagination)
*/
@@ -3423,6 +3426,9 @@ export const userDailyActivityAggregatedCall = async (accessToken: string, start
queryParams.append("end_date", formatDate(endTime));
// Send timezone offset so backend can adjust date range for UTC storage
queryParams.append("timezone", new Date().getTimezoneOffset().toString());
+ if (userId) {
+ queryParams.append("user_id", userId);
+ }
const queryString = queryParams.toString();
if (queryString) {
url += `?${queryString}`;
diff --git a/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsx b/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsx
index 8f9869e4dd5..35828922012 100644
--- a/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsx
+++ b/ui/litellm-dashboard/src/components/view_logs/GuardrailViewer/GuardrailViewer.tsx
@@ -1,11 +1,13 @@
-import React, { useState } from "react";
-import { Tooltip, Collapse } from "antd";
+import React, { useState, useMemo } from "react";
+import { Tooltip } from "antd";
import PresidioDetectedEntities from "./PresidioDetectedEntities";
import BedrockGuardrailDetails, {
BedrockGuardrailResponse,
} from "@/components/view_logs/GuardrailViewer/BedrockGuardrailDetails";
import ContentFilterDetails from "./ContentFilterDetails";
+// ── Interfaces ──────────────────────────────────────────────────────────────
+
interface RecognitionMetadata {
recognizer_name: string;
recognizer_identifier: string;
@@ -51,121 +53,159 @@ interface GuardrailInformation {
match_details?: MatchDetail[];
patterns_checked?: number;
alert_recipients?: string[];
+ risk_score?: number;
}
interface GuardrailViewerProps {
data: GuardrailInformation | GuardrailInformation[];
}
-interface GuardrailDetailsProps {
- entry: GuardrailInformation;
- index: number;
- total: number;
-}
+// ── Helpers ─────────────────────────────────────────────────────────────────
-const formatTime = (timestamp: number) => {
- const date = new Date(timestamp * 1000);
- return date.toLocaleString();
+const PROVIDERS_WITH_CUSTOM_RENDERERS = new Set([
+ "presidio",
+ "bedrock",
+ "litellm_content_filter",
+]);
+
+const formatMode = (mode: string): string => {
+ return mode.replace(/_/g, "-").toUpperCase();
};
-// Providers with custom renderers
-const PROVIDERS_WITH_CUSTOM_RENDERERS = new Set(["presidio", "bedrock", "litellm_content_filter"]);
+const formatDurationMs = (seconds: number): string => {
+ const ms = Math.round(seconds * 1000);
+ return `${ms}ms`;
+};
-const GenericGuardrailResponse = ({ response }: { response: any }) => {
- const [showRaw, setShowRaw] = useState(false);
- return (
- <div className="mt-4">
- <div className="border rounded-lg overflow-hidden">
- <div
- className="flex items-center justify-between p-3 bg-gray-50 cursor-pointer hover:bg-gray-100"
- onClick={() => setShowRaw(!showRaw)}
- >
- <div className="flex items-center">
- <svg
- className={`w-5 h-5 mr-2 transition-transform ${showRaw ? "transform rotate-90" : ""}`}
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
- >
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
- </svg>
- <h5 className="font-medium">Raw Guardrail Response</h5>
- </div>
- </div>
- {showRaw && (
- <div className="p-3 border-t bg-white">
- <pre className="bg-gray-50 rounded p-3 text-xs overflow-x-auto">
- {JSON.stringify(response, null, 2)}
- </pre>
- </div>
- )}
- </div>
- </div>
+const getTotalMasked = (entry: GuardrailInformation): number => {
+ return Object.values(entry.masked_entity_count || {}).reduce(
+ (sum, count) => sum + (typeof count === "number" ? count : 0),
+ 0,
);
};
-const PolicyDetectionRow = ({ entry }: { entry: GuardrailInformation }) => {
- const hasData = entry.policy_template || entry.detection_method || entry.confidence_score != null || entry.patterns_checked != null;
- if (!hasData) return null;
+const isEntrySuccess = (entry: GuardrailInformation): boolean => {
+ return (entry.guardrail_status ?? "").toLowerCase() === "success";
+};
- return (
- <div className="mt-4 pt-4 border-t">
- <div className="flex flex-wrap gap-4">
- {entry.policy_template && (
- <div className="flex items-center gap-2">
- <span className="font-medium text-sm">Policy:</span>
- <span className="px-2 py-1 bg-purple-50 text-purple-700 rounded-md text-xs font-medium">
- {entry.policy_template}
- </span>
- </div>
- )}
- {entry.detection_method && (
- <div className="flex items-center gap-2">
- <span className="font-medium text-sm">Detection:</span>
- {entry.detection_method.split(",").map((method) => (
- <span key={method} className="px-2 py-1 bg-slate-100 text-slate-700 rounded-md text-xs font-medium">
- {method.trim()}
- </span>
- ))}
- </div>
- )}
- {entry.confidence_score != null && (
- <div className="flex items-center gap-2">
- <span className="font-medium text-sm">Confidence:</span>
- <span className={`px-2 py-1 rounded-md text-xs font-medium ${
- entry.confidence_score >= 0.8 ? "bg-red-100 text-red-800" :
- entry.confidence_score >= 0.5 ? "bg-amber-100 text-amber-800" :
- "bg-green-100 text-green-800"
- }`}>
- {(entry.confidence_score * 100).toFixed(0)}%
- </span>
- </div>
- )}
- {entry.patterns_checked != null && (
- <div className="flex items-center gap-2">
- <span className="font-medium text-sm">Patterns checked:</span>
- <span className="text-sm text-gray-600">{entry.patterns_checked}</span>
- </div>
- )}
- </div>
- </div>
- );
+const getRiskColor = (score: number): string => {
+ if (score <= 3) return "text-green-600 bg-green-50 border-green-200";
+ if (score <= 6) return "text-amber-600 bg-amber-50 border-amber-200";
+ return "text-red-600 bg-red-50 border-red-200";
};
+const getRiskScore = (entry: GuardrailInformation): number | null => {
+ if (!isEntrySuccess(entry)) return null;
+
+ // Prefer backend-computed score
+ if (entry.risk_score != null) return entry.risk_score;
+
+ // Fallback: compute from available data
+ const totalMasked = getTotalMasked(entry);
+ const patternsChecked = entry.patterns_checked ?? 0;
+ const confidence = entry.confidence_score ?? 0;
+
+ if (patternsChecked === 0 && confidence === 0) return 0;
+
+ const matchRatio = patternsChecked > 0 ? totalMasked / patternsChecked : 0;
+ let score = matchRatio * 7 + confidence * 3;
+ if (totalMasked > 0 && score < 2) score = 2;
+ return Math.min(10, Math.round(score * 10) / 10);
+};
+
+const getDisplayName = (entry: GuardrailInformation): string => {
+ return entry.policy_template || entry.guardrail_name;
+};
+
+// ── Icons (inline SVGs) ─────────────────────────────────────────────────────
+
+const ShieldIcon = () => (
+ <svg width="40" height="40" viewBox="0 0 40 40" fill="none">
+ <circle cx="20" cy="20" r="20" fill="#EEF2FF" />
+ <path
+ d="M20 10l8 4v6c0 5.25-3.4 10.15-8 11.5C15.4 30.15 12 25.25 12 20v-6l8-4z"
+ stroke="#6366F1"
+ strokeWidth="1.5"
+ fill="none"
+ />
+ <path
+ d="M16 20l3 3 5-6"
+ stroke="#6366F1"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ fill="none"
+ />
+ </svg>
+);
+
+const CheckCircleIcon = ({ className }: { className?: string }) => (
+ <svg width="22" height="22" viewBox="0 0 22 22" fill="none" className={className}>
+ <circle cx="11" cy="11" r="10" stroke="#16A34A" strokeWidth="1.5" fill="#F0FDF4" />
+ <path d="M7 11l3 3 5-6" stroke="#16A34A" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+);
+
+const FailCircleIcon = ({ className }: { className?: string }) => (
+ <svg width="22" height="22" viewBox="0 0 22 22" fill="none" className={className}>
+ <circle cx="11" cy="11" r="10" stroke="#DC2626" strokeWidth="1.5" fill="#FEF2F2" />
+ <path d="M8 8l6 6M14 8l-6 6" stroke="#DC2626" strokeWidth="1.5" strokeLinecap="round" />
+ </svg>
+);
+
+const PlayCircleIcon = () => (
+ <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
+ <circle cx="11" cy="11" r="10" stroke="#3B82F6" strokeWidth="1.5" fill="#EFF6FF" />
+ <path d="M9 7.5l6 3.5-6 3.5V7.5z" fill="#3B82F6" />
+ </svg>
+);
+
+const GrayDotIcon = () => (
+ <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
+ <circle cx="11" cy="11" r="5" fill="#9CA3AF" />
+ </svg>
+);
+
+const ChevronIcon = ({ expanded }: { expanded: boolean }) => (
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 20 20"
+ fill="none"
+ className={`transition-transform ${expanded ? "rotate-180" : ""}`}
+ >
+ <path d="M6 8l4 4 4-4" stroke="#6B7280" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+);
+
+const DownloadIcon = () => (
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
+ <path d="M8 2v8m0 0l-3-3m3 3l3-3M3 12h10" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+);
+
+const ExternalLinkIcon = () => (
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none" className="inline ml-1">
+ <path d="M6 2H3a1 1 0 00-1 1v8a1 1 0 001 1h8a1 1 0 001-1V8M8 2h4m0 0v4m0-4L6.5 7.5" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+);
+
+// ── Sub-components ──────────────────────────────────────────────────────────
+
const MatchDetailsTable = ({ matchDetails }: { matchDetails: MatchDetail[] }) => {
if (!matchDetails || matchDetails.length === 0) return null;
return (
- <div className="mt-4 pt-4 border-t">
- <h5 className="font-medium mb-2">Match Details ({matchDetails.length})</h5>
+ <div className="mt-3">
+ <h5 className="text-sm font-medium mb-2 text-gray-700">Match Details ({matchDetails.length})</h5>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b text-left text-gray-500">
- <th className="pb-2 pr-4">Type</th>
- <th className="pb-2 pr-4">Method</th>
- <th className="pb-2 pr-4">Action</th>
- <th className="pb-2">Detail</th>
+ <th className="pb-2 pr-4 font-medium">Type</th>
+ <th className="pb-2 pr-4 font-medium">Method</th>
+ <th className="pb-2 pr-4 font-medium">Action</th>
+ <th className="pb-2 font-medium">Detail</th>
</tr>
</thead>
<tbody>
@@ -178,14 +218,17 @@ const MatchDetailsTable = ({ matchDetails }: { matchDetails: MatchDetail[] }) =>
</span>
</td>
<td className="py-2 pr-4">
- <span className={`px-2 py-0.5 rounded text-xs font-medium ${
- match.action_taken === "BLOCK" ? "bg-red-100 text-red-800" : "bg-blue-50 text-blue-700"
- }`}>
+ <span
+ className={`px-2 py-0.5 rounded text-xs font-medium ${
+ match.action_taken === "BLOCK" ? "bg-red-100 text-red-800" : "bg-blue-50 text-blue-700"
+ }`}
+ >
{match.action_taken ?? "-"}
</span>
</td>
<td className="py-2 font-mono text-xs text-gray-600 break-all">
- {match.category ? `[${match.category}] ` : ""}{match.snippet ?? "-"}
+ {match.category ? `[${match.category}] ` : ""}
+ {match.snippet ?? "-"}
</td>
</tr>
))}
@@ -196,35 +239,25 @@ const MatchDetailsTable = ({ matchDetails }: { matchDetails: MatchDetail[] }) =>
);
};
-const ClassificationDetails = ({ classification }: { classification: Record<string, any> }) => {
- if (!classification) return null;
-
+const GenericGuardrailResponse = ({ response }: { response: any }) => {
+ const [showRaw, setShowRaw] = useState(false);
return (
- <div className="mt-4 pt-4 border-t">
- <h5 className="font-medium mb-2">Classification</h5>
- <div className="space-y-2 bg-gray-50 rounded-lg p-3">
- {classification.category && (
- <div className="flex">
- <span className="font-medium w-1/3 text-sm">Category:</span>
- <span className="text-sm">{classification.category}</span>
- </div>
- )}
- {classification.article_reference && (
- <div className="flex">
- <span className="font-medium w-1/3 text-sm">Reference:</span>
- <span className="text-sm font-mono">{classification.article_reference}</span>
- </div>
- )}
- {classification.confidence != null && (
- <div className="flex">
- <span className="font-medium w-1/3 text-sm">Confidence:</span>
- <span className="text-sm">{(classification.confidence * 100).toFixed(0)}%</span>
+ <div className="mt-3">
+ <div className="border rounded-lg overflow-hidden">
+ <div
+ className="flex items-center justify-between p-3 bg-gray-50 cursor-pointer hover:bg-gray-100"
+ onClick={() => setShowRaw(!showRaw)}
+ >
+ <div className="flex items-center">
+ <ChevronIcon expanded={showRaw} />
+ <h5 className="font-medium text-sm ml-1">Raw Guardrail Response</h5>
</div>
- )}
- {classification.reason && (
- <div className="flex">
- <span className="font-medium w-1/3 text-sm">Reason:</span>
- <span className="text-sm">{classification.reason}</span>
+ </div>
+ {showRaw && (
+ <div className="p-3 border-t bg-white">
+ <pre className="bg-gray-50 rounded p-3 text-xs overflow-x-auto">
+ {JSON.stringify(response, null, 2)}
+ </pre>
</div>
)}
</div>
@@ -232,61 +265,162 @@ const ClassificationDetails = ({ classification }: { classification: Record<stri
);
};
-const ExecutionTimeline = ({ entries }: { entries: GuardrailInformation[] }) => {
- if (entries.length <= 1) return null;
+// ── Timeline entry types ────────────────────────────────────────────────────
+
+interface TimelineEntry {
+ type: "request" | "guardrail" | "llm" | "response";
+ label: string;
+ offsetMs: number;
+ status?: string;
+ isSuccess?: boolean;
+}
+
+const RequestLifecycle = ({ entries }: { entries: GuardrailInformation[] }) => {
+ const sorted = useMemo(
+ () => [...entries].sort((a, b) => (a.start_time ?? 0) - (b.start_time ?? 0)),
+ [entries],
+ );
- const sorted = [...entries].sort((a, b) => (a.start_time ?? 0) - (b.start_time ?? 0));
+ const timeline = useMemo(() => {
+ if (sorted.length === 0) return [];
+
+ const baseTime = sorted[0].start_time;
+ const items: TimelineEntry[] = [];
+
+ // Request received
+ items.push({ type: "request", label: "Request received", offsetMs: 0 });
+
+ // Pre-call guardrails
+ const preCalls = sorted.filter((e) => e.guardrail_mode === "pre_call");
+ const postCalls = sorted.filter((e) => e.guardrail_mode === "post_call" || e.guardrail_mode === "logging_only");
+ const duringCalls = sorted.filter((e) => e.guardrail_mode === "during_call");
+
+ for (const e of preCalls) {
+ const offsetMs = Math.round((e.end_time - baseTime) * 1000);
+ items.push({
+ type: "guardrail",
+ label: `Pre-call guardrail: ${getDisplayName(e)}`,
+ offsetMs,
+ status: isEntrySuccess(e) ? "PASSED" : "FAILED",
+ isSuccess: isEntrySuccess(e),
+ });
+ }
+
+ // LLM call — infer from gap between pre-call end and post-call start
+ const lastPreEnd = preCalls.length > 0 ? Math.max(...preCalls.map((e) => e.end_time)) : baseTime;
+ const firstPostStart = postCalls.length > 0 ? Math.min(...postCalls.map((e) => e.start_time)) : undefined;
+ const llmEndTime = firstPostStart ?? (lastPreEnd + 1);
+ const llmOffsetMs = Math.round((llmEndTime - baseTime) * 1000);
+
+ items.push({
+ type: "llm",
+ label: "LLM call",
+ offsetMs: llmOffsetMs,
+ });
+
+ // During-call guardrails (rare)
+ for (const e of duringCalls) {
+ const offsetMs = Math.round((e.end_time - baseTime) * 1000);
+ items.push({
+ type: "guardrail",
+ label: `During-call guardrail: ${getDisplayName(e)}`,
+ offsetMs,
+ status: isEntrySuccess(e) ? "PASSED" : "FAILED",
+ isSuccess: isEntrySuccess(e),
+ });
+ }
+
+ // Post-call guardrails
+ for (const e of postCalls) {
+ const offsetMs = Math.round((e.end_time - baseTime) * 1000);
+ items.push({
+ type: "guardrail",
+ label: `Post-call guardrail: ${getDisplayName(e)}`,
+ offsetMs,
+ status: isEntrySuccess(e) ? "PASSED" : "FAILED",
+ isSuccess: isEntrySuccess(e),
+ });
+ }
+
+ // Response returned
+ const maxEnd = Math.max(...sorted.map((e) => e.end_time));
+ const responseOffsetMs = Math.round((maxEnd - baseTime) * 1000) + 1;
+ items.push({ type: "response", label: "Response returned", offsetMs: responseOffsetMs });
+
+ return items;
+ }, [sorted]);
return (
- <div className="mb-4">
- <h5 className="font-medium mb-3">Execution Timeline</h5>
- <div className="relative pl-4 border-l-2 border-gray-200 space-y-3">
- {sorted.map((e, idx) => {
- const isSuccess = (e.guardrail_status ?? "").toLowerCase() === "success";
- return (
- <div key={idx} className="relative">
- <div
- className={`absolute -left-[calc(1rem+5px)] w-2.5 h-2.5 rounded-full mt-1.5 ${
- isSuccess ? "bg-green-500" : "bg-red-500"
- }`}
- />
+ <div>
+ <h4 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-4">
+ Request Lifecycle
+ </h4>
+ <div className="relative">
+ {timeline.map((item, idx) => (
+ <div key={idx} className="flex items-start gap-3 relative">
+ {/* Vertical line */}
+ <div className="flex flex-col items-center">
+ <div className="flex-shrink-0">
+ {item.type === "request" || item.type === "response" ? (
+ <GrayDotIcon />
+ ) : item.type === "llm" ? (
+ <PlayCircleIcon />
+ ) : item.isSuccess ? (
+ <CheckCircleIcon />
+ ) : (
+ <FailCircleIcon />
+ )}
+ </div>
+ {idx < timeline.length - 1 && (
+ <div className="w-0.5 bg-gray-200 flex-grow" style={{ minHeight: "24px" }} />
+ )}
+ </div>
+
+ {/* Content */}
+ <div className="pb-4 flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
- <span className="font-mono text-xs text-gray-500">
- {e.duration?.toFixed(3)}s
- </span>
- <span className="text-sm font-medium">{e.guardrail_name}</span>
- <span className="px-1.5 py-0.5 bg-gray-100 text-gray-600 rounded text-xs">
- {e.guardrail_mode}
- </span>
- <span className={`px-1.5 py-0.5 rounded text-xs font-medium ${
- isSuccess ? "bg-green-100 text-green-800" : "bg-red-100 text-red-800"
- }`}>
- {e.guardrail_status}
+ <span
+ className={`text-sm ${
+ item.type === "llm" ? "text-blue-600 font-medium" : "text-gray-900"
+ }`}
+ >
+ {item.label}
</span>
- {e.policy_template && (
- <span className="px-1.5 py-0.5 bg-purple-50 text-purple-700 rounded text-xs">
- {e.policy_template}
+ {item.status && (
+ <span
+ className={`px-1.5 py-0.5 rounded text-[10px] font-bold uppercase ${
+ item.isSuccess
+ ? "bg-green-100 text-green-700"
+ : "bg-red-100 text-red-700"
+ }`}
+ >
+ {item.status}
</span>
)}
+ <span className="text-xs text-gray-400 font-mono ml-auto flex-shrink-0">
+ T+{item.offsetMs}ms
+ </span>
</div>
</div>
- );
- })}
+ </div>
+ ))}
</div>
</div>
);
};
-const GuardrailDetails = ({ entry, index, total }: GuardrailDetailsProps) => {
- const guardrailProvider = entry.guardrail_provider ?? "presidio";
- const statusLabel = entry.guardrail_status ?? "unknown";
- const isSuccess = statusLabel.toLowerCase() === "success";
- const maskedEntityCount = entry.masked_entity_count || {};
- const totalMaskedEntities = Object.values(maskedEntityCount).reduce(
- (sum, count) => sum + (typeof count === "number" ? count : 0),
- 0,
- );
+// ── Evaluation Card ─────────────────────────────────────────────────────────
+const EvaluationCard = ({ entry }: { entry: GuardrailInformation }) => {
+ const [expanded, setExpanded] = useState(false);
+ const success = isEntrySuccess(entry);
+ const totalMasked = getTotalMasked(entry);
+ const displayName = getDisplayName(entry);
+ const durationStr = formatDurationMs(entry.duration);
+ const modeStr = formatMode(entry.guardrail_mode);
+ const riskScore = getRiskScore(entry);
+
+ const guardrailProvider = entry.guardrail_provider ?? "presidio";
const guardrailResponse = entry.guardrail_response;
const presidioEntities = Array.isArray(guardrailResponse) ? guardrailResponse : [];
const bedrockResponse =
@@ -297,201 +431,287 @@ const GuardrailDetails = ({ entry, index, total }: GuardrailDetailsProps) => {
? (guardrailResponse as BedrockGuardrailResponse)
: undefined;
+ // Match count string: "X/Y matched" or "X matched"
+ const matchCountStr =
+ entry.patterns_checked != null
+ ? `${totalMasked}/${entry.patterns_checked} matched`
+ : totalMasked > 0
+ ? `${totalMasked} matched`
+ : null;
+
return (
- <div className="bg-white rounded-lg border border-gray-200 p-4">
- {total > 1 && (
- <div className="flex items-center justify-between mb-4">
- <h4 className="text-base font-semibold">
- Guardrail #{index + 1}
- <span className="ml-2 font-mono text-sm text-gray-600">{entry.guardrail_name}</span>
- </h4>
- <span className="px-2 py-0.5 bg-gray-100 text-gray-600 rounded-md text-xs capitalize">
- {guardrailProvider}
- </span>
+ <div className="border border-gray-200 rounded-lg bg-white">
+ {/* Collapsed header row */}
+ <div
+ className="flex items-center gap-3 px-4 py-3 cursor-pointer hover:bg-gray-50 transition-colors"
+ onClick={() => setExpanded(!expanded)}
+ >
+ {/* Status icon */}
+ <div className="flex-shrink-0">
+ {success ? <CheckCircleIcon /> : <FailCircleIcon />}
</div>
- )}
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
- <div className="space-y-2">
- <div className="flex">
- <span className="font-medium w-1/3">Guardrail Name:</span>
- <span className="font-mono break-words">{entry.guardrail_name}</span>
- </div>
- {entry.guardrail_id && entry.guardrail_id !== entry.guardrail_name && (
- <div className="flex">
- <span className="font-medium w-1/3">Guardrail ID:</span>
- <span className="font-mono break-words text-gray-600">{entry.guardrail_id}</span>
- </div>
+ {/* Name + badges */}
+ <div className="flex items-center gap-2 flex-wrap flex-1 min-w-0">
+ <span className="font-semibold text-gray-900 text-sm truncate">{displayName}</span>
+
+ <span className="px-2 py-0.5 border border-blue-200 bg-blue-50 text-blue-700 rounded text-[11px] font-semibold uppercase flex-shrink-0">
+ {modeStr}
+ </span>
+
+ <span
+ className={`px-2 py-0.5 rounded text-[11px] font-semibold uppercase flex-shrink-0 ${
+ success ? "bg-green-100 text-green-700 border border-green-200" : "bg-red-100 text-red-700 border border-red-200"
+ }`}
+ >
+ {success ? "PASSED" : "FAILED"}
+ </span>
+
+ {matchCountStr && (
+ <span
+ className={`px-2 py-0.5 rounded text-[11px] font-medium flex-shrink-0 ${
+ totalMasked === 0 ? "bg-green-50 text-green-700 border border-green-200" : "bg-amber-50 text-amber-700 border border-amber-200"
+ }`}
+ >
+ {matchCountStr}
+ </span>
)}
- <div className="flex">
- <span className="font-medium w-1/3">Mode:</span>
- <span className="font-mono break-words">{entry.guardrail_mode}</span>
- </div>
- <div className="flex">
- <span className="font-medium w-1/3">Status:</span>
- <Tooltip title={isSuccess ? null : "Guardrail failed to run."} placement="top" arrow destroyTooltipOnHide>
- <span
- className={`px-2 py-1 rounded-md text-xs font-medium inline-block ${
- isSuccess ? "bg-green-100 text-green-800" : "bg-red-100 text-red-800 cursor-help"
- }`}
- >
- {statusLabel}
+
+ {entry.confidence_score != null && (
+ <span className="px-2 py-0.5 bg-gray-100 text-gray-600 border border-gray-200 rounded text-[11px] font-medium flex-shrink-0">
+ {(entry.confidence_score * 100).toFixed(0)}% conf
+ </span>
+ )}
+
+ {riskScore != null && success && (
+ <Tooltip title={`Risk score: ${riskScore}/10`}>
+ <span className={`px-2 py-0.5 border rounded text-[11px] font-semibold flex-shrink-0 ${getRiskColor(riskScore)}`}>
+ Risk {riskScore}/10
</span>
</Tooltip>
- </div>
+ )}
</div>
- <div className="space-y-2">
- <div className="flex">
- <span className="font-medium w-1/3">Start Time:</span>
- <span>{formatTime(entry.start_time)}</span>
- </div>
- <div className="flex">
- <span className="font-medium w-1/3">End Time:</span>
- <span>{formatTime(entry.end_time)}</span>
- </div>
- <div className="flex">
- <span className="font-medium w-1/3">Duration:</span>
- <span>{entry.duration.toFixed(4)}s</span>
- </div>
+ {/* Right side: duration + method + chevron */}
+ <div className="flex items-center gap-3 flex-shrink-0">
+ <span className="text-sm text-gray-500 font-mono">{durationStr}</span>
+ {entry.detection_method && (
+ <span className="px-2 py-0.5 bg-gray-100 text-gray-600 border border-gray-200 rounded text-[11px] font-medium">
+ {entry.detection_method.split(",")[0].trim()}
+ </span>
+ )}
+ <ChevronIcon expanded={expanded} />
</div>
</div>
- {/* Policy, detection method, confidence, patterns checked */}
- <PolicyDetectionRow entry={entry} />
-
- {/* Classification details (LLM-judge) */}
- {entry.classification && <ClassificationDetails classification={entry.classification} />}
-
- {/* Match details table */}
- {entry.match_details && entry.match_details.length > 0 && (
- <MatchDetailsTable matchDetails={entry.match_details} />
- )}
+ {/* Expanded details */}
+ {expanded && (
+ <div className="border-t border-gray-100 px-4 py-3">
+ {/* View Policy Configuration link */}
+ {entry.policy_template && (
+ <div className="flex justify-end mb-3">
+ <a
+ href="/ui/policies"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-sm text-blue-600 hover:text-blue-800 font-medium"
+ >
+ View Policy Configuration
+ <ExternalLinkIcon />
+ </a>
+ </div>
+ )}
- {totalMaskedEntities > 0 && (
- <div className="mt-4 pt-4 border-t">
- <h5 className="font-medium mb-2">Masked Entity Summary</h5>
- <div className="flex flex-wrap gap-2">
- {Object.entries(maskedEntityCount).map(([entityType, count]) => (
- <span key={entityType} className="px-3 py-1.5 bg-blue-50 text-blue-700 rounded-md text-xs font-medium">
- {entityType}: {count}
- </span>
- ))}
- </div>
- </div>
- )}
+ {/* Classification details for llm-judge */}
+ {entry.classification && (
+ <div className="mb-3 bg-gray-50 rounded-lg p-3 space-y-1">
+ <h5 className="text-sm font-medium text-gray-700 mb-2">Classification</h5>
+ {entry.classification.category && (
+ <div className="flex text-sm">
+ <span className="font-medium w-1/3 text-gray-500">Category:</span>
+ <span>{entry.classification.category}</span>
+ </div>
+ )}
+ {entry.classification.article_reference && (
+ <div className="flex text-sm">
+ <span className="font-medium w-1/3 text-gray-500">Reference:</span>
+ <span className="font-mono">{entry.classification.article_reference}</span>
+ </div>
+ )}
+ {entry.classification.confidence != null && (
+ <div className="flex text-sm">
+ <span className="font-medium w-1/3 text-gray-500">Confidence:</span>
+ <span>{(entry.classification.confidence * 100).toFixed(0)}%</span>
+ </div>
+ )}
+ {entry.classification.reason && (
+ <div className="flex text-sm">
+ <span className="font-medium w-1/3 text-gray-500">Reason:</span>
+ <span>{entry.classification.reason}</span>
+ </div>
+ )}
+ </div>
+ )}
- {guardrailProvider === "presidio" && presidioEntities.length > 0 && (
- <div className="mt-4">
- <PresidioDetectedEntities entities={presidioEntities} />
- </div>
- )}
+ {/* Match details table */}
+ {entry.match_details && entry.match_details.length > 0 && (
+ <MatchDetailsTable matchDetails={entry.match_details} />
+ )}
- {guardrailProvider === "bedrock" && bedrockResponse && (
- <div className="mt-4">
- <BedrockGuardrailDetails response={bedrockResponse} />
- </div>
- )}
+ {/* Masked entity summary */}
+ {totalMasked > 0 && (
+ <div className="mt-3">
+ <h5 className="text-sm font-medium text-gray-700 mb-2">Masked Entities</h5>
+ <div className="flex flex-wrap gap-2">
+ {Object.entries(entry.masked_entity_count || {}).map(([entityType, count]) => (
+ <span key={entityType} className="px-2 py-1 bg-blue-50 text-blue-700 rounded text-xs font-medium">
+ {entityType}: {count}
+ </span>
+ ))}
+ </div>
+ </div>
+ )}
- {guardrailProvider === "litellm_content_filter" && guardrailResponse && (
- <div className="mt-4">
- <ContentFilterDetails response={guardrailResponse} />
+ {/* Provider-specific details */}
+ {guardrailProvider === "presidio" && presidioEntities.length > 0 && (
+ <div className="mt-3">
+ <PresidioDetectedEntities entities={presidioEntities} />
+ </div>
+ )}
+ {guardrailProvider === "bedrock" && bedrockResponse && (
+ <div className="mt-3">
+ <BedrockGuardrailDetails response={bedrockResponse} />
+ </div>
+ )}
+ {guardrailProvider === "litellm_content_filter" && guardrailResponse && (
+ <div className="mt-3">
+ <ContentFilterDetails response={guardrailResponse} />
+ </div>
+ )}
+ {guardrailProvider &&
+ !PROVIDERS_WITH_CUSTOM_RENDERERS.has(guardrailProvider) &&
+ guardrailResponse && <GenericGuardrailResponse response={guardrailResponse} />}
</div>
)}
-
- {/* Generic fallback for unknown guardrail providers */}
- {guardrailProvider &&
- !PROVIDERS_WITH_CUSTOM_RENDERERS.has(guardrailProvider) &&
- guardrailResponse && <GenericGuardrailResponse response={guardrailResponse} />}
</div>
);
};
+// ── Main Component ──────────────────────────────────────────────────────────
+
const GuardrailViewer = ({ data }: GuardrailViewerProps) => {
- const guardrailEntries = Array.isArray(data)
- ? data.filter((entry): entry is GuardrailInformation => Boolean(entry))
- : data
- ? [data]
- : [];
-
- const primaryName =
- guardrailEntries.length === 1 ? guardrailEntries[0].guardrail_name : `${guardrailEntries.length} guardrails`;
- const statuses = Array.from(new Set(guardrailEntries.map((entry) => entry.guardrail_status)));
- const allSucceeded = statuses.every((status) => (status ?? "").toLowerCase() === "success");
- const aggregatedStatus = allSucceeded ? "success" : "failure";
- const totalMaskedEntities = guardrailEntries.reduce((sum, entry) => {
- return (
- sum +
- Object.values(entry.masked_entity_count || {}).reduce(
- (acc, count) => acc + (typeof count === "number" ? count : 0),
- 0,
- )
- );
- }, 0);
-
- const policyTemplates = Array.from(
- new Set(guardrailEntries.map((e) => e.policy_template).filter(Boolean))
- );
+ const guardrailEntries = useMemo(() => {
+ return Array.isArray(data)
+ ? data.filter((entry): entry is GuardrailInformation => Boolean(entry))
+ : data
+ ? [data]
+ : [];
+ }, [data]);
+
+ const passedCount = guardrailEntries.filter(isEntrySuccess).length;
+ const allPassed = passedCount === guardrailEntries.length;
+
+ const totalOverheadMs = useMemo(() => {
+ return Math.round(guardrailEntries.reduce((sum, e) => sum + (e.duration ?? 0), 0) * 1000);
+ }, [guardrailEntries]);
- const tooltipTitle = allSucceeded ? null : "Guardrail failed to run.";
+ const policyTemplates = useMemo(() => {
+ return Array.from(new Set(guardrailEntries.map((e) => e.policy_template).filter(Boolean)));
+ }, [guardrailEntries]);
if (guardrailEntries.length === 0) {
return null;
}
+ const handleExport = () => {
+ const blob = new Blob([JSON.stringify(guardrailEntries, null, 2)], {
+ type: "application/json",
+ });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `guardrail-compliance-log-${new Date().toISOString().slice(0, 10)}.json`;
+ a.click();
+ URL.revokeObjectURL(url);
+ };
+
return (
- <div className="bg-white rounded-lg shadow w-full max-w-full overflow-hidden mb-6">
- <Collapse
- defaultActiveKey={["1"]}
- expandIconPosition="start"
- items={[
- {
- key: "1",
- label: (
- <div className="flex items-center gap-2 flex-wrap">
- <h3 className="text-lg font-medium text-gray-900">Guardrail Information</h3>
+ <div className="bg-white rounded-xl border border-gray-200 shadow-sm w-full max-w-full overflow-hidden mb-6">
+ {/* ── Header ─────────────────────────────────────────────── */}
+ <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100">
+ <div className="flex items-center gap-4">
+ <ShieldIcon />
+ <div>
+ <h3 className="text-lg font-semibold text-gray-900">
+ Guardrails &amp; Policy Compliance
+ </h3>
+ <div className="flex items-center gap-2 mt-0.5">
+ <span className="text-sm text-gray-500">
+ {guardrailEntries.length} guardrail{guardrailEntries.length !== 1 ? "s" : ""} evaluated
+ </span>
+ <span className="text-gray-300">|</span>
+ <span
+ className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold ${
+ allPassed
+ ? "bg-green-50 text-green-700 border border-green-200"
+ : "bg-red-50 text-red-700 border border-red-200"
+ }`}
+ >
+ {allPassed ? (
+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
+ <path d="M3 6l2.5 2.5L9 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+ ) : null}
+ {passedCount} Passed
+ </span>
+ </div>
+ </div>
+ </div>
- <Tooltip title={tooltipTitle} placement="top" arrow destroyTooltipOnHide>
- <span
- className={`px-2 py-1 rounded-md text-xs font-medium inline-block ${
- allSucceeded ? "bg-green-100 text-green-800" : "bg-red-100 text-red-800 cursor-help"
- }`}
- >
- {aggregatedStatus}
- </span>
- </Tooltip>
+ <div className="flex items-center gap-6">
+ <div className="text-right">
+ <div className="text-sm font-medium text-gray-900">
+ Total: {totalOverheadMs}ms overhead
+ </div>
+ {policyTemplates.length > 0 && (
+ <div className="text-xs text-gray-500 mt-0.5">
+ Policy: {policyTemplates.join(" / ")}
+ </div>
+ )}
+ </div>
- <span className="font-mono text-sm text-gray-600">{primaryName}</span>
+ <button
+ onClick={handleExport}
+ className="inline-flex items-center gap-2 px-4 py-2 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 transition-colors"
+ >
+ <DownloadIcon />
+ Export Compliance Log
+ </button>
+ </div>
+ </div>
- {totalMaskedEntities > 0 && (
- <span className="px-2 py-1 bg-blue-50 text-blue-700 rounded-md text-xs font-medium">
- {totalMaskedEntities} masked {totalMaskedEntities === 1 ? "entity" : "entities"}
- </span>
- )}
+ {/* ── Body: two columns ──────────────────────────────────── */}
+ <div className="flex">
+ {/* Left column: Request Lifecycle */}
+ <div className="w-[340px] flex-shrink-0 border-r border-gray-100 px-6 py-5">
+ <RequestLifecycle entries={guardrailEntries} />
+ </div>
- {policyTemplates.map((pt) => (
- <span key={pt} className="px-2 py-1 bg-purple-50 text-purple-700 rounded-md text-xs font-medium">
- {pt}
- </span>
- ))}
- </div>
- ),
- children: (
- <div className="p-4 space-y-6">
- <ExecutionTimeline entries={guardrailEntries} />
- {guardrailEntries.map((entry, index) => (
- <GuardrailDetails
- key={`${entry.guardrail_name ?? "guardrail"}-${index}`}
- entry={entry}
- index={index}
- total={guardrailEntries.length}
- />
- ))}
- </div>
- ),
- },
- ]}
- />
+ {/* Right column: Evaluation Details */}
+ <div className="flex-1 px-6 py-5 min-w-0">
+ <h4 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-4">
+ Evaluation Details
+ </h4>
+ <div className="space-y-3">
+ {guardrailEntries.map((entry, index) => (
+ <EvaluationCard
+ key={`${entry.guardrail_name ?? "guardrail"}-${index}`}
+ entry={entry}
+ />
+ ))}
+ </div>
+ </div>
+ </div>
</div>
);
};
diff --git a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx
index 9081219d5be..f0f4041531c 100644
--- a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx
+++ b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx
@@ -66,6 +66,9 @@ export function LogDetailContent({ logEntry, onOpenSettings, isLoadingDetails =
const hasGuardrailData = guardrailEntries.length > 0;
const totalMaskedEntities = calculateTotalMaskedEntities(guardrailEntries);
const primaryGuardrailLabel = getGuardrailLabel(guardrailEntries);
+ const guardrailPolicyNames = Array.from(
+ new Set(guardrailEntries.map((e: any) => e?.policy_template).filter(Boolean))
+ ) as string[];
// Vector store data
const hasVectorStoreData = checkHasVectorStoreData(metadata);
@@ -124,7 +127,7 @@ export function LogDetailContent({ logEntry, onOpenSettings, isLoadingDetails =
)}
{hasGuardrailData && (
<Descriptions.Item label="Guardrail">
- <GuardrailLabel label={primaryGuardrailLabel} maskedCount={totalMaskedEntities} />
+ <GuardrailLabel label={primaryGuardrailLabel} maskedCount={totalMaskedEntities} policyNames={guardrailPolicyNames} />
</Descriptions.Item>
)}
</Descriptions>
@@ -164,7 +167,11 @@ export function LogDetailContent({ logEntry, onOpenSettings, isLoadingDetails =
)}
{/* Guardrail Data */}
- {hasGuardrailData && <GuardrailViewer data={guardrailInfo} />}
+ {hasGuardrailData && (
+ <div id="guardrail-section">
+ <GuardrailViewer data={guardrailInfo} />
+ </div>
+ )}
{/* Vector Store Data */}
{hasVectorStoreData && <VectorStoreViewer data={metadata.vector_store_request_metadata} />}
@@ -218,15 +225,23 @@ function TagsSection({ tags }: { tags: Record<string, any> }) {
);
}
-function GuardrailLabel({ label, maskedCount }: { label: string; maskedCount: number }) {
+function GuardrailLabel({ label, maskedCount, policyNames }: { label: string; maskedCount: number; policyNames: string[] }) {
+ const handleClick = () => {
+ const el = document.getElementById("guardrail-section");
+ if (el) el.scrollIntoView({ behavior: "smooth" });
+ };
+
return (
<Space size={SPACING_MEDIUM}>
- <span>{label}</span>
+ <a onClick={handleClick} style={{ cursor: "pointer" }}>{label}</a>
{maskedCount > 0 && (
<Tag color="blue">
{maskedCount} masked
</Tag>
)}
+ {policyNames.map((name) => (
+ <Tag key={name} color="purple">{name}</Tag>
+ ))}
</Space>
);
}