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
filters working properly for team virtual keys
Alejandro Tapia6d98622923f9
diff --git a/ui/litellm-dashboard/src/components/key_team_helpers/filter_helpers.ts b/ui/litellm-dashboard/src/components/key_team_helpers/filter_helpers.tsindex fa12a75aacd..08eccc4ed2c 100644--- a/ui/litellm-dashboard/src/components/key_team_helpers/filter_helpers.ts+++ b/ui/litellm-dashboard/src/components/key_team_helpers/filter_helpers.ts@@ -1,7 +1,82 @@-import { teamListCall, organizationListCall, keyAliasesCall } from "../networking"+import { teamListCall, organizationListCall, keyAliasesCall, keyListCall } from "../networking";import { Team } from "./key_list";import { Organization } from "../networking";+export interface TeamFilterOptions {+ keyAliases: string[];+ organizationIds: string[];+ userIds: Array<{ id: string; email: string }>;+}++/**+ * Fetches filter options (key aliases, org IDs, user IDs) scoped to a team's keys.+ * Used by TeamVirtualKeysTable to show only relevant filter options.+ */+export const fetchTeamFilterOptions = async (+ accessToken: string | null,+ teamId: string,+): Promise<TeamFilterOptions> => {+ if (!accessToken || !teamId) {+ return { keyAliases: [], organizationIds: [], userIds: [] };+ }++ try {+ const keyAliases = new Set<string>();+ const organizationIds = new Set<string>();+ const userMap = new Map<string, string>(); // user_id -> user_email++ let page = 1;+ let totalPages = 1;++ do {+ const response = await keyListCall(+ accessToken,+ null,+ teamId,+ null,+ null,+ null,+ page,+ 100,+ null,+ null,+ "user",+ null,+ );++ const keys = response?.keys || [];+ totalPages = response?.total_pages ?? 1;++ for (const key of keys) {+ const alias = key?.key_alias;+ if (alias && typeof alias === "string") {+ keyAliases.add(alias.trim());+ }+ const orgId = key?.organization_id;+ if (orgId && typeof orgId === "string") {+ organizationIds.add(orgId.trim());+ }+ const userId = key?.user_id;+ if (userId && typeof userId === "string") {+ const email = key?.user?.user_email || userId;+ userMap.set(userId, email);+ }+ }++ page++;+ } while (page <= totalPages);++ return {+ keyAliases: Array.from(keyAliases).sort(),+ organizationIds: Array.from(organizationIds).sort(),+ userIds: Array.from(userMap.entries()).map(([id, email]) => ({ id, email })),+ };+ } catch (error) {+ console.error("Error fetching team filter options:", error);+ return { keyAliases: [], organizationIds: [], userIds: [] };+ }+};+/*** Fetches all key aliases via the dedicated /key/aliases endpoint* @param accessToken The access token for API authenticationdiff --git a/ui/litellm-dashboard/src/components/team/TeamInfo.test.tsx b/ui/litellm-dashboard/src/components/team/TeamInfo.test.tsxindex 75fe76902bd..317db7b37fd 100644--- a/ui/litellm-dashboard/src/components/team/TeamInfo.test.tsx+++ b/ui/litellm-dashboard/src/components/team/TeamInfo.test.tsx@@ -110,6 +110,11 @@ vi.mock("@/app/(dashboard)/hooks/keys/useKeys", () => ({}));vi.mock("../key_team_helpers/filter_helpers", () => ({+ fetchTeamFilterOptions: vi.fn().mockResolvedValue({+ keyAliases: [],+ organizationIds: [],+ userIds: [],+ }),fetchAllKeyAliases: vi.fn().mockResolvedValue([]),fetchAllOrganizations: vi.fn().mockResolvedValue([]),}));@@ -597,8 +602,22 @@ describe("TeamInfoView", () => {it("should display X Members in Virtual Keys tab when navigated to", async () => {const user = userEvent.setup();vi.mocked(networking.teamInfoCall).mockResolvedValue(createMockTeamData());+ const fiveKeys = Array.from({ length: 5 }, (_, i) => ({+ token: `sk-${i}`,+ token_id: `key-${i}`,+ key_alias: `key_${i}`,+ key_name: `sk-...${i}`,+ user_id: `user-${i}`,+ organization_id: null,+ user: { user_id: `user-${i}`, user_email: `user${i}@test.com` },+ created_at: "2024-01-01T00:00:00Z",+ team_id: "123",+ spend: 0,+ max_budget: 100,+ models: ["gpt-4"],+ }));mockUseKeys.mockReturnValue({- data: { keys: [], total_count: 5, current_page: 1, total_pages: 1 },+ data: { keys: fiveKeys, total_count: 5, current_page: 1, total_pages: 1 },isPending: false,isFetching: false,refetch: vi.fn(),@@ -619,6 +638,56 @@ describe("TeamInfoView", () => {});});+ it("should show Filters and pagination controls in Virtual Keys tab", async () => {+ const user = userEvent.setup();+ vi.mocked(networking.teamInfoCall).mockResolvedValue(createMockTeamData());+ mockUseKeys.mockReturnValue({+ data: {+ keys: [+ {+ token: "sk-1",+ token_id: "key-1",+ key_alias: "key1",+ key_name: "sk-...1",+ user_id: "user-1",+ organization_id: null,+ user: { user_id: "user-1", user_email: "[email protected]" },+ created_at: "2024-01-01T00:00:00Z",+ team_id: "123",+ spend: 0,+ max_budget: 100,+ models: ["gpt-4"],+ },+ ],+ total_count: 1,+ current_page: 1,+ total_pages: 1,+ },+ isPending: false,+ isFetching: false,+ refetch: vi.fn(),+ } as any);++ renderWithProviders(<TeamInfoView {...defaultProps} />);++ await waitFor(() => {+ const teamNameElements = screen.queryAllByText("Test Team");+ expect(teamNameElements.length).toBeGreaterThan(0);+ });++ const virtualKeysTab = screen.getByRole("tab", { name: "Virtual Keys" });+ await user.click(virtualKeysTab);++ await waitFor(() => {+ expect(screen.getByText("1 Member")).toBeInTheDocument();+ });+ expect(screen.getByRole("button", { name: "Filters" })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Reset Filters" })).toBeInTheDocument();+ expect(screen.getByText("Page 1 of 1")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Previous" })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Next" })).toBeInTheDocument();+ });+it("should display object permissions when present", async () => {vi.mocked(networking.teamInfoCall).mockResolvedValue(createMockTeamData({diff --git a/ui/litellm-dashboard/src/components/team/TeamVirtualKeysTable.test.tsx b/ui/litellm-dashboard/src/components/team/TeamVirtualKeysTable.test.tsxindex e4b7b00fb58..41df5611e07 100644--- a/ui/litellm-dashboard/src/components/team/TeamVirtualKeysTable.test.tsx+++ b/ui/litellm-dashboard/src/components/team/TeamVirtualKeysTable.test.tsx@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi, MockedFunction } from "vitest";import { renderWithProviders } from "../../../tests/test-utils";import { TeamVirtualKeysTable } from "./TeamVirtualKeysTable";import { KeysResponse, useKeys } from "@/app/(dashboard)/hooks/keys/useKeys";+import { fetchTeamFilterOptions } from "../key_team_helpers/filter_helpers";import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";import { KeyResponse } from "../key_team_helpers/key_list";import { Organization } from "../networking";@@ -17,8 +18,11 @@ vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({}));vi.mock("../key_team_helpers/filter_helpers", () => ({- fetchAllKeyAliases: vi.fn().mockResolvedValue([]),- fetchAllOrganizations: vi.fn().mockResolvedValue([]),+ fetchTeamFilterOptions: vi.fn().mockResolvedValue({+ keyAliases: [],+ organizationIds: [],+ userIds: [],+ }),}));vi.mock("../key_team_helpers/fetch_available_models_team_key", () => ({@@ -139,7 +143,7 @@ describe("TeamVirtualKeysTable", () => {});});- it("should call useKeys with expand user to fetch user email", async () => {+ it("should call useKeys with page, pageSize, and expand user for server-side pagination", async () => {renderWithProviders(<TeamVirtualKeysTable {...defaultProps} />);await waitFor(() => {@@ -189,4 +193,164 @@ describe("TeamVirtualKeysTable", () => {});expect(screen.getByText("Key ID")).toBeInTheDocument();});++ it("should display keys in table when data is loaded", async () => {+ mockUseKeys.mockReturnValue({+ data: {+ keys: [+ createMockKey({ key_alias: "alice_key_team1" }),+ createMockKey({ token: "sk-2", token_id: "key-2", key_alias: "bob_key_team1" }),+ ],+ total_count: 2,+ current_page: 1,+ total_pages: 1,+ } as KeysResponse,+ isPending: false,+ isFetching: false,+ refetch: vi.fn(),+ } as any);++ renderWithProviders(<TeamVirtualKeysTable {...defaultProps} />);++ await waitFor(() => {+ expect(screen.getByText("2 Members")).toBeInTheDocument();+ });+ expect(screen.getByText("alice_key_team1")).toBeInTheDocument();+ expect(screen.getByText("bob_key_team1")).toBeInTheDocument();+ });++ it("should show Page X of Y when multiple pages exist", async () => {+ mockUseKeys.mockReturnValue({+ data: {+ keys: [createMockKey()],+ total_count: 100,+ current_page: 1,+ total_pages: 3,+ } as KeysResponse,+ isPending: false,+ isFetching: false,+ refetch: vi.fn(),+ } as any);++ renderWithProviders(<TeamVirtualKeysTable {...defaultProps} />);++ await waitFor(() => {+ expect(screen.getByText("Page 1 of 3")).toBeInTheDocument();+ });+ expect(screen.getByText("100 Members")).toBeInTheDocument();+ });++ it("should fetch page 2 when Next is clicked", async () => {+ const user = userEvent.setup();+ mockUseKeys.mockImplementation((page: number) => ({+ data: {+ keys: page === 1 ? [createMockKey()] : [createMockKey({ token: "sk-page2", key_alias: "page2_key" })],+ total_count: 100,+ current_page: page,+ total_pages: 3,+ } as KeysResponse,+ isPending: false,+ isFetching: false,+ refetch: vi.fn(),+ } as any));++ renderWithProviders(<TeamVirtualKeysTable {...defaultProps} />);++ await waitFor(() => {+ expect(screen.getByText("Page 1 of 3")).toBeInTheDocument();+ });++ const nextButton = screen.getByRole("button", { name: "Next" });+ await user.click(nextButton);++ await waitFor(() => {+ expect(mockUseKeys).toHaveBeenLastCalledWith(+ 2,+ 50,+ expect.objectContaining({ teamID: "team-1" })+ );+ });+ });++ it("should show Loading keys when isPending", async () => {+ mockUseKeys.mockReturnValue({+ data: undefined,+ isPending: true,+ isFetching: true,+ refetch: vi.fn(),+ } as any);++ renderWithProviders(<TeamVirtualKeysTable {...defaultProps} />);++ await waitFor(() => {+ expect(screen.getByText("Loading keys...")).toBeInTheDocument();+ });+ });++ it("should show No keys found when keys array is empty", async () => {+ mockUseKeys.mockReturnValue({+ data: { keys: [], total_count: 0, current_page: 1, total_pages: 1 } as KeysResponse,+ isPending: false,+ isFetching: false,+ refetch: vi.fn(),+ } as any);++ renderWithProviders(<TeamVirtualKeysTable {...defaultProps} />);++ await waitFor(() => {+ expect(screen.getByText("0 Members")).toBeInTheDocument();+ });+ expect(screen.getByText("No keys found")).toBeInTheDocument();+ });++ it("should fetch team-scoped filter options for Key Alias, Organization ID, and User ID", async () => {+ const mockFetchTeamFilterOptions = vi.mocked(fetchTeamFilterOptions);+ mockFetchTeamFilterOptions.mockResolvedValue({+ keyAliases: ["alice_key_team1", "charlie_key_team1"],+ organizationIds: ["org-123"],+ userIds: [+ { id: "user-1", email: "[email protected]" },+ { id: "user-2", email: "[email protected]" },+ ],+ });++ // Use unique teamId to avoid cache hit from previous tests (refetchOnMount: false)+ renderWithProviders(+ <TeamVirtualKeysTable {...defaultProps} teamId="team-filter-options-test" />+ );++ await waitFor(() => {+ expect(mockFetchTeamFilterOptions).toHaveBeenCalledWith(+ "test-token",+ "team-filter-options-test"+ );+ });+ });++ it("should open Key Info View when key is clicked", async () => {+ mockUseKeys.mockReturnValue({+ data: {+ keys: [createMockKey({ token: "sk-click-me", key_alias: "clickable_key" })],+ total_count: 1,+ current_page: 1,+ total_pages: 1,+ } as KeysResponse,+ isPending: false,+ isFetching: false,+ refetch: vi.fn(),+ } as any);++ renderWithProviders(<TeamVirtualKeysTable {...defaultProps} />);++ await waitFor(() => {+ expect(screen.getByText("clickable_key")).toBeInTheDocument();+ });++ const keyButton = screen.getByRole("button", { name: /sk-click-me|clickable_key/ });+ await userEvent.click(keyButton);++ await waitFor(() => {+ expect(screen.getByText("Key Info View")).toBeInTheDocument();+ });+ });});diff --git a/ui/litellm-dashboard/src/components/team/TeamVirtualKeysTable.tsx b/ui/litellm-dashboard/src/components/team/TeamVirtualKeysTable.tsxindex ce998d18677..ddbffa118b1 100644--- a/ui/litellm-dashboard/src/components/team/TeamVirtualKeysTable.tsx+++ b/ui/litellm-dashboard/src/components/team/TeamVirtualKeysTable.tsx@@ -8,7 +8,6 @@ import {ColumnDef,flexRender,getCoreRowModel,- getPaginationRowModel,getSortedRowModel,PaginationState,SortingState,@@ -28,14 +27,14 @@ import {} from "@tremor/react";import { InfoCircleOutlined } from "@ant-design/icons";import { Popover, Skeleton, Tooltip } from "antd";-import React, { useEffect, useMemo, useState } from "react";+import React, { useCallback, useEffect, useMemo, useState } from "react";import { getModelDisplayName } from "../key_team_helpers/fetch_available_models_team_key";import { KeyResponse, Team } from "../key_team_helpers/key_list";import FilterComponent, { FilterOption } from "../molecules/filter";import { Organization } from "../networking";import KeyInfoView from "../templates/key_info_view";import { useQuery } from "@tanstack/react-query";-import { fetchAllKeyAliases, fetchAllOrganizations } from "../key_team_helpers/filter_helpers";+import { fetchTeamFilterOptions } from "../key_team_helpers/filter_helpers";import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";interface TeamVirtualKeysTableProps {@@ -69,22 +68,24 @@ export function TeamVirtualKeysTable({ teamId, teamAlias, organization }: TeamViconst sortBy = sorting.length > 0 ? sorting[0].id : "created_at";const sortOrder = sorting.length > 0 ? (sorting[0].desc ? "desc" : "asc") : "desc";+ const pageIndex = tablePagination.pageIndex;+ const pageSize = tablePagination.pageSize;+const {data: keys,isPending: isLoading,isFetching,refetch,- } = useKeys(tablePagination.pageIndex + 1, tablePagination.pageSize, {+ } = useKeys(pageIndex + 1, pageSize, {teamID: teamId,+ organizationID: filters["Organization ID"]?.trim() || undefined,+ selectedKeyAlias: filters["Key Alias"]?.trim() || undefined,+ userID: filters["User ID"]?.trim() || undefined,sortBy: sortBy || undefined,sortOrder: sortOrder || undefined,- organizationID: filters["Organization ID"] || undefined,- selectedKeyAlias: filters["Key Alias"] || undefined,- userID: filters["User ID"] || undefined,expand: "user",});- const totalCount = keys?.total_count || 0;const displayKeys = useMemo(() => {const kList = keys?.keys || [];const orgId = organization?.organization_id;@@ -94,6 +95,9 @@ export function TeamVirtualKeysTable({ teamId, teamAlias, organization }: TeamViorganization_id: k.organization_id || orgId,}));}, [keys?.keys, organization?.organization_id]);++ const totalCount = keys?.total_count ?? 0;+ const pageCount = keys?.total_pages ?? 0;const [expandedAccordions, setExpandedAccordions] = useState<Record<string, boolean>>({});const currentTeam: Team = useMemo(@@ -114,29 +118,27 @@ export function TeamVirtualKeysTable({ teamId, teamAlias, organization }: TeamVi[teamId, teamAlias, organization],);- const allKeyAliasesQuery = useQuery({- queryKey: ["allKeyAliases"],- queryFn: async () => fetchAllKeyAliases(accessToken),- enabled: !!accessToken,+ const teamFilterOptionsQuery = useQuery({+ queryKey: ["teamFilterOptions", teamId],+ queryFn: async () => fetchTeamFilterOptions(accessToken, teamId),+ enabled: !!accessToken && !!teamId,});- const allKeyAliases = allKeyAliasesQuery.data || [];+ const teamFilterOptions = teamFilterOptionsQuery.data || {+ keyAliases: [],+ organizationIds: [],+ userIds: [],+ };- const allOrganizationsQuery = useQuery({- queryKey: ["allOrganizations"],- queryFn: async () => fetchAllOrganizations(accessToken),- enabled: !!accessToken,- });- const allOrganizations = allOrganizationsQuery.data || [];+ const handleStorageChange = useCallback(() => {+ refetch?.();+ }, [refetch]);useEffect(() => {- if (refetch) {- const handleStorageChange = () => refetch();- window.addEventListener("storage", handleStorageChange);- return () => window.removeEventListener("storage", handleStorageChange);- }- }, [refetch]);+ window.addEventListener("storage", handleStorageChange);+ return () => window.removeEventListener("storage", handleStorageChange);+ }, [handleStorageChange]);- const handleFilterChange = (newFilters: Record<string, string>, skipDebounce = false) => {+ const handleFilterChange = useCallback((newFilters: Record<string, string>, skipDebounce = false) => {setFilters((prev) => ({...prev,"Organization ID": newFilters["Organization ID"] ?? prev["Organization ID"],@@ -148,9 +150,9 @@ export function TeamVirtualKeysTable({ teamId, teamAlias, organization }: TeamViif (!skipDebounce) {setTablePagination((prev) => ({ ...prev, pageIndex: 0 }));}- };+ }, []);- const handleFilterReset = () => {+ const handleFilterReset = useCallback(() => {setFilters({"Organization ID": "","Key Alias": "",@@ -159,7 +161,7 @@ export function TeamVirtualKeysTable({ teamId, teamAlias, organization }: TeamVi"Sort Order": "desc",});setTablePagination((prev) => ({ ...prev, pageIndex: 0 }));- };+ }, []);const filterOptions: FilterOption[] = useMemo(() => [@@ -168,16 +170,13 @@ export function TeamVirtualKeysTable({ teamId, teamAlias, organization }: TeamVilabel: "Organization ID",isSearchable: true,searchFn: async (searchText: string) => {- if (!allOrganizations.length) return [];- const filtered = allOrganizations.filter(- (org) => org.organization_id?.toLowerCase().includes(searchText.toLowerCase()) ?? false,- );- return filtered- .filter((org) => org.organization_id != null)- .map((org) => ({- label: `${org.organization_id || "Unknown"} (${org.organization_id})`,- value: org.organization_id as string,- }));+ const { organizationIds } = teamFilterOptions;+ if (!organizationIds.length) return [];+ const lower = searchText.toLowerCase();+ const filtered = lower+ ? organizationIds.filter((id) => id.toLowerCase().includes(lower))+ : organizationIds;+ return filtered.map((id) => ({ label: id, value: id }));},},{@@ -185,15 +184,35 @@ export function TeamVirtualKeysTable({ teamId, teamAlias, organization }: TeamVilabel: "Key Alias",isSearchable: true,searchFn: async (searchText: string) => {- const filtered = allKeyAliases.filter((alias) =>- alias.toLowerCase().includes(searchText.toLowerCase()),- );+ const { keyAliases } = teamFilterOptions;+ const lower = searchText.toLowerCase();+ const filtered = lower+ ? keyAliases.filter((alias) => alias.toLowerCase().includes(lower))+ : keyAliases;return filtered.map((alias) => ({ label: alias, value: alias }));},},- { name: "User ID", label: "User ID", isSearchable: false },+ {+ name: "User ID",+ label: "User ID",+ isSearchable: true,+ searchFn: async (searchText: string) => {+ const { userIds } = teamFilterOptions;+ const lower = searchText.toLowerCase();+ const filtered = lower+ ? userIds.filter(+ (u) =>+ u.id.toLowerCase().includes(lower) || u.email.toLowerCase().includes(lower),+ )+ : userIds;+ return filtered.map((u) => ({+ label: u.email ? `${u.id} (${u.email})` : u.id,+ value: u.id,+ }));+ },+ },],- [allOrganizations, allKeyAliases],+ [teamFilterOptions],);const columns: ColumnDef<KeyResponse>[] = useMemo(@@ -521,13 +540,8 @@ export function TeamVirtualKeysTable({ teamId, teamAlias, organization }: TeamVi[expandedAccordions],);- const table = useReactTable({- data: displayKeys,- columns,- columnResizeMode: "onChange",- columnResizeDirection: "ltr",- state: { sorting, pagination: tablePagination },- onSortingChange: (updaterOrValue) => {+ const handleSortingChange = useCallback(+ (updaterOrValue: React.SetStateAction<SortingState>) => {const newSorting =typeof updaterOrValue === "function" ? updaterOrValue(sorting) : updaterOrValue;setSorting(newSorting);@@ -535,7 +549,6 @@ export function TeamVirtualKeysTable({ teamId, teamAlias, organization }: TeamViconst sortState = newSorting[0];handleFilterChange({- ...filters,"Sort By": sortState.id,"Sort Order": sortState.desc ? "desc" : "asc",},@@ -543,17 +556,25 @@ export function TeamVirtualKeysTable({ teamId, teamAlias, organization }: TeamVi);}},+ [sorting, handleFilterChange],+ );++ const table = useReactTable({+ data: displayKeys,+ columns,+ columnResizeMode: "onChange",+ columnResizeDirection: "ltr",+ state: { sorting, pagination: tablePagination },+ onSortingChange: handleSortingChange,onPaginationChange: setTablePagination,getCoreRowModel: getCoreRowModel(),getSortedRowModel: getSortedRowModel(),- getPaginationRowModel: getPaginationRowModel(),enableSorting: true,manualSorting: false,manualPagination: true,- pageCount: Math.ceil(totalCount / tablePagination.pageSize),+ pageCount: pageCount,});- const { pageIndex, pageSize } = table.getState().pagination;return (<div className="w-full h-full overflow-hidden">{selectedKey ? (