Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
"use client";

import React, { useEffect, useMemo, useState } from "react";
import { Info } from "lucide-react";

import { AreaChart, BarChart, CustomLegend, DonutChart, SEQUENTIAL_COLOR_RAMP } from "@/components/shared/charts";
import AdvancedDatePicker from "@/components/shared/advanced_date_picker";
import { Card, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import useCan from "@/app/(dashboard)/hooks/useCan";
import { getToolSpend, ToolSpendResponse } from "@/components/networking";
import { SpendMetrics } from "@/components/UsagePage/types";
import { formatNumberWithCommas } from "@/utils/dataUtils";
import {
autorouterOf,
buildDailyToolSeries,
cachingOf,
compressionOf,
formatRangeLabel,
localIsoDay,
MAX_POINTS_WITH_DOTS,
Expand All @@ -22,11 +21,13 @@
SAVINGS_SERIES,
SavingsAccumulation,
SavingsPoint,
shortDate,
toCumulative,
topToolsBySpend,
usd,
withStartAnchor,
} from "./costOptimizationUtils";
import SavingsTiles, { useSavingsTotals } from "@/components/shared/SavingsTiles";
import { DailyActivityRange } from "./useDailyActivityRange";

interface UsageTabProps {
Expand All @@ -41,42 +42,8 @@
end_date: null,
};

const shortDate = (iso: string): string =>
new Date(`${iso}T00:00:00`).toLocaleDateString("en-US", { month: "short", day: "numeric" });

const isoDay = (d: Date): string => d.toISOString().slice(0, 10);

const compressionOf = (m: SpendMetrics): number => m.compression_savings_spend ?? 0;
const cachingOf = (m: SpendMetrics): number => m.prompt_caching_savings_spend ?? 0;
const autorouterOf = (m: SpendMetrics): number => m.autorouter_savings_spend ?? 0;
const savedTokensOf = (m: SpendMetrics): number => m.compression_saved_tokens ?? 0;

const SummaryCard = ({ label, value, hint, info }: { label: string; value: string; hint?: string; info?: string }) => (
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0">
<CardTitle className="text-sm font-medium text-muted-foreground">{label}</CardTitle>
{info && (
<Popover>
<PopoverTrigger
aria-label={`How ${label.toLowerCase()} is calculated`}
data-testid={`summary-card-info-${label.toLowerCase().replace(/\s+/g, "-")}`}
className="cursor-pointer text-muted-foreground hover:text-foreground"
>
<Info className="size-3.5" />
</PopoverTrigger>
<PopoverContent align="end" className="w-64 text-sm text-muted-foreground">
{info}
</PopoverContent>
</Popover>
)}
</CardHeader>
<CardContent>
<p className="text-2xl font-semibold text-foreground">{value}</p>
{hint && <p className="mt-1 text-xs text-muted-foreground">{hint}</p>}
</CardContent>
</Card>
);

const UsageTab: React.FC<UsageTabProps> = ({ accessToken, activity }) => {
const { dateValue, onDateChange, results, loading, isFetchingMore } = activity;

Expand All @@ -84,12 +51,12 @@
const endTime = dateValue.to ?? null;

const canViewProxyWideCostData = useCan("viewProxyWideCostData");
const toolSpendEnabled = canViewProxyWideCostData && !!accessToken && !!startTime && !!endTime;

Check warning on line 54 in ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Boolean expression combines 4 conditions; extract it into a named variable
const rangeKey = startTime && endTime ? `${isoDay(startTime)}|${isoDay(endTime)}` : "";
const [toolSpendState, setToolSpendState] = useState<{ key: string; data: ToolSpendResponse } | null>(null);

useEffect(() => {
if (!canViewProxyWideCostData || !accessToken || !startTime || !endTime) return;

Check warning on line 59 in ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Boolean expression combines 4 conditions; extract it into a named variable
let cancelled = false;
getToolSpend(accessToken, isoDay(startTime), isoDay(endTime))
.then((res) => {
Expand All @@ -106,11 +73,7 @@
const toolSpend = toolSpendState?.key === rangeKey ? toolSpendState.data : null;
const toolSpendLoading = toolSpendEnabled && toolSpend === null;

const compressionTotal = useMemo(() => results.reduce((sum, d) => sum + compressionOf(d.metrics), 0), [results]);
const cachingTotal = useMemo(() => results.reduce((sum, d) => sum + cachingOf(d.metrics), 0), [results]);
const autorouterTotal = useMemo(() => results.reduce((sum, d) => sum + autorouterOf(d.metrics), 0), [results]);
const savedTokensTotal = useMemo(() => results.reduce((sum, d) => sum + savedTokensOf(d.metrics), 0), [results]);
const totalSaved = compressionTotal + cachingTotal + autorouterTotal;
const totals = useSavingsTotals(results);

const [accumulation, setAccumulation] = useState<SavingsAccumulation>("cumulative");

Expand Down Expand Up @@ -156,9 +119,11 @@
SAVINGS_DRIVERS.map(({ name, color }) => ({
driver: name,
color,
usd: { Compression: compressionTotal, "Prompt caching": cachingTotal, "Auto-router": autorouterTotal }[name],
usd: { Compression: totals.compression, "Prompt caching": totals.caching, "Auto-router": totals.autorouter }[
name
],
})).filter((d) => d.usd > 0),
[compressionTotal, cachingTotal, autorouterTotal],
[totals],
);
const plottedDriverTotal = useMemo(() => byDriver.reduce((sum, d) => sum + d.usd, 0), [byDriver]);

Expand All @@ -185,31 +150,7 @@
<AdvancedDatePicker value={dateValue} onValueChange={onDateChange} />
</div>

<div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
<SummaryCard
label="Total saved"
value={usd(totalSaved)}
hint={loading || isFetchingMore ? "Loading..." : "Compression + prompt caching + auto-router"}
/>
<SummaryCard
label="Compression savings"
value={usd(compressionTotal)}
hint={`${formatNumberWithCommas(savedTokensTotal)} tokens compressed`}
info="Tokens Headroom removed before the call, priced at the model's input rate."
/>
<SummaryCard
label="Prompt caching savings"
value={usd(cachingTotal)}
hint="Cache reads, net of write premium"
info="What caching saved against paying the input rate for every token: the discount on tokens served from cache, less the premium providers charge to write a cache entry. Can be negative on traffic that writes more cache than it reuses."
/>
<SummaryCard
label="Auto-router savings"
value={usd(autorouterTotal)}
hint="vs. the priciest model it could pick"
info="What this traffic would have cost had every request gone to the most expensive model the auto-router can route to, minus what it actually cost. Switching leaves the new model with a cold cache, so it pays to write the prompt again while the baseline is priced as already warm; a route that thrashes the cache can total below zero, and a genuine first turn, where neither side had anything cached, is undercounted."
/>
</div>
<SavingsTiles results={results} isLoading={loading || isFetchingMore} />

<div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
<Card className="lg:col-span-2">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ export const usd = (value: number): string => {

export const pct = (ratio: number): string => `${formatNumberWithCommas(ratio * 100, 1)}%`;

export const shortDate = (iso: string): string =>
new Date(`${iso}T00:00:00`).toLocaleDateString("en-US", { month: "short", day: "numeric" });

export const compressionOf = (m: SpendMetrics): number => m.compression_savings_spend ?? 0;
export const cachingOf = (m: SpendMetrics): number => m.prompt_caching_savings_spend ?? 0;
export const autorouterOf = (m: SpendMetrics): number => m.autorouter_savings_spend ?? 0;
export const savedTokensOf = (m: SpendMetrics): number => m.compression_saved_tokens ?? 0;

export type CacheLeakageDimension = "key" | "model";

export interface CacheLeakageRow {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { renderHook, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";

import { useScopedDailyActivityRange } from "./useDailyActivityRange";

// The sibling unit test mocks networking, so it pins the positional args array against itself and
// would still pass if the array and the two networking signatures drifted apart. Nothing else runs
// the real callers, which is what makes the ordering a comment-enforced rule. This drives the hook
// through the actual query serializer instead, so an argument appended or inserted on one side only
// lands its value on the wrong filter and fails here.
describe("useScopedDailyActivityRange wiring", () => {
const originalFetch = global.fetch;

afterEach(() => {
global.fetch = originalFetch;
});

it("lands each scope field on its own query param through the real networking callers", async () => {
const mockFetch = vi.fn<typeof fetch>().mockResolvedValue(
new Response(JSON.stringify({ results: [], metadata: {} }), {
status: 200,
headers: { "Content-Type": "application/json" },
}),
);
global.fetch = mockFetch;

renderHook(() => useScopedDailyActivityRange("sk-token", { userId: "u1", apiKey: "hash-abc" }));

await waitFor(() => expect(mockFetch).toHaveBeenCalled());

const url = String(mockFetch.mock.calls[0][0]);
expect(url).toContain("user_id=u1");
expect(url).toContain("api_key=hash-abc");
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,24 @@ describe("useDailyActivityRange", () => {
it("queries every user's activity for an admin", () => {
renderHook(() => useDailyActivityRange("test-token", "u1", "proxy_admin"));

expect(argsOfLastCall()).toEqual(["test-token", expect.any(Date), expect.any(Date), null, true]);
expect(argsOfLastCall()).toEqual(["test-token", expect.any(Date), expect.any(Date), null, true, null]);
});

it("scopes the query to the caller for a non-admin", () => {
renderHook(() => useDailyActivityRange("test-token", "u1", "internal_user"));

expect(argsOfLastCall()).toEqual(["test-token", expect.any(Date), expect.any(Date), "u1", true]);
expect(argsOfLastCall()).toEqual(["test-token", expect.any(Date), expect.any(Date), "u1", true, null]);
});

it.each(["org_admin", "Org Admin"])(
"scopes the query to the caller for %s, who has no admin view on this endpoint",
(role) => {
renderHook(() => useDailyActivityRange("test-token", "u1", role));

expect(argsOfLastCall()).toEqual(["test-token", expect.any(Date), expect.any(Date), "u1", true, null]);
},
);

it("fetches through the single-shot aggregated endpoint first so days never fragment across pages", () => {
renderHook(() => useDailyActivityRange("test-token", "u1", "proxy_admin"));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import { userDailyActivityAggregatedCall, userDailyActivityCall } from "@/components/networking";
import { DailyData } from "@/components/UsagePage/types";
import { all_admin_roles } from "@/utils/roles";
import { spendScopeUserId } from "@/utils/roles";
import { usePaginatedDailyActivity } from "@/app/(dashboard)/usage/_components/hooks/usePaginatedDailyActivity";

const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000;
Expand All @@ -20,23 +20,39 @@
isFetchingMore: boolean;
}

export const useDailyActivityRange = (
/**
* Which slice of daily activity to read. Both fields are passed straight through to the
* endpoint as filters, so the caller — not this hook — decides what the viewer may see.
*
* `userId: null` asks for the whole proxy, which the backend only honours for admins;
* a non-admin must send its own id or the request is rejected. That role decision lives in
* `useDailyActivityRange` below rather than in here, so a caller scoping to one key is not
* silently re-scoped to a user as well.
*/
export interface DailyActivityScope {
userId: string | null;
apiKey?: string | null;
}

export const useScopedDailyActivityRange = (
accessToken: string | null,
userId: string | null,
userRole: string,
scope: DailyActivityScope,
): DailyActivityRange => {
const initialFrom = useMemo(() => new Date(new Date().getTime() - THIRTY_DAYS_MS), []);
const initialTo = useMemo(() => new Date(), []);
const [dateValue, setDateValue] = useState<DateRange>({ from: initialFrom, to: initialTo });

const startTime = dateValue.from ?? null;
const endTime = dateValue.to ?? null;
const effectiveUserId = all_admin_roles.includes(userRole) ? null : userId;
const { userId, apiKey = null } = scope;

const { data, loading, isFetchingMore } = usePaginatedDailyActivity({
fetchFn: userDailyActivityCall,
aggregatedFetchFn: userDailyActivityAggregatedCall,
args: [accessToken, startTime, endTime, effectiveUserId, true],
// Positional, and read by two functions whose signatures diverge at index 3: the paginated

Check warning on line 52 in ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/useDailyActivityRange.ts

View workflow job for this annotation

GitHub Actions / frontend-lint

Object literal with 4 properties passed inline as an argument; assign it to a named variable first
// call takes `page` there (injected by the hook) and the aggregated one does not. Anything
// appended here must therefore be appended to BOTH networking signatures, in this order.
args: [accessToken, startTime, endTime, userId, true, apiKey],
enabled: !!accessToken && !!startTime && !!endTime,
});

Expand All @@ -48,3 +64,12 @@
isFetchingMore,
};
};

export const useDailyActivityRange = (
accessToken: string | null,
userId: string | null,
userRole: string,
): DailyActivityRange =>
useScopedDailyActivityRange(accessToken, {
userId: spendScopeUserId(userRole, userId),
});
82 changes: 82 additions & 0 deletions ui/litellm-dashboard/src/components/networking.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,14 @@
const mockFetch = vi.fn().mockResolvedValue({
ok: false,
json: vi.fn().mockResolvedValue(backendError),
} as any);

Check warning on line 57 in ui/litellm-dashboard/src/components/networking.test.ts

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type

global.fetch = mockFetch as any;

Check warning on line 59 in ui/litellm-dashboard/src/components/networking.test.ts

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type

try {
await Networking.updateSSOSettings("token", { some: "setting" });
} catch (error) {
const thrownError = error as any;

Check warning on line 64 in ui/litellm-dashboard/src/components/networking.test.ts

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
expect(thrownError).toBeInstanceOf(Error);
expect(thrownError.message).toBe(backendError.detail.error);
expect(thrownError.detail).toEqual(backendError.detail);
Expand All @@ -87,7 +87,7 @@
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ redirect_url: "/ui/?login=success", token: "my-jwt" }),
}) as any;

Check warning on line 90 in ui/litellm-dashboard/src/components/networking.test.ts

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
const { storeLoginToken } = await import("@/utils/cookieUtils");
await Networking.loginCall("admin", "pass");
expect(storeLoginToken).toHaveBeenCalledWith("my-jwt");
Expand All @@ -97,7 +97,7 @@
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ redirect_url: "/ui/?login=success" }),
}) as any;

Check warning on line 100 in ui/litellm-dashboard/src/components/networking.test.ts

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
const { storeLoginToken } = await import("@/utils/cookieUtils");
await Networking.loginCall("admin", "pass");
expect(storeLoginToken).not.toHaveBeenCalled();
Expand All @@ -113,8 +113,8 @@
const mockFetch = vi.fn().mockResolvedValue({
ok: true,
json: vi.fn().mockResolvedValue({ data: [] }),
} as any);

Check warning on line 116 in ui/litellm-dashboard/src/components/networking.test.ts

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
global.fetch = mockFetch as any;

Check warning on line 117 in ui/litellm-dashboard/src/components/networking.test.ts

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
return mockFetch;
};

Expand Down Expand Up @@ -627,3 +627,85 @@
expect(String(mockFetch.mock.calls[1][0])).not.toContain("tier_labels");
});
});

describe("daily activity api_key filter", () => {
const originalFetch = global.fetch;

const captureFetch = () => {
const mockFetch = vi.fn<typeof fetch>().mockResolvedValue(
new Response(JSON.stringify({ results: [], metadata: {} }), {
status: 200,
headers: { "Content-Type": "application/json" },
}),
);
global.fetch = mockFetch;
return mockFetch;
};

const requestedUrl = (mockFetch: ReturnType<typeof captureFetch>): string => String(mockFetch.mock.calls[0][0]);

const start = new Date("2025-01-01T00:00:00Z");
const end = new Date("2025-01-31T00:00:00Z");

afterEach(() => {
global.fetch = originalFetch;
});

it("sends the key hash as api_key from the paginated caller", async () => {
const mockFetch = captureFetch();

await Networking.userDailyActivityCall("sk-key", start, end, 1, null, false, "hash-abc");

expect(requestedUrl(mockFetch)).toContain("api_key=hash-abc");
});

it("sends the key hash as api_key from the aggregated caller", async () => {
const mockFetch = captureFetch();

await Networking.userDailyActivityAggregatedCall("sk-key", start, end, null, false, "hash-abc");

expect(requestedUrl(mockFetch)).toContain("api_key=hash-abc");
});

// The two wrappers serialize the same optional filters through different transports, so an
// absent key has to drop the param in both. Dropping it on one side and sending it empty on
// the other would widen a key-scoped read into an unscoped one.
it.each([
["paginated", () => Networking.userDailyActivityCall("sk-key", start, end, 1, null, false, null)],
["aggregated", () => Networking.userDailyActivityAggregatedCall("sk-key", start, end, null, false, null)],
])("omits api_key entirely from the %s caller when no key is given", async (_label, call) => {
const mockFetch = captureFetch();

await call();

expect(requestedUrl(mockFetch)).not.toContain("api_key");
});

// An empty key must not be coerced into "no filter". Dropping it would turn a key-scoped read
// into a proxy-wide one and report every key's savings as this key's, so both callers send it
// through and let the filter match nothing instead.
it.each([
["paginated", () => Networking.userDailyActivityCall("sk-key", start, end, 1, null, false, "")],
["aggregated", () => Networking.userDailyActivityAggregatedCall("sk-key", start, end, null, false, "")],
])("keeps an empty api_key as a filter rather than widening the %s read", async (_label, call) => {
const mockFetch = captureFetch();

await call();

expect(requestedUrl(mockFetch)).toContain("api_key=");
});

// user_id rides the same two transports and widens the same way, so it gets the same guard.
// The aggregated caller used to drop "" via `||`; without this the two filters could drift
// apart again on one side only.
it.each([
["paginated", () => Networking.userDailyActivityCall("sk-key", start, end, 1, "", false, null)],
["aggregated", () => Networking.userDailyActivityAggregatedCall("sk-key", start, end, "", false, null)],
])("keeps an empty user_id as a filter rather than widening the %s read", async (_label, call) => {
const mockFetch = captureFetch();

await call();

expect(requestedUrl(mockFetch)).toContain("user_id=");
});
});
Loading
Loading