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
[Feature] UI - Usage: Prominent fetch banner, batched pagination renders
yuneng-jiangf72931a46332
diff --git a/ui/litellm-dashboard/src/components/UsagePage/components/EntityUsage/EntityUsage.tsx b/ui/litellm-dashboard/src/components/UsagePage/components/EntityUsage/EntityUsage.tsxindex e075e8b34eb..cb1a08d3ff1 100644--- a/ui/litellm-dashboard/src/components/UsagePage/components/EntityUsage/EntityUsage.tsx+++ b/ui/litellm-dashboard/src/components/UsagePage/components/EntityUsage/EntityUsage.tsx@@ -22,7 +22,8 @@ import {Text,Title,} from "@tremor/react";-import { LoadingOutlined } from "@ant-design/icons";+import { ExportOutlined } from "@ant-design/icons";+import { Alert, Button } from "antd";import React, { useMemo, useState } from "react";import { ActivityMetrics, processActivityData } from "../../../activity_metrics";import { UsageExportHeader } from "../../../EntityUsageExport";@@ -105,8 +106,8 @@ const EntityUsage: React.FC<EntityUsageProps> = ({ accessToken, entityType, enticonst [topModelsLimit, setTopModelsLimit] = useState<number>(5);const [topAgentsLimit, setTopAgentsLimit] = useState<number>(5);- const startTime = useMemo(() => dateValue.from ? new Date(dateValue.from) : null, [dateValue.from]);- const endTime = useMemo(() => dateValue.to ? new Date(dateValue.to) : null, [dateValue.to]);+ const startTime = useMemo(() => (dateValue.from ? new Date(dateValue.from) : null), [dateValue.from]);+ const endTime = useMemo(() => (dateValue.to ? new Date(dateValue.to) : null), [dateValue.to]);const entityFilterArg = useMemo(() => {if (entityType === "user") return selectedTags.length > 0 ? selectedTags[0] : null;@@ -395,33 +396,75 @@ const EntityUsage: React.FC<EntityUsageProps> = ({ accessToken, entityType, entireturn (<div style={{ width: "100%" }} className="relative">- {(isFetchingMore || cancelled || agentIsFetchingMore || agentCancelled) && (- <div className="flex items-center gap-2 text-sm text-gray-500 mb-2">- {isFetchingMore && (- <>- <LoadingOutlined spin className="text-xs" />- <span>Loading spend data... (page {progress.currentPage}/{progress.totalPages})</span>- <button onClick={cancel} className="text-blue-600 hover:text-blue-800 underline text-xs">Stop</button>- </>- )}- {cancelled && (- <span className="text-yellow-600 text-xs">+ {isFetchingMore && (+ <Alert+ banner+ type="warning"+ className="mb-2"+ message={+ <div className="flex items-center justify-between">+ <span>+ Currently fetching spend data: fetched {progress.currentPage} / {progress.totalPages} pages. Charts will+ update periodically as data loads. Moving off of this page will stop and reset this. To continue using+ the UI in the meantime,{" "}+ <a href={window.location.href} target="_blank" rel="noopener noreferrer">+ open a new tab <ExportOutlined />+ </a>+ .+ </span>+ <Button type="primary" danger onClick={cancel}>+ Stop+ </Button>+ </div>+ }+ />+ )}+ {cancelled && (+ <Alert+ banner+ type="info"+ className="mb-2"+ message={+ <span>Showing partial data ({progress.currentPage}/{progress.totalPages} pages loaded)</span>- )}- {agentIsFetchingMore && entityType === "team" && (- <>- <LoadingOutlined spin className="text-xs" />- <span>Loading agent data... (page {agentProgress.currentPage}/{agentProgress.totalPages})</span>- <button onClick={agentCancel} className="text-blue-600 hover:text-blue-800 underline text-xs">Stop</button>- </>- )}- {agentCancelled && entityType === "team" && (- <span className="text-yellow-600 text-xs">+ }+ />+ )}+ {agentIsFetchingMore && entityType === "team" && (+ <Alert+ banner+ type="warning"+ className="mb-2"+ message={+ <div className="flex items-center justify-between">+ <span>+ Currently fetching agent data: fetched {agentProgress.currentPage} / {agentProgress.totalPages} pages.+ Charts will update periodically as data loads. Moving off of this page will stop and reset this. To+ continue using the UI in the meantime,{" "}+ <a href={window.location.href} target="_blank" rel="noopener noreferrer">+ open a new tab <ExportOutlined />+ </a>+ .+ </span>+ <Button type="primary" danger onClick={agentCancel}>+ Stop+ </Button>+ </div>+ }+ />+ )}+ {agentCancelled && entityType === "team" && (+ <Alert+ banner+ type="info"+ className="mb-2"+ message={+ <span>Showing partial agent data ({agentProgress.currentPage}/{agentProgress.totalPages} pages loaded)</span>- )}- </div>+ }+ />)}<UsageExportHeaderdateValue={dateValue}@@ -747,7 +790,9 @@ const EntityUsage: React.FC<EntityUsageProps> = ({ accessToken, entityType, enti<TabPanel><ActivityMetrics modelMetrics={agentMetrics} /></TabPanel>- ) : <></>}+ ) : (+ <></>+ )}<TabPanel><ActivityMetrics modelMetrics={keyMetrics} hidePromptCachingMetrics={entityType === "agent"} /></TabPanel>diff --git a/ui/litellm-dashboard/src/components/UsagePage/components/UsagePageView.test.tsx b/ui/litellm-dashboard/src/components/UsagePage/components/UsagePageView.test.tsxindex b9fe1687e6c..bbcddd572cd 100644--- a/ui/litellm-dashboard/src/components/UsagePage/components/UsagePageView.test.tsx+++ b/ui/litellm-dashboard/src/components/UsagePage/components/UsagePageView.test.tsx@@ -251,6 +251,7 @@ vi.mock("@ant-design/icons", async () => {UserOutlined: Icon,DownOutlined: Icon,RightOutlined: Icon,+ ExportOutlined: Icon,LoadingOutlined,};});diff --git a/ui/litellm-dashboard/src/components/UsagePage/components/UsagePageView.tsx b/ui/litellm-dashboard/src/components/UsagePage/components/UsagePageView.tsxindex 3ebe8205052..8b111c63c90 100644--- a/ui/litellm-dashboard/src/components/UsagePage/components/UsagePageView.tsx+++ b/ui/litellm-dashboard/src/components/UsagePage/components/UsagePageView.tsx@@ -6,7 +6,8 @@* Works at 1m+ spend logs, by querying an aggregate table instead.*/-import { DownOutlined, InfoCircleOutlined, LoadingOutlined, RightOutlined } from "@ant-design/icons";+import { DownOutlined, ExportOutlined, InfoCircleOutlined, LoadingOutlined, RightOutlined } from "@ant-design/icons";+import { useDebouncedState } from "@tanstack/react-pacer/debouncer";import {BarChart,Card,@@ -19,10 +20,9 @@ import {TabPanel,TabPanels,Text,- Title+ Title,} from "@tremor/react";-import { Alert, Segmented, Select, Tooltip, Typography } from "antd";-import { useDebouncedState } from "@tanstack/react-pacer/debouncer";+import { Alert, Button, Segmented, Select, Tooltip, Typography } from "antd";import React, { useCallback, useEffect, useMemo, useRef, useState, type UIEvent } from "react";import { useAgents } from "@/app/(dashboard)/hooks/agents/useAgents";@@ -31,7 +31,6 @@ import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";import { useCurrentUser } from "@/app/(dashboard)/hooks/users/useCurrentUser";import { useInfiniteUsers } from "@/app/(dashboard)/hooks/users/useUsers";import { formatNumberWithCommas } from "@/utils/dataUtils";-import { Button } from "@tremor/react";import { all_admin_roles } from "../../../utils/roles";import { ActivityMetrics, processActivityData } from "../../activity_metrics";import CloudZeroExportModal from "../../cloudzero_export_modal";@@ -50,8 +49,8 @@ import EndpointUsage from "./EndpointUsage/EndpointUsage";import EntityUsage, { EntityList } from "./EntityUsage/EntityUsage";import SpendByProvider from "./EntityUsage/SpendByProvider";import TopKeyView from "./EntityUsage/TopKeyView";-import { UsageOption, UsageViewSelect } from "./UsageViewSelect/UsageViewSelect";import UsageAIChatPanel from "./UsageAIChatPanel";+import { UsageOption, UsageViewSelect } from "./UsageViewSelect/UsageViewSelect";interface UsagePageProps {teams: Team[];@@ -128,8 +127,7 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {const handleUserPopupScroll = (e: UIEvent<HTMLDivElement>) => {const target = e.currentTarget;- const scrollRatio =- (target.scrollTop + target.clientHeight) / target.scrollHeight;+ const scrollRatio = (target.scrollTop + target.clientHeight) / target.scrollHeight;if (scrollRatio >= 0.8 && hasNextUsersPage && !isFetchingNextUsersPage) {fetchNextUsersPage();}@@ -137,9 +135,7 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {// For admins: null means global view (all users), a string means filter by that user// For non-admins: always set to their own user ID- const [selectedUserId, setSelectedUserId] = useState<string | null>(- isAdmin ? null : (userID || null)- );+ const [selectedUserId, setSelectedUserId] = useState<string | null>(isAdmin ? null : userID || null);const [modelViewType, setModelViewType] = useState<"groups" | "individual">("groups");const [isCloudZeroModalOpen, setIsCloudZeroModalOpen] = useState(false);const [isGlobalExportModalOpen, setIsGlobalExportModalOpen] = useState(false);@@ -174,10 +170,10 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {}, [isAdmin, userID]);// For non-admins, always pass their own user_id- const effectiveUserId = isAdmin ? selectedUserId : (userID || null);+ const effectiveUserId = isAdmin ? selectedUserId : userID || null;- const startTime = useMemo(() => dateValue.from ? new Date(dateValue.from) : null, [dateValue.from]);- const endTime = useMemo(() => dateValue.to ? new Date(dateValue.to) : null, [dateValue.to]);+ const startTime = useMemo(() => (dateValue.from ? new Date(dateValue.from) : null), [dateValue.from]);+ const endTime = useMemo(() => (dateValue.to ? new Date(dateValue.to) : null), [dateValue.to]);// Try aggregated endpoint first, fall back to paginated on failureconst aggregatedFetchIdRef = useRef(0);@@ -361,7 +357,8 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {providerSpendMap[provider].metrics.successful_requests += metrics.metrics.successful_requests || 0;providerSpendMap[provider].metrics.failed_requests += metrics.metrics.failed_requests || 0;providerSpendMap[provider].metrics.cache_read_input_tokens += metrics.metrics.cache_read_input_tokens || 0;- providerSpendMap[provider].metrics.cache_creation_input_tokens += metrics.metrics.cache_creation_input_tokens || 0;+ providerSpendMap[provider].metrics.cache_creation_input_tokens +=+ metrics.metrics.cache_creation_input_tokens || 0;});});@@ -429,430 +426,408 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {);const modelMetrics = useMemo(() => processActivityData(userSpendData, "models", teams), [userSpendData, teams]);const keyMetrics = useMemo(() => processActivityData(userSpendData, "api_keys", teams), [userSpendData, teams]);- const mcpServerMetrics = useMemo(() => processActivityData(userSpendData, "mcp_servers", teams), [userSpendData, teams]);+ const mcpServerMetrics = useMemo(+ () => processActivityData(userSpendData, "mcp_servers", teams),+ [userSpendData, teams],+ );return (<div style={{ width: "100%" }} className="p-8 relative">- {/* Export Data Button - Positioned in top right corner */}- {/* {all_admin_roles.includes(userRole || "") && (- <div className="absolute top-4 right-4 z-10">- <button- onClick={() => setIsCloudZeroModalOpen(true)}- className="bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded-full flex items-center gap-2 shadow-lg transition-colors duration-200 text-sm font-medium"- >- <svg- className="w-4 h-4"- fill="none"- stroke="currentColor"- viewBox="0 0 24 24"- strokeWidth={2}- >- <path- strokeLinecap="round"- strokeLinejoin="round"- d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"- />- </svg>- Export Data- <svg- className="w-3 h-3"- fill="none"- stroke="currentColor"- viewBox="0 0 24 24"- strokeWidth={2}- >- <path- strokeLinecap="round"- strokeLinejoin="round"- d="M19 9l-7 7-7-7"- />- </svg>- </button>- </div>- )} */}-{/* Global Date Picker and Tabs - Single Row */}<div className="flex items-end justify-between gap-6 mb-6"><div className="flex-1"><div className="flex items-end justify-between gap-6 mb-4 w-full">- <UsageViewSelect- value={usageView}- onChange={(value) => setUsageView(value)}- isAdmin={isAdmin}- />+ <UsageViewSelect value={usageView} onChange={(value) => setUsageView(value)} isAdmin={isAdmin} /><AdvancedDatePicker value={dateValue} onValueChange={handleDateChange} /></div>- {(paginatedResult.isFetchingMore || paginatedResult.cancelled) && (- <div className="flex items-center gap-2 text-sm text-gray-500 mb-2">- {paginatedResult.isFetchingMore && (- <>- <LoadingOutlined spin className="text-xs" />+ {paginatedResult.isFetchingMore && (+ <Alert+ banner+ type="warning"+ className="mb-2"+ message={+ <div className="flex items-center justify-between"><span>- Loading spend data... (page {paginatedResult.progress.currentPage}/{paginatedResult.progress.totalPages})+ Currently fetching spend data: fetched {paginatedResult.progress.currentPage} /{" "}+ {paginatedResult.progress.totalPages} pages. Charts will update periodically as data loads. Moving+ off of this page will stop and reset this. To continue using the UI in the meantime,{" "}+ <a href={window.location.href} target="_blank" rel="noopener noreferrer">+ open a new tab <ExportOutlined />+ </a>+ .</span>- <button- onClick={paginatedResult.cancel}- className="text-blue-600 hover:text-blue-800 underline text-xs"- >+ <Button type="primary" danger onClick={paginatedResult.cancel}>Stop- </button>- </>- )}- {paginatedResult.cancelled && (- <span className="text-yellow-600 text-xs">- Showing partial data ({paginatedResult.progress.currentPage}/{paginatedResult.progress.totalPages} pages loaded)+ </Button>+ </div>+ }+ />+ )}+ {paginatedResult.cancelled && (+ <Alert+ banner+ type="info"+ className="mb-2"+ message={+ <span>+ Showing partial data ({paginatedResult.progress.currentPage}/{paginatedResult.progress.totalPages}{" "}+ pages loaded)</span>- )}- </div>+ }+ />)}{/* Your Usage Panel */}{usageView === "global" && (<>- {isAdmin && (- <div className="mb-4">- <Text className="mb-2">Filter by user</Text>- <Select- showSearch- allowClear- style={{ width: "100%" }}- placeholder="Select user to filter..."- value={selectedUserId}- onChange={(value) => setSelectedUserId(value ?? null)}- filterOption={false}- onSearch={handleUserSearchChange}- searchValue={userSearchInput}- onPopupScroll={handleUserPopupScroll}- loading={isLoadingUsers}- notFoundContent={isLoadingUsers ? <LoadingOutlined spin /> : "No users found"}- options={userOptions}- popupRender={(menu) => (- <>- {menu}- {isFetchingNextUsersPage && (- <div style={{ textAlign: "center", padding: 8 }}>- <LoadingOutlined spin />- </div>- )}- </>- )}- />- </div>- )}- <TabGroup>- <div className="flex justify-between items-center">- <TabList variant="solid" className="mt-1">- <Tab>Cost</Tab>- <Tab>Model Activity</Tab>- <Tab>Key Activity</Tab>- <Tab>MCP Server Activity</Tab>- <Tab>Endpoint Activity</Tab>- </TabList>- <div className="flex items-center gap-2">- <Button- onClick={() => setIsAiChatOpen(true)}- icon={() => (- <svg className="w-4 h-4" viewBox="0 0 16 16" fill="currentColor">- <path d="M8 1l1.5 3.5L13 6l-3.5 1.5L8 11 6.5 7.5 3 6l3.5-1.5L8 1zm4 7l.75 1.75L14.5 10.5l-1.75.75L12 13l-.75-1.75L9.5 10.5l1.75-.75L12 8zM4 9l.75 1.75L6.5 11.5l-1.75.75L4 14l-.75-1.75L1.5 11.5l1.75-.75L4 9z" />- </svg>- )}- >- Ask AI- </Button>- <Button- onClick={() => setIsGlobalExportModalOpen(true)}- icon={() => (- <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path- strokeLinecap="round"- strokeLinejoin="round"- strokeWidth={2}- d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"- />- </svg>+ {isAdmin && (+ <div className="mb-4">+ <Text className="mb-2">Filter by user</Text>+ <Select+ showSearch+ allowClear+ style={{ width: "100%" }}+ placeholder="Select user to filter..."+ value={selectedUserId}+ onChange={(value) => setSelectedUserId(value ?? null)}+ filterOption={false}+ onSearch={handleUserSearchChange}+ searchValue={userSearchInput}+ onPopupScroll={handleUserPopupScroll}+ loading={isLoadingUsers}+ notFoundContent={isLoadingUsers ? <LoadingOutlined spin /> : "No users found"}+ options={userOptions}+ popupRender={(menu) => (+ <>+ {menu}+ {isFetchingNextUsersPage && (+ <div style={{ textAlign: "center", padding: 8 }}>+ <LoadingOutlined spin />+ </div>+ )}+ </>)}- >- Export Data- </Button>+ /></div>- </div>- <TabPanels>- {/* Cost Panel */}- <TabPanel>- <Grid numItems={2} className="gap-2 w-full">- {/* Total Spend Card */}- <Col numColSpan={2}>- <div className="flex items-center gap-4 mt-2 mb-2">- <Text className="text-tremor-default text-tremor-content dark:text-dark-tremor-content text-lg">- Project Spend{" "}- {dateValue.from && dateValue.to && (- <>- {dateValue.from.toLocaleDateString("en-US", {- month: "short",- day: "numeric",- year: dateValue.from.getFullYear() !== dateValue.to.getFullYear() ? "numeric" : undefined,- })}- {" - "}- {dateValue.to.toLocaleDateString("en-US", {- month: "short",- day: "numeric",- year: "numeric",- })}- </>- )}- </Text>- </div>+ )}+ <TabGroup>+ <div className="flex justify-between items-center">+ <TabList variant="solid" className="mt-1">+ <Tab>Cost</Tab>+ <Tab>Model Activity</Tab>+ <Tab>Key Activity</Tab>+ <Tab>MCP Server Activity</Tab>+ <Tab>Endpoint Activity</Tab>+ </TabList>+ <div className="flex items-center gap-2">+ <Button+ onClick={() => setIsAiChatOpen(true)}+ icon={+ <svg className="w-4 h-4" viewBox="0 0 16 16" fill="currentColor">+ <path d="M8 1l1.5 3.5L13 6l-3.5 1.5L8 11 6.5 7.5 3 6l3.5-1.5L8 1zm4 7l.75 1.75L14.5 10.5l-1.75.75L12 13l-.75-1.75L9.5 10.5l1.75-.75L12 8zM4 9l.75 1.75L6.5 11.5l-1.75.75L4 14l-.75-1.75L1.5 11.5l1.75-.75L4 9z" />+ </svg>+ }+ >+ Ask AI+ </Button>+ <Button+ onClick={() => setIsGlobalExportModalOpen(true)}+ icon={+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth={2}+ d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"+ />+ </svg>+ }+ >+ Export Data+ </Button>+ </div>+ </div>+ <TabPanels>+ {/* Cost Panel */}+ <TabPanel>+ <Grid numItems={2} className="gap-2 w-full">+ {/* Total Spend Card */}+ <Col numColSpan={2}>+ <div className="flex items-center gap-4 mt-2 mb-2">+ <Text className="text-tremor-default text-tremor-content dark:text-dark-tremor-content text-lg">+ Project Spend{" "}+ {dateValue.from && dateValue.to && (+ <>+ {dateValue.from.toLocaleDateString("en-US", {+ month: "short",+ day: "numeric",+ year:+ dateValue.from.getFullYear() !== dateValue.to.getFullYear() ? "numeric" : undefined,+ })}+ {" - "}+ {dateValue.to.toLocaleDateString("en-US", {+ month: "short",+ day: "numeric",+ year: "numeric",+ })}+ </>+ )}+ </Text>+ </div>- <ViewUserSpend- userSpend={totalSpend}- selectedTeam={null}- userMaxBudget={currentUser?.max_budget || null}- />- </Col>+ <ViewUserSpend+ userSpend={totalSpend}+ selectedTeam={null}+ userMaxBudget={currentUser?.max_budget || null}+ />+ </Col>- <Col numColSpan={2}>- <Card>- <Title>Usage Metrics</Title>- <Grid numItems={5} className="gap-4 mt-4">- <Card>- <Title>Total Requests</Title>- <Text className="text-2xl font-bold mt-2">- {userSpendData.metadata?.total_api_requests?.toLocaleString() || 0}- </Text>- </Card>- <Card>- <Title>Successful Requests</Title>- <Text className="text-2xl font-bold mt-2 text-green-600">- {userSpendData.metadata?.total_successful_requests?.toLocaleString() || 0}- </Text>- </Card>- <Card>- <div className="flex items-center gap-2">- <Title>Failed Requests</Title>- <Tooltip title="Includes requests that failed to route to a provider, tool usage failures, and other request errors where the provider cannot be determined.">- <InfoCircleOutlined className="text-gray-400 hover:text-gray-600" />- </Tooltip>- </div>- <Text className="text-2xl font-bold mt-2 text-red-600">- {userSpendData.metadata?.total_failed_requests?.toLocaleString() || 0}- </Text>- </Card>- <Card>- <Title>Average Cost per Request</Title>- <Text className="text-2xl font-bold mt-2">- $- {formatNumberWithCommas(- (totalSpend || 0) / (userSpendData.metadata?.total_api_requests || 1),- 4,- )}- </Text>- </Card>- <Card- className="cursor-pointer hover:bg-gray-50 transition-colors"- onClick={() => setShowTokenBreakdown(!showTokenBreakdown)}- >- <div className="flex items-center gap-2">- <Title>Total Tokens</Title>- {showTokenBreakdown ? (- <DownOutlined className="text-gray-400 text-xs" />- ) : (- <RightOutlined className="text-gray-400 text-xs" />- )}- </div>- <Text className="text-2xl font-bold mt-2">- {userSpendData.metadata?.total_tokens?.toLocaleString() || 0}- </Text>- </Card>- </Grid>- {showTokenBreakdown && (- <Grid numItems={4} className="gap-4 mt-4">+ <Col numColSpan={2}>+ <Card>+ <Title>Usage Metrics</Title>+ <Grid numItems={5} className="gap-4 mt-4"><Card>- <Title>Input Tokens</Title>- <Text className="text-2xl font-bold mt-2 text-blue-600">- {userSpendData.metadata?.total_prompt_tokens?.toLocaleString() || 0}+ <Title>Total Requests</Title>+ <Text className="text-2xl font-bold mt-2">+ {userSpendData.metadata?.total_api_requests?.toLocaleString() || 0}</Text></Card><Card>- <Title>Output Tokens</Title>- <Text className="text-2xl font-bold mt-2 text-cyan-600">- {userSpendData.metadata?.total_completion_tokens?.toLocaleString() || 0}+ <Title>Successful Requests</Title>+ <Text className="text-2xl font-bold mt-2 text-green-600">+ {userSpendData.metadata?.total_successful_requests?.toLocaleString() || 0}</Text></Card><Card>- <Title>Cache Read Tokens</Title>- <Text className="text-2xl font-bold mt-2 text-green-600">- {userSpendData.metadata?.total_cache_read_input_tokens?.toLocaleString() || 0}+ <div className="flex items-center gap-2">+ <Title>Failed Requests</Title>+ <Tooltip title="Includes requests that failed to route to a provider, tool usage failures, and other request errors where the provider cannot be determined.">+ <InfoCircleOutlined className="text-gray-400 hover:text-gray-600" />+ </Tooltip>+ </div>+ <Text className="text-2xl font-bold mt-2 text-red-600">+ {userSpendData.metadata?.total_failed_requests?.toLocaleString() || 0}</Text></Card><Card>- <Title>Cache Write Tokens</Title>- <Text className="text-2xl font-bold mt-2 text-purple-600">- {userSpendData.metadata?.total_cache_creation_input_tokens?.toLocaleString() || 0}+ <Title>Average Cost per Request</Title>+ <Text className="text-2xl font-bold mt-2">+ $+ {formatNumberWithCommas(+ (totalSpend || 0) / (userSpendData.metadata?.total_api_requests || 1),+ 4,+ )}+ </Text>+ </Card>+ <Card+ className="cursor-pointer hover:bg-gray-50 transition-colors"+ onClick={() => setShowTokenBreakdown(!showTokenBreakdown)}+ >+ <div className="flex items-center gap-2">+ <Title>Total Tokens</Title>+ {showTokenBreakdown ? (+ <DownOutlined className="text-gray-400 text-xs" />+ ) : (+ <RightOutlined className="text-gray-400 text-xs" />+ )}+ </div>+ <Text className="text-2xl font-bold mt-2">+ {userSpendData.metadata?.total_tokens?.toLocaleString() || 0}</Text></Card></Grid>- )}- </Card>- </Col>-- {/* Daily Spend Chart */}- <Col numColSpan={2}>- <Card>- <Title>Daily Spend</Title>- {loading ? (- <ChartLoader isDateChanging={isDateChanging} />- ) : (- <BarChart- data={sortedDailyResults}- index="date"- categories={["metrics.spend"]}- colors={["cyan"]}- valueFormatter={valueFormatterSpend}- yAxisWidth={100}- showLegend={false}- customTooltip={({ payload, active }) => {- if (!active || !payload?.[0]) return null;- const data = payload[0].payload;- return (- <div className="bg-white p-4 shadow-lg rounded-lg border">- <p className="font-bold">{data.date}</p>- <p className="text-cyan-500">- Spend: ${formatNumberWithCommas(data.metrics.spend, 2)}- </p>- <p className="text-gray-600">Requests: {data.metrics.api_requests}</p>- <p className="text-gray-600">Successful: {data.metrics.successful_requests}</p>- <p className="text-gray-600">Failed: {data.metrics.failed_requests}</p>- <p className="text-gray-600">Tokens: {data.metrics.total_tokens}</p>- </div>- );- }}- />- )}- </Card>- </Col>- {/* Top API Keys */}- <Col numColSpan={1}>- <Card className="h-full">- <Title>Top Virtual Keys</Title>- <TopKeyView- topKeys={topKeys}- teams={null}- topKeysLimit={topKeysLimit}- setTopKeysLimit={setTopKeysLimit}- />- </Card>- </Col>-- {/* Top Models */}- <Col numColSpan={1}>- <Card className="h-full">- <Title>{modelViewType === "groups" ? "Top Public Model Names" : "Top Litellm Models"}</Title>- <div className="flex justify-between items-center mb-4">- <Segmented- options={[- { label: "5", value: 5 },- { label: "10", value: 10 },- { label: "25", value: 25 },- { label: "50", value: 50 },- ]}- value={topModelsLimit}- onChange={(value) => setTopModelsLimit(value as number)}+ {showTokenBreakdown && (+ <Grid numItems={4} className="gap-4 mt-4">+ <Card>+ <Title>Input Tokens</Title>+ <Text className="text-2xl font-bold mt-2 text-blue-600">+ {userSpendData.metadata?.total_prompt_tokens?.toLocaleString() || 0}+ </Text>+ </Card>+ <Card>+ <Title>Output Tokens</Title>+ <Text className="text-2xl font-bold mt-2 text-cyan-600">+ {userSpendData.metadata?.total_completion_tokens?.toLocaleString() || 0}+ </Text>+ </Card>+ <Card>+ <Title>Cache Read Tokens</Title>+ <Text className="text-2xl font-bold mt-2 text-green-600">+ {userSpendData.metadata?.total_cache_read_input_tokens?.toLocaleString() || 0}+ </Text>+ </Card>+ <Card>+ <Title>Cache Write Tokens</Title>+ <Text className="text-2xl font-bold mt-2 text-purple-600">+ {userSpendData.metadata?.total_cache_creation_input_tokens?.toLocaleString() || 0}+ </Text>+ </Card>+ </Grid>+ )}+ </Card>+ </Col>++ {/* Daily Spend Chart */}+ <Col numColSpan={2}>+ <Card>+ <Title>Daily Spend</Title>+ {loading ? (+ <ChartLoader isDateChanging={isDateChanging} />+ ) : (+ <BarChart+ data={sortedDailyResults}+ index="date"+ categories={["metrics.spend"]}+ colors={["cyan"]}+ valueFormatter={valueFormatterSpend}+ yAxisWidth={100}+ showLegend={false}+ customTooltip={({ payload, active }) => {+ if (!active || !payload?.[0]) return null;+ const data = payload[0].payload;+ return (+ <div className="bg-white p-4 shadow-lg rounded-lg border">+ <p className="font-bold">{data.date}</p>+ <p className="text-cyan-500">+ Spend: ${formatNumberWithCommas(data.metrics.spend, 2)}+ </p>+ <p className="text-gray-600">Requests: {data.metrics.api_requests}</p>+ <p className="text-gray-600">Successful: {data.metrics.successful_requests}</p>+ <p className="text-gray-600">Failed: {data.metrics.failed_requests}</p>+ <p className="text-gray-600">Tokens: {data.metrics.total_tokens}</p>+ </div>+ );+ }}+ />+ )}+ </Card>+ </Col>+ {/* Top API Keys */}+ <Col numColSpan={1}>+ <Card className="h-full">+ <Title>Top Virtual Keys</Title>+ <TopKeyView+ topKeys={topKeys}+ teams={null}+ topKeysLimit={topKeysLimit}+ setTopKeysLimit={setTopKeysLimit}/>- <div className="flex bg-gray-100 rounded-lg p-1">- <button- className={`px-3 py-1 text-sm rounded-md transition-colors ${modelViewType === "groups"- ? "bg-white shadow-sm text-gray-900"- : "text-gray-600 hover:text-gray-900"+ </Card>+ </Col>++ {/* Top Models */}+ <Col numColSpan={1}>+ <Card className="h-full">+ <Title>{modelViewType === "groups" ? "Top Public Model Names" : "Top Litellm Models"}</Title>+ <div className="flex justify-between items-center mb-4">+ <Segmented+ options={[+ { label: "5", value: 5 },+ { label: "10", value: 10 },+ { label: "25", value: 25 },+ { label: "50", value: 50 },+ ]}+ value={topModelsLimit}+ onChange={(value) => setTopModelsLimit(value as number)}+ />+ <div className="flex bg-gray-100 rounded-lg p-1">+ <button+ className={`px-3 py-1 text-sm rounded-md transition-colors ${+ modelViewType === "groups"+ ? "bg-white shadow-sm text-gray-900"+ : "text-gray-600 hover:text-gray-900"}`}- onClick={() => setModelViewType("groups")}- >- Public Model Name- </button>- <button- className={`px-3 py-1 text-sm rounded-md transition-colors ${modelViewType === "individual"- ? "bg-white shadow-sm text-gray-900"- : "text-gray-600 hover:text-gray-900"+ onClick={() => setModelViewType("groups")}+ >+ Public Model Name+ </button>+ <button+ className={`px-3 py-1 text-sm rounded-md transition-colors ${+ modelViewType === "individual"+ ? "bg-white shadow-sm text-gray-900"+ : "text-gray-600 hover:text-gray-900"}`}- onClick={() => setModelViewType("individual")}- >- Litellm Model Name- </button>- </div>- </div>- {loading ? (- <ChartLoader isDateChanging={isDateChanging} />- ) : (- <div className="relative max-h-[600px] overflow-y-auto">- {(() => {- const modelData =- modelViewType === "groups"- ? topModelGroups- : topModels;- return (- <BarChart- className="mt-4"- style={{ height: Math.min(modelData.length, topModelsLimit) * 52 }}- data={modelData}- index="key"- categories={["spend"]}- colors={["cyan"]}- valueFormatter={valueFormatterSpend}- layout="vertical"- yAxisWidth={200}- showLegend={false}- customTooltip={({ payload, active }) => {- if (!active || !payload?.[0]) return null;- const data = payload[0].payload;- return (- <div className="bg-white p-4 shadow-lg rounded-lg border">- <p className="font-bold">{data.key}</p>- <p className="text-cyan-500">Spend: ${formatNumberWithCommas(data.spend, 2)}</p>- <p className="text-gray-600">- Total Requests: {data.requests.toLocaleString()}- </p>- <p className="text-green-600">- Successful: {data.successful_requests.toLocaleString()}- </p>- <p className="text-red-600">Failed: {data.failed_requests.toLocaleString()}</p>- <p className="text-gray-600">Tokens: {data.tokens.toLocaleString()}</p>- </div>- );- }}- />- );- })()}+ onClick={() => setModelViewType("individual")}+ >+ Litellm Model Name+ </button>+ </div></div>- )}- </Card>- </Col>-- {/* Spend by Provider */}- <Col numColSpan={2}>- <SpendByProvider- loading={loading}- isDateChanging={isDateChanging}- providerSpend={providerSpend}- />- </Col>-- {/* Usage Metrics */}- </Grid>- </TabPanel>-- {/* Activity Panel */}- <TabPanel>- <ActivityMetrics modelMetrics={modelMetrics} />- </TabPanel>- <TabPanel>- <ActivityMetrics modelMetrics={keyMetrics} />- </TabPanel>- <TabPanel>- <ActivityMetrics modelMetrics={mcpServerMetrics} />- </TabPanel>- <TabPanel>- <EndpointUsage userSpendData={userSpendData} />- </TabPanel>- </TabPanels>- </TabGroup>+ {loading ? (+ <ChartLoader isDateChanging={isDateChanging} />+ ) : (+ <div className="relative max-h-[600px] overflow-y-auto">+ {(() => {+ const modelData = modelViewType === "groups" ? topModelGroups : topModels;+ return (+ <BarChart+ className="mt-4"+ style={{ height: Math.min(modelData.length, topModelsLimit) * 52 }}+ data={modelData}+ index="key"+ categories={["spend"]}+ colors={["cyan"]}+ valueFormatter={valueFormatterSpend}+ layout="vertical"+ yAxisWidth={200}+ showLegend={false}+ customTooltip={({ payload, active }) => {+ if (!active || !payload?.[0]) return null;+ const data = payload[0].payload;+ return (+ <div className="bg-white p-4 shadow-lg rounded-lg border">+ <p className="font-bold">{data.key}</p>+ <p className="text-cyan-500">+ Spend: ${formatNumberWithCommas(data.spend, 2)}+ </p>+ <p className="text-gray-600">+ Total Requests: {data.requests.toLocaleString()}+ </p>+ <p className="text-green-600">+ Successful: {data.successful_requests.toLocaleString()}+ </p>+ <p className="text-red-600">+ Failed: {data.failed_requests.toLocaleString()}+ </p>+ <p className="text-gray-600">Tokens: {data.tokens.toLocaleString()}</p>+ </div>+ );+ }}+ />+ );+ })()}+ </div>+ )}+ </Card>+ </Col>++ {/* Spend by Provider */}+ <Col numColSpan={2}>+ <SpendByProvider+ loading={loading}+ isDateChanging={isDateChanging}+ providerSpend={providerSpend}+ />+ </Col>++ {/* Usage Metrics */}+ </Grid>+ </TabPanel>++ {/* Activity Panel */}+ <TabPanel>+ <ActivityMetrics modelMetrics={modelMetrics} />+ </TabPanel>+ <TabPanel>+ <ActivityMetrics modelMetrics={keyMetrics} />+ </TabPanel>+ <TabPanel>+ <ActivityMetrics modelMetrics={mcpServerMetrics} />+ </TabPanel>+ <TabPanel>+ <EndpointUsage userSpendData={userSpendData} />+ </TabPanel>+ </TabPanels>+ </TabGroup></>)}{/* Organization Usage Panel */}@@ -994,11 +969,7 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {/>{/* AI Chat Panel */}- <UsageAIChatPanel- open={isAiChatOpen}- onClose={() => setIsAiChatOpen(false)}- accessToken={accessToken}- />+ <UsageAIChatPanel open={isAiChatOpen} onClose={() => setIsAiChatOpen(false)} accessToken={accessToken} /></div>);};diff --git a/ui/litellm-dashboard/src/components/UsagePage/hooks/usePaginatedDailyActivity.ts b/ui/litellm-dashboard/src/components/UsagePage/hooks/usePaginatedDailyActivity.tsindex 498c4c07a2b..1716c33ed2d 100644--- a/ui/litellm-dashboard/src/components/UsagePage/hooks/usePaginatedDailyActivity.ts+++ b/ui/litellm-dashboard/src/components/UsagePage/hooks/usePaginatedDailyActivity.ts@@ -7,7 +7,10 @@ export interface PaginationProgress {}/** Delay between sequential page fetches (ms) to avoid overloading the backend. */-const PAGE_FETCH_DELAY_MS = 500;+const PAGE_FETCH_DELAY_MS = 300;++/** Number of pages to accumulate before flushing to React state (reduces re-renders). */+const RENDER_BATCH_SIZE = 5;/** The metadata fields returned by the daily activity API that should be summed across pages. */const SUMMABLE_METADATA_KEYS = [@@ -201,11 +204,19 @@ export function usePaginatedDailyActivity({accumulatedMetadata.has_more = page < totalPages;accumulatedMetadata.page = page;- setData({- results: accumulatedResults,- metadata: accumulatedMetadata,- });+ // Always update progress so the banner stays responsive.setProgress({ currentPage: page, totalPages });++ // Flush accumulated data to React state every RENDER_BATCH_SIZE pages+ // (or on the final page) to avoid expensive per-page re-renders.+ const isLastPage = page === totalPages;+ const isBatchBoundary = (page - 1) % RENDER_BATCH_SIZE === 0;+ if (isLastPage || isBatchBoundary) {+ setData({+ results: accumulatedResults,+ metadata: accumulatedMetadata,+ });+ }}setIsFetchingMore(false);