The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(ui): add error-code drilldown for failed requests on caching page
ryan-crabbe-berri0de0e1cef6bf
diff --git a/litellm/proxy/analytics_endpoints/cache_activity.py b/litellm/proxy/analytics_endpoints/cache_activity.pyindex 751d6c15dfa..b87b8eac3ef 100644--- a/litellm/proxy/analytics_endpoints/cache_activity.py+++ b/litellm/proxy/analytics_endpoints/cache_activity.py@@ -34,10 +34,18 @@ class CacheActivityFilterOptions(BaseModel):models: list[str]+class CacheActivityErrorBucket(BaseModel):+ call_type: str+ error_code: str+ error_class: str+ count: int++class CacheActivityResponse(BaseModel):groups: list[CacheActivityGroup]totals: CacheActivityTotalsfilter_options: CacheActivityFilterOptions+ error_breakdown: tuple[CacheActivityErrorBucket, ...]GROUPS_SQL: Final = """@@ -65,6 +73,26 @@ GROUPS_SQL: Final = """ORDER BY (COUNT(*)) DESC"""+ERROR_BREAKDOWN_SQL: Final = """+ SELECT+ CASE WHEN sl."call_type" = '' THEN 'Unknown' ELSE sl."call_type" END AS call_type,+ COALESCE(NULLIF(sl."metadata"->'error_information'->>'error_code', ''), 'Unknown') AS error_code,+ COALESCE(NULLIF(sl."metadata"->'error_information'->>'error_class', ''), 'Unknown') AS error_class,+ COUNT(*)::int AS count+ FROM "LiteLLM_SpendLogs" sl+ LEFT JOIN "LiteLLM_VerificationToken" vt ON sl."api_key" = vt."token"+ WHERE+ sl."status" = 'failure'+ AND sl."startTime" >= ($1::timestamptz AT TIME ZONE 'UTC')+ AND sl."startTime" < (($2::timestamptz + INTERVAL '1 day') AT TIME ZONE 'UTC')+ AND ($3::jsonb = '[]'::jsonb+ OR COALESCE(vt."key_alias", 'Unnamed Key') IN (SELECT jsonb_array_elements_text($3::jsonb)))+ AND ($4::jsonb = '[]'::jsonb+ OR sl."model" IN (SELECT jsonb_array_elements_text($4::jsonb)))+ GROUP BY 1, 2, 3+ ORDER BY (COUNT(*)) DESC+"""+KEY_ALIAS_OPTIONS_SQL: Final = """SELECT DISTINCT COALESCE(vt."key_alias", 'Unnamed Key') AS key_aliasFROM "LiteLLM_SpendLogs" sl@@ -95,6 +123,7 @@ class _ModelRow(BaseModel):_groups_adapter: Final = TypeAdapter(list[CacheActivityGroup])+_error_buckets_adapter: Final = TypeAdapter(tuple[CacheActivityErrorBucket, ...])_key_alias_rows_adapter: Final = TypeAdapter(list[_KeyAliasRow])_model_rows_adapter: Final = TypeAdapter(list[_ModelRow])@@ -120,10 +149,11 @@ async def get_cache_activity(key_aliases: Sequence[str],models: Sequence[str],) -> CacheActivityResponse:- group_rows, key_alias_rows, model_rows = await asyncio.gather(- prisma_client.db.query_raw(- GROUPS_SQL, start_date, end_date, json.dumps(list(key_aliases)), json.dumps(list(models))- ),+ key_aliases_json: Final = json.dumps(list(key_aliases))+ models_json: Final = json.dumps(list(models))+ group_rows, error_rows, key_alias_rows, model_rows = await asyncio.gather(+ prisma_client.db.query_raw(GROUPS_SQL, start_date, end_date, key_aliases_json, models_json),+ prisma_client.db.query_raw(ERROR_BREAKDOWN_SQL, start_date, end_date, key_aliases_json, models_json),prisma_client.db.query_raw(KEY_ALIAS_OPTIONS_SQL, start_date, end_date),prisma_client.db.query_raw(MODEL_OPTIONS_SQL, start_date, end_date),)@@ -135,4 +165,5 @@ async def get_cache_activity(key_aliases=[row.key_alias for row in _key_alias_rows_adapter.validate_python(key_alias_rows or [])],models=[row.model for row in _model_rows_adapter.validate_python(model_rows or [])],),+ error_breakdown=_error_buckets_adapter.validate_python(error_rows or []),)diff --git a/tests/test_litellm/proxy/analytics_endpoints/test_analytics_endpoints.py b/tests/test_litellm/proxy/analytics_endpoints/test_analytics_endpoints.pyindex c48b8cfd5a5..4072f83511e 100644--- a/tests/test_litellm/proxy/analytics_endpoints/test_analytics_endpoints.py+++ b/tests/test_litellm/proxy/analytics_endpoints/test_analytics_endpoints.py@@ -14,6 +14,7 @@ from fastapi import HTTPExceptionfrom litellm.proxy.analytics_endpoints.analytics_endpoints import get_global_activityfrom litellm.proxy.analytics_endpoints.cache_activity import (+ ERROR_BREAKDOWN_SQL,GROUPS_SQL,CacheActivityGroup,compute_totals,@@ -37,6 +38,11 @@ GROUP_ROWS = ["generated_completion_tokens": 0,},]+ERROR_ROWS = [+ {"call_type": "acompletion", "error_code": "429", "error_class": "RateLimitError", "count": 150},+ {"call_type": "acompletion", "error_code": "401", "error_class": "AuthenticationError", "count": 50},+ {"call_type": "Unknown", "error_code": "Unknown", "error_class": "Unknown", "count": 110},+]KEY_ALIAS_ROWS = [{"key_alias": "Unnamed Key"}, {"key_alias": "my-key"}]MODEL_ROWS = [{"model": "gpt-5.1"}]@@ -49,6 +55,8 @@ def build_prisma(query_raw: AsyncMock) -> MagicMock:def dispatching_query_raw() -> AsyncMock:async def dispatch(sql: str, *params: object) -> list[dict[str, object]]:+ if "error_code" in sql:+ return ERROR_ROWSif "GROUP BY" in sql:return GROUP_ROWSif "key_alias" in sql:@@ -67,9 +75,7 @@ def mock_prisma(monkeypatch: pytest.MonkeyPatch) -> MagicMock:@pytest.mark.asyncioasync def test_returns_groups_totals_and_filter_options(mock_prisma: MagicMock):- response = await get_global_activity(- start_date="2026-07-01", end_date="2026-07-27", key_aliases=[], models=[]- )+ response = await get_global_activity(start_date="2026-07-01", end_date="2026-07-27", key_aliases=[], models=[])assert [group.call_type for group in response.groups] == ["acompletion", "Unknown"]assert response.groups[0].api_requests == 1000@@ -81,6 +87,11 @@ async def test_returns_groups_totals_and_filter_options(mock_prisma: MagicMock):assert response.totals.cache_hit_ratio == pytest.approx((300 / 1610) * 100)assert response.filter_options.key_aliases == ["Unnamed Key", "my-key"]assert response.filter_options.models == ["gpt-5.1"]+ assert [(bucket.error_code, bucket.error_class, bucket.count) for bucket in response.error_breakdown] == [+ ("429", "RateLimitError", 150),+ ("401", "AuthenticationError", 50),+ ("Unknown", "Unknown", 110),+ ]@pytest.mark.asyncio@@ -92,11 +103,13 @@ async def test_filters_are_passed_to_sql_as_json_arrays(mock_prisma: MagicMock):models=["gpt-5.1", "claude-opus-4-8"],)- groups_call = next(- call for call in mock_prisma.db.query_raw.call_args_list if "GROUP BY" in call.args[0]- )- assert groups_call.args[3] == json.dumps(["my-key"])- assert groups_call.args[4] == json.dumps(["gpt-5.1", "claude-opus-4-8"])+ filtered_calls = [+ call for call in mock_prisma.db.query_raw.call_args_list if call.args[0] in (GROUPS_SQL, ERROR_BREAKDOWN_SQL)+ ]+ assert len(filtered_calls) == 2+ for call in filtered_calls:+ assert call.args[3] == json.dumps(["my-key"])+ assert call.args[4] == json.dumps(["gpt-5.1", "claude-opus-4-8"])@pytest.mark.asyncio@@ -131,3 +144,10 @@ def test_totals_denominator_includes_failed_requests():def test_groups_sql_splits_failures_and_labels_empty_call_type_unknown():assert "SUM(CASE WHEN sl.\"status\" = 'failure' THEN 1 ELSE 0 END)" in GROUPS_SQLassert "CASE WHEN sl.\"call_type\" = '' THEN 'Unknown' ELSE sl.\"call_type\" END" in GROUPS_SQL+++def test_error_breakdown_sql_counts_only_failures_bucketed_by_code_and_class():+ assert "sl.\"status\" = 'failure'" in ERROR_BREAKDOWN_SQL+ assert "sl.\"metadata\"->'error_information'->>'error_code'" in ERROR_BREAKDOWN_SQL+ assert "sl.\"metadata\"->'error_information'->>'error_class'" in ERROR_BREAKDOWN_SQL+ assert "GROUP BY 1, 2, 3" in ERROR_BREAKDOWN_SQLdiff --git a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/ErrorDrilldown.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/ErrorDrilldown.test.tsxnew file mode 100644index 00000000000..a29d23d0af5--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/ErrorDrilldown.test.tsx@@ -0,0 +1,55 @@+import React from "react";+import { describe, it, expect } from "vitest";+import { render, screen } from "@testing-library/react";+import { ErrorCodeTooltip, groupErrorBuckets, type CacheActivityErrorBucket } from "./ErrorDrilldown";++const BUCKETS: CacheActivityErrorBucket[] = [+ { call_type: "acompletion", error_code: "401", error_class: "AuthenticationError", count: 50 },+ { call_type: "acompletion", error_code: "429", error_class: "RateLimitError", count: 120 },+ { call_type: "acompletion", error_code: "429", error_class: "InternalServerError", count: 30 },+ { call_type: "aembedding", error_code: "500", error_class: "InternalServerError", count: 999 },+];++describe("groupErrorBuckets", () => {+ it("keeps only the requested call_type, totals per code, and sorts codes and classes by count desc", () => {+ expect(groupErrorBuckets(BUCKETS, "acompletion")).toEqual([+ {+ error_code: "429",+ "Failed requests": 150,+ classes: [+ { error_class: "RateLimitError", count: 120 },+ { error_class: "InternalServerError", count: 30 },+ ],+ },+ {+ error_code: "401",+ "Failed requests": 50,+ classes: [{ error_class: "AuthenticationError", count: 50 }],+ },+ ]);+ });++ it("returns no data for a call_type without failures", () => {+ expect(groupErrorBuckets(BUCKETS, "atranscription")).toEqual([]);+ });+});++describe("ErrorCodeTooltip", () => {+ const datum = groupErrorBuckets(BUCKETS, "acompletion")[0];++ it("shows the code total and one row per error class on hover", () => {+ render(<ErrorCodeTooltip active label="429" payload={[{ payload: datum, value: 150, graphicalItemId: "bar" }]} />);++ expect(screen.getByText("Error code 429: 150 failed")).toBeInTheDocument();+ expect(screen.getByText("RateLimitError")).toBeInTheDocument();+ expect(screen.getByText("120")).toBeInTheDocument();+ expect(screen.getByText("InternalServerError")).toBeInTheDocument();+ expect(screen.getByText("30")).toBeInTheDocument();+ });++ it("renders nothing when inactive", () => {+ const { container } = render(<ErrorCodeTooltip active={false} label="429" payload={[]} />);++ expect(container).toBeEmptyDOMElement();+ });+});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/ErrorDrilldown.tsx b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/ErrorDrilldown.tsxnew file mode 100644index 00000000000..c20b881c47c--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/ErrorDrilldown.tsx@@ -0,0 +1,99 @@+"use client";++import React from "react";+import { X } from "lucide-react";+import { BarChart } from "@/components/shared/charts";+import type { ChartTooltipProps } from "@/components/shared/charts/chart_tooltip";+import { Button } from "@/components/ui/button";+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";+import type { components } from "@/lib/http/schema";++export type CacheActivityErrorBucket = components["schemas"]["CacheActivityErrorBucket"];++export const FAILED_REQUESTS_SERIES = "Failed requests";++export type ErrorClassCount = {+ error_class: string;+ count: number;+};++export type ErrorCodeDatum = {+ error_code: string;+ [FAILED_REQUESTS_SERIES]: number;+ classes: ErrorClassCount[];+};++export const groupErrorBuckets = (buckets: readonly CacheActivityErrorBucket[], callType: string): ErrorCodeDatum[] => {+ const byCode = new Map<string, Map<string, number>>();+ for (const bucket of buckets) {+ if (bucket.call_type !== callType) continue;+ const classes = byCode.get(bucket.error_code) ?? new Map<string, number>();+ classes.set(bucket.error_class, (classes.get(bucket.error_class) ?? 0) + bucket.count);+ byCode.set(bucket.error_code, classes);+ }+ return [...byCode.entries()]+ .map(([errorCode, classes]) => ({+ error_code: errorCode,+ [FAILED_REQUESTS_SERIES]: [...classes.values()].reduce((total, count) => total + count, 0),+ classes: [...classes.entries()]+ .map(([errorClass, count]) => ({ error_class: errorClass, count }))+ .sort((a, b) => b.count - a.count),+ }))+ .sort((a, b) => b[FAILED_REQUESTS_SERIES] - a[FAILED_REQUESTS_SERIES]);+};++export const ErrorCodeTooltip = ({ active, payload, label }: ChartTooltipProps) => {+ if (!active || !payload || payload.length === 0) return null;+ const datum = payload[0]?.payload as ErrorCodeDatum | undefined;+ if (!datum) return null;++ return (+ <div className="min-w-40 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl">+ <p className="mb-1.5 font-medium text-foreground">+ Error code {String(label)}: {datum[FAILED_REQUESTS_SERIES].toLocaleString()} failed+ </p>+ <div className="grid gap-1.5">+ {datum.classes.map((errorClass) => (+ <div key={errorClass.error_class} className="flex w-full items-center justify-between gap-4">+ <span className="text-muted-foreground">{errorClass.error_class}</span>+ <span className="font-mono font-medium tabular-nums text-foreground">+ {errorClass.count.toLocaleString()}+ </span>+ </div>+ ))}+ </div>+ </div>+ );+};++interface ErrorDrilldownCardProps {+ callType: string;+ buckets: readonly CacheActivityErrorBucket[];+ valueFormatter: (value: number) => string;+ onClose: () => void;+}++export const ErrorDrilldownCard = ({ callType, buckets, valueFormatter, onClose }: ErrorDrilldownCardProps) => (+ <Card className="mt-4">+ <CardHeader className="flex flex-row items-center justify-between">+ <CardTitle className="text-base font-semibold">Failed requests by error code: {callType}</CardTitle>+ <Button variant="outline" size="icon-sm" onClick={onClose} aria-label="Close error breakdown">+ <X />+ </Button>+ </CardHeader>+ <CardContent>+ <p className="text-sm text-muted-foreground">Hover a bar to see the error classes behind that code.</p>+ <BarChart+ data={groupErrorBuckets(buckets, callType)}+ index="error_code"+ categories={[FAILED_REQUESTS_SERIES]}+ colors={["red"]}+ valueFormatter={valueFormatter}+ showLegend={false}+ customTooltip={ErrorCodeTooltip}+ yAxisWidth={48}+ className="mt-2"+ />+ </CardContent>+ </Card>+);diff --git a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_dashboard.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_dashboard.test.tsxindex fd8dd011b05..73ff0d8ba1a 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_dashboard.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_dashboard.test.tsx@@ -1,6 +1,6 @@import React from "react";import { describe, it, expect, vi, beforeEach } from "vitest";-import { screen, waitFor, within } from "@testing-library/react";+import { fireEvent, screen, waitFor, within } from "@testing-library/react";import { renderWithProviders } from "../../../../../tests/test-utils";import CacheDashboard from "./cache_dashboard";@@ -47,6 +47,11 @@ const cacheActivity = {key_aliases: ["my-key", "Unnamed Key"],models: ["gpt-5.1", "text-embedding-3-large"],},+ error_breakdown: [+ { call_type: "acompletion", error_code: "429", error_class: "RateLimitError", count: 150 },+ { call_type: "acompletion", error_code: "401", error_class: "AuthenticationError", count: 50 },+ { call_type: "aembedding", error_code: "500", error_class: "InternalServerError", count: 50 },+ ],};const renderDashboard = () =>@@ -185,6 +190,27 @@ describe("CacheDashboard cache analytics charts", () => {});});+ it("opens the error-code drilldown for a call_type when its failed segment is clicked, and closes it again", async () => {+ renderDashboard();+ const { requestsCard } = await findChartCards();++ const redBar = Array.from(requestsCard.querySelectorAll(".recharts-bar")).find((bar) =>+ bar.querySelector("path.recharts-rectangle")?.getAttribute("fill")?.includes("red"),+ );+ expect(redBar).toBeDefined();+ expect(screen.queryByText(/Failed requests by error code/)).not.toBeInTheDocument();++ fireEvent.click(redBar!.querySelectorAll("path.recharts-rectangle")[0]);++ const drilldownCard = cardTitled("Failed requests by error code: acompletion");+ expect(within(drilldownCard).getAllByText("429").length).toBeGreaterThan(0);+ expect(within(drilldownCard).getAllByText("401").length).toBeGreaterThan(0);+ expect(within(drilldownCard).queryByText("500")).not.toBeInTheDocument();++ fireEvent.click(within(drilldownCard).getByRole("button", { name: "Close error breakdown" }));+ expect(screen.queryByText(/Failed requests by error code/)).not.toBeInTheDocument();+ });+it("formats y-axis ticks with compact notation", async () => {renderDashboard();const { requestsCard, tokensCard } = await findChartCards();diff --git a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_dashboard.tsx b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_dashboard.tsxindex cafa7a2ce37..bae6cee1d6c 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_dashboard.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/caching/_components/cache_dashboard.tsx@@ -27,6 +27,7 @@ import { useCacheActivity, type CacheActivityGroup } from "@/app/(dashboard)/hooimport { CacheHealthTab } from "./cache_health";import CacheSettings from "./cache_settings";import CoordinationRedisSettings from "./coordination_redis_settings";+import { ErrorDrilldownCard } from "./ErrorDrilldown";const REQUEST_SERIES = {apiRequests: "LLM API requests",@@ -73,6 +74,7 @@ const CacheDashboard: React.FC<CachePageProps> = ({ accessToken, token, userRoleconst anchor2 = useComboboxAnchor();const [selectedApiKeys, setSelectedApiKeys] = useState<string[]>([]);const [selectedModels, setSelectedModels] = useState<string[]>([]);+ const [errorDrilldownCallType, setErrorDrilldownCallType] = useState<string | null>(null);const [dateValue, setDateValue] = useState<DateRangePickerValue>({from: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),@@ -277,6 +279,9 @@ const CacheDashboard: React.FC<CachePageProps> = ({ accessToken, token, userRole<CardTitle className="text-base font-semibold">Cache Hits vs API Requests</CardTitle></CardHeader><CardContent>+ <p className="text-sm text-muted-foreground">+ Click a red failed-requests segment to see which error codes caused those failures.+ </p><BarChartdata={chartData}stack={true}@@ -285,10 +290,23 @@ const CacheDashboard: React.FC<CachePageProps> = ({ accessToken, token, userRolecategories={[REQUEST_SERIES.apiRequests, REQUEST_SERIES.cacheHits, REQUEST_SERIES.failed]}colors={["sky", "teal", "red"]}yAxisWidth={48}+ className="mt-2"+ onValueChange={(item) => {+ if (item.categoryClicked === REQUEST_SERIES.failed) setErrorDrilldownCallType(item.name);+ }}/></CardContent></Card>+ {errorDrilldownCallType !== null && (+ <ErrorDrilldownCard+ callType={errorDrilldownCallType}+ buckets={activity?.error_breakdown ?? []}+ valueFormatter={valueFormatterNumbers}+ onClose={() => setErrorDrilldownCallType(null)}+ />+ )}+<Card className="mt-6"><CardHeader><CardTitle className="text-base font-semibold">diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex 86138f16248..87f050e417f 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -23009,6 +23009,17 @@ export interface components {/** Total Requested */total_requested: number;};+ /** CacheActivityErrorBucket */+ CacheActivityErrorBucket: {+ /** Call Type */+ call_type: string;+ /** Count */+ count: number;+ /** Error Class */+ error_class: string;+ /** Error Code */+ error_code: string;+ };/** CacheActivityFilterOptions */CacheActivityFilterOptions: {/** Key Aliases */@@ -23033,6 +23044,8 @@ export interface components {};/** CacheActivityResponse */CacheActivityResponse: {+ /** Error Breakdown */+ error_breakdown: components["schemas"]["CacheActivityErrorBucket"][];filter_options: components["schemas"]["CacheActivityFilterOptions"];/** Groups */groups: components["schemas"]["CacheActivityGroup"][];