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
Merge pull request #20720 from OrionCodeDev/fix-spend-logs
yuneng-jiang21b38a403018
diff --git a/litellm/proxy/spend_tracking/spend_management_endpoints.py b/litellm/proxy/spend_tracking/spend_management_endpoints.pyindex 9c0190bdfec..0c91fd00b38 100644--- a/litellm/proxy/spend_tracking/spend_management_endpoints.py+++ b/litellm/proxy/spend_tracking/spend_management_endpoints.py@@ -3,7 +3,6 @@ import collectionsimport jsonimport osfrom datetime import datetime, timedelta, timezone-from functools import lru_cachefrom typing import TYPE_CHECKING, Any, Dict, List, Literal, Optionalimport fastapi@@ -1865,13 +1864,87 @@ async def ui_view_spend_logs( # noqa: PLR0915where=where_conditions,)- # Get paginated data- data = await prisma_client.db.litellm_spendlogs.find_many(- where=where_conditions,- order=order_clause,- skip=skip,- take=page_size,- )+ # Build raw SQL to fetch paginated data WITHOUT heavy columns+ # (messages, response, proxy_server_request can be hundreds of KB per row).+ # These are only needed in the detail endpoint /spend/logs/ui/{request_id}.+ sql_conditions: List[str] = []+ sql_params: List[Any] = []+ p = 1 # parameter index counter++ # Date range (always present)+ sql_conditions.append(f'"startTime" >= ${p}::timestamptz')+ sql_params.append(start_date_obj)+ p += 1+ sql_conditions.append(f'"startTime" <= ${p}::timestamptz')+ sql_params.append(end_date_obj)+ p += 1++ # Equality filters - read effective values from where_conditions (post-authorization)+ for sql_col, wc_key in [+ ("team_id", "team_id"),+ ('"user"', "user"),+ ("api_key", "api_key"),+ ("request_id", "request_id"),+ ("model", "model"),+ ("model_id", "model_id"),+ ("end_user", "end_user"),+ ]:+ val = where_conditions.get(wc_key)+ if val is not None and isinstance(val, str):+ sql_conditions.append(f"{sql_col} = ${p}")+ sql_params.append(val)+ p += 1++ # Status filter+ if status_filter is not None:+ if status_filter == "success":+ sql_conditions.append("(status = 'success' OR status IS NULL)")+ else:+ sql_conditions.append(f"status = ${p}")+ sql_params.append(status_filter)+ p += 1++ # Spend range+ if min_spend is not None:+ sql_conditions.append(f"spend >= ${p}")+ sql_params.append(min_spend)+ p += 1+ if max_spend is not None:+ sql_conditions.append(f"spend <= ${p}")+ sql_params.append(max_spend)+ p += 1++ # Metadata JSON filters (PostgreSQL JSONB operators)+ if key_alias is not None:+ sql_conditions.append(f"metadata->>'user_api_key_alias' LIKE ${p}")+ sql_params.append(f"%{key_alias}%")+ p += 1+ if error_code is not None:+ sql_conditions.append(f"metadata->'error_information'->>'error_code' = ${p}")+ sql_params.append(error_code)+ p += 1+ if error_message is not None:+ sql_conditions.append(f"metadata->'error_information'->>'error_message' LIKE ${p}")+ sql_params.append(f"%{error_message}%")+ p += 1++ sql_query = f"""+ SELECT+ request_id, call_type, api_key, spend, total_tokens,+ prompt_tokens, completion_tokens, "startTime", "endTime",+ "completionStartTime", model, model_id, model_group,+ custom_llm_provider, api_base, "user", metadata,+ cache_hit, cache_key, request_tags, team_id,+ organization_id, end_user, requester_ip_address,+ session_id, status, mcp_namespaced_tool_name, agent_id+ FROM "LiteLLM_SpendLogs"+ WHERE {" AND ".join(sql_conditions)}+ ORDER BY "startTime" DESC+ LIMIT ${p} OFFSET ${p + 1}+ """+ sql_params.extend([page_size, skip])++ data = await prisma_client.db.query_raw(sql_query, *sql_params)# Calculate total pagestotal_pages = (total_records + page_size - 1) // page_size@@ -1892,7 +1965,6 @@ async def ui_view_spend_logs( # noqa: PLR0915raise handle_exception_on_proxy(e)-@lru_cache(maxsize=128)@router.get("/spend/logs/ui/{request_id}",tags=["Budget & Spend Tracking"],@@ -1939,6 +2011,29 @@ async def ui_view_request_response_for_request_id(if payload is not None:return payload+ # Fallback: fetch heavy columns directly from the database.+ # The list endpoint (/spend/logs/ui) intentionally excludes messages,+ # response, and proxy_server_request for performance. When no custom+ # logger (S3, GCS, etc.) is configured, we still need to serve these+ # fields from the DB for the detail/drawer view.+ from litellm.proxy.proxy_server import prisma_client++ if prisma_client is not None:+ sql_query = """+ SELECT messages, response, proxy_server_request+ FROM "LiteLLM_SpendLogs"+ WHERE request_id = $1+ LIMIT 1+ """+ db_result = await prisma_client.db.query_raw(sql_query, request_id)+ if db_result and len(db_result) > 0:+ row = db_result[0]+ return {+ "messages": row.get("messages"),+ "response": row.get("response"),+ "proxy_server_request": row.get("proxy_server_request"),+ }+return None@@ -3104,13 +3199,22 @@ async def ui_view_session_spend_logs(where=where_conditions)- # Query the database with pagination- result = await prisma_client.db.litellm_spendlogs.find_many(- where=where_conditions,- order={"startTime": "asc"},- skip=skip,- take=page_size,- )+ # Query with raw SQL to exclude heavy columns (messages, response, proxy_server_request)+ sql_query = """+ SELECT+ request_id, call_type, api_key, spend, total_tokens,+ prompt_tokens, completion_tokens, "startTime", "endTime",+ "completionStartTime", model, model_id, model_group,+ custom_llm_provider, api_base, "user", metadata,+ cache_hit, cache_key, request_tags, team_id,+ organization_id, end_user, requester_ip_address,+ session_id, status, mcp_namespaced_tool_name, agent_id+ FROM "LiteLLM_SpendLogs"+ WHERE session_id = $1+ ORDER BY "startTime" ASC+ LIMIT $2 OFFSET $3+ """+ result = await prisma_client.db.query_raw(sql_query, session_id, page_size, skip)total_pages = (total_records + page_size - 1) // page_sizediff --git a/ui/litellm-dashboard/src/app/(dashboard)/hooks/logDetails/useLogDetails.ts b/ui/litellm-dashboard/src/app/(dashboard)/hooks/logDetails/useLogDetails.tsnew file mode 100644index 00000000000..6c0f95d5995--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/hooks/logDetails/useLogDetails.ts@@ -0,0 +1,30 @@+import { useQuery } from "@tanstack/react-query";+import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";+import { uiSpendLogDetailsCall } from "@/components/networking";++/**+ * Hook to lazy-load log details (messages/response) for a specific log entry.+ * Fetches data on-demand when the drawer is open, instead of prefetching all logs.+ *+ * @param requestId - The request_id of the log entry+ * @param startTime - The formatted start time for the query+ * @param enabled - Whether the query should be enabled (e.g., drawer is open)+ */+export const useLogDetails = (+ requestId: string | undefined,+ startTime: string | undefined,+ enabled: boolean,+) => {+ const { accessToken } = useAuthorized();++ return useQuery({+ queryKey: ["logDetails", requestId, startTime, accessToken],+ queryFn: async () => {+ if (!accessToken || !requestId || !startTime) return null;+ return await uiSpendLogDetailsCall(accessToken, requestId, startTime);+ },+ enabled: enabled && !!accessToken && !!requestId && !!startTime,+ staleTime: 10 * 60 * 1000, // 10 minutes+ gcTime: 10 * 60 * 1000, // 10 minutes+ });+};diff --git a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsxindex ef5de9febc3..9081219d5be 100644--- a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx@@ -1,5 +1,5 @@import { useState } from "react";-import { Typography, Descriptions, Card, Tag, Tabs, Alert, Collapse, Radio, Space } from "antd";+import { Typography, Descriptions, Card, Tag, Tabs, Alert, Collapse, Radio, Space, Spin } from "antd";import moment from "moment";import { LogEntry } from "../columns";import { formatNumberWithCommas } from "@/utils/dataUtils";@@ -38,6 +38,8 @@ const { Text } = Typography;export interface LogDetailContentProps {logEntry: LogEntry;onOpenSettings?: () => void;+ /** When true, log details (messages/response) are still being lazy-loaded. */+ isLoadingDetails?: boolean;}/**@@ -48,14 +50,15 @@ export interface LogDetailContentProps {* Designed to be placed inside LogDetailsDrawer's right panel so it can* be reused for both single-log and session-mode views.*/-export function LogDetailContent({ logEntry, onOpenSettings }: LogDetailContentProps) {+export function LogDetailContent({ logEntry, onOpenSettings, isLoadingDetails = false }: LogDetailContentProps) {const metadata = logEntry.metadata || {};const hasError = metadata.status === "failure";const errorInfo = hasError ? metadata.error_information : null;const hasMessages = checkHasMessages(logEntry.messages);const hasResponse = checkHasResponse(logEntry.response);- const missingData = !hasMessages && !hasResponse && !hasError;+ // Don't show "missing data" warning while details are still loading+ const missingData = !hasMessages && !hasResponse && !hasError && !isLoadingDetails;// Guardrail dataconst guardrailInfo = metadata?.guardrail_information;@@ -145,13 +148,20 @@ export function LogDetailContent({ logEntry, onOpenSettings }: LogDetailContentP)}{/* Request/Response JSON */}- <RequestResponseSection- hasResponse={hasResponse}- hasError={hasError}- getRawRequest={getRawRequest}- getFormattedResponse={getFormattedResponse}- logEntry={logEntry}- />+ {isLoadingDetails ? (+ <div className="bg-white rounded-lg shadow w-full max-w-full overflow-hidden mb-6 p-8 text-center">+ <Spin size="default" />+ <div style={{ marginTop: 8, color: "#999" }}>Loading request & response data...</div>+ </div>+ ) : (+ <RequestResponseSection+ hasResponse={hasResponse}+ hasError={hasError}+ getRawRequest={getRawRequest}+ getFormattedResponse={getFormattedResponse}+ logEntry={logEntry}+ />+ )}{/* Guardrail Data */}{hasGuardrailData && <GuardrailViewer data={guardrailInfo} />}diff --git a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailsDrawer.tsx b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailsDrawer.tsxindex 8d087fed708..b6feff77a1c 100644--- a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailsDrawer.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailsDrawer.tsx@@ -17,6 +17,7 @@ import { sessionSpendLogsCall } from "../../networking";import { useQuery } from "@tanstack/react-query";import { getSpendString } from "@/utils/dataUtils";import { DRAWER_WIDTH } from "./constants";+import { useLogDetails } from "@/app/(dashboard)/hooks/logDetails/useLogDetails";export interface LogDetailsDrawerProps {open: boolean;@@ -27,6 +28,7 @@ export interface LogDetailsDrawerProps {onOpenSettings?: () => void;allLogs?: LogEntry[];onSelectLog?: (log: LogEntry) => void;+ startTime?: string;}const SIDEBAR_WIDTH_PX = 224;@@ -106,6 +108,7 @@ export function LogDetailsDrawer({onOpenSettings,allLogs = [],onSelectLog,+ startTime,}: LogDetailsDrawerProps) {const isSessionMode = Boolean(sessionId);const [selectedSessionRequestId, setSelectedSessionRequestId] = useState<string | null>(null);@@ -180,6 +183,25 @@ export function LogDetailsDrawer({},});+ // Lazy-load log details (messages/response) only when drawer is open.+ // This fetches data for a single log on-demand instead of prefetching all 50.+ const logDetails = useLogDetails(currentLog?.request_id, startTime, open && !!currentLog?.request_id);+ const detailsData = logDetails.data as any;+ const isLoadingDetails = logDetails.isLoading;++ // Build an enriched log entry that merges lazy-loaded details.+ // The list endpoint may already include messages/response when store_prompts_in_spend_logs is enabled,+ // while the detail endpoint fetches from custom loggers (S3, GCS, etc.) or DB fallback.+ const enrichedLog = useMemo(() => {+ if (!currentLog) return null;+ return {+ ...currentLog,+ messages: detailsData?.messages || currentLog.messages,+ response: detailsData?.response || currentLog.response,+ proxy_server_request: detailsData?.proxy_server_request || currentLog.proxy_server_request,+ };+ }, [currentLog, detailsData]);+const metadata = currentLog?.metadata || {};// Status display values@@ -212,7 +234,7 @@ export function LogDetailsDrawer({} catch { /* clipboard unavailable in non-secure contexts */ }};- if (!currentLog) return null;+ if (!currentLog || !enrichedLog) return null;return (<Drawer@@ -352,7 +374,11 @@ export function LogDetailsDrawer({environment={environment}/><div className="flex-1 overflow-y-auto">- <LogDetailContent logEntry={currentLog} onOpenSettings={onOpenSettings} />+ <LogDetailContent+ logEntry={enrichedLog}+ onOpenSettings={onOpenSettings}+ isLoadingDetails={isLoadingDetails}+ /></div></div></div>diff --git a/ui/litellm-dashboard/src/components/view_logs/index.tsx b/ui/litellm-dashboard/src/components/view_logs/index.tsxindex a247a1be4a3..0214a6ecf87 100644--- a/ui/litellm-dashboard/src/components/view_logs/index.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/index.tsx@@ -28,7 +28,6 @@ import { ErrorViewer } from "./ErrorViewer";import { useLogFilterLogic } from "./log_filter_logic";import { LogDetailsDrawer } from "./LogDetailsDrawer";import { getTimeRangeDisplay } from "./logs_utils";-import { prefetchLogDetails } from "./prefetch";import { RequestResponsePanel } from "./RequestResponsePanel";import SpendLogsSettingsModal from "./SpendLogsSettingsModal/SpendLogsSettingsModal";import { DataTable } from "./table";@@ -51,11 +50,6 @@ export interface PaginatedResponse {total_pages: number;}-interface PrefetchedLog {- messages: any[];- response: any;-}-export default function SpendLogsTable({accessToken,token,@@ -193,6 +187,8 @@ export default function SpendLogsTable({: moment().utc().format("YYYY-MM-DD HH:mm:ss");// Get base response from API+ // NOTE: We only fetch the list of logs here (lightweight).+ // Log details (messages/response) are fetched on-demand when user clicks a row.const response = await uiSpendLogsCall(accessToken,selectedKeyHash || undefined,@@ -209,25 +205,6 @@ export default function SpendLogsTable({selectedModel || 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 && activeTab === "request logs",@@ -751,6 +728,7 @@ export default function SpendLogsTable({onOpenSettings={() => setIsSpendLogsSettingsModalVisible(true)}allLogs={filteredData}onSelectLog={handleSelectLog}+ startTime={moment(startTime).utc().format("YYYY-MM-DD HH:mm:ss")}/></div>);