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]

feat(ui): show models under each tier in routing benchmark chart (#36291)

tin-berridca7ba18d4a9
diff --git a/litellm/types/management_endpoints/auto_router_endpoints.py b/litellm/types/management_endpoints/auto_router_endpoints.py
index 6626dea6849..269d9b50414 100644
--- a/litellm/types/management_endpoints/auto_router_endpoints.py
+++ b/litellm/types/management_endpoints/auto_router_endpoints.py
@@ -126,8 +126,8 @@ class AutoRouterBenchmarkGroup(AutoRouterBenchmarkTotals):
description="Turns per tier, keyed by the tier name the routing decision recorded at "
"request time (never re-derived at read time, since the tier-to-model mapping is "
"mutable config). Tier names are scoped to this group's router_type and are not "
- "comparable across types: a complexity router reports 'simple'/'medium'/'complex'/"
- "'reasoning', a quality router reports its numeric quality tier, and an adaptive router "
+ "comparable across types: a complexity router reports 'SIMPLE'/'MEDIUM'/'COMPLEX'/"
+ "'REASONING', a quality router reports its numeric quality tier, and an adaptive router "
"records no tier at all. Turns no tier served (the classifier fell back to default_model) "
"are absent rather than pooled under a sentinel key, so the values may sum to less than turns",
)
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/AutoRouterBenchmarksTab.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/AutoRouterBenchmarksTab.test.tsx
index a5767383307..4a6ff77d99b 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/AutoRouterBenchmarksTab.test.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/AutoRouterBenchmarksTab.test.tsx
@@ -1,10 +1,15 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen } from "@testing-library/react";
import React from "react";
-import { describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { AutoRouterDeployment } from "@/app/(dashboard)/hooks/models/useModels";
import { ApiError } from "@/lib/http/client";
vi.mock("./useAutoRouterBenchmarks", () => ({ useAutoRouterBenchmarks: vi.fn() }));
+vi.mock("@/app/(dashboard)/hooks/models/useModels", () => ({ useAutoRouters: vi.fn() }));
+
+import { useAutoRouters } from "@/app/(dashboard)/hooks/models/useModels";
import AutoRouterBenchmarksTab from "./AutoRouterBenchmarksTab";
import type {
@@ -16,6 +21,10 @@ import { useAutoRouterBenchmarks } from "./useAutoRouterBenchmarks";
type HookResult = ReturnType<typeof useAutoRouterBenchmarks>;
+const mockAutoRouters = (deployments: AutoRouterDeployment[] = []) => {
+ vi.mocked(useAutoRouters).mockReturnValue({ data: deployments } as unknown as ReturnType<typeof useAutoRouters>);
+};
+
const mockHook = (result: { data?: AutoRouterBenchmarksResponse; isPending?: boolean; error?: Error }) => {
vi.mocked(useAutoRouterBenchmarks).mockReturnValue({
data: result.data,
@@ -71,9 +80,20 @@ const response = (groups: AutoRouterBenchmarkGroup[], shared: Totals = totals())
groups,
});
-const renderTab = () => render(<AutoRouterBenchmarksTab accessToken="sk-test" />);
+const renderTab = () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <AutoRouterBenchmarksTab accessToken="sk-test" />
+ </QueryClientProvider>,
+ );
+};
describe("AutoRouterBenchmarksTab", () => {
+ beforeEach(() => {
+ mockAutoRouters();
+ });
+
it("leads with total estimated savings, before the three session-shape metrics", () => {
mockHook({ data: response([group(), group({ router_name: "gpt-auto" })]) });
renderTab();
@@ -97,7 +117,7 @@ describe("AutoRouterBenchmarksTab", () => {
expect(screen.getByText("-86%")).toBeInTheDocument();
expect(screen.getByText("Actual auto-router spend")).toBeInTheDocument();
expect(screen.getByText("$359.86")).toBeInTheDocument();
- expect(screen.getByText("Estimated spend at highest-cost model")).toBeInTheDocument();
+ expect(screen.getByText("Estimated spend at highest-tier model")).toBeInTheDocument();
expect(screen.getByText("$2,534.45")).toBeInTheDocument();
expect(screen.getByText("32.7")).toBeInTheDocument();
expect(screen.getByText("2.1h")).toBeInTheDocument();
@@ -108,12 +128,9 @@ describe("AutoRouterBenchmarksTab", () => {
mockHook({ data: response([group(), group({ router_name: "gpt-auto" })]) });
renderTab();
- expect(screen.getByText("Total sessions")).toBeInTheDocument();
- expect(screen.getByText("94")).toBeInTheDocument();
- expect(screen.getByText("Total turns")).toBeInTheDocument();
- expect(screen.getByText("3,073")).toBeInTheDocument();
expect(screen.getByText("Avg saved per session")).toBeInTheDocument();
expect(screen.getByText("$23.13")).toBeInTheDocument();
+ expect(screen.getByText("across 94 sessions")).toBeInTheDocument();
});
it("shows a cost increase as a positive delta rather than a saving", () => {
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/AutoRouterBenchmarksTab.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/AutoRouterBenchmarksTab.tsx
index ff0f52940b2..5d4fda765e7 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/AutoRouterBenchmarksTab.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/AutoRouterBenchmarksTab.tsx
@@ -2,6 +2,8 @@
import React, { useState } from "react";
+import type { AutoRouterDeployment } from "@/app/(dashboard)/hooks/models/useModels";
+import { useAutoRouters } from "@/app/(dashboard)/hooks/models/useModels";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
@@ -29,6 +31,7 @@ import {
type BucketRow,
} from "./autoRouterBenchmarks";
import { usd } from "./costOptimizationUtils";
+import TierTurnsChart from "./TierTurnsChart";
import { useAutoRouterBenchmarks } from "./useAutoRouterBenchmarks";
const Message: React.FC<{ children: React.ReactNode }> = ({ children }) => (
@@ -51,7 +54,7 @@ const HeroCard: React.FC<{ view: BenchmarkView }> = ({ view }) => {
const cheaper = stats.saved_spend >= 0;
return (
<Card className="overflow-hidden py-0">
- <div className="grid md:grid-cols-[4fr_3fr_5fr]">
+ <div className="grid md:grid-cols-[1fr_1fr]">
<div className="flex flex-col justify-center gap-3 p-6">
<p className="text-sm text-muted-foreground">Total estimated savings</p>
<div className="flex flex-wrap items-center gap-3">
@@ -64,38 +67,22 @@ const HeroCard: React.FC<{ view: BenchmarkView }> = ({ view }) => {
{Math.abs(stats.saved_pct).toFixed(0)}%
</Badge>
</div>
- </div>
-
- <div className="flex flex-col justify-center px-6 pb-6 md:py-6">
<dl className="divide-y text-sm">
<div className="flex items-baseline justify-between gap-6 py-3">
<dt className="text-muted-foreground">Actual auto-router spend</dt>
<dd className="font-medium tabular-nums text-foreground">{usd(stats.spend)}</dd>
</div>
<div className="flex items-baseline justify-between gap-6 py-3">
- <dt className="text-muted-foreground">Estimated spend at highest-cost model</dt>
+ <dt className="text-muted-foreground">Estimated spend at highest-tier model</dt>
<dd className="font-medium tabular-nums text-foreground">{usd(stats.baseline_spend)}</dd>
</div>
</dl>
</div>
- <div className="flex flex-col border-t md:border-t-0 md:border-l">
- <div className="grid flex-1 grid-cols-2 divide-x">
- <div className="flex flex-col justify-center gap-1 px-6 py-4">
- <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Total sessions</p>
- <p className="text-3xl font-semibold text-foreground">{stats.sessions.toLocaleString()}</p>
- </div>
- <div className="flex flex-col justify-center gap-1 px-6 py-4">
- <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Total turns</p>
- <p className="text-3xl font-semibold text-foreground">{stats.turns.toLocaleString()}</p>
- </div>
- </div>
- <dl className="flex flex-col divide-y border-t text-sm">
- <div className="flex items-center justify-between gap-2 px-6 py-3">
- <dt className="text-[11px] uppercase tracking-wide text-muted-foreground">Avg saved per session</dt>
- <dd className="text-lg font-semibold tabular-nums text-foreground">{usd(stats.saved_per_session)}</dd>
- </div>
- </dl>
+ <div className="flex flex-col items-center justify-center gap-2 border-t p-6 md:border-t-0 md:border-l">
+ <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Avg saved per session</p>
+ <p className="text-5xl font-semibold tracking-tight text-foreground">{usd(stats.saved_per_session)}</p>
+ <p className="text-sm text-muted-foreground">across {stats.sessions.toLocaleString()} sessions</p>
</div>
</div>
</Card>
@@ -233,9 +220,10 @@ interface BenchmarksBodyProps {
error: unknown;
data: AutoRouterBenchmarksResponse | undefined;
selectedKey: string;
+ autoRouters: readonly AutoRouterDeployment[];
}
-const BenchmarksBody: React.FC<BenchmarksBodyProps> = ({ isPending, error, data, selectedKey }) => {
+const BenchmarksBody: React.FC<BenchmarksBodyProps> = ({ isPending, error, data, selectedKey, autoRouters }) => {
if (isPending) return <Message>Loading auto-router usage...</Message>;
if (error instanceof ApiError && error.status === 403) {
return <Message>Auto-router usage is visible to proxy admin roles only</Message>;
@@ -249,6 +237,8 @@ const BenchmarksBody: React.FC<BenchmarksBodyProps> = ({ isPending, error, data,
<>
<HeroCard view={view} />
+ <TierTurnsChart view={view} autoRouters={autoRouters} />
+
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
<Metric label="Avg turns per session" value={stats.avg_turns_per_session.toFixed(1)} />
<Metric label="Avg session length" value={durationLabel(stats.avg_session_seconds)} />
@@ -282,6 +272,7 @@ const AutoRouterBenchmarksTab: React.FC<AutoRouterBenchmarksTabProps> = ({ acces
const [range, setRange] = useState<BenchmarkWindow>("30d");
const { data, isPending, error } = useAutoRouterBenchmarks(accessToken, range);
const [selectedKey, setSelectedKey] = useState<string>(ALL_ROUTERS);
+ const { data: autoRouters } = useAutoRouters();
const groups = data?.groups ?? [];
const selectedLabel = data ? viewFor(data, selectedKey).label : "All auto-routers";
@@ -319,7 +310,13 @@ const AutoRouterBenchmarksTab: React.FC<AutoRouterBenchmarksTabProps> = ({ acces
</div>
</div>
- <BenchmarksBody isPending={isPending} error={error} data={data} selectedKey={selectedKey} />
+ <BenchmarksBody
+ isPending={isPending}
+ error={error}
+ data={data}
+ selectedKey={selectedKey}
+ autoRouters={autoRouters ?? []}
+ />
</div>
);
};
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/CostOptimizationView.activity.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/CostOptimizationView.activity.test.tsx
index ca7adf07941..96502cac953 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/CostOptimizationView.activity.test.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/CostOptimizationView.activity.test.tsx
@@ -1,12 +1,23 @@
+import React from "react";
import { fireEvent, render, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
const mockUserDailyActivityCall = vi.fn();
+const { useAuthorizedMock, mockToolSpendResponse } = vi.hoisted(() => ({
+ useAuthorizedMock: vi.fn(),
+ mockToolSpendResponse: { by_tool: [], daily: [], start_date: null, end_date: null },
+}));
+
+vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({
+ default: useAuthorizedMock,
+}));
vi.mock("@/components/networking", () => ({
userDailyActivityCall: (...args: unknown[]) => mockUserDailyActivityCall(...args),
- getToolSpend: vi.fn().mockResolvedValue({ by_tool: [], daily: [], start_date: null, end_date: null }),
+ getToolSpend: vi.fn().mockResolvedValue(mockToolSpendResponse),
getGeneralSettingsCall: vi.fn().mockResolvedValue([]),
+ organizationListCall: vi.fn().mockResolvedValue([]),
}));
vi.mock("@/components/shared/advanced_date_picker", () => ({
@@ -38,9 +49,13 @@ const singlePage = {
describe("CostOptimizationView daily activity", () => {
it("fetches daily activity once for the page and shares it with every tab that needs it", async () => {
mockUserDailyActivityCall.mockResolvedValue(singlePage);
+ useAuthorizedMock.mockReturnValue({ accessToken: "test-token", userId: "u1", userRole: "proxy_admin" });
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const { getByRole, getByTestId } = render(
- <CostOptimizationView accessToken="test-token" userId="u1" userRole="proxy_admin" />,
+ <QueryClientProvider client={queryClient}>
+ <CostOptimizationView accessToken="test-token" userId="u1" userRole="proxy_admin" />
+ </QueryClientProvider>,
);
await waitFor(() => expect(mockUserDailyActivityCall).toHaveBeenCalledTimes(1));
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/CostOptimizationView.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/CostOptimizationView.test.tsx
index c6d5a410418..60926f575bc 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/CostOptimizationView.test.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/CostOptimizationView.test.tsx
@@ -1,5 +1,7 @@
+import React from "react";
import { fireEvent, render } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
const { useAuthorizedMock } = vi.hoisted(() => ({ useAuthorizedMock: vi.fn() }));
@@ -7,6 +9,13 @@ vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({
default: useAuthorizedMock,
}));
+vi.mock("@/components/networking", () => ({
+ organizationListCall: vi.fn().mockResolvedValue([]),
+ userDailyActivityCall: vi
+ .fn()
+ .mockResolvedValue({ results: [], metadata: { total_pages: 1, has_more: false, page: 1 } }),
+}));
+
vi.mock("./UsageTab", () => ({ __esModule: true, default: () => <div data-testid="usage-tab" /> }));
vi.mock("./PromptCompressionTab", () => ({ __esModule: true, default: () => <div data-testid="compression-tab" /> }));
vi.mock("./PromptCachingTab", () => ({ __esModule: true, default: () => <div data-testid="caching-tab" /> }));
@@ -19,7 +28,12 @@ import CostOptimizationView from "./CostOptimizationView";
const renderView = (userRole = "Admin") => {
useAuthorizedMock.mockReturnValue({ accessToken: "test-token", userId: "u1", userRole });
- return render(<CostOptimizationView accessToken="test-token" userId="u1" userRole={userRole} />);
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <CostOptimizationView accessToken="test-token" userId="u1" userRole={userRole} />
+ </QueryClientProvider>,
+ );
};
describe("CostOptimizationView", () => {
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/TierTurnsChart.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/TierTurnsChart.test.tsx
new file mode 100644
index 00000000000..057eb54ee4e
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/TierTurnsChart.test.tsx
@@ -0,0 +1,163 @@
+import { render, screen } from "@testing-library/react";
+import React from "react";
+import { describe, expect, it, vi } from "vitest";
+
+import type { AutoRouterDeployment } from "@/app/(dashboard)/hooks/models/useModels";
+
+vi.mock("@/components/shared/charts", () => ({
+ DonutChart: ({ label }: { label: string }) => <div data-testid="donut">{label}</div>,
+ SEQUENTIAL_COLOR_RAMP: ["indigo", "blue"],
+ chartColorValue: (color: string) => color,
+}));
+
+import TierTurnsChart, { tierDisplayLabel } from "./TierTurnsChart";
+import type { AutoRouterBenchmarkGroup, BenchmarkView } from "./autoRouterBenchmarks";
+
+const totalsOnly = {
+ sessions: 3,
+ turns: 9,
+ avg_turns_per_session: 3,
+ avg_session_seconds: 60,
+ avg_tokens_per_session: 100,
+ spend: 1,
+ saved_spend: 1,
+ baseline_spend: 2,
+ saved_pct: 50,
+ saved_per_session: 0.33,
+ cache: {
+ coverage_pct: 0,
+ hit_rate_pct: 0,
+ same_model: { turns: 0, hits: 0, hit_rate_pct: 0 },
+ first_visit: { turns: 0, hits: 0, hit_rate_pct: 0 },
+ return_to_tier: { turns: 0, hits: 0, hit_rate_pct: 0 },
+ unordered_turns: 0,
+ return_misses_expired: 0,
+ return_misses_within_ttl: 0,
+ return_misses_unknown: 0,
+ ttl_5m_turns: 0,
+ ttl_1h_turns: 0,
+ },
+};
+
+const groupView = (overrides: Partial<AutoRouterBenchmarkGroup> = {}): BenchmarkView => ({
+ label: "claude-auto",
+ stats: {
+ ...totalsOnly,
+ router_name: "claude-auto",
+ router_type: "complexity",
+ tier_turns: { SIMPLE: 3, COMPLEX: 1 },
+ ...overrides,
+ } as AutoRouterBenchmarkGroup,
+});
+
+const deployment = (config: unknown): AutoRouterDeployment => ({
+ model_name: "claude-auto",
+ litellm_params: { model: "auto_router/claude-auto", complexity_router_config: config },
+});
+
+describe("tierDisplayLabel", () => {
+ it("prefers the admin's custom label for a canonical complexity tier", () => {
+ expect(tierDisplayLabel("SIMPLE", { SIMPLE: "Cheap" })).toBe("Cheap");
+ });
+
+ it("falls back to the canonical name when that tier has no custom label", () => {
+ expect(tierDisplayLabel("COMPLEX", { SIMPLE: "Cheap" })).toBe("Complex");
+ expect(tierDisplayLabel("REASONING", undefined)).toBe("Reasoning");
+ });
+
+ it("shows a non-complexity tier verbatim, since no label map covers a quality router's tier", () => {
+ expect(tierDisplayLabel("3", { SIMPLE: "Cheap" })).toBe("3");
+ });
+});
+
+describe("TierTurnsChart", () => {
+ it("labels each slice with its tier and share of the tiered turns", () => {
+ render(<TierTurnsChart view={groupView()} autoRouters={[deployment({ tier_labels: { SIMPLE: "Cheap" } })]} />);
+
+ expect(screen.getByText("Cheap 75%")).toBeInTheDocument();
+ expect(screen.getByText("Complex 25%")).toBeInTheDocument();
+ expect(screen.getByTestId("donut")).toHaveTextContent("4 total turns");
+ });
+
+ it("reads tier_labels out of a config stored as a JSON string", () => {
+ const stored = JSON.stringify({ tier_labels: { SIMPLE: "Cheap" } });
+ render(<TierTurnsChart view={groupView()} autoRouters={[deployment(stored)]} />);
+
+ expect(screen.getByText("Cheap 75%")).toBeInTheDocument();
+ });
+
+ it("uses canonical names when the router is not in the deployment list", () => {
+ render(<TierTurnsChart view={groupView()} autoRouters={[]} />);
+
+ expect(screen.getByText("Simple 75%")).toBeInTheDocument();
+ expect(screen.getByText("Complex 25%")).toBeInTheDocument();
+ });
+
+ it("lists each tier's assigned models below its name and share", () => {
+ render(
+ <TierTurnsChart
+ view={groupView()}
+ autoRouters={[deployment({ tiers: { SIMPLE: ["gpt-4o-mini"], COMPLEX: ["gpt-4o", "claude-3-opus"] } })]}
+ />,
+ );
+
+ expect(screen.getByText("gpt-4o-mini")).toBeInTheDocument();
+ expect(screen.getByText("gpt-4o, claude-3-opus")).toBeInTheDocument();
+ });
+
+ it("widens a bare string tier (pinned single model) into its one-model list", () => {
+ render(<TierTurnsChart view={groupView()} autoRouters={[deployment({ tiers: { SIMPLE: "gpt-4o-mini" } })]} />);
+
+ expect(screen.getByText("gpt-4o-mini")).toBeInTheDocument();
+ });
+
+ it("omits the model line for a tier with no configured models", () => {
+ render(<TierTurnsChart view={groupView()} autoRouters={[deployment({ tiers: { SIMPLE: [] } })]} />);
+
+ expect(screen.getByText("Simple 75%")).toBeInTheDocument();
+ });
+
+ it("shows no models for a quality router's numeric tier, which has no per-tier model list", () => {
+ render(
+ <TierTurnsChart
+ view={groupView({ router_type: "quality", tier_turns: { "3": 3, "1": 1 } })}
+ autoRouters={[deployment({ quality_router_config: { available_models: ["gpt-4o"] } })]}
+ />,
+ );
+
+ expect(screen.getByText("3 75%")).toBeInTheDocument();
+ expect(screen.getByText("1 25%")).toBeInTheDocument();
+ expect(screen.queryByText("gpt-4o")).not.toBeInTheDocument();
+ });
+
+ it("ignores a same-named deployment of a different router type", () => {
+ const qualityDeployment = {
+ model_name: "claude-auto",
+ litellm_params: { model: "auto_router/claude-auto", quality_router_config: { available_models: ["gpt-4o"] } },
+ };
+
+ render(
+ <TierTurnsChart
+ view={groupView()} // complexity router
+ autoRouters={[qualityDeployment] as AutoRouterDeployment[]}
+ />,
+ );
+
+ expect(screen.getByText("Simple 75%")).toBeInTheDocument();
+ expect(screen.queryByText("gpt-4o")).not.toBeInTheDocument();
+ });
+
+ it("renders nothing for the all-routers view, which carries no router identity", () => {
+ const { container } = render(
+ <TierTurnsChart view={{ label: "All auto-routers", stats: totalsOnly }} autoRouters={[]} />,
+ );
+
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("renders nothing when the router recorded no tiers", () => {
+ const { container } = render(<TierTurnsChart view={groupView({ tier_turns: {} })} autoRouters={[]} />);
+
+ expect(container).toBeEmptyDOMElement();
+ });
+});
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/TierTurnsChart.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/TierTurnsChart.tsx
new file mode 100644
index 00000000000..5b9b8563baa
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/TierTurnsChart.tsx
@@ -0,0 +1,148 @@
+"use client";
+
+import React from "react";
+
+import type { AutoRouterDeployment } from "@/app/(dashboard)/hooks/models/useModels";
+import { hydrateTierLabels } from "@/components/add_model/build_complexity_router_config";
+import {
+ TIER_KEYS,
+ effectiveTierLabel,
+ type ComplexityTierLabels,
+ type ComplexityTiers,
+} from "@/components/add_model/ComplexityRouterConfig";
+import { normalizeTierModels } from "@/components/add_model/complexity_router_tiers";
+import { chartColorValue, DonutChart, type ChartColor } from "@/components/shared/charts";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+
+import { viewGroup, type BenchmarkView } from "./autoRouterBenchmarks";
+
+const safeParse = (value: string): unknown => {
+ try {
+ return JSON.parse(value);
+ } catch {
+ return null;
+ }
+};
+
+const asRecord = (value: unknown): Record<string, unknown> => {
+ const parsed: unknown = typeof value === "string" ? safeParse(value) : value;
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
+ ? (parsed as Record<string, unknown>)
+ : {};
+};
+
+const isComplexityTier = (tier: string): tier is keyof ComplexityTiers =>
+ (TIER_KEYS as readonly string[]).includes(tier);
+
+export const tierDisplayLabel = (tier: string, tierLabels: ComplexityTierLabels | undefined): string =>
+ isComplexityTier(tier) ? effectiveTierLabel(tier, tierLabels) : tier;
+
+const CONFIG_KEY_BY_ROUTER_TYPE: Record<string, keyof NonNullable<AutoRouterDeployment["litellm_params"]>> = {
+ complexity: "complexity_router_config",
+ quality: "quality_router_config",
+ auto_router: "auto_router_config",
+ adaptive: "adaptive_router_config",
+};
+
+const deploymentFor = (
+ routerName: string,
+ routerType: string,
+ autoRouters: readonly AutoRouterDeployment[],
+): AutoRouterDeployment | undefined => {
+ const configKey = CONFIG_KEY_BY_ROUTER_TYPE[routerType];
+ if (!configKey) return undefined;
+ return autoRouters.find((d) => d.model_name === routerName && d.litellm_params?.[configKey]);
+};
+
+const tierLabelsFor = (
+ routerName: string,
+ routerType: string,
+ autoRouters: readonly AutoRouterDeployment[],
+): ComplexityTierLabels | undefined => {
+ const deployment = deploymentFor(routerName, routerType, autoRouters);
+ if (!deployment) return undefined;
+ const config = asRecord(deployment.litellm_params?.complexity_router_config);
+ return hydrateTierLabels(config.tier_labels);
+};
+
+const tierModelsFor = (
+ tier: string,
+ routerName: string,
+ routerType: string,
+ autoRouters: readonly AutoRouterDeployment[],
+): string[] => {
+ if (!isComplexityTier(tier)) return [];
+ const deployment = deploymentFor(routerName, routerType, autoRouters);
+ if (!deployment) return [];
+ const config = asRecord(deployment.litellm_params?.complexity_router_config);
+ const tiers = asRecord(config.tiers);
+ return normalizeTierModels(tiers[tier]);
+};
+
+interface TierTurnsChartProps {
+ view: BenchmarkView;
+ autoRouters: readonly AutoRouterDeployment[];
+}
+
+const TIER_DONUT_COLORS: readonly ChartColor[] = ["#c7d2fe", "#1e293b", "#d4b483", "#87a878"];
+
+const TierTurnsChart: React.FC<TierTurnsChartProps> = ({ view, autoRouters }) => {
+ const group = viewGroup(view);
+ const entries = Object.entries(group?.tier_turns ?? {}).filter(([, turns]) => turns > 0);
+ if (!group || entries.length === 0) return null;
+
+ const tierLabels = tierLabelsFor(group.router_name, group.router_type, autoRouters);
+ const total = entries.reduce((sum, [, turns]) => sum + turns, 0);
+ const slices = entries.map(([tier, turns]) => ({
+ tier: tierDisplayLabel(tier, tierLabels),
+ turns,
+ models: tierModelsFor(tier, group.router_name, group.router_type, autoRouters),
+ }));
+ const colors = slices.map((_, idx) => TIER_DONUT_COLORS[idx % TIER_DONUT_COLORS.length]);
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Routing by tier</CardTitle>
+ <p className="text-sm text-muted-foreground">
+ Turns each tier served. Turns the classifier sent to the default model belong to no tier and are not counted
+ here, so this can total less than the router&apos;s turns.
+ </p>
+ </CardHeader>
+ <CardContent>
+ <div className="grid grid-cols-1 items-center gap-6 lg:grid-cols-2">
+ <DonutChart
+ className="h-80"
+ data={slices}
+ index="tier"
+ category="turns"
+ colors={colors}
+ valueFormatter={(value) => value.toLocaleString()}
+ showLabel
+ label={`${total.toLocaleString()} total turns`}
+ />
+ <ul className="flex flex-col gap-6">
+ {slices.map((slice, idx) => (
+ <li key={slice.tier} className="flex items-start gap-2">
+ <span
+ className="mt-1.5 h-2 w-2 shrink-0 rounded-full ring-4 ring-white"
+ style={{ backgroundColor: chartColorValue(colors[idx]) }}
+ />
+ <div className="min-w-0">
+ <p className="text-sm text-muted-foreground">
+ {slice.tier} {Math.round((100 * slice.turns) / total).toLocaleString()}%
+ </p>
+ {slice.models.length > 0 && (
+ <p className="text-xs break-words text-muted-foreground/70">{slice.models.join(", ")}</p>
+ )}
+ </div>
+ </li>
+ ))}
+ </ul>
+ </div>
+ </CardContent>
+ </Card>
+ );
+};
+
+export default TierTurnsChart;
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/autoRouterBenchmarks.ts b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/autoRouterBenchmarks.ts
index 00793548278..2e1031ce701 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/autoRouterBenchmarks.ts
+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/autoRouterBenchmarks.ts
@@ -24,9 +24,12 @@ export const windowFor = (range: BenchmarkWindow, now: Date): { start_date: stri
export interface BenchmarkView {
label: string;
- stats: AutoRouterBenchmarkTotals;
+ stats: AutoRouterBenchmarkTotals | AutoRouterBenchmarkGroup;
}
+export const viewGroup = (view: BenchmarkView): AutoRouterBenchmarkGroup | null =>
+ "router_name" in view.stats ? view.stats : null;
+
export const groupKey = (group: AutoRouterBenchmarkGroup): string => `${group.router_name} ${group.router_type}`;
export const groupLabel = (group: AutoRouterBenchmarkGroup, groups: readonly AutoRouterBenchmarkGroup[]): string => {
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index 966d2162a62..8989e098f54 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -21403,7 +21403,7 @@ export interface components {
spend: number;
/**
* Tier Turns
- * @description Turns per tier, keyed by the tier name the routing decision recorded at request time (never re-derived at read time, since the tier-to-model mapping is mutable config). Tier names are scoped to this group's router_type and are not comparable across types: a complexity router reports 'simple'/'medium'/'complex'/'reasoning', a quality router reports its numeric quality tier, and an adaptive router records no tier at all. Turns no tier served (the classifier fell back to default_model) are absent rather than pooled under a sentinel key, so the values may sum to less than turns
+ * @description Turns per tier, keyed by the tier name the routing decision recorded at request time (never re-derived at read time, since the tier-to-model mapping is mutable config). Tier names are scoped to this group's router_type and are not comparable across types: a complexity router reports 'SIMPLE'/'MEDIUM'/'COMPLEX'/'REASONING', a quality router reports its numeric quality tier, and an adaptive router records no tier at all. Turns no tier served (the classifier fell back to default_model) are absent rather than pooled under a sentinel key, so the values may sum to less than turns
*/
tier_turns?: {
[key: string]: number;