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
Filter on logs table (#10644)
tanjiro959ba215851c
diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsxindex 6cfbd330900..4050ed2c82c 100644--- a/ui/litellm-dashboard/src/components/networking.tsx+++ b/ui/litellm-dashboard/src/components/networking.tsx@@ -4922,4 +4922,7 @@ export const vectorStoreInfoCall = async (console.error('Error getting vector store info:', error);throw error;}-};\ No newline at end of file+};++export { type UserInfo } from "./view_users/types"; // Re-export UserInfo+export { type Team } from "./key_team_helpers/key_list"; // Re-export Team\ No newline at end of filediff --git a/ui/litellm-dashboard/src/components/view_logs/index.tsx b/ui/litellm-dashboard/src/components/view_logs/index.tsxindex 8a4e280cbfe..9fab24c9a23 100644--- a/ui/litellm-dashboard/src/components/view_logs/index.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/index.tsx@@ -1,22 +1,28 @@import moment from "moment";-import { useQuery } from "@tanstack/react-query";-import { useState, useRef, useEffect } from "react";-import { useQueryClient } from "@tanstack/react-query";+import React, { useState, useRef, useEffect, useMemo } from "react";+import { useQueryClient, useQuery } from "@tanstack/react-query";+import { ColumnDef, Row } from "@tanstack/react-table";import { uiSpendLogsCall, keyInfoV1Call, sessionSpendLogsCall } from "../networking";import { DataTable } from "./table";-import { columns, LogEntry } from "./columns";-import { Row } from "@tanstack/react-table";+import { LogEntry } from "./columns";+import { getCountryFromIP } from "./ip_lookup";+import { CountryCell } from "./country_cell";+import { TimeCell } from "./time_cell";import { prefetchLogDetails } from "./prefetch";import { RequestResponsePanel } from "./columns";import { ErrorViewer } from './ErrorViewer';import { internalUserRoles } from "../../utils/roles";import { ConfigInfoMessage } from './ConfigInfoMessage';-import { Tooltip } from "antd";+import { Tooltip, Button as AntButton } from "antd";+import { Button } from "@tremor/react";import { KeyResponse, Team } from "../key_team_helpers/key_list";import KeyInfoView from "../key_info_view";import { SessionView } from './SessionView';import { VectorStoreViewer } from './VectorStoreViewer';+import FilterComponent from "../common_components/filter";+import { FilterOption } from "../common_components/filter";+import { useLogFilterLogic } from "./log_filter_logic";interface SpendLogsTableProps {accessToken: string | null;@@ -26,14 +32,6 @@ interface SpendLogsTableProps {allTeams: Team[];}-interface PaginatedResponse {- data: LogEntry[];- total: number;- page: number;- page_size: number;- total_pages: number;-}-interface PrefetchedLog {messages: any[];response: any;@@ -47,12 +45,7 @@ export default function SpendLogsTable({allTeams,}: SpendLogsTableProps) {const [searchTerm, setSearchTerm] = useState("");- const [showFilters, setShowFilters] = useState(false);- const [showColumnDropdown, setShowColumnDropdown] = useState(false);- const [currentPage, setCurrentPage] = useState(1);const [pageSize] = useState(50);- const dropdownRef = useRef<HTMLDivElement>(null);- const filtersRef = useRef<HTMLDivElement>(null);const quickSelectRef = useRef<HTMLDivElement>(null);// New state variables for Start and End Time@@ -66,22 +59,54 @@ export default function SpendLogsTable({// Add these new state variables at the top with other useState declarationsconst [isCustomDate, setIsCustomDate] = useState(false);const [quickSelectOpen, setQuickSelectOpen] = useState(false);- const [tempTeamId, setTempTeamId] = useState("");- const [tempKeyHash, setTempKeyHash] = useState("");- const [selectedTeamId, setSelectedTeamId] = useState("");- const [selectedKeyHash, setSelectedKeyHash] = useState("");const [selectedKeyInfo, setSelectedKeyInfo] = useState<KeyResponse | null>(null);const [selectedKeyIdInfoView, setSelectedKeyIdInfoView] = useState<string | null>(null);- const [selectedFilter, setSelectedFilter] = useState("Team ID");- const [filterByCurrentUser, setFilterByCurrentUser] = useState(- userRole && internalUserRoles.includes(userRole)- );-+const [expandedRequestId, setExpandedRequestId] = useState<string | null>(null);const [selectedSessionId, setSelectedSessionId] = useState<string | null>(null);const queryClient = useQueryClient();+ const {+ filters,+ filteredLogs,+ allTeams: hookAllTeams,+ allOrganizations,+ allUsers,+ allKeyAliases,+ handleFilterChange,+ handleFilterReset,+ isLoading,+ pagination,+ setCurrentPage,+ } = useLogFilterLogic({+ accessToken,+ startTime,+ endTime,+ pageSize,+ });++ const sessionLogs = useQuery<{data: LogEntry[]}>({+ queryKey: ["sessionLogs", selectedSessionId],+ queryFn: async () => {+ if (!accessToken || !selectedSessionId) return { data: [] };+ const response = await sessionSpendLogsCall(accessToken, selectedSessionId);+ return {+ data: response.data || response || [],+ };+ },+ enabled: !!accessToken && !!selectedSessionId,+ });++ useEffect(() => {+ if (filteredLogs && expandedRequestId) {+ const stillExists = filteredLogs.some((log: LogEntry) => log.request_id === expandedRequestId);+ if (!stillExists) {+ setExpandedRequestId(null);+ }+ }+ }, [filteredLogs, expandedRequestId]);+useEffect(() => {const fetchKeyInfo = async () => {if (selectedKeyIdInfoView && accessToken) {@@ -102,18 +127,6 @@ export default function SpendLogsTable({// Close dropdown when clicking outsideuseEffect(() => {function handleClickOutside(event: MouseEvent) {- if (- dropdownRef.current &&- !dropdownRef.current.contains(event.target as Node)- ) {- setShowColumnDropdown(false);- }- if (- filtersRef.current &&- !filtersRef.current.contains(event.target as Node)- ) {- setShowFilters(false);- }if (quickSelectRef.current &&!quickSelectRef.current.contains(event.target as Node)@@ -127,154 +140,39 @@ export default function SpendLogsTable({document.removeEventListener("mousedown", handleClickOutside);}, []);-- useEffect(() => {- if (userRole && internalUserRoles.includes(userRole)) {- setFilterByCurrentUser(true);- }- }, [userRole]);-- const logs = useQuery<PaginatedResponse>({- queryKey: [- "logs",- "table",- currentPage,- pageSize,- startTime,- endTime,- selectedTeamId,- selectedKeyHash,- filterByCurrentUser ? userID : null,- ],- queryFn: async () => {- if (!accessToken || !token || !userRole || !userID) {- console.log("Missing required auth parameters");- return {- data: [],- total: 0,- page: 1,- page_size: pageSize,- total_pages: 0,- };- }-- const formattedStartTime = moment(startTime).utc().format("YYYY-MM-DD HH:mm:ss");- const formattedEndTime = isCustomDate- ? moment(endTime).utc().format("YYYY-MM-DD HH:mm:ss")- : moment().utc().format("YYYY-MM-DD HH:mm:ss");-- // Get base response from API- const response = await uiSpendLogsCall(- accessToken,- selectedKeyHash || undefined,- selectedTeamId || undefined,- undefined,- formattedStartTime,- formattedEndTime,- currentPage,- pageSize,- filterByCurrentUser ? userID : undefined- );-- // Trigger prefetch for all logs- await prefetchLogDetails(- response.data,- formattedStartTime,- accessToken,- queryClient- );-- // Update logs with prefetched data if available- response.data = response.data.map((log: LogEntry) => {- const prefetchedData = queryClient.getQueryData<PrefetchedLog>(- ["logDetails", log.request_id, formattedStartTime]- );-- if (prefetchedData?.messages && prefetchedData?.response) {- log.messages = prefetchedData.messages;- log.response = prefetchedData.response;- return log;- }- return log;- });-- return response;- },- enabled: !!accessToken && !!token && !!userRole && !!userID,- refetchInterval: 5000,- refetchIntervalInBackground: true,- });-- // Fetch logs for a session if selected- const sessionLogs = useQuery<PaginatedResponse>({- queryKey: ["sessionLogs", selectedSessionId],- queryFn: async () => {- if (!accessToken || !selectedSessionId) return { data: [], total: 0, page: 1, page_size: 50, total_pages: 1 };- const response = await sessionSpendLogsCall(accessToken, selectedSessionId);- // If the API returns an array, wrap it in the same shape as PaginatedResponse- return {- data: response.data || response || [],- total: (response.data || response || []).length,- page: 1,- page_size: 1000,- total_pages: 1,- };- },- enabled: !!accessToken && !!selectedSessionId,- });-- // Add this effect to preserve expanded state when data refreshes- useEffect(() => {- if (logs.data?.data && expandedRequestId) {- // Check if the expanded request ID still exists in the new data- const stillExists = logs.data.data.some(log => log.request_id === expandedRequestId);- if (!stillExists) {- // If the request ID no longer exists in the data, clear the expanded state- setExpandedRequestId(null);- }- }- }, [logs.data?.data, expandedRequestId]);-- if (!accessToken || !token || !userRole || !userID) {+ if (!accessToken || !userID) {console.log(- "got None values for one of accessToken, token, userRole, userID",+ "Missing accessToken or userID",);return null;}- const filteredData =- logs.data?.data?.filter((log) => {- const matchesSearch =- !searchTerm ||- log.request_id.includes(searchTerm) ||- log.model.includes(searchTerm) ||- (log.user && log.user.includes(searchTerm));-- // No need for additional filtering since we're now handling this in the API call- return matchesSearch;-- }).map(log => ({- ...log,- onKeyHashClick: (keyHash: string) => setSelectedKeyIdInfoView(keyHash),- onSessionClick: (sessionId: string) => {- if (sessionId) setSelectedSessionId(sessionId);- },- })) || [];+ const processedLogs = filteredLogs.filter((log: LogEntry) => {+ const matchesSearch =+ !searchTerm ||+ log.request_id.includes(searchTerm) ||+ log.model.includes(searchTerm) ||+ (log.user && log.user.includes(searchTerm));+ return matchesSearch;+ }).map((log: LogEntry) => ({+ ...log,+ onKeyHashClick: (keyHash: string) => setSelectedKeyIdInfoView(keyHash),+ onSessionClick: (sessionId: string) => {+ if (sessionId) setSelectedSessionId(sessionId);+ },+ }));- // For session logs, add onKeyHashClick/onSessionClick as wellconst sessionData =- sessionLogs.data?.data?.map(log => ({+ sessionLogs.data?.data?.map((log: LogEntry) => ({...log,onKeyHashClick: (keyHash: string) => setSelectedKeyIdInfoView(keyHash),onSessionClick: (sessionId: string) => {},})) || [];- // Add this function to handle manual refreshconst handleRefresh = () => {- logs.refetch();+ queryClient.invalidateQueries({ queryKey: ['logs', 'table', accessToken, startTime, endTime, filters] });};- // Add this function to format the time range displayconst getTimeRangeDisplay = () => {if (isCustomDate) {return `${moment(startTime).format('MMM D, h:mm A')} - ${moment(endTime).format('MMM D, h:mm A')}`;@@ -298,7 +196,298 @@ export default function SpendLogsTable({setExpandedRequestId(requestId);};- // When a session is selected, render the SessionView component+ const logFilterOptions: FilterOption[] = [+ {+ name: 'Team ID',+ label: 'Team ID',+ isSearchable: true,+ searchFn: async (searchText: string) => {+ if (!hookAllTeams || hookAllTeams.length === 0) return [];+ const filtered = hookAllTeams.filter((team: Team) =>{+ console.log("team", searchText)+ return team.team_id.toLowerCase().includes(searchText.toLowerCase()) ||+ (team.team_alias && team.team_alias.toLowerCase().includes(searchText.toLowerCase()))+ });+ return filtered.map((team: Team) => ({+ label: `${team.team_alias || team.team_id} (${team.team_id})`,+ value: team.team_id+ }));+ }+ },+ // {+ // name: 'Key Alias',+ // label: 'Key Alias',+ // isSearchable: true,+ // searchFn: async (searchText: string) => {+ // const filteredKeyAliases = allKeyAliases.filter(key => {+ // console.log("key", searchText);+ // return key.toLowerCase().includes(searchText.toLowerCase())+ // });++ // return filteredKeyAliases.map((key) => {+ // return {+ // label: key,+ // value: key+ // }+ // });+ // }+ // },+ // {+ // name: 'Key Hash',+ // label: 'Key Hash',+ // isSearchable: false,+ // },+ // {+ // name: 'Request ID',+ // label: 'Request ID',+ // isSearchable: false,+ // },+ // {+ // name: 'Model',+ // label: 'Model',+ // isSearchable: false,+ // },+ // {+ // name: 'User',+ // label: 'User',+ // isSearchable: true,+ // searchFn: async (searchText: string) => {+ // if (!allUsers || allUsers.length === 0) return [];+ // const filtered = allUsers.filter((user: UserInfo) =>+ // (user.user_id && user.user_id.toLowerCase().includes(searchText.toLowerCase())) ||+ // (user.user_email && user.user_email.toLowerCase().includes(searchText.toLowerCase()))+ // );+ // return filtered.map((user: UserInfo) => ({+ // label: `${user.user_email || user.user_id} (${user.user_id})`,+ // value: user.user_id+ // }));+ // }+ // },+ ];++ if (selectedSessionId && sessionLogs.data) {+ return (+ <div className="w-full p-6">+ <SessionView+ sessionId={selectedSessionId}+ logs={sessionLogs.data.data}+ onBack={() => setSelectedSessionId(null)}+ />+ </div>+ );+ }++ const columns: ColumnDef<LogEntry>[] = [+ {+ id: "expander",+ header: () => null,+ cell: ({ row }) => {+ const ExpanderCell = () => {+ const [localExpanded, setLocalExpanded] = React.useState(row.getIsExpanded());+ const toggleHandler = React.useCallback(() => {+ setLocalExpanded((prev) => !prev);+ row.getToggleExpandedHandler()();+ }, [row]);++ return row.getCanExpand() ? (+ <button+ onClick={toggleHandler}+ style={{ cursor: "pointer" }}+ aria-label={localExpanded ? "Collapse row" : "Expand row"}+ className="w-6 h-6 flex items-center justify-center focus:outline-none"+ >+ <svg+ className={`w-4 h-4 transform transition-transform duration-75 ${+ localExpanded ? 'rotate-90' : ''+ }`}+ fill="none"+ stroke="currentColor"+ viewBox="0 0 24 24"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth={2}+ d="M9 5l7 7-7 7"+ />+ </svg>+ </button>+ ) : (+ <span className="w-6 h-6 flex items-center justify-center">●</span>+ );+ };+ return <ExpanderCell />;+ },+ },+ {+ header: "Time",+ accessorKey: "startTime",+ cell: (info: any) => <TimeCell utcTime={info.getValue()} />,+ },+ {+ header: "Status",+ accessorFn: (row) => row.metadata?.status || "Success",+ cell: (info: any) => {+ const status = info.getValue() as string;+ const isSuccess = status.toLowerCase() !== "failure";+ return (+ <span className={`px-2 py-1 rounded-md text-xs font-medium inline-block text-center w-16 ${+ isSuccess+ ? 'bg-green-100 text-green-800'+ : 'bg-red-100 text-red-800'+ }`}>+ {isSuccess ? "Success" : "Failure"}+ </span>+ );+ },+ },+ {+ header: "Session ID",+ accessorKey: "session_id",+ cell: (info: any) => {+ const value = String(info.getValue() || "");+ const onSessionClick = info.row.original.onSessionClick;+ return value ? (+ <Tooltip title={value}>+ <Button+ size="xs"+ variant="light"+ className="font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal text-xs max-w-[15ch] truncate block"+ onClick={() => onSessionClick?.(value)}+ >+ {value}+ </Button>+ </Tooltip>+ ) : "-";+ },+ },+ {+ header: "Request ID",+ accessorKey: "request_id",+ cell: (info: any) => (+ <Tooltip title={String(info.getValue() || "")}>+ <span className="font-mono text-xs max-w-[15ch] truncate block">+ {String(info.getValue() || "")}+ </span>+ </Tooltip>+ ),+ },+ {+ header: "Cost",+ accessorKey: "spend",+ cell: (info: any) => (+ <span>${Number(info.getValue() || 0).toFixed(6)}</span>+ ),+ },+ {+ header: "Country",+ accessorKey: "requester_ip_address",+ cell: (info: any) => <CountryCell ipAddress={info.getValue()} />,+ },+ {+ header: "Team Name",+ accessorKey: "team_id",+ cell: ({ row }) => {+ const teamId = row.original.team_id;+ if (!teamId) return "-";+ const team = hookAllTeams.find(t => t.team_id === teamId);+ const teamDisplayName = team?.team_alias || teamId;+ const truncatedName = teamDisplayName.length > 20+ ? `${teamDisplayName.slice(0, 20)}...`+ : teamDisplayName;++ return (+ <Tooltip title={teamDisplayName}>+ <span className="max-w-[15ch] truncate block">{truncatedName}</span>+ </Tooltip>+ );+ },+ },+ {+ header: "Key Hash",+ accessorFn: (row) => row.metadata?.user_api_key || "-",+ cell: (info: any) => {+ const value = String(info.getValue());+ const onKeyHashClick = info.row.original.onKeyHashClick;+ return value !== "-" ? (+ <Tooltip title={value}>+ <span+ className="font-mono max-w-[15ch] truncate block cursor-pointer hover:text-blue-600"+ onClick={() => onKeyHashClick?.(value)}+ >+ {value}+ </span>+ </Tooltip>+ ) : "-";+ },+ },+ {+ header: "Key Name",+ accessorFn: (row) => row.metadata?.user_api_key_alias || "-",+ cell: (info: any) => (+ <Tooltip title={String(info.getValue())}>+ <span className="max-w-[15ch] truncate block">{String(info.getValue())}</span>+ </Tooltip>+ ),+ },+ {+ header: "User",+ accessorKey: "user",+ cell: (info: any) => (+ <Tooltip title={String(info.getValue() || "-")}>+ <span className="max-w-[15ch] truncate block">{String(info.getValue() || "-")}</span>+ </Tooltip>+ ),+ },+ {+ header: "End User",+ accessorKey: "end_user",+ cell: (info: any) => (+ <Tooltip title={String(info.getValue() || "-")}>+ <span className="max-w-[15ch] truncate block">{String(info.getValue() || "-")}</span>+ </Tooltip>+ ),+ },+ {+ header: "Model",+ accessorKey: "model",+ cell: (info: any) => (+ <Tooltip title={String(info.getValue() || "-")}>+ <span className="max-w-[15ch] truncate block">{String(info.getValue() || "-")}</span>+ </Tooltip>+ ),+ },+ {+ header: "Provider",+ accessorKey: "custom_llm_provider",+ cell: (info: any) => (+ <Tooltip title={String(info.getValue() || "-")}>+ <span className="max-w-[15ch] truncate block">{String(info.getValue() || "-")}</span>+ </Tooltip>+ ),+ },+ {+ header: "Cache",+ accessorKey: "cache_hit",+ cell: (info: any) => info.getValue() || "-",+ },+ {+ header: "Tokens",+ accessorKey: "total_tokens",+ cell: (info: any) => {+ const total = info.row.original.total_tokens || 0;+ const prompt = info.row.original.prompt_tokens || 0;+ const completion = info.row.original.completion_tokens || 0;+ return (+ <Tooltip title={`Prompt: ${prompt}, Completion: ${completion}`}>+ <span>{total}</span>+ </Tooltip>+ );+ },+ },+ ];+if (selectedSessionId && sessionLogs.data) {return (<div className="w-full p-6">@@ -315,35 +504,14 @@ export default function SpendLogsTable({<div className="w-full p-6"><div className="flex items-center justify-between mb-4"><h1 className="text-xl font-semibold">- {selectedSessionId ? (- <>- Session: <span className="font-mono">{selectedSessionId}</span>- <button- className="ml-4 px-3 py-1 text-sm border rounded hover:bg-gray-50"- onClick={() => setSelectedSessionId(null)}- >- ← Back to All Logs- </button>- </>- ) : (- "Request Logs"- )}+ Request Logs</h1></div>{selectedKeyInfo && selectedKeyIdInfoView && selectedKeyInfo.api_key === selectedKeyIdInfoView ? (- <KeyInfoView keyId={selectedKeyIdInfoView} keyData={selectedKeyInfo} accessToken={accessToken} userID={userID} userRole={userRole} teams={allTeams} onClose={() => setSelectedKeyIdInfoView(null)} />- ) : selectedSessionId ? (- <div className="bg-white rounded-lg shadow">- <DataTable- columns={columns}- data={sessionData}- renderSubComponent={RequestViewer}- getRowCanExpand={() => true}- // Optionally: add session-specific row expansion state- />- </div>+ <KeyInfoView keyId={selectedKeyIdInfoView} keyData={selectedKeyInfo} accessToken={accessToken} userID={userID} userRole={userRole} teams={hookAllTeams} onClose={() => setSelectedKeyIdInfoView(null)} />) : (<>+ <FilterComponent options={logFilterOptions} onApplyFilters={handleFilterChange} onResetFilters={handleFilterReset} /><div className="bg-white rounded-lg shadow"><div className="border-b px-6 py-4"><div className="flex flex-col md:flex-row items-start md:items-center justify-between space-y-4 md:space-y-0">@@ -351,7 +519,7 @@ export default function SpendLogsTable({<div className="relative w-64"><inputtype="text"- placeholder="Search by Request ID"+ placeholder="Search by Request ID, Model, User"className="w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"value={searchTerm}onChange={(e) => setSearchTerm(e.target.value)}@@ -370,10 +538,13 @@ export default function SpendLogsTable({/></svg></div>- <div className="relative" ref={filtersRef}>+ </div>++ <div className="flex items-center gap-2">+ <div className="relative" ref={quickSelectRef}><button+ onClick={() => setQuickSelectOpen(!quickSelectOpen)}className="px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2"- onClick={() => setShowFilters(!showFilters)}><svgclassName="w-4 h-4"@@ -385,322 +556,121 @@ export default function SpendLogsTable({strokeLinecap="round"strokeLinejoin="round"strokeWidth={2}- d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"+ d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>- Filter+ {getTimeRangeDisplay()}</button>- {showFilters && (- <div className="absolute left-0 mt-2 w-[500px] bg-white rounded-lg shadow-lg border p-4 z-50">- <div className="flex flex-col gap-4">- <div className="flex items-center gap-2">- <span className="text-sm font-medium">Where</span>- <div className="relative">- <button- onClick={() => setShowColumnDropdown(!showColumnDropdown)}- className="px-3 py-1.5 border rounded-md bg-white text-sm min-w-[160px] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-left flex justify-between items-center"- >- {selectedFilter}- <svg- className="h-4 w-4 text-gray-500"- fill="none"- stroke="currentColor"- viewBox="0 0 24 24"- >- <path- strokeLinecap="round"- strokeLinejoin="round"- strokeWidth={2}- d="M19 9l-7 7-7-7"- />- </svg>- </button>- {showColumnDropdown && (- <div className="absolute left-0 mt-1 w-[160px] bg-white border rounded-md shadow-lg z-50">- {["Team ID", "Key Hash"].map((option) => (- <button- key={option}- className={`w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-2 ${- selectedFilter === option- ? "bg-blue-50 text-blue-600"- : ""- }`}- onClick={() => {- setSelectedFilter(option);- setShowColumnDropdown(false);- if (option === "Team ID") {- setTempKeyHash("");- } else {- setTempTeamId("");- }- }}- >- {selectedFilter === option && (- <svg- className="h-4 w-4 text-blue-600"- fill="none"- viewBox="0 0 24 24"- stroke="currentColor"- >- <path- strokeLinecap="round"- strokeLinejoin="round"- strokeWidth={2}- d="M5 13l4 4L19 7"- />- </svg>- )}- {option}- </button>- ))}- </div>- )}- </div>- <input- type="text"- placeholder="Enter value..."- className="px-3 py-1.5 border rounded-md text-sm flex-1 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"- value={selectedFilter === "Team ID" ? tempTeamId : tempKeyHash}- onChange={(e) => {- if (selectedFilter === "Team ID") {- setTempTeamId(e.target.value);- } else {- setTempKeyHash(e.target.value);- }- }}- />- <button- className="p-1 hover:bg-gray-100 rounded-md"- onClick={() => {- setTempTeamId("");- setTempKeyHash("");- }}- >- <span className="text-gray-500">×</span>- </button>- </div>-- <div className="flex justify-end gap-2">+ {quickSelectOpen && (+ <div className="absolute right-0 mt-2 w-64 bg-white rounded-lg shadow-lg border p-2 z-50">+ <div className="space-y-1">+ {[+ { label: "Last 15 Minutes", value: 15, unit: "minutes" },+ { label: "Last Hour", value: 1, unit: "hours" },+ { label: "Last 4 Hours", value: 4, unit: "hours" },+ { label: "Last 24 Hours", value: 24, unit: "hours" },+ { label: "Last 7 Days", value: 7, unit: "days" },+ ].map((option) => (<button- className="px-3 py-1.5 text-sm border rounded-md hover:bg-gray-50"- onClick={() => {- setTempTeamId("");- setTempKeyHash("");- setShowFilters(false);- }}- >- Cancel- </button>- <button- className="px-3 py-1.5 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700"+ key={option.label}+ className={`w-full px-3 py-2 text-left text-sm hover:bg-gray-50 rounded-md ${+ getTimeRangeDisplay() === option.label ? 'bg-blue-50 text-blue-600' : ''+ }`}onClick={() => {- setSelectedTeamId(tempTeamId);- setSelectedKeyHash(tempKeyHash);- setCurrentPage(1); // Reset to first page when applying new filters- setShowFilters(false);+ setEndTime(moment().format("YYYY-MM-DDTHH:mm"));+ setStartTime(+ moment()+ .subtract(option.value, option.unit as any)+ .format("YYYY-MM-DDTHH:mm")+ );+ setQuickSelectOpen(false);+ setIsCustomDate(false);}}>- Apply Filters+ {option.label}</button>- </div>+ ))}+ <div className="border-t my-2" />+ <button+ className={`w-full px-3 py-2 text-left text-sm hover:bg-gray-50 rounded-md ${+ isCustomDate ? 'bg-blue-50 text-blue-600' : ''+ }`}+ onClick={() => setIsCustomDate(!isCustomDate)}+ >+ Custom Range+ </button></div></div>)}</div>++ <button+ onClick={handleRefresh}+ className="px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2"+ title="Refresh data"+ >+ <svg+ className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`}+ fill="none"+ stroke="currentColor"+ viewBox="0 0 24 24"+ >+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth={2}+ d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"+ />+ </svg>+ <span>Refresh</span>+ </button>+ </div>+ {isCustomDate && (<div className="flex items-center gap-2">- <div className="relative" ref={quickSelectRef}>- <button- onClick={() => setQuickSelectOpen(!quickSelectOpen)}- className="px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2"- >- <svg- className="w-4 h-4"- fill="none"- stroke="currentColor"- viewBox="0 0 24 24"- >- <path- strokeLinecap="round"- strokeLinejoin="round"- strokeWidth={2}- d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"- />- </svg>- {getTimeRangeDisplay()}- </button>-- {quickSelectOpen && (- <div className="absolute right-0 mt-2 w-64 bg-white rounded-lg shadow-lg border p-2 z-50">- <div className="space-y-1">- {[- { label: "Last 15 Minutes", value: 15, unit: "minutes" },- { label: "Last Hour", value: 1, unit: "hours" },- { label: "Last 4 Hours", value: 4, unit: "hours" },- { label: "Last 24 Hours", value: 24, unit: "hours" },- { label: "Last 7 Days", value: 7, unit: "days" },- ].map((option) => (- <button- key={option.label}- className={`w-full px-3 py-2 text-left text-sm hover:bg-gray-50 rounded-md ${- getTimeRangeDisplay() === option.label ? 'bg-blue-50 text-blue-600' : ''- }`}- onClick={() => {- setEndTime(moment().format("YYYY-MM-DDTHH:mm"));- setStartTime(- moment()- .subtract(option.value, option.unit as any)- .format("YYYY-MM-DDTHH:mm")- );- setQuickSelectOpen(false);- setIsCustomDate(false);- }}- >- {option.label}- </button>- ))}- <div className="border-t my-2" />- <button- className={`w-full px-3 py-2 text-left text-sm hover:bg-gray-50 rounded-md ${- isCustomDate ? 'bg-blue-50 text-blue-600' : ''- }`}- onClick={() => setIsCustomDate(!isCustomDate)}- >- Custom Range- </button>- </div>- </div>- )}+ <div>+ <input+ type="datetime-local"+ value={startTime}+ onChange={(e) => {+ setStartTime(e.target.value);+ setCurrentPage(1);+ }}+ className="px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"+ /></div>-- <button- onClick={handleRefresh}- className="px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2"- title="Refresh data"- >- <svg- className={`w-4 h-4 ${logs.isFetching ? 'animate-spin' : ''}`}- fill="none"- stroke="currentColor"- viewBox="0 0 24 24"- >- <path- strokeLinecap="round"- strokeLinejoin="round"- strokeWidth={2}- d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"- />- </svg>- <span>Refresh</span>- </button>- </div>-- {isCustomDate && (- <div className="flex items-center gap-2">- <div>- <input- type="datetime-local"- value={startTime}- onChange={(e) => {- setStartTime(e.target.value);- setCurrentPage(1);- }}- className="px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"- />- </div>- <span className="text-gray-500">to</span>- <div>- <input- type="datetime-local"- value={endTime}- onChange={(e) => {- setEndTime(e.target.value);- setCurrentPage(1);- }}- className="px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"- />- </div>+ <span className="text-gray-500">to</span>+ <div>+ <input+ type="datetime-local"+ value={endTime}+ onChange={(e) => {+ setEndTime(e.target.value);+ setCurrentPage(1);+ }}+ className="px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"+ /></div>- )}- </div>-- <div className="flex items-center space-x-4">- <span className="text-sm text-gray-700">- Showing{" "}- {logs.isLoading- ? "..."- : logs.data- ? (currentPage - 1) * pageSize + 1- : 0}{" "}- -{" "}- {logs.isLoading- ? "..."- : logs.data- ? Math.min(currentPage * pageSize, logs.data.total)- : 0}{" "}- of{" "}- {logs.isLoading- ? "..."- : logs.data- ? logs.data.total- : 0}{" "}- results- </span>- <div className="flex items-center space-x-2">- <span className="text-sm text-gray-700">- Page {logs.isLoading ? "..." : currentPage} of{" "}- {logs.isLoading- ? "..."- : logs.data- ? logs.data.total_pages- : 1}- </span>- <button- onClick={() =>- setCurrentPage((p) => Math.max(1, p - 1))- }- disabled={logs.isLoading || currentPage === 1}- className="px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"- >- Previous- </button>- <button- onClick={() =>- setCurrentPage((p) =>- Math.min(- logs.data?.total_pages || 1,- p + 1,- ),- )- }- disabled={- logs.isLoading ||- currentPage === (logs.data?.total_pages || 1)- }- className="px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"- >- Next- </button></div>- </div>+ )}</div></div><DataTablecolumns={columns}- data={filteredData}+ data={processedLogs}renderSubComponent={RequestViewer}getRowCanExpand={() => true}+ isLoading={isLoading}/></div></>- )}+ )}</div>);}export function RequestViewer({ row }: { row: Row<LogEntry> }) {- // Helper function to clean metadata by removing specific fieldsconst formatData = (input: any) => {if (typeof input === "string") {try {@@ -712,28 +682,22 @@ export function RequestViewer({ row }: { row: Row<LogEntry> }) {return input;};- // New helper function to get raw requestconst getRawRequest = () => {- // First check if proxy_server_request exists in metadataif (row.original?.proxy_server_request) {return formatData(row.original.proxy_server_request);}- // Fall back to messages if proxy_server_request is emptyreturn formatData(row.original.messages);};- // Extract error information from metadata if availableconst metadata = row.original.metadata || {};const hasError = metadata.status === "failure";const errorInfo = hasError ? metadata.error_information : null;- // Check if request/response data is missingconst hasMessages = row.original.messages &&(Array.isArray(row.original.messages) ? row.original.messages.length > 0 : Object.keys(row.original.messages).length > 0);const hasResponse = row.original.response && Object.keys(formatData(row.original.response)).length > 0;const missingData = !hasMessages && !hasResponse;- // Format the response with error details if presentconst formattedResponse = () => {if (hasError && errorInfo) {return {@@ -748,14 +712,12 @@ export function RequestViewer({ row }: { row: Row<LogEntry> }) {return formatData(row.original.response);};- // Extract vector store request metadata if availableconst hasVectorStoreData = metadata.vector_store_request_metadata &&Array.isArray(metadata.vector_store_request_metadata) &&metadata.vector_store_request_metadata.length > 0;return (<div className="p-6 bg-gray-50 space-y-6">- {/* Combined Info Card */}<div className="bg-white rounded-lg shadow"><div className="p-4 border-b"><h3 className="text-lg font-medium">Request Details</h3>@@ -811,7 +773,7 @@ export function RequestViewer({ row }: { row: Row<LogEntry> }) {)}<div className="flex"><span className="font-medium w-1/3">Status:</span>- <span className={`px-2 py-1 rounded-md text-xs font-medium inline-block text-center w-16 ${+ <span className={`px-2 py-1 rounded-md text-xs font-medium inline-block text-center w-16 ${(row.original.metadata?.status || "Success").toLowerCase() !== "failure"? 'bg-green-100 text-green-800': 'bg-red-100 text-red-800'@@ -828,12 +790,9 @@ export function RequestViewer({ row }: { row: Row<LogEntry> }) {</div></div>- {/* Configuration Info Message - Show when data is missing */}<ConfigInfoMessage show={missingData} />- {/* Request/Response Panel */}<div className="grid grid-cols-2 gap-4">- {/* Request Side */}<div className="bg-white rounded-lg shadow"><div className="flex justify-between items-center p-4 border-b"><h3 className="text-lg font-medium">Request</h3>@@ -854,7 +813,6 @@ export function RequestViewer({ row }: { row: Row<LogEntry> }) {</div></div>- {/* Response Side */}<div className="bg-white rounded-lg shadow"><div className="flex justify-between items-center p-4 border-b"><h3 className="text-lg font-medium">@@ -887,15 +845,12 @@ export function RequestViewer({ row }: { row: Row<LogEntry> }) {</div></div>- {/* Vector Store Request Data - Show only if present */}- {hasVectorStoreData && (+ {hasVectorStoreData && (<VectorStoreViewer data={metadata.vector_store_request_metadata} />)}- {/* Error Card - Only show for failures */}{hasError && errorInfo && <ErrorViewer errorInfo={errorInfo} />}- {/* Tags Card - Only show if there are tags */}{row.original.request_tags && Object.keys(row.original.request_tags).length > 0 && (<div className="bg-white rounded-lg shadow"><div className="flex justify-between items-center p-4 border-b">@@ -913,7 +868,6 @@ export function RequestViewer({ row }: { row: Row<LogEntry> }) {</div>)}- {/* Metadata Card - Only show if there's metadata */}{row.original.metadata && Object.keys(row.original.metadata).length > 0 && (<div className="bg-white rounded-lg shadow"><div className="flex justify-between items-center p-4 border-b">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.tsxnew file mode 100644index 00000000000..0a04e161ea2--- /dev/null+++ b/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.tsx@@ -0,0 +1,243 @@+import { useCallback, useEffect, useState, useRef, useMemo } from "react";+import { LogEntry } from "./columns";+import { uiSpendLogsCall, Organization, Team, UserInfo, teamListCall, userListCall, keyListCall as fetchAllKeysCall } from "../networking";+import { KeyResponse } from "../key_team_helpers/key_list";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { Setter } from "@/types";+import { debounce } from "lodash";+import { defaultPageSize } from "../constants";+import moment from "moment";+import { fetchAllKeyAliases, fetchAllTeams } from "../key_team_helpers/filter_helpers"; // Import fetchAllTeams++// Define the shape of the filter state for logs+export interface LogFilterState {+ 'Team ID': string;+ 'Organization ID': string; // Added for potential future use+ 'Key Alias': string;+ 'Key Hash': string;+ 'Request ID': string;+ 'Model': string;+ 'User': string;+ 'Cache Hit': 'true' | 'false' | ''; // Example for boolean filter+ 'Status': 'success' | 'failure' | ''; // Example for status filter+ [key: string]: string | ''; // Allow for other string-based filters+}++// Define the shape of the pagination state+export interface PaginationState {+ currentPage: number;+ totalPages: number;+ totalCount: number;+ pageSize: number;+}++export function useLogFilterLogic({+ accessToken,+ startTime, // Receive from SpendLogsTable+ endTime, // Receive from SpendLogsTable+ pageSize = defaultPageSize,+ initialPage = 1,+ initialFilters = {}+}: {+ accessToken: string | null;+ startTime: string;+ endTime: string;+ pageSize?: number;+ initialPage?: number;+ initialFilters?: Partial<LogFilterState>;+}) {+ const defaultFilters: LogFilterState = {+ 'Team ID': '',+ 'Organization ID': '',+ 'Key Alias': '',+ 'Key Hash': '',+ 'Request ID': '',+ 'Model': '',+ 'User': '',+ 'Cache Hit': '',+ 'Status': '',+ ...initialFilters+ };++ const [filters, setFilters] = useState<LogFilterState>(defaultFilters);+ const [currentPage, setCurrentPage] = useState<number>(initialPage);+ const queryClient = useQueryClient();++ // States for manually managed data, loading, and error+ const [logEntries, setLogEntries] = useState<LogEntry[]>([]);+ const [paginationDetails, setPaginationDetails] = useState<PaginationState>({+ currentPage: initialPage,+ totalPages: 0,+ totalCount: 0,+ pageSize+ });+ const [isLoadingLogs, setIsLoadingLogs] = useState<boolean>(false);+ const [logsError, setLogsError] = useState<Error | null>(null);+ const lastSearchTimestamp = useRef(0);++ const queryAllKeysQuery = useQuery({+ queryKey: ['allKeysForLogFilters', accessToken], // Ensure unique queryKey+ queryFn: async () => {+ if (!accessToken) throw new Error('Access token required');+ return await fetchAllKeyAliases(accessToken);+ },+ enabled: !!accessToken+ });+ const allKeyAliases = queryAllKeysQuery.data || []+++ // Fetch all teams and users for potential filter dropdowns (optional, can be adapted)+ const { data: allTeams } = useQuery<Team[], Error>({+ queryKey: ["allTeamsForLogFilters", accessToken],+ queryFn: async () => {+ if (!accessToken) return [];+ // Use fetchAllTeams helper function for consistency and abstraction+ // Assuming fetchAllTeams returns Team[] directly+ const teamsData = await fetchAllTeams(accessToken);+ return teamsData || []; // Ensure it returns an array+ },+ enabled: !!accessToken,+ });++ const { data: allUsers } = useQuery<UserInfo[], Error>({+ queryKey: ["allUsersForLogFilters", accessToken],+ queryFn: async () => {+ if (!accessToken) return [];+ // Assuming userListCall fetches all users. Adapt if pagination or specific params are needed.+ const response = await userListCall(accessToken, null, 1, 1000); // Fetch a large number for dropdown+ return response.users || [];+ },+ enabled: !!accessToken,+ });++ // Debounced API call+ const debouncedSearch = useCallback(+ debounce(async (currentFilters: LogFilterState, pageToFetch: number) => {+ if (!accessToken) {+ setLogEntries([]);+ setPaginationDetails({ currentPage: pageToFetch, totalPages: 0, totalCount: 0, pageSize });+ setIsLoadingLogs(false);+ setLogsError(null);+ return;+ }++ const currentTimestamp = Date.now();+ lastSearchTimestamp.current = currentTimestamp;+ setIsLoadingLogs(true);+ setLogsError(null);++ try {+ const formattedStartTime = moment(startTime).utc().format("YYYY-MM-DD HH:mm:ss");+ const formattedEndTime = moment(endTime).utc().format("YYYY-MM-DD HH:mm:ss");++ const apiKeyParam = currentFilters['Key Hash'] || undefined;+ const teamIdParam = currentFilters['Team ID'] || undefined;+ const requestIdParam = currentFilters['Request ID'] || undefined;+ const userIdParam = currentFilters['User'] || undefined;+ // const modelParam = currentFilters['Model'] || undefined; // Prepared if uiSpendLogsCall is updated++ const response = await uiSpendLogsCall(+ accessToken,+ apiKeyParam,+ teamIdParam,+ requestIdParam,+ formattedStartTime,+ formattedEndTime,+ pageToFetch,+ pageSize,+ userIdParam+ // If uiSpendLogsCall is updated to accept more params (e.g., model), pass them here:+ // modelParam,+ );++ if (currentTimestamp === lastSearchTimestamp.current) {+ if (response && response.data) {+ setLogEntries(response.data);+ setPaginationDetails({+ currentPage: response.page,+ totalPages: response.total_pages,+ totalCount: response.total,+ pageSize: response.page_size || pageSize,+ });+ } else {+ setLogEntries([]);+ setPaginationDetails({ currentPage: pageToFetch, totalPages: 0, totalCount: 0, pageSize });+ }+ }+ } catch (error: any) {+ if (currentTimestamp === lastSearchTimestamp.current) {+ console.error("Error fetching logs:", error);+ setLogsError(error);+ setLogEntries([]);+ setPaginationDetails({ currentPage: pageToFetch, totalPages: 0, totalCount: 0, pageSize });+ }+ } finally {+ if (currentTimestamp === lastSearchTimestamp.current) {+ setIsLoadingLogs(false);+ }+ }+ }, 300),+ [accessToken, startTime, endTime, pageSize, setLogEntries, setPaginationDetails, setIsLoadingLogs, setLogsError]+ );++ // useEffect to trigger debouncedSearch when dependencies change+ useEffect(() => {+ if (accessToken) {+ debouncedSearch(filters, currentPage);+ } else {+ // Clear data if accessToken is lost or not present+ setLogEntries([]);+ setPaginationDetails(prev => ({ ...prev, currentPage, totalPages: 0, totalCount: 0 }));+ setIsLoadingLogs(false);+ setLogsError(null);+ }+ // Cleanup function for debounce+ return () => {+ debouncedSearch.cancel();+ };+ }, [accessToken, filters, currentPage, startTime, endTime, pageSize, debouncedSearch]);+++ const handleFilterChange = (newFilters: Partial<LogFilterState>) => {+ setFilters(prev => {+ const updatedFilters = { ...prev, ...newFilters }; // Simpler update+ // Ensure all keys in LogFilterState are present, defaulting to '' if not in newFilters+ for (const key of Object.keys(defaultFilters) as Array<keyof LogFilterState>) {+ if (!(key in updatedFilters)) {+ updatedFilters[key] = defaultFilters[key];+ }+ }+ return updatedFilters as LogFilterState;+ });+ setCurrentPage(1); // Reset to first page when filters change+ // debouncedSearch will be called by the useEffect hook+ };++ const handleFilterReset = () => {+ setFilters(defaultFilters);+ setCurrentPage(1);+ // debouncedSearch will be called by the useEffect hook+ };++ const pagination: PaginationState = {+ currentPage: paginationDetails.currentPage,+ totalPages: paginationDetails.totalPages,+ totalCount: paginationDetails.totalCount,+ pageSize: paginationDetails.pageSize,+ };++ return {+ filters,+ filteredLogs: logEntries,+ allKeyAliases,+ allTeams: allTeams || [],+ allUsers: allUsers || [],+ allOrganizations: [], // Placeholder for now, can be fetched if needed+ handleFilterChange,+ handleFilterReset,+ isLoading: isLoadingLogs,+ pagination,+ setCurrentPage,+ error: logsError+ };+}\ No newline at end of file