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
Searchable Paginated Model Select For Spend Logs
yuneng-jiang7fd8c0e16045
diff --git a/litellm/proxy/spend_tracking/spend_management_endpoints.py b/litellm/proxy/spend_tracking/spend_management_endpoints.pyindex 6e49e4244e7..c05eda85c81 100644--- a/litellm/proxy/spend_tracking/spend_management_endpoints.py+++ b/litellm/proxy/spend_tracking/spend_management_endpoints.py@@ -1672,6 +1672,9 @@ async def ui_view_spend_logs( # noqa: PLR0915model: Optional[str] = fastapi.Query(default=None, description="Filter logs by model"),+ model_id: Optional[str] = fastapi.Query(+ default=None, description="Filter logs by model ID (litellm model deployment id)"+ ),key_alias: Optional[str] = fastapi.Query(default=None, description="Filter logs by key alias"),@@ -1763,6 +1766,9 @@ async def ui_view_spend_logs( # noqa: PLR0915if model is not None:where_conditions["model"] = model+ if model_id is not None:+ where_conditions["model_id"] = model_id+# Build metadata filtersmetadata_filters = []if key_alias is not None:diff --git a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.pyindex 54a276bc97f..dd34cb47da4 100644--- a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py+++ b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py@@ -1025,6 +1025,85 @@ async def test_ui_view_spend_logs_with_model(client, monkeypatch):assert data["data"][0]["model"] == "gpt-3.5-turbo"+async def test_ui_view_spend_logs_with_model_id(client, monkeypatch):+ """Test that the model_id query param filters spend logs by litellm model deployment id."""+ mock_spend_logs = [+ {+ "id": "log1",+ "request_id": "req1",+ "api_key": "sk-test-key",+ "user": "test_user_1",+ "team_id": "team1",+ "spend": 0.05,+ "startTime": datetime.datetime.now(timezone.utc).isoformat(),+ "model": "gpt-3.5-turbo",+ "model_id": "deployment-id-1",+ "status": "success",+ },+ {+ "id": "log2",+ "request_id": "req2",+ "api_key": "sk-test-key",+ "user": "test_user_2",+ "team_id": "team1",+ "spend": 0.10,+ "startTime": datetime.datetime.now(timezone.utc).isoformat(),+ "model": "gpt-4",+ "model_id": "deployment-id-2",+ "status": "success",+ },+ ]++ class MockDB:+ async def find_many(self, *args, **kwargs):+ if (+ "where" in kwargs+ and "model_id" in kwargs["where"]+ and kwargs["where"]["model_id"] == "deployment-id-1"+ ):+ return [mock_spend_logs[0]]+ return mock_spend_logs++ async def count(self, *args, **kwargs):+ if (+ "where" in kwargs+ and "model_id" in kwargs["where"]+ and kwargs["where"]["model_id"] == "deployment-id-1"+ ):+ return 1+ return len(mock_spend_logs)++ class MockPrismaClient:+ def __init__(self):+ self.db = MockDB()+ self.db.litellm_spendlogs = self.db++ mock_prisma_client = MockPrismaClient()+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)++ start_date = (+ datetime.datetime.now(timezone.utc) - datetime.timedelta(days=7)+ ).strftime("%Y-%m-%d %H:%M:%S")+ end_date = datetime.datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")++ response = client.get(+ "/spend/logs/ui",+ params={+ "model_id": "deployment-id-1",+ "start_date": start_date,+ "end_date": end_date,+ },+ headers={"Authorization": "Bearer sk-test"},+ )++ assert response.status_code == 200+ data = response.json()+ assert data["total"] == 1+ assert len(data["data"]) == 1+ assert data["data"][0]["model_id"] == "deployment-id-1"++@pytest.mark.asyncioasync def test_ui_view_spend_logs_with_key_hash(client, monkeypatch):# Mock data for the testdiff --git a/ui/litellm-dashboard/src/app/(dashboard)/hooks/models/useModels.test.ts b/ui/litellm-dashboard/src/app/(dashboard)/hooks/models/useModels.test.tsindex 4985206092f..2539cc63f95 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/hooks/models/useModels.test.ts+++ b/ui/litellm-dashboard/src/app/(dashboard)/hooks/models/useModels.test.ts@@ -3,13 +3,14 @@ import { renderHook, waitFor } from "@testing-library/react";import React, { ReactNode } from "react";import { beforeEach, describe, expect, it, vi } from "vitest";import {- useModelsInfo,- useModelHub,useAllProxyModels,+ useInfiniteModelInfo,+ useModelHub,+ useModelsInfo,useSelectedTeamModels,- type ProxyModel,type AllProxyModelsResponse,type PaginatedModelInfoResponse,+ type ProxyModel,} from "./useModels";vi.mock("@/components/networking", () => ({@@ -23,7 +24,7 @@ vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({default: () => mockUseAuthorized(),}));-import { modelInfoCall, modelHubCall, modelAvailableCall } from "@/components/networking";+import { modelAvailableCall, modelHubCall, modelInfoCall } from "@/components/networking";const mockProxyModel: ProxyModel = {id: "model-1",@@ -106,7 +107,7 @@ describe("useModelsInfo", () => {undefined,undefined,undefined,- undefined+ undefined,);expect(modelInfoCall).toHaveBeenCalledTimes(1);});@@ -130,7 +131,7 @@ describe("useModelsInfo", () => {undefined,undefined,undefined,- undefined+ undefined,);});@@ -393,7 +394,7 @@ describe("useAllProxyModels", () => {null,true,false,- "expand"+ "expand",);expect(modelAvailableCall).toHaveBeenCalledTimes(1);});@@ -531,13 +532,7 @@ describe("useSelectedTeamModels", () => {expect(result.current.data).toEqual(mockAllProxyModelsResponse);expect(result.current.error).toBeNull();- expect(modelAvailableCall).toHaveBeenCalledWith(- "test-access-token",- "test-user-id",- "Admin",- true,- "team-1"- );+ expect(modelAvailableCall).toHaveBeenCalledWith("test-access-token", "test-user-id", "Admin", true, "team-1");expect(modelAvailableCall).toHaveBeenCalledTimes(1);});@@ -639,3 +634,222 @@ describe("useSelectedTeamModels", () => {expect(modelAvailableCall).not.toHaveBeenCalled();});});++describe("useInfiniteModelInfo", () => {+ let queryClient: QueryClient;++ const mockPageOneResponse: PaginatedModelInfoResponse = {+ data: [{ model_name: "gpt-4", model_info: { id: "model-1" } }],+ total_count: 2,+ current_page: 1,+ total_pages: 2,+ size: 50,+ };++ const mockPageTwoResponse: PaginatedModelInfoResponse = {+ data: [{ model_name: "claude-3", model_info: { id: "model-2" } }],+ total_count: 2,+ current_page: 2,+ total_pages: 2,+ size: 50,+ };++ beforeEach(() => {+ queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ });++ vi.clearAllMocks();++ mockUseAuthorized.mockReturnValue({+ accessToken: "test-access-token",+ userId: "test-user-id",+ userRole: "Admin",+ token: "test-token",+ userEmail: "[email protected]",+ premiumUser: false,+ disabledPersonalKeyCreation: null,+ showSSOBanner: false,+ });+ });++ const wrapper = ({ children }: { children: ReactNode }) =>+ React.createElement(QueryClientProvider, { client: queryClient }, children);++ it("should return defined result", () => {+ (modelInfoCall as any).mockResolvedValue(mockPageOneResponse);++ const { result } = renderHook(() => useInfiniteModelInfo(), { wrapper });++ expect(result.current).toBeDefined();+ expect(result.current).toHaveProperty("data");+ expect(result.current).toHaveProperty("fetchNextPage");+ expect(result.current).toHaveProperty("hasNextPage");+ expect(result.current).toHaveProperty("isFetchingNextPage");+ expect(result.current).toHaveProperty("isLoading");+ });++ it("should return paginated data and call modelInfoCall with page 1 initially", async () => {+ (modelInfoCall as any).mockResolvedValue(mockPageOneResponse);++ const { result } = renderHook(() => useInfiniteModelInfo(), { wrapper });++ expect(result.current.isLoading).toBe(true);++ await waitFor(() => {+ expect(result.current.isLoading).toBe(false);+ expect(result.current.isSuccess).toBe(true);+ });++ expect(result.current.data?.pages).toHaveLength(1);+ expect(result.current.data?.pages[0]).toEqual(mockPageOneResponse);+ expect(result.current.hasNextPage).toBe(true);+ expect(modelInfoCall).toHaveBeenCalledWith("test-access-token", "test-user-id", "Admin", 1, 50, undefined);+ expect(modelInfoCall).toHaveBeenCalledTimes(1);+ });++ it("should use custom size parameter", async () => {+ (modelInfoCall as any).mockResolvedValue(mockPageOneResponse);++ const { result } = renderHook(() => useInfiniteModelInfo(25), { wrapper });++ await waitFor(() => {+ expect(result.current.isLoading).toBe(false);+ });++ expect(modelInfoCall).toHaveBeenCalledWith("test-access-token", "test-user-id", "Admin", 1, 25, undefined);+ });++ it("should pass search parameter to modelInfoCall", async () => {+ (modelInfoCall as any).mockResolvedValue(mockPageOneResponse);++ const { result } = renderHook(() => useInfiniteModelInfo(50, "gpt"), { wrapper });++ await waitFor(() => {+ expect(result.current.isLoading).toBe(false);+ });++ expect(modelInfoCall).toHaveBeenCalledWith("test-access-token", "test-user-id", "Admin", 1, 50, "gpt");+ });++ it("should fetch next page when fetchNextPage is called", async () => {+ (modelInfoCall as any).mockResolvedValueOnce(mockPageOneResponse).mockResolvedValueOnce(mockPageTwoResponse);++ const { result } = renderHook(() => useInfiniteModelInfo(), { wrapper });++ await waitFor(() => {+ expect(result.current.isSuccess).toBe(true);+ expect(result.current.hasNextPage).toBe(true);+ });++ await result.current.fetchNextPage();++ await waitFor(() => {+ expect(result.current.data?.pages).toHaveLength(2);+ expect(result.current.data?.pages[1]).toEqual(mockPageTwoResponse);+ expect(result.current.hasNextPage).toBe(false);+ });++ expect(modelInfoCall).toHaveBeenNthCalledWith(2, "test-access-token", "test-user-id", "Admin", 2, 50, undefined);+ });++ it("should return undefined for hasNextPage when on last page", async () => {+ const lastPageResponse: PaginatedModelInfoResponse = {+ ...mockPageOneResponse,+ current_page: 1,+ total_pages: 1,+ };+ (modelInfoCall as any).mockResolvedValue(lastPageResponse);++ const { result } = renderHook(() => useInfiniteModelInfo(), { wrapper });++ await waitFor(() => {+ expect(result.current.isSuccess).toBe(true);+ });++ expect(result.current.hasNextPage).toBe(false);+ });++ it("should handle error when modelInfoCall fails", async () => {+ const errorMessage = "Failed to fetch models";+ const testError = new Error(errorMessage);+ (modelInfoCall as any).mockRejectedValue(testError);++ const { result } = renderHook(() => useInfiniteModelInfo(), { wrapper });++ expect(result.current.isLoading).toBe(true);++ await waitFor(() => {+ expect(result.current.isLoading).toBe(false);+ expect(result.current.isError).toBe(true);+ });++ expect(result.current.error).toEqual(testError);+ expect(result.current.data).toBeUndefined();+ expect(modelInfoCall).toHaveBeenCalledTimes(1);+ });++ it("should not execute query when accessToken is missing", () => {+ mockUseAuthorized.mockReturnValue({+ accessToken: null,+ userId: "test-user-id",+ userRole: "Admin",+ token: null,+ userEmail: "[email protected]",+ premiumUser: false,+ disabledPersonalKeyCreation: null,+ showSSOBanner: false,+ });++ const { result } = renderHook(() => useInfiniteModelInfo(), { wrapper });++ expect(result.current.isLoading).toBe(false);+ expect(result.current.data).toBeUndefined();+ expect(result.current.isFetched).toBe(false);+ expect(modelInfoCall).not.toHaveBeenCalled();+ });++ it("should not execute query when userId is missing", () => {+ mockUseAuthorized.mockReturnValue({+ accessToken: "test-access-token",+ userId: null,+ userRole: "Admin",+ token: "test-token",+ userEmail: "[email protected]",+ premiumUser: false,+ disabledPersonalKeyCreation: null,+ showSSOBanner: false,+ });++ const { result } = renderHook(() => useInfiniteModelInfo(), { wrapper });++ expect(result.current.isLoading).toBe(false);+ expect(result.current.data).toBeUndefined();+ expect(result.current.isFetched).toBe(false);+ expect(modelInfoCall).not.toHaveBeenCalled();+ });++ it("should not execute query when userRole is missing", () => {+ mockUseAuthorized.mockReturnValue({+ accessToken: "test-access-token",+ userId: "test-user-id",+ userRole: null,+ token: "test-token",+ userEmail: "[email protected]",+ premiumUser: false,+ disabledPersonalKeyCreation: null,+ showSSOBanner: false,+ });++ const { result } = renderHook(() => useInfiniteModelInfo(), { wrapper });++ expect(result.current.isLoading).toBe(false);+ expect(result.current.data).toBeUndefined();+ expect(result.current.isFetched).toBe(false);+ expect(modelInfoCall).not.toHaveBeenCalled();+ });+});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/hooks/models/useModels.ts b/ui/litellm-dashboard/src/app/(dashboard)/hooks/models/useModels.tsindex c57de675e0e..fe1afdcc39f 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/hooks/models/useModels.ts+++ b/ui/litellm-dashboard/src/app/(dashboard)/hooks/models/useModels.ts@@ -1,4 +1,4 @@-import { useQuery } from "@tanstack/react-query";+import { useQuery, useInfiniteQuery } from "@tanstack/react-query";import { createQueryKeys } from "../common/queryKeysFactory";import { modelInfoCall, modelHubCall, modelAvailableCall } from "@/components/networking";import useAuthorized from "../useAuthorized";@@ -26,6 +26,7 @@ const modelKeys = createQueryKeys("models");const modelHubKeys = createQueryKeys("modelHub");const allProxyModelsKeys = createQueryKeys("allProxyModels");const selectedTeamModelsKeys = createQueryKeys("selectedTeamModels");+const infiniteModelKeys = createQueryKeys("infiniteModels");export const useModelsInfo = (page: number = 1, size: number = 50, search?: string, modelId?: string, teamId?: string, sortBy?: string, sortOrder?: string) => {const { accessToken, userId, userRole } = useAuthorized();@@ -74,3 +75,38 @@ export const useSelectedTeamModels = (teamID: string | null) => {enabled: Boolean(accessToken && userId && userRole && teamID),});};++export const useInfiniteModelInfo = (+ size: number = 50,+ search?: string,+) => {+ const { accessToken, userId, userRole } = useAuthorized();+ return useInfiniteQuery<PaginatedModelInfoResponse>({+ queryKey: infiniteModelKeys.list({+ filters: {+ ...(userId && { userId }),+ ...(userRole && { userRole }),+ size,+ ...(search && { search }),+ },+ }),+ queryFn: async ({ pageParam }) => {+ return await modelInfoCall(+ accessToken!,+ userId!,+ userRole!,+ pageParam as number,+ size,+ search,+ );+ },+ initialPageParam: 1,+ getNextPageParam: (lastPage) => {+ if (lastPage.current_page < lastPage.total_pages) {+ return lastPage.current_page + 1;+ }+ return undefined;+ },+ enabled: Boolean(accessToken && userId && userRole),+ });+};diff --git a/ui/litellm-dashboard/src/components/ModelSelect/PaginatedModelSelect/PaginatedModelSelect.test.tsx b/ui/litellm-dashboard/src/components/ModelSelect/PaginatedModelSelect/PaginatedModelSelect.test.tsxnew file mode 100644index 00000000000..b91f97885e6--- /dev/null+++ b/ui/litellm-dashboard/src/components/ModelSelect/PaginatedModelSelect/PaginatedModelSelect.test.tsx@@ -0,0 +1,301 @@+import { screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { renderWithProviders } from "../../../../tests/test-utils";+import { PaginatedModelSelect } from "./PaginatedModelSelect";++const mockFetchNextPage = vi.fn();++vi.mock("@/app/(dashboard)/hooks/models/useModels", () => ({+ useInfiniteModelInfo: vi.fn(),+}));++vi.mock("@tanstack/react-pacer/debouncer", () => {+ const React = require("react");+ return {+ useDebouncedState: (initial: string) => {+ const [value, setValue] = React.useState(initial);+ return [value, setValue];+ },+ };+});++import { useInfiniteModelInfo } from "@/app/(dashboard)/hooks/models/useModels";++const mockUseInfiniteModelInfo = vi.mocked(useInfiniteModelInfo);++const mockPagesWithModels = {+ pages: [+ {+ data: [+ { model_name: "GPT-4", model_info: { id: "model-1" } },+ { model_name: "Claude-3", model_info: { id: "model-2" } },+ ],+ total_count: 2,+ current_page: 1,+ total_pages: 1,+ size: 50,+ },+ ],+};++const mockEmptyPages = {+ pages: [{ data: [], total_count: 0, current_page: 1, total_pages: 1, size: 50 }],+};++describe("PaginatedModelSelect", () => {+ const mockOnChange = vi.fn();++ const defaultHookReturn = {+ data: mockPagesWithModels,+ fetchNextPage: mockFetchNextPage,+ hasNextPage: false,+ isFetchingNextPage: false,+ isLoading: false,+ };++ beforeEach(() => {+ vi.clearAllMocks();+ mockUseInfiniteModelInfo.mockReturnValue(defaultHookReturn as any);+ });++ it("should render", () => {+ renderWithProviders(<PaginatedModelSelect onChange={mockOnChange} />);++ expect(screen.getByRole("combobox")).toBeInTheDocument();+ expect(screen.getByText("Select a model")).toBeInTheDocument();+ });++ it("should display custom placeholder when provided", () => {+ renderWithProviders(+ <PaginatedModelSelect onChange={mockOnChange} placeholder="Choose model" />,+ );++ expect(screen.getByText("Choose model")).toBeInTheDocument();+ });++ it("should display model options when data is loaded", async () => {+ renderWithProviders(<PaginatedModelSelect onChange={mockOnChange} />);++ const combobox = screen.getByRole("combobox");+ await userEvent.click(combobox);++ await waitFor(() => {+ expect(screen.getByRole("option", { name: "GPT-4 (model-1)" })).toBeInTheDocument();+ expect(screen.getByRole("option", { name: "Claude-3 (model-2)" })).toBeInTheDocument();+ });+ });++ it("should call onChange when user selects a model", async () => {+ const user = userEvent.setup({ delay: null });+ renderWithProviders(<PaginatedModelSelect onChange={mockOnChange} />);++ const combobox = screen.getByRole("combobox");+ await user.click(combobox);++ const visibleOption = await screen.findByTitle("GPT-4 (model-1)");+ await user.click(visibleOption);++ await waitFor(() => {+ expect(mockOnChange).toHaveBeenCalledWith("model-1");+ });+ });++ it("should display selected value when value prop is provided", async () => {+ renderWithProviders(+ <PaginatedModelSelect value="model-1" onChange={mockOnChange} />,+ );++ const combobox = screen.getByRole("combobox");+ await userEvent.click(combobox);++ await waitFor(() => {+ expect(screen.getByRole("option", { name: "GPT-4 (model-1)" })).toBeInTheDocument();+ });+ });++ it("should show loading state when isLoading is true", () => {+ mockUseInfiniteModelInfo.mockReturnValue({+ ...defaultHookReturn,+ isLoading: true,+ } as any);++ renderWithProviders(<PaginatedModelSelect onChange={mockOnChange} />);++ expect(screen.getByRole("combobox")).toHaveAttribute("aria-expanded", "false");+ });++ it("should pass pageSize to useInfiniteModelInfo", () => {+ renderWithProviders(<PaginatedModelSelect onChange={mockOnChange} pageSize={25} />);++ expect(mockUseInfiniteModelInfo).toHaveBeenCalledWith(25, undefined);+ });++ it("should pass search to useInfiniteModelInfo when user types", async () => {+ const user = userEvent.setup();+ renderWithProviders(<PaginatedModelSelect onChange={mockOnChange} />);++ const combobox = screen.getByRole("combobox");+ await user.click(combobox);+ await user.keyboard("gpt");++ await waitFor(() => {+ expect(mockUseInfiniteModelInfo).toHaveBeenCalledWith(50, "gpt");+ });+ });++ it("should have scroll container for infinite loading when hasNextPage is true", async () => {+ mockUseInfiniteModelInfo.mockReturnValue({+ ...defaultHookReturn,+ hasNextPage: true,+ isFetchingNextPage: false,+ } as any);++ renderWithProviders(<PaginatedModelSelect onChange={mockOnChange} />);++ const combobox = screen.getByRole("combobox");+ await userEvent.click(combobox);++ await waitFor(() => {+ expect(screen.getByRole("option", { name: "GPT-4 (model-1)" })).toBeInTheDocument();+ });++ const scrollableContainer = document.querySelector(+ ".ant-select-dropdown .rc-virtual-list-holder",+ );+ expect(scrollableContainer).toBeInTheDocument();+ expect(scrollableContainer).toHaveAttribute("style");+ });++ it("should deduplicate models with same id across pages", async () => {+ mockUseInfiniteModelInfo.mockReturnValue({+ ...defaultHookReturn,+ data: {+ pages: [+ {+ data: [+ { model_name: "GPT-4", model_info: { id: "model-1" } },+ { model_name: "GPT-4 Dupe", model_info: { id: "model-1" } },+ ],+ total_count: 2,+ current_page: 1,+ total_pages: 1,+ size: 50,+ },+ ],+ },+ fetchNextPage: mockFetchNextPage,+ hasNextPage: false,+ isFetchingNextPage: false,+ isLoading: false,+ } as any);++ renderWithProviders(<PaginatedModelSelect onChange={mockOnChange} />);++ const combobox = screen.getByRole("combobox");+ await userEvent.click(combobox);++ await waitFor(() => {+ const model1Options = screen.queryAllByRole("option", { name: /model-1/ });+ expect(model1Options.length).toBe(1);+ });+ });++ it("should skip models without model_info id", async () => {+ mockUseInfiniteModelInfo.mockReturnValue({+ ...defaultHookReturn,+ data: {+ pages: [+ {+ data: [+ { model_name: "Valid Model", model_info: { id: "valid-id" } },+ { model_name: "No ID", model_info: null },+ { model_name: "Empty ID", model_info: { id: "" } },+ ],+ total_count: 3,+ current_page: 1,+ total_pages: 1,+ size: 50,+ },+ ],+ },+ fetchNextPage: mockFetchNextPage,+ hasNextPage: false,+ isFetchingNextPage: false,+ isLoading: false,+ } as any);++ renderWithProviders(<PaginatedModelSelect onChange={mockOnChange} />);++ const combobox = screen.getByRole("combobox");+ await userEvent.click(combobox);++ await waitFor(() => {+ expect(screen.getByRole("option", { name: "Valid Model (valid-id)" })).toBeInTheDocument();+ expect(screen.queryByRole("option", { name: "No ID" })).not.toBeInTheDocument();+ expect(screen.queryByRole("option", { name: "Empty ID" })).not.toBeInTheDocument();+ });+ });++ it("should show model ID only when model_name is empty", async () => {+ mockUseInfiniteModelInfo.mockReturnValue({+ ...defaultHookReturn,+ data: {+ pages: [+ {+ data: [{ model_name: "", model_info: { id: "id-only" } }],+ total_count: 1,+ current_page: 1,+ total_pages: 1,+ size: 50,+ },+ ],+ },+ fetchNextPage: mockFetchNextPage,+ hasNextPage: false,+ isFetchingNextPage: false,+ isLoading: false,+ } as any);++ renderWithProviders(<PaginatedModelSelect onChange={mockOnChange} />);++ const combobox = screen.getByRole("combobox");+ await userEvent.click(combobox);++ await waitFor(() => {+ expect(screen.getByRole("option", { name: "id-only" })).toBeInTheDocument();+ });+ });++ it("should respect allowClear prop", () => {+ renderWithProviders(+ <PaginatedModelSelect value="model-1" onChange={mockOnChange} allowClear={false} />,+ );++ expect(screen.getByRole("combobox")).toBeInTheDocument();+ });++ it("should respect disabled prop", () => {+ renderWithProviders(<PaginatedModelSelect onChange={mockOnChange} disabled />);++ const combobox = screen.getByRole("combobox");+ expect(combobox.closest(".ant-select")).toHaveClass("ant-select-disabled");+ });++ it("should not call fetchNextPage when hasNextPage is false", async () => {+ mockUseInfiniteModelInfo.mockReturnValue({+ ...defaultHookReturn,+ hasNextPage: false,+ } as any);++ renderWithProviders(<PaginatedModelSelect onChange={mockOnChange} />);++ await userEvent.click(screen.getByRole("combobox"));++ await waitFor(() => {+ expect(screen.getByRole("option", { name: "GPT-4 (model-1)" })).toBeInTheDocument();+ });++ expect(mockFetchNextPage).not.toHaveBeenCalled();+ });+});diff --git a/ui/litellm-dashboard/src/components/ModelSelect/PaginatedModelSelect/PaginatedModelSelect.tsx b/ui/litellm-dashboard/src/components/ModelSelect/PaginatedModelSelect/PaginatedModelSelect.tsxnew file mode 100644index 00000000000..285f4e94d68--- /dev/null+++ b/ui/litellm-dashboard/src/components/ModelSelect/PaginatedModelSelect/PaginatedModelSelect.tsx@@ -0,0 +1,143 @@+import { useInfiniteModelInfo } from "@/app/(dashboard)/hooks/models/useModels";+import { LoadingOutlined } from "@ant-design/icons";+import { useDebouncedState } from "@tanstack/react-pacer/debouncer";+import { Select, Space, Typography } from "antd";+import { useMemo, useState, type UIEvent } from "react";++const { Text } = Typography;++export interface PaginatedModelSelectProps {+ value?: string;+ onChange?: (value: string) => void;+ placeholder?: string;+ style?: React.CSSProperties;+ pageSize?: number;+ allowClear?: boolean;+ disabled?: boolean;+}++const SCROLL_THRESHOLD = 0.8;+const DEBOUNCE_MS = 300;++export const PaginatedModelSelect = ({+ value,+ onChange,+ placeholder = "Select a model",+ style,+ pageSize = 50,+ allowClear = true,+ disabled = false,+}: PaginatedModelSelectProps) => {+ const [searchInput, setSearchInput] = useState("");+ const [debouncedSearch, setDebouncedSearch] = useDebouncedState("", {+ wait: DEBOUNCE_MS,+ });++ const {+ data,+ fetchNextPage,+ hasNextPage,+ isFetchingNextPage,+ isLoading,+ } = useInfiniteModelInfo(pageSize, debouncedSearch || undefined);++ const options = useMemo(() => {+ if (!data?.pages) return [];++ const seen = new Set<string>();+ const result: { label: string; value: string; modelName: string; modelId: string }[] = [];++ for (const page of data.pages) {+ for (const model of page.data) {+ const modelId = model.model_info?.id ?? "";+ const modelName = model.model_name ?? "";++ // Dedupe by id - skip models without id (can't uniquely identify)+ if (!modelId || seen.has(modelId)) continue;+ seen.add(modelId);++ result.push({+ label: modelName ? `${modelName} (${modelId})` : modelId,+ value: modelId,+ modelName,+ modelId,+ });+ }+ }++ return result;+ }, [data]);++ const optionRender = (option: { data: { modelName: string; modelId: string; label: string } }) => {+ const { modelName, modelId } = option.data;++ return (+ <Space direction="vertical">+ {modelName ? (+ <>+ <Space direction="horizontal">+ <Text strong>Model name:</Text>+ <Text>{modelName}</Text>+ </Space>+ <Text type="secondary" >+ Model ID: {modelId}+ </Text>+ </>+ ) : (+ <Text type="secondary">Model ID: {modelId}</Text>+ )}+ </Space>+ );+ };++ const handlePopupScroll = (e: UIEvent<HTMLDivElement>) => {+ const target = e.currentTarget;+ const scrollRatio =+ (target.scrollTop + target.clientHeight) / target.scrollHeight;++ if (scrollRatio >= SCROLL_THRESHOLD && hasNextPage && !isFetchingNextPage) {+ fetchNextPage();+ }+ };++ const handleSearch = (value: string) => {+ setSearchInput(value);+ setDebouncedSearch(value);+ };++ const handleChange = (v: string | string[] | null) => {+ const normalized =+ typeof v === "string" ? v : Array.isArray(v) ? v[0] ?? "" : "";+ onChange?.(normalized);+ };++ return (+ <Select+ value={value || undefined}+ onChange={handleChange}+ placeholder={placeholder}+ style={{ width: "100%", ...style }}+ allowClear={allowClear}+ disabled={disabled}+ showSearch+ filterOption={false}+ onSearch={handleSearch}+ searchValue={searchInput}+ onPopupScroll={handlePopupScroll}+ loading={isLoading}+ notFoundContent={isLoading ? <LoadingOutlined spin /> : "No models found"}+ options={options}+ optionRender={optionRender}+ popupRender={(menu) => (+ <>+ {menu}+ {isFetchingNextPage && (+ <div style={{ textAlign: "center", padding: 8 }}>+ <LoadingOutlined spin />+ </div>+ )}+ </>+ )}+ />+ );+};diff --git a/ui/litellm-dashboard/src/components/molecules/filter.tsx b/ui/litellm-dashboard/src/components/molecules/filter.tsxindex a3a12fdf759..dcf22293f86 100644--- a/ui/litellm-dashboard/src/components/molecules/filter.tsx+++ b/ui/litellm-dashboard/src/components/molecules/filter.tsx@@ -1,7 +1,13 @@-import React, { useState, useCallback, useEffect } from "react";-import { Button, Input, Select } from "antd";import { FilterIcon } from "@heroicons/react/outline";+import { Button, Input, Select } from "antd";import debounce from "lodash/debounce";+import React, { useCallback, useEffect, useState } from "react";++export interface FilterOptionCustomComponentProps {+ value?: string;+ onChange: (value: string) => void;+ placeholder?: string;+}export interface FilterOption {name: string;@@ -9,6 +15,7 @@ export interface FilterOption {isSearchable?: boolean;searchFn?: (searchText: string) => Promise<Array<{ label: string; value: string }>>;options?: Array<{ label: string; value: string }>;+ customComponent?: React.ComponentType<FilterOptionCustomComponentProps>;}interface FilterValues {@@ -194,6 +201,17 @@ const FilterComponent: React.FC<FilterComponentProps> = ({</Select.Option>))}</Select>+ ) : option.customComponent ? (+ (() => {+ const CustomComponent = option.customComponent;+ return (+ <CustomComponent+ value={tempValues[option.name] || undefined}+ onChange={(value) => handleFilterChange(option.name, value ?? "")}+ placeholder={`Select ${option.label || option.name}...`}+ />+ );+ })()) : (<InputclassName="w-full"diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsxindex 023c88c5e83..aa509c65aa4 100644--- a/ui/litellm-dashboard/src/components/networking.tsx+++ b/ui/litellm-dashboard/src/components/networking.tsx@@ -2593,6 +2593,7 @@ export const uiSpendLogsCall = async (end_user?: string,status_filter?: string,model?: string,+ modelId?: string,keyAlias?: string,error_code?: string,error_message?: string,@@ -2614,6 +2615,7 @@ export const uiSpendLogsCall = async (if (end_user) queryParams.append("end_user", end_user);if (status_filter) queryParams.append("status_filter", status_filter);if (model) queryParams.append("model", model);+ if (modelId) queryParams.append("model_id", modelId);if (keyAlias) queryParams.append("key_alias", keyAlias);if (error_code) queryParams.append("error_code", error_code);if (error_message) queryParams.append("error_message", error_message);diff --git a/ui/litellm-dashboard/src/components/view_logs/index.tsx b/ui/litellm-dashboard/src/components/view_logs/index.tsxindex b791663cee3..b43ff5220db 100644--- a/ui/litellm-dashboard/src/components/view_logs/index.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/index.tsx@@ -10,29 +10,30 @@ import { Row } from "@tanstack/react-table";import { Switch, Tab, TabGroup, TabList, TabPanel, TabPanels } from "@tremor/react";import { Button, Tooltip } from "antd";import { internalUserRoles } from "../../utils/roles";+import NewBadge from "../common_components/NewBadge";import DeletedKeysPage from "../DeletedKeysPage/DeletedKeysPage";import DeletedTeamsPage from "../DeletedTeamsPage/DeletedTeamsPage";import { fetchAllKeyAliases } from "../key_team_helpers/filter_helpers";import { KeyResponse, Team } from "../key_team_helpers/key_list";+import { PaginatedModelSelect } from "../ModelSelect/PaginatedModelSelect/PaginatedModelSelect";import FilterComponent, { FilterOption } from "../molecules/filter";import { allEndUsersCall, keyInfoV1Call, keyListCall, sessionSpendLogsCall, uiSpendLogsCall } from "../networking";import KeyInfoView from "../templates/key_info_view";import AuditLogs from "./audit_logs";import { columns, LogEntry } from "./columns";import { ConfigInfoMessage } from "./ConfigInfoMessage";+import { ERROR_CODE_OPTIONS, QUICK_SELECT_OPTIONS } from "./constants";import { CostBreakdownViewer } from "./CostBreakdownViewer";import { ErrorViewer } from "./ErrorViewer";import { useLogFilterLogic } from "./log_filter_logic";+import { LogDetailsDrawer } from "./LogDetailsDrawer";import { getTimeRangeDisplay } from "./logs_utils";import { prefetchLogDetails } from "./prefetch";-import { ERROR_CODE_OPTIONS, QUICK_SELECT_OPTIONS } from "./constants";import { RequestResponsePanel } from "./RequestResponsePanel";import { SessionView } from "./SessionView";import SpendLogsSettingsModal from "./SpendLogsSettingsModal/SpendLogsSettingsModal";import { DataTable } from "./table";import { VectorStoreViewer } from "./VectorStoreViewer";-import NewBadge from "../common_components/NewBadge";-import { LogDetailsDrawer } from "./LogDetailsDrawer";interface SpendLogsTableProps {accessToken: string | null;@@ -205,7 +206,8 @@ export default function SpendLogsTable({filterByCurrentUser ? userID : undefined,selectedEndUser,selectedStatus,- selectedModel,+ undefined,+ selectedModel || undefined,);// Trigger prefetch for all logs@@ -404,7 +406,7 @@ export default function SpendLogsTable({{name: "Model",label: "Model",- isSearchable: false,+ customComponent: PaginatedModelSelect,},{name: "Key Alias",diff --git a/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.tsx b/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.tsxindex 628a2ecfd57..85eea0a8272 100644--- a/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.tsx@@ -96,6 +96,7 @@ export function useLogFilterLogic({filters[FILTER_KEYS.USER_ID] || undefined,filters[FILTER_KEYS.END_USER] || undefined,filters[FILTER_KEYS.STATUS] || undefined,+ undefined,filters[FILTER_KEYS.MODEL] || undefined,filters[FILTER_KEYS.KEY_ALIAS] || undefined,filters[FILTER_KEYS.ERROR_CODE] || undefined,