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]

fix(all_keys_table.tsx): fix filtering on key alias across multiple p… (#10455)

Krish Dholakiac0a464e4eb75
diff --git a/.circleci/config.yml b/.circleci/config.yml
index a1d668fa273..a88e577e174 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -833,6 +833,7 @@ jobs:
pip install "hypercorn==0.17.3"
pip install "pydantic==2.10.2"
pip install "mcp==1.5.0"
+ pip install "requests-mock==1.12.1"
# Run pytest and generate JUnit XML report
- run:
name: Run tests
diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py
index 449b00ebbcf..89d0284750d 100644
--- a/litellm/proxy/management_endpoints/key_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py
@@ -664,6 +664,7 @@ def prepare_key_update_data(
and len(budget_duration) > 0
):
from litellm.proxy.common_utils.timezone_utils import get_budget_reset_time
+
key_reset_at = get_budget_reset_time(budget_duration=budget_duration)
non_default_values["budget_reset_at"] = key_reset_at
non_default_values["budget_duration"] = budget_duration
@@ -2004,6 +2005,11 @@ async def list_keys(
include_team_keys: bool = Query(
False, description="Include all keys for teams that user is an admin of."
),
+ sort_by: Optional[str] = Query(
+ default=None,
+ description="Column to sort by (e.g. 'user_id', 'created_at', 'spend')",
+ ),
+ sort_order: str = Query(default="desc", description="Sort order ('asc' or 'desc')"),
) -> KeyListResponseObject:
"""
List all keys for a given user / team / organization.
@@ -2061,6 +2067,8 @@ async def list_keys(
return_full_object=return_full_object,
organization_id=organization_id,
admin_team_ids=admin_team_ids,
+ sort_by=sort_by,
+ sort_order=sort_order,
)
verbose_proxy_logger.debug("Successfully prepared response")
@@ -2086,6 +2094,42 @@ async def list_keys(
)
+def _validate_sort_params(
+ sort_by: Optional[str], sort_order: str
+) -> Optional[Dict[str, str]]:
+ order_by: Dict[str, str] = {}
+
+ if sort_by is None:
+ return None
+ # Validate sort_by is a valid column
+ valid_columns = [
+ "spend",
+ "max_budget",
+ "created_at",
+ "updated_at",
+ "token",
+ "key_alias",
+ ]
+ if sort_by not in valid_columns:
+ raise HTTPException(
+ status_code=400,
+ detail={
+ "error": f"Invalid sort column. Must be one of: {', '.join(valid_columns)}"
+ },
+ )
+
+ # Validate sort_order
+ if sort_order.lower() not in ["asc", "desc"]:
+ raise HTTPException(
+ status_code=400,
+ detail={"error": "Invalid sort order. Must be 'asc' or 'desc'"},
+ )
+
+ order_by[sort_by] = sort_order.lower()
+
+ return order_by
+
+
async def _list_key_helper(
prisma_client: PrismaClient,
page: int,
@@ -2100,6 +2144,8 @@ async def _list_key_helper(
admin_team_ids: Optional[
List[str]
] = None, # New parameter for teams where user is admin
+ sort_by: Optional[str] = None,
+ sort_order: str = "desc",
) -> KeyListResponseObject:
"""
Helper function to list keys
@@ -2164,12 +2210,20 @@ async def _list_key_helper(
verbose_proxy_logger.debug(f"Pagination: skip={skip}, take={size}")
+ order_by: Optional[Dict[str, str]] = (
+ _validate_sort_params(sort_by, sort_order)
+ if sort_by is not None and isinstance(sort_by, str)
+ else None
+ )
+
# Fetch keys with pagination
keys = await prisma_client.db.litellm_verificationtoken.find_many(
where=where, # type: ignore
skip=skip, # type: ignore
take=size, # type: ignore
- order=[
+ order=order_by
+ if order_by
+ else [
{"created_at": "desc"},
{"token": "desc"}, # fallback sort
],
diff --git a/ui/litellm-dashboard/src/components/all_keys_table.tsx b/ui/litellm-dashboard/src/components/all_keys_table.tsx
index 54f9d647f8e..6812bb15df8 100644
--- a/ui/litellm-dashboard/src/components/all_keys_table.tsx
+++ b/ui/litellm-dashboard/src/components/all_keys_table.tsx
@@ -19,6 +19,23 @@ import { debounce } from "lodash";
import { defaultPageSize } from "./constants";
import { fetchAllTeams } from "./key_team_helpers/filter_helpers";
import { fetchAllOrganizations } from "./key_team_helpers/filter_helpers";
+import {
+ flexRender,
+ getCoreRowModel,
+ getSortedRowModel,
+ SortingState,
+ useReactTable,
+} from "@tanstack/react-table";
+import {
+ Table,
+ TableHead,
+ TableHeaderCell,
+ TableBody,
+ TableRow,
+ TableCell,
+} from "@tremor/react";
+import { SwitchVerticalIcon, ChevronUpIcon, ChevronDownIcon } from "@heroicons/react/outline";
+
interface AllKeysTableProps {
keys: KeyResponse[];
setKeys: Setter<KeyResponse[]>;
@@ -41,6 +58,11 @@ interface AllKeysTableProps {
organizations: Organization[] | null;
setCurrentOrg: React.Dispatch<React.SetStateAction<Organization | null>>;
refresh?: () => void;
+ onSortChange?: (sortBy: string, sortOrder: 'asc' | 'desc') => void;
+ currentSort?: {
+ sortBy: string;
+ sortOrder: 'asc' | 'desc';
+ };
}
// Define columns similar to our logs table
@@ -113,9 +135,24 @@ export function AllKeysTable({
organizations,
setCurrentOrg,
refresh,
+ onSortChange,
+ currentSort,
}: AllKeysTableProps) {
const [selectedKeyId, setSelectedKeyId] = useState<string | null>(null);
const [userList, setUserList] = useState<UserResponse[]>([]);
+ const [sorting, setSorting] = React.useState<SortingState>(() => {
+ if (currentSort) {
+ return [{
+ id: currentSort.sortBy,
+ desc: currentSort.sortOrder === 'desc'
+ }];
+ }
+ return [{
+ id: "created_at",
+ desc: true
+ }];
+ });
+
// Use the filter logic hook
const {
@@ -177,8 +214,9 @@ export function AllKeysTable({
) : null,
},
{
- header: "Key ID",
+ id: "token",
accessorKey: "token",
+ header: "Key ID",
cell: (info) => (
<div className="overflow-hidden">
<Tooltip title={info.getValue() as string}>
@@ -195,21 +233,24 @@ export function AllKeysTable({
),
},
{
- header: "Key Alias",
+ id: "key_alias",
accessorKey: "key_alias",
+ header: "Key Alias",
cell: (info) => {
const value = info.getValue() as string;
return <Tooltip title={value}>{value ? (value.length > 20 ? `${value.slice(0, 20)}...` : value) : "-"}</Tooltip>
}
},
{
- header: "Secret Key",
+ id: "key_name",
accessorKey: "key_name",
+ header: "Secret Key",
cell: (info) => <span className="font-mono text-xs">{info.getValue() as string}</span>,
},
{
+ id: "team_alias",
+ accessorKey: "team_id",
header: "Team Alias",
- accessorKey: "team_id", // Change to access the team_id
cell: ({ row, getValue }) => {
const teamId = getValue() as string;
const team = teams?.find(t => t.team_id === teamId);
@@ -217,18 +258,21 @@ export function AllKeysTable({
},
},
{
- header: "Team ID",
+ id: "team_id",
accessorKey: "team_id",
+ header: "Team ID",
cell: (info) => <Tooltip title={info.getValue() as string}>{info.getValue() ? `${(info.getValue() as string).slice(0, 7)}...` : "-"}</Tooltip>
},
{
- header: "Organization ID",
+ id: "organization_id",
accessorKey: "organization_id",
+ header: "Organization ID",
cell: (info) => info.getValue() ? info.renderValue() : "-",
},
{
- header: "User Email",
+ id: "user_email",
accessorKey: "user_id",
+ header: "User Email",
cell: (info) => {
const userId = info.getValue() as string;
const user = userList.find(u => u.user_id === userId);
@@ -236,8 +280,9 @@ export function AllKeysTable({
},
},
{
- header: "User ID",
+ id: "user_id",
accessorKey: "user_id",
+ header: "User ID",
cell: (info) => {
const userId = info.getValue() as string;
return userId ? (
@@ -248,53 +293,60 @@ export function AllKeysTable({
},
},
{
- header: "Created At",
+ id: "created_at",
accessorKey: "created_at",
+ header: "Created At",
cell: (info) => {
const value = info.getValue();
return value ? new Date(value as string).toLocaleDateString() : "-";
},
},
{
- header: "Created By",
+ id: "created_by",
accessorKey: "created_by",
+ header: "Created By",
cell: (info) => {
const value = info.getValue();
return value ? value : "Unknown";
},
},
{
- header: "Expires",
+ id: "expires",
accessorKey: "expires",
+ header: "Expires",
cell: (info) => {
const value = info.getValue();
return value ? new Date(value as string).toLocaleDateString() : "Never";
},
},
{
- header: "Spend (USD)",
+ id: "spend",
accessorKey: "spend",
+ header: "Spend (USD)",
cell: (info) => Number(info.getValue()).toFixed(4),
},
{
- header: "Budget (USD)",
+ id: "max_budget",
accessorKey: "max_budget",
+ header: "Budget (USD)",
cell: (info) =>
info.getValue() !== null && info.getValue() !== undefined
? info.getValue()
: "Unlimited",
},
{
- header: "Budget Reset",
+ id: "budget_reset_at",
accessorKey: "budget_reset_at",
+ header: "Budget Reset",
cell: (info) => {
const value = info.getValue();
return value ? new Date(value as string).toLocaleString() : "Never";
},
},
{
- header: "Models",
+ id: "models",
accessorKey: "models",
+ header: "Models",
cell: (info) => {
const models = info.getValue() as string[];
return (
@@ -316,6 +368,7 @@ export function AllKeysTable({
},
},
{
+ id: "rate_limits",
header: "Rate Limits",
cell: ({ row }) => {
const key = row.original;
@@ -397,25 +450,61 @@ export function AllKeysTable({
];
-
+ console.log(`keys: ${JSON.stringify(keys)}`)
+
+ const table = useReactTable({
+ data: filteredKeys,
+ columns: columns.filter(col => col.id !== 'expander'),
+ state: {
+ sorting,
+ },
+ onSortingChange: (updaterOrValue) => {
+ const newSorting = typeof updaterOrValue === 'function'
+ ? updaterOrValue(sorting)
+ : updaterOrValue;
+ console.log(`newSorting: ${JSON.stringify(newSorting)}`)
+ setSorting(newSorting);
+ if (newSorting && newSorting.length > 0) {
+ const sortState = newSorting[0];
+ const sortBy = sortState.id;
+ const sortOrder = sortState.desc ? 'desc' : 'asc';
+ console.log(`sortBy: ${sortBy}, sortOrder: ${sortOrder}`)
+ handleFilterChange({
+ ...filters,
+ 'Sort By': sortBy,
+ 'Sort Order': sortOrder
+ });
+ onSortChange?.(sortBy, sortOrder);
+ }
+ },
+ getCoreRowModel: getCoreRowModel(),
+ getSortedRowModel: getSortedRowModel(),
+ enableSorting: true,
+ manualSorting: false,
+ });
+
+ // Update local sorting state when currentSort prop changes
+ React.useEffect(() => {
+ if (currentSort) {
+ setSorting([{
+ id: currentSort.sortBy,
+ desc: currentSort.sortOrder === 'desc'
+ }]);
+ }
+ }, [currentSort]);
+
return (
<div className="w-full h-full overflow-hidden">
{selectedKeyId ? (
<KeyInfoView
keyId={selectedKeyId}
onClose={() => setSelectedKeyId(null)}
- keyData={keys.find(k => k.token === selectedKeyId)}
+ keyData={filteredKeys.find(k => k.token === selectedKeyId)}
onKeyDataUpdate={(updatedKeyData) => {
setKeys(keys => keys.map(key => {
if (key.token === updatedKeyData.token) {
- // The shape of key is different from that of
- // updatedKeyData(received from keyUpdateCall in networking.tsx).
- // Hence, we can't replace key with updatedKeys since it might lead
- // to unintended bugs/behaviors.
- // So instead, we only update fields that are present in both.
return updateExistingKeys(key, updatedKeyData)
}
-
return key
}))
}}
@@ -461,20 +550,91 @@ export function AllKeysTable({
</div>
</div>
<div className="h-[75vh] overflow-auto">
-
- <DataTable
- columns={columns.filter(col => col.id !== 'expander') as any}
- data={filteredKeys as any}
- isLoading={isLoading}
- loadingMessage="🚅 Loading keys..."
- noDataMessage="No keys found"
- getRowCanExpand={() => false}
- renderSubComponent={() => <></>}
- />
+ <div className="rounded-lg custom-border relative">
+ <div className="overflow-x-auto">
+ <Table className="[&_td]:py-0.5 [&_th]:py-1">
+ <TableHead>
+ {table.getHeaderGroups().map((headerGroup) => (
+ <TableRow key={headerGroup.id}>
+ {headerGroup.headers.map((header) => (
+ <TableHeaderCell
+ key={header.id}
+ className={`py-1 h-8 ${
+ header.id === 'actions'
+ ? 'sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]'
+ : ''
+ }`}
+ onClick={header.column.getToggleSortingHandler()}
+ >
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex items-center">
+ {header.isPlaceholder ? null : (
+ flexRender(
+ header.column.columnDef.header,
+ header.getContext()
+ )
+ )}
+ </div>
+ {header.id !== 'actions' && (
+ <div className="w-4">
+ {header.column.getIsSorted() ? (
+ {
+ asc: <ChevronUpIcon className="h-4 w-4 text-blue-500" />,
+ desc: <ChevronDownIcon className="h-4 w-4 text-blue-500" />
+ }[header.column.getIsSorted() as string]
+ ) : (
+ <SwitchVerticalIcon className="h-4 w-4 text-gray-400" />
+ )}
+ </div>
+ )}
+ </div>
+ </TableHeaderCell>
+ ))}
+ </TableRow>
+ ))}
+ </TableHead>
+ <TableBody>
+ {isLoading ? (
+ <TableRow>
+ <TableCell colSpan={columns.length} className="h-8 text-center">
+ <div className="text-center text-gray-500">
+ <p>🚅 Loading keys...</p>
+ </div>
+ </TableCell>
+ </TableRow>
+ ) : filteredKeys.length > 0 ? (
+ table.getRowModel().rows.map((row) => (
+ <TableRow key={row.id} className="h-8">
+ {row.getVisibleCells().map((cell) => (
+ <TableCell
+ key={cell.id}
+ className={`py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap ${
+ cell.column.id === 'actions'
+ ? 'sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]'
+ : ''
+ }`}
+ >
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ </TableCell>
+ ))}
+ </TableRow>
+ ))
+ ) : (
+ <TableRow>
+ <TableCell colSpan={columns.length} className="h-8 text-center">
+ <div className="text-center text-gray-500">
+ <p>No keys found</p>
+ </div>
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ </Table>
+ </div>
+ </div>
</div>
</div>
)}
-
</div>
);
}
\ No newline at end of file
diff --git a/ui/litellm-dashboard/src/components/key_team_helpers/filter_logic.tsx b/ui/litellm-dashboard/src/components/key_team_helpers/filter_logic.tsx
index 1ebca77461e..799f0e82063 100644
--- a/ui/litellm-dashboard/src/components/key_team_helpers/filter_logic.tsx
+++ b/ui/litellm-dashboard/src/components/key_team_helpers/filter_logic.tsx
@@ -14,6 +14,8 @@ export interface FilterState {
'Key Alias': string;
[key: string]: string;
'User ID': string;
+ 'Sort By': string;
+ 'Sort Order': string;
}
@@ -33,7 +35,9 @@ export function useFilterLogic({
'Team ID': '',
'Organization ID': '',
'Key Alias': '',
- 'User ID': ''
+ 'User ID': '',
+ 'Sort By': 'created_at',
+ 'Sort Order': 'desc'
}
const [filters, setFilters] = useState<FilterState>(defaultFilters);
const [allTeams, setAllTeams] = useState<Team[]>(teams || []);
@@ -59,7 +63,9 @@ export function useFilterLogic({
filters["User ID"] || null,
filters["Key Hash"] || null,
1, // Reset to first page when searching
- defaultPageSize
+ defaultPageSize,
+ filters["Sort By"] || null,
+ filters["Sort Order"] || null
);
// Only update state if this is the most recent search
@@ -157,7 +163,9 @@ export function useFilterLogic({
'Team ID': newFilters['Team ID'] || '',
'Organization ID': newFilters['Organization ID'] || '',
'Key Alias': newFilters['Key Alias'] || '',
- 'User ID': newFilters['User ID'] || ''
+ 'User ID': newFilters['User ID'] || '',
+ 'Sort By': newFilters['Sort By'] || 'created_at',
+ 'Sort Order': newFilters['Sort Order'] || 'desc'
});
// Fetch keys based on new filters
diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsx
index 4b649a946ee..2c112e29bee 100644
--- a/ui/litellm-dashboard/src/components/networking.tsx
+++ b/ui/litellm-dashboard/src/components/networking.tsx
@@ -2701,6 +2701,8 @@ export const keyListCall = async (
keyHash: string | null,
page: number,
pageSize: number,
+ sortBy: string | null = null,
+ sortOrder: string | null = null,
) => {
/**
* Get all available teams on proxy
@@ -2738,6 +2740,13 @@ export const keyListCall = async (
queryParams.append('size', pageSize.toString());
}
+ if (sortBy) {
+ queryParams.append('sort_by', sortBy);
+ }
+
+ if (sortOrder) {
+ queryParams.append('sort_order', sortOrder);
+ }
queryParams.append('return_full_object', 'true');
queryParams.append('include_team_keys', 'true');
diff --git a/ui/litellm-dashboard/src/components/view_key_table.tsx b/ui/litellm-dashboard/src/components/view_key_table.tsx
index 84b319a7076..c6f801b4911 100644
--- a/ui/litellm-dashboard/src/components/view_key_table.tsx
+++ b/ui/litellm-dashboard/src/components/view_key_table.tsx
@@ -280,42 +280,6 @@ const ViewKeyTable: React.FC<ViewKeyTableProps> = ({
fetchUserModels();
}, [accessToken, userID, userRole]);
- const handleModelLimitClick = (token: KeyResponse) => {
- setSelectedToken(token);
- setModelLimitModalVisible(true);
- };
-
- const handleModelLimitSubmit = async (updatedMetadata: any) => {
- if (accessToken == null || selectedToken == null) {
- return;
- }
-
- const formValues = {
- ...selectedToken,
- metadata: updatedMetadata,
- key: selectedToken.token,
- };
-
- try {
- let newKeyValues = await keyUpdateCall(accessToken, formValues);
- console.log("Model limits updated:", newKeyValues);
-
- // Update the keys with the updated key
- if (data) {
- const updatedData = data.map((key) =>
- key.token === selectedToken.token ? newKeyValues : key
- );
- setData(updatedData);
- }
- message.success("Model-specific limits updated successfully");
- } catch (error) {
- console.error("Error updating model-specific limits:", error);
- message.error("Failed to update model-specific limits");
- }
-
- setModelLimitModalVisible(false);
- setSelectedToken(null);
- };
useEffect(() => {
if (teams) {