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]

refactor(ui): convert endpoint usage charts to shadcn/recharts (#32723)

ryan-crabbe-berri5fc1a3c671bf
diff --git a/ui/litellm-dashboard/eslint-suppressions.json b/ui/litellm-dashboard/eslint-suppressions.json
index eb8bdee0ea2..3f6f4da25d0 100644
--- a/ui/litellm-dashboard/eslint-suppressions.json
+++ b/ui/litellm-dashboard/eslint-suppressions.json
@@ -858,9 +858,6 @@
"src/app/(dashboard)/projects/_components/ProjectDetailsPage.tsx": {
"no-nested-ternary": {
"count": 3
- },
- "no-restricted-imports": {
- "count": 1
}
},
"src/app/(dashboard)/projects/_components/ProjectKeysSection.tsx": {
@@ -1079,6 +1076,51 @@
"count": 1
}
},
+ "src/app/(dashboard)/usage/_components/components/EndpointUsage/components/EndpointUsageTable.tsx": {
+ "no-nested-ternary": {
+ "count": 1
+ }
+ },
+ "src/app/(dashboard)/usage/_components/components/EntityUsage/EntityUsage.tsx": {
+ "no-restricted-imports": {
+ "count": 1
+ }
+ },
+ "src/app/(dashboard)/usage/_components/components/EntityUsage/SpendByProvider.tsx": {
+ "no-restricted-imports": {
+ "count": 1
+ }
+ },
+ "src/app/(dashboard)/usage/_components/components/UsageAIChatPanel.tsx": {
+ "no-nested-ternary": {
+ "count": 1
+ },
+ "react-hooks/immutability": {
+ "count": 1
+ }
+ },
+ "src/app/(dashboard)/usage/_components/components/UsagePageView.tsx": {
+ "no-nested-ternary": {
+ "count": 1
+ },
+ "no-restricted-imports": {
+ "count": 1
+ },
+ "react-hooks/purity": {
+ "count": 1
+ },
+ "react-hooks/set-state-in-effect": {
+ "count": 3
+ }
+ },
+ "src/app/(dashboard)/usage/_components/hooks/usePaginatedDailyActivity.ts": {
+ "react-hooks/refs": {
+ "count": 1
+ },
+ "react-hooks/set-state-in-effect": {
+ "count": 1
+ }
+ },
"src/app/(dashboard)/users/_components/DefaultUserSettings.tsx": {
"no-restricted-imports": {
"count": 1
@@ -1502,61 +1544,6 @@
"count": 1
}
},
- "src/app/(dashboard)/usage/_components/components/EndpointUsage/components/EndpointUsageBarChart.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
- "src/app/(dashboard)/usage/_components/components/EndpointUsage/components/EndpointUsageLineChart.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
- "src/app/(dashboard)/usage/_components/components/EndpointUsage/components/EndpointUsageTable.tsx": {
- "no-nested-ternary": {
- "count": 1
- }
- },
- "src/app/(dashboard)/usage/_components/components/EntityUsage/EntityUsage.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
- "src/app/(dashboard)/usage/_components/components/EntityUsage/SpendByProvider.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
- "src/app/(dashboard)/usage/_components/components/UsageAIChatPanel.tsx": {
- "no-nested-ternary": {
- "count": 1
- },
- "react-hooks/immutability": {
- "count": 1
- }
- },
- "src/app/(dashboard)/usage/_components/components/UsagePageView.tsx": {
- "no-nested-ternary": {
- "count": 1
- },
- "no-restricted-imports": {
- "count": 1
- },
- "react-hooks/purity": {
- "count": 1
- },
- "react-hooks/set-state-in-effect": {
- "count": 3
- }
- },
- "src/app/(dashboard)/usage/_components/hooks/usePaginatedDailyActivity.ts": {
- "react-hooks/refs": {
- "count": 1
- },
- "react-hooks/set-state-in-effect": {
- "count": 1
- }
- },
"src/components/VirtualKeysPage/VirtualKeysTable.tsx": {
"no-nested-ternary": {
"count": 2
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EndpointUsage/EndpointUsage.tsx b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EndpointUsage/EndpointUsage.tsx
index 64fdb13a0b9..51e451ca770 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EndpointUsage/EndpointUsage.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EndpointUsage/EndpointUsage.tsx
@@ -59,7 +59,7 @@ const EndpointUsage: React.FC<EndpointUsageProps> = ({ userSpendData }) => {
<div className="space-y-4">
<EndpointUsageTable endpointData={endpointData} />
<EndpointUsageBarChart endpointData={endpointData} />
- <EndpointUsageLineChart dailyData={userSpendData} endpointData={endpointData} />
+ <EndpointUsageLineChart dailyData={userSpendData} />
</div>
);
};
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EndpointUsage/components/EndpointUsageBarChart.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EndpointUsage/components/EndpointUsageBarChart.test.tsx
index f200b8a6a18..a9e65b21f4b 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EndpointUsage/components/EndpointUsageBarChart.test.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EndpointUsage/components/EndpointUsageBarChart.test.tsx
@@ -1,39 +1,70 @@
-import { render, screen } from "@testing-library/react";
-import { describe, expect, it, vi } from "vitest";
+import { screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { renderWithProviders } from "@/../tests/test-utils";
+import { MetricWithMetadata } from "@/components/UsagePage/types";
import EndpointUsageBarChart from "./EndpointUsageBarChart";
-vi.mock("@tremor/react", async () => {
- const React = await import("react");
+const metric = (successful: number, failed: number): MetricWithMetadata => ({
+ metrics: {
+ spend: 0,
+ prompt_tokens: 0,
+ completion_tokens: 0,
+ total_tokens: 0,
+ api_requests: successful + failed,
+ successful_requests: successful,
+ failed_requests: failed,
+ cache_read_input_tokens: 0,
+ cache_creation_input_tokens: 0,
+ },
+ metadata: {},
+ api_key_breakdown: {},
+});
- function Card({ children }: any) {
- return React.createElement("div", { "data-testid": "tremor-card" }, children);
- }
- (Card as any).displayName = "Card";
+const endpointData = {
+ "/chat/completions": metric(120, 5),
+ "/embeddings": metric(40, 2),
+};
- function Title({ children }: any) {
- return React.createElement("h2", { "data-testid": "tremor-title" }, children);
- }
- (Title as any).displayName = "Title";
+describe("EndpointUsageBarChart", () => {
+ it("renders the title and the header legend labels", () => {
+ renderWithProviders(<EndpointUsageBarChart endpointData={endpointData} />);
- function BarChart(_props: any) {
- return React.createElement("div", { "data-testid": "tremor-bar-chart" }, "Bar Chart");
- }
- (BarChart as any).displayName = "BarChart";
+ expect(screen.getByText("Success vs Failed Requests by Endpoint")).toBeInTheDocument();
+ expect(screen.getByText("Successful Requests")).toBeInTheDocument();
+ expect(screen.getByText("Failed Requests")).toBeInTheDocument();
+ });
- return { Card, Title, BarChart };
-});
+ it("renders stacked green and red bars per endpoint", () => {
+ const { container } = renderWithProviders(<EndpointUsageBarChart endpointData={endpointData} />);
-vi.mock("@/components/common_components/chartUtils", () => ({
- CustomLegend: ({ categories }: any) => <div data-testid="custom-legend">{categories.join(", ")}</div>,
- CustomTooltip: () => <div data-testid="custom-tooltip">Tooltip</div>,
-}));
+ expect(container.querySelectorAll(".recharts-bar")).toHaveLength(2);
+ const rectangles = Array.from(container.querySelectorAll("path.recharts-rectangle"));
+ expect(rectangles).toHaveLength(4);
+ const fills = new Set(rectangles.map((rect) => rect.getAttribute("fill")));
+ expect(fills).toEqual(new Set(["var(--color-green-500, #22c55e)", "var(--color-red-500, #ef4444)"]));
-describe("EndpointUsageBarChart", () => {
- it("should render", () => {
- render(<EndpointUsageBarChart />);
+ const xPositions = rectangles.map((rect) => rect.getAttribute("d")?.split(",")[0]);
+ expect(new Set(xPositions).size).toBe(2);
+ });
+
+ it("labels the x axis with endpoint names", () => {
+ renderWithProviders(<EndpointUsageBarChart endpointData={endpointData} />);
+
+ expect(screen.getAllByText("/chat/completions").length).toBeGreaterThan(0);
+ expect(screen.getAllByText("/embeddings").length).toBeGreaterThan(0);
+ });
+
+ it("keeps the chart's own legend off; only the header legend is shown", () => {
+ const { container } = renderWithProviders(<EndpointUsageBarChart endpointData={endpointData} />);
+
+ expect(container.querySelector(".recharts-legend-wrapper")).toBeNull();
+ expect(screen.queryByText("metrics.successful_requests")).not.toBeInTheDocument();
+ });
+
+ it("renders an empty chart without bars when endpointData is absent", () => {
+ const { container } = renderWithProviders(<EndpointUsageBarChart />);
- expect(screen.getByTestId("tremor-card")).toBeInTheDocument();
expect(screen.getByText("Success vs Failed Requests by Endpoint")).toBeInTheDocument();
- expect(screen.getByTestId("tremor-bar-chart")).toBeInTheDocument();
+ expect(container.querySelectorAll("path.recharts-rectangle")).toHaveLength(0);
});
});
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EndpointUsage/components/EndpointUsageBarChart.tsx b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EndpointUsage/components/EndpointUsageBarChart.tsx
index 2badbe30868..bf9868d77cf 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EndpointUsage/components/EndpointUsageBarChart.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EndpointUsage/components/EndpointUsageBarChart.tsx
@@ -1,6 +1,6 @@
import React from "react";
-import { BarChart, Card, Title } from "@tremor/react";
-import { CustomLegend, CustomTooltip } from "@/components/common_components/chartUtils";
+import { BarChart, CustomLegend, CustomTooltip } from "@/components/shared/charts";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { MetricWithMetadata } from "@/components/UsagePage/types";
interface EndpointUsageBarChartProps {
@@ -8,11 +8,9 @@ interface EndpointUsageBarChartProps {
}
const EndpointUsageBarChart: React.FC<EndpointUsageBarChartProps> = ({ endpointData }) => {
- const dataToUse = endpointData || {};
-
// Transform endpoint data into chart format
const chartData = React.useMemo(() => {
- return Object.entries(dataToUse).map(([endpoint, data]) => ({
+ return Object.entries(endpointData || {}).map(([endpoint, data]) => ({
endpoint,
"metrics.successful_requests": data.metrics.successful_requests,
"metrics.failed_requests": data.metrics.failed_requests,
@@ -21,31 +19,34 @@ const EndpointUsageBarChart: React.FC<EndpointUsageBarChartProps> = ({ endpointD
failed_requests: data.metrics.failed_requests,
},
}));
- }, [dataToUse]);
+ }, [endpointData]);
const valueFormatter = (value: number) => value.toLocaleString();
return (
<Card>
- <div className="flex justify-between items-center">
- <Title>Success vs Failed Requests by Endpoint</Title>
- <CustomLegend
+ <CardHeader>
+ <div className="flex justify-between items-center">
+ <CardTitle className="text-base font-semibold">Success vs Failed Requests by Endpoint</CardTitle>
+ <CustomLegend
+ categories={["metrics.successful_requests", "metrics.failed_requests"]}
+ colors={["green", "red"]}
+ />
+ </div>
+ </CardHeader>
+ <CardContent>
+ <BarChart
+ data={chartData}
+ index="endpoint"
categories={["metrics.successful_requests", "metrics.failed_requests"]}
colors={["green", "red"]}
+ valueFormatter={valueFormatter}
+ customTooltip={CustomTooltip}
+ showLegend={false}
+ stack={true}
+ yAxisWidth={60}
/>
- </div>
- <BarChart
- className="mt-4"
- data={chartData}
- index="endpoint"
- categories={["metrics.successful_requests", "metrics.failed_requests"]}
- colors={["green", "red"]}
- valueFormatter={valueFormatter}
- customTooltip={CustomTooltip}
- showLegend={false}
- stack={true}
- yAxisWidth={60}
- />
+ </CardContent>
</Card>
);
};
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EndpointUsage/components/EndpointUsageLineChart.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EndpointUsage/components/EndpointUsageLineChart.test.tsx
index ec99825289c..33914e627dc 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EndpointUsage/components/EndpointUsageLineChart.test.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EndpointUsage/components/EndpointUsageLineChart.test.tsx
@@ -1,34 +1,103 @@
-import { render, screen } from "@testing-library/react";
-import { describe, expect, it, vi } from "vitest";
+import { screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { renderWithProviders } from "@/../tests/test-utils";
+import { DailyData, MetricWithMetadata, SpendMetrics } from "@/components/UsagePage/types";
import EndpointUsageLineChart from "./EndpointUsageLineChart";
-vi.mock("@tremor/react", async () => {
- const React = await import("react");
-
- function Card({ children }: any) {
- return React.createElement("div", { "data-testid": "tremor-card" }, children);
- }
- (Card as any).displayName = "Card";
-
- function Title({ children }: any) {
- return React.createElement("h2", { "data-testid": "tremor-title" }, children);
- }
- (Title as any).displayName = "Title";
+const spendMetrics = (apiRequests: number): SpendMetrics => ({
+ spend: 0,
+ prompt_tokens: 0,
+ completion_tokens: 0,
+ total_tokens: 0,
+ api_requests: apiRequests,
+ successful_requests: apiRequests,
+ failed_requests: 0,
+ cache_read_input_tokens: 0,
+ cache_creation_input_tokens: 0,
+});
- function LineChart(_props: any) {
- return React.createElement("div", { "data-testid": "tremor-line-chart" }, "Line Chart");
- }
- (LineChart as any).displayName = "LineChart";
+const endpointMetric = (apiRequests: number): MetricWithMetadata => ({
+ metrics: spendMetrics(apiRequests),
+ metadata: {},
+ api_key_breakdown: {},
+});
- return { Card, Title, LineChart };
+const day = (date: string, endpoints: Record<string, number>): DailyData => ({
+ date,
+ metrics: spendMetrics(0),
+ breakdown: {
+ models: {},
+ model_groups: {},
+ mcp_servers: {},
+ providers: {},
+ api_keys: {},
+ entities: {},
+ endpoints: Object.fromEntries(
+ Object.entries(endpoints).map(([name, requests]) => [name, endpointMetric(requests)]),
+ ),
+ },
});
+const dailyData = {
+ results: [
+ day("2026-06-03T12:00:00", { "/chat/completions": 4000, "/embeddings": 900 }),
+ day("2026-06-02T12:00:00", { "/chat/completions": 2500, "/embeddings": 700 }),
+ day("2026-06-01T12:00:00", { "/chat/completions": 1200 }),
+ ],
+};
+
describe("EndpointUsageLineChart", () => {
- it("should render", () => {
- render(<EndpointUsageLineChart />);
+ it("renders the title", () => {
+ renderWithProviders(<EndpointUsageLineChart dailyData={dailyData} />);
+
+ expect(screen.getByText("Endpoint Usage Trends")).toBeInTheDocument();
+ });
+
+ it("renders one line per endpoint with the tremor palette strokes", () => {
+ const { container } = renderWithProviders(<EndpointUsageLineChart dailyData={dailyData} />);
+
+ const curves = Array.from(container.querySelectorAll("path.recharts-line-curve"));
+ expect(curves).toHaveLength(2);
+ expect(new Set(curves.map((curve) => curve.getAttribute("stroke")))).toEqual(
+ new Set(["var(--color-blue-500, #3b82f6)", "var(--color-cyan-500, #06b6d4)"]),
+ );
+ });
+
+ it("shows a legend with the endpoint names", () => {
+ const { container } = renderWithProviders(<EndpointUsageLineChart dailyData={dailyData} />);
+
+ const legend = container.querySelector(".recharts-legend-wrapper");
+ expect(legend).not.toBeNull();
+ expect(legend!.textContent).toContain("/chat/completions");
+ expect(legend!.textContent).toContain("/embeddings");
+ });
+
+ it("orders formatted dates oldest to newest on the x axis", () => {
+ const { container } = renderWithProviders(<EndpointUsageLineChart dailyData={dailyData} />);
+
+ const tickLabels = Array.from(container.querySelectorAll(".recharts-xAxis-tick-labels text")).map(
+ (tick) => tick.textContent,
+ );
+ expect(tickLabels).toEqual(["Jun 1", "Jun 2", "Jun 3"]);
+ });
+
+ it("formats y axis ticks with toLocaleString", () => {
+ renderWithProviders(<EndpointUsageLineChart dailyData={dailyData} />);
+
+ expect(screen.getAllByText(/^\d,\d{3}$/).length).toBeGreaterThan(0);
+ });
+
+ it("draws smooth natural curves", () => {
+ const { container } = renderWithProviders(<EndpointUsageLineChart dailyData={dailyData} />);
+
+ const path = container.querySelector("path.recharts-line-curve")?.getAttribute("d") ?? "";
+ expect(path).toContain("C");
+ });
+
+ it("renders an empty chart without lines when dailyData is absent", () => {
+ const { container } = renderWithProviders(<EndpointUsageLineChart />);
- expect(screen.getByTestId("tremor-card")).toBeInTheDocument();
expect(screen.getByText("Endpoint Usage Trends")).toBeInTheDocument();
- expect(screen.getByTestId("tremor-line-chart")).toBeInTheDocument();
+ expect(container.querySelectorAll("path.recharts-line-curve")).toHaveLength(0);
});
});
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EndpointUsage/components/EndpointUsageLineChart.tsx b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EndpointUsage/components/EndpointUsageLineChart.tsx
index 9f838d6156a..483a30b1639 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EndpointUsage/components/EndpointUsageLineChart.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/usage/_components/components/EndpointUsage/components/EndpointUsageLineChart.tsx
@@ -1,10 +1,10 @@
-import { Card, LineChart, Title } from "@tremor/react";
import { useMemo } from "react";
+import { LineChart, type ChartColor } from "@/components/shared/charts";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { DailyData } from "@/components/UsagePage/types";
interface EndpointUsageLineChartProps {
dailyData?: { results: DailyData[] };
- endpointData?: Record<string, any>;
}
// Transform daily data into chart format
@@ -42,7 +42,7 @@ function transformDailyDataToChart(dailyData: DailyData[]): Array<Record<string,
return chartData.reverse();
}
-export function EndpointUsageLineChart({ dailyData, endpointData }: EndpointUsageLineChartProps) {
+export function EndpointUsageLineChart({ dailyData }: EndpointUsageLineChartProps) {
const chartData = useMemo(() => {
if (!dailyData?.results || dailyData.results.length === 0) {
return [];
@@ -59,26 +59,39 @@ export function EndpointUsageLineChart({ dailyData, endpointData }: EndpointUsag
}, [chartData]);
// Tremor color palette for multiple lines
- const colors = ["blue", "cyan", "indigo", "violet", "purple", "fuchsia", "pink", "rose", "red", "orange"];
+ const colors: readonly ChartColor[] = [
+ "blue",
+ "cyan",
+ "indigo",
+ "violet",
+ "purple",
+ "fuchsia",
+ "pink",
+ "rose",
+ "red",
+ "orange",
+ ];
return (
<Card className="mb-6">
- <div className="flex items-center justify-between mb-4">
- <Title>Endpoint Usage Trends</Title>
- </div>
- <LineChart
- className="h-80"
- data={chartData}
- index="date"
- categories={categories}
- colors={colors.slice(0, categories.length)}
- valueFormatter={(value) => value.toLocaleString()}
- showLegend={true}
- showGridLines={true}
- yAxisWidth={60}
- connectNulls={true}
- curveType="natural"
- />
+ <CardHeader>
+ <CardTitle className="text-base font-semibold">Endpoint Usage Trends</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <LineChart
+ className="h-80"
+ data={chartData}
+ index="date"
+ categories={categories}
+ colors={colors.slice(0, categories.length)}
+ valueFormatter={(value) => value.toLocaleString()}
+ showLegend={true}
+ showGridLines={true}
+ yAxisWidth={60}
+ connectNulls={true}
+ curveType="natural"
+ />
+ </CardContent>
</Card>
);
}
diff --git a/ui/litellm-dashboard/src/components/shared/charts/index.ts b/ui/litellm-dashboard/src/components/shared/charts/index.ts
index ba0a7544ddb..8383c767064 100644
--- a/ui/litellm-dashboard/src/components/shared/charts/index.ts
+++ b/ui/litellm-dashboard/src/components/shared/charts/index.ts
@@ -10,3 +10,4 @@ export {
} from "./chart_tooltip";
export { CHART_COLOR_HEX, DEFAULT_COLOR_CYCLE, categoryFills, chartColorValue, type ChartColor } from "./colors";
export { DonutChart, type DonutChartProps } from "./donut_chart";
+export { LineChart, type LineChartCurveType, type LineChartProps } from "./line_chart";
diff --git a/ui/litellm-dashboard/src/components/shared/charts/line_chart.test.tsx b/ui/litellm-dashboard/src/components/shared/charts/line_chart.test.tsx
new file mode 100644
index 00000000000..9385dc49494
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/shared/charts/line_chart.test.tsx
@@ -0,0 +1,117 @@
+import { render, screen } from "@testing-library/react";
+import React from "react";
+import { describe, expect, it } from "vitest";
+import { LineChart } from "./line_chart";
+
+const data = [
+ { date: "Jun 1", "/chat/completions": 10, "/embeddings": 4 },
+ { date: "Jun 2", "/chat/completions": 15, "/embeddings": 6 },
+ { date: "Jun 3", "/chat/completions": 12, "/embeddings": 9 },
+];
+
+describe("LineChart", () => {
+ it("renders one line per category with the mapped tremor stroke colors", () => {
+ const { container } = render(
+ <LineChart
+ data={data}
+ index="date"
+ categories={["/chat/completions", "/embeddings"]}
+ colors={["blue", "cyan"]}
+ />,
+ );
+
+ const curves = Array.from(container.querySelectorAll("path.recharts-line-curve"));
+ expect(curves).toHaveLength(2);
+ expect(curves.map((curve) => curve.getAttribute("stroke"))).toEqual([
+ "var(--color-blue-500, #3b82f6)",
+ "var(--color-cyan-500, #06b6d4)",
+ ]);
+ });
+
+ it("falls back to the tremor default color cycle when no colors are passed", () => {
+ const { container } = render(
+ <LineChart data={data} index="date" categories={["/chat/completions", "/embeddings"]} />,
+ );
+
+ const strokes = Array.from(container.querySelectorAll("path.recharts-line-curve")).map((curve) =>
+ curve.getAttribute("stroke"),
+ );
+ expect(strokes).toEqual(["var(--color-blue-500, #3b82f6)", "var(--color-cyan-500, #06b6d4)"]);
+ });
+
+ it("applies valueFormatter to the value axis ticks", () => {
+ render(
+ <LineChart
+ data={data}
+ index="date"
+ categories={["/chat/completions"]}
+ colors={["blue"]}
+ valueFormatter={(v) => `${v} req`}
+ />,
+ );
+
+ expect(screen.getAllByText(/ req$/).length).toBeGreaterThan(0);
+ });
+
+ it("renders a legend by default, matching tremor, and hides it when showLegend is false", () => {
+ const { container, rerender } = render(
+ <LineChart data={data} index="date" categories={["/chat/completions"]} colors={["blue"]} />,
+ );
+ expect(screen.getByText("/chat/completions")).toBeInTheDocument();
+ expect(container.querySelector(".recharts-legend-wrapper")).not.toBeNull();
+
+ rerender(
+ <LineChart data={data} index="date" categories={["/chat/completions"]} colors={["blue"]} showLegend={false} />,
+ );
+ expect(screen.queryByText("/chat/completions")).not.toBeInTheDocument();
+ });
+
+ it("draws straight segments by default and curved segments for curveType natural", () => {
+ const { container: linear } = render(
+ <LineChart data={data} index="date" categories={["/chat/completions"]} colors={["blue"]} />,
+ );
+ const { container: natural } = render(
+ <LineChart data={data} index="date" categories={["/chat/completions"]} colors={["blue"]} curveType="natural" />,
+ );
+
+ const linearPath = linear.querySelector("path.recharts-line-curve")?.getAttribute("d") ?? "";
+ const naturalPath = natural.querySelector("path.recharts-line-curve")?.getAttribute("d") ?? "";
+ expect(linearPath).not.toContain("C");
+ expect(naturalPath).toContain("C");
+ });
+
+ it("bridges gaps over null values only when connectNulls is set", () => {
+ const gappedData = [
+ { date: "Jun 1", "/chat/completions": 10 },
+ { date: "Jun 2", "/chat/completions": null },
+ { date: "Jun 3", "/chat/completions": 12 },
+ { date: "Jun 4", "/chat/completions": 15 },
+ ];
+
+ const { container: broken } = render(
+ <LineChart data={gappedData} index="date" categories={["/chat/completions"]} colors={["blue"]} />,
+ );
+ const { container: bridged } = render(
+ <LineChart data={gappedData} index="date" categories={["/chat/completions"]} colors={["blue"]} connectNulls />,
+ );
+
+ const brokenPath = broken.querySelector("path.recharts-line-curve")?.getAttribute("d") ?? "";
+ const bridgedPath = bridged.querySelector("path.recharts-line-curve")?.getAttribute("d") ?? "";
+ expect((brokenPath.match(/M/g) ?? []).length).toBeGreaterThan(1);
+ expect((bridgedPath.match(/M/g) ?? []).length).toBe(1);
+ });
+
+ it("renders an empty chart without lines when there are no categories", () => {
+ const { container } = render(<LineChart data={[]} index="date" categories={[]} />);
+
+ expect(container.querySelector("[data-slot='chart']")).not.toBeNull();
+ expect(container.querySelectorAll("path.recharts-line-curve")).toHaveLength(0);
+ });
+
+ it("emits no per-chart style tag; colors flow through strokes, not CSS vars", () => {
+ const { container } = render(
+ <LineChart data={data} index="date" categories={["/chat/completions"]} colors={["blue"]} />,
+ );
+ expect(container.querySelector("style")).toBeNull();
+ });
+});
diff --git a/ui/litellm-dashboard/src/components/shared/charts/line_chart.tsx b/ui/litellm-dashboard/src/components/shared/charts/line_chart.tsx
new file mode 100644
index 00000000000..2dc8747118d
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/shared/charts/line_chart.tsx
@@ -0,0 +1,99 @@
+"use client";
+
+import * as React from "react";
+import { CartesianGrid, Line, LineChart as RechartsLineChart, XAxis, YAxis } from "recharts";
+import { ChartContainer, ChartLegend, ChartLegendContent, ChartTooltip, type ChartConfig } from "@/components/ui/chart";
+import { cn } from "@/lib/cva.config";
+import { ValueTooltip, type ChartTooltipComponent } from "./chart_tooltip";
+import { categoryFills, type ChartColor } from "./colors";
+
+export type LineChartCurveType = "linear" | "natural" | "monotone" | "step";
+
+export type LineChartProps<TDatum extends Record<string, unknown>> = {
+ data: readonly TDatum[];
+ index: string;
+ categories: readonly string[];
+ colors?: readonly ChartColor[];
+ valueFormatter?: (value: number) => string;
+ yAxisWidth?: number;
+ tickGap?: number;
+ showLegend?: boolean;
+ showXAxis?: boolean;
+ showGridLines?: boolean;
+ showTooltip?: boolean;
+ customTooltip?: ChartTooltipComponent;
+ connectNulls?: boolean;
+ curveType?: LineChartCurveType;
+ className?: string;
+ style?: React.CSSProperties;
+};
+
+export function LineChart<TDatum extends Record<string, unknown>>({
+ data,
+ index,
+ categories,
+ colors,
+ valueFormatter,
+ yAxisWidth = 56,
+ tickGap = 5,
+ showLegend = true,
+ showXAxis = true,
+ showGridLines = true,
+ showTooltip = true,
+ customTooltip,
+ connectNulls = false,
+ curveType = "linear",
+ className,
+ style,
+}: LineChartProps<TDatum>) {
+ const fills = categoryFills(categories.length, colors);
+ const config: ChartConfig = Object.fromEntries(categories.map((category) => [category, { label: category }]));
+ const TooltipContent = customTooltip ?? ValueTooltip;
+
+ return (
+ <ChartContainer config={config} className={cn("aspect-auto h-80 w-full", className)} style={style}>
+ <RechartsLineChart data={[...data]}>
+ {showGridLines && <CartesianGrid vertical={false} />}
+ <XAxis
+ dataKey={index}
+ hide={!showXAxis}
+ tickLine={false}
+ axisLine={false}
+ minTickGap={tickGap}
+ interval="equidistantPreserveStart"
+ />
+ <YAxis width={yAxisWidth} tickLine={false} axisLine={false} tickFormatter={valueFormatter} />
+ {showTooltip && (
+ <ChartTooltip
+ content={({ active, payload, label }) => (
+ <TooltipContent
+ active={active}
+ payload={payload}
+ label={label}
+ {...(customTooltip ? {} : { valueFormatter })}
+ />
+ )}
+ />
+ )}
+ {showLegend && (
+ <ChartLegend
+ verticalAlign="top"
+ content={<ChartLegendContent className="justify-end text-muted-foreground" />}
+ />
+ )}
+ {categories.map((category, i) => (
+ <Line
+ key={category}
+ type={curveType}
+ dataKey={category}
+ stroke={fills[i]}
+ strokeWidth={2}
+ dot={false}
+ isAnimationActive={false}
+ connectNulls={connectNulls}
+ />
+ ))}
+ </RechartsLineChart>
+ </ChartContainer>
+ );
+}