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
feat(ui): session-level cache observability in request logs (#38442)
devin-ai-integration[bot]eb0e3f8c184d
diff --git a/litellm/proxy/spend_tracking/spend_management_endpoints.py b/litellm/proxy/spend_tracking/spend_management_endpoints.pyindex 1c49ad51beb..41c65b1d5c5 100644--- a/litellm/proxy/spend_tracking/spend_management_endpoints.py+++ b/litellm/proxy/spend_tracking/spend_management_endpoints.py@@ -158,6 +158,7 @@ class _SessionSpendRow(TypedDict):session_total_spend: floatmcp_tool_call_count: intmcp_tool_call_spend: float+ session_cache_hit_count: ReadOnly[int]class _SpendSumAggregate(TypedDict, total=False):@@ -4135,7 +4136,8 @@ async def _build_ui_spend_logs_response()::int AS mcp_tool_call_count,COALESCE(SUM(spend) FILTER (WHERE call_type IN ('call_mcp_tool', 'list_mcp_tools')- ), 0)::double precision AS mcp_tool_call_spend+ ), 0)::double precision AS mcp_tool_call_spend,+ COUNT(*) FILTER (WHERE LOWER(cache_hit) = 'true')::int AS session_cache_hit_countFROM "LiteLLM_SpendLogs"WHERE session_id = ANY($1::text[])AND api_key = ANY($2::text[])@@ -4149,6 +4151,7 @@ async def _build_ui_spend_logs_response("session_total_spend": float(row.get("session_total_spend") or 0.0),"mcp_tool_call_count": int(row.get("mcp_tool_call_count") or 0),"mcp_tool_call_spend": float(row.get("mcp_tool_call_spend") or 0.0),+ "session_cache_hit_count": int(row.get("session_cache_hit_count") or 0),}for row in rowsif row.get("session_id")@@ -4171,6 +4174,7 @@ async def _build_ui_spend_logs_response(if session_stats["mcp_tool_call_count"]:row_dict["mcp_tool_call_count"] = session_stats["mcp_tool_call_count"]row_dict["mcp_tool_call_spend"] = session_stats["mcp_tool_call_spend"]+ row_dict["session_cache_hit_count"] = session_stats["session_cache_hit_count"]enriched.append(row_dict)response_data: list = enrichedelse:diff --git a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.pyindex 19ceb3d3d1f..9455d79f2ba 100644--- a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py+++ b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py@@ -4069,6 +4069,62 @@ async def test_build_ui_spend_logs_response_sums_multi_round_session_spend():assert call_args[2] == [api_key]+async def test_build_ui_spend_logs_response_session_cache_hit_count():+ """+ Each row of a session must carry session_cache_hit_count aggregated across+ the whole session so the UI can show how many requests in the session were+ served from the response cache.+ """+ from litellm.proxy.spend_tracking.spend_management_endpoints import (+ _build_ui_spend_logs_response,+ )++ session_id = "sess-cache-hits"+ api_key = "hashed-key-xyz"+ dict_rows = [+ {"request_id": "req-1", "session_id": session_id, "call_type": "completion", "api_key": api_key},+ {"request_id": "req-2", "session_id": session_id, "call_type": "completion", "api_key": api_key},+ {"request_id": "req-3", "session_id": None, "call_type": "completion", "api_key": api_key},+ ]++ mock_prisma = MagicMock()+ mock_prisma.db.litellm_spendlogs.group_by = AsyncMock(+ return_value=[{"session_id": session_id, "_count": {"session_id": 2}}]+ )+ mock_prisma.db.query_raw = AsyncMock(+ return_value=[+ {+ "session_id": session_id,+ "session_total_spend": 0.05,+ "mcp_tool_call_count": 0,+ "mcp_tool_call_spend": 0.0,+ "session_cache_hit_count": 2,+ }+ ]+ )++ result = await _build_ui_spend_logs_response(+ prisma_client=mock_prisma,+ data=dict_rows,+ total_records=3,+ page=1,+ page_size=50,+ total_pages=1,+ enrich_session_counts=True,+ )++ rows = result["data"]+ assert rows[0]["session_cache_hit_count"] == 2+ assert rows[1]["session_cache_hit_count"] == 2+ assert "session_cache_hit_count" not in rows[2]++ # The aggregate SQL must actually compute the cache-hit count.+ _, call_args, _ = mock_prisma.db.query_raw.mock_calls[0]+ assert "session_cache_hit_count" in call_args[0]+ assert "LOWER(cache_hit) = 'true'" in call_args[0]++# ---------------------------------------------------------------------------# Tests for /spend/logs team-member permission# ---------------------------------------------------------------------------diff --git a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.test.tsx b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.test.tsxindex aab8d2b8cb9..a679dc49427 100644--- a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.test.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.test.tsx@@ -359,6 +359,36 @@ describe("LogDetailContent", () => {expect(screen.queryByText("Response Cache")).not.toBeInTheDocument();});+ it("should display the Cache Key next to the Response Cache result", () => {+ render(<LogDetailContent logEntry={createLogEntry({ cache_hit: "True", cache_key: "abc123cachekey" })} />);++ expect(screen.getByText("Cache Key")).toBeInTheDocument();+ expect(screen.getByText("abc123cachekey")).toBeInTheDocument();+ });++ it("should display a cache miss and Cache Key for the request that populates the response cache", () => {+ render(<LogDetailContent logEntry={createLogEntry({ cache_hit: "None", cache_key: "abc123cachekey" })} />);++ expect(screen.getByText("Response Cache")).toBeInTheDocument();+ expect(screen.getByText("Miss")).toBeInTheDocument();+ expect(screen.getByText("Cache Key")).toBeInTheDocument();+ expect(screen.getByText("abc123cachekey")).toBeInTheDocument();+ });++ it("should hide the Cache Key row when caching is off", () => {+ render(<LogDetailContent logEntry={createLogEntry({ cache_hit: "False", cache_key: "Cache OFF" })} />);++ expect(screen.getByText("Response Cache")).toBeInTheDocument();+ expect(screen.queryByText("Cache Key")).not.toBeInTheDocument();+ });++ it("should hide response cache metadata when caching is off and cache_hit is None", () => {+ render(<LogDetailContent logEntry={createLogEntry({ cache_hit: "None", cache_key: "Cache OFF" })} />);++ expect(screen.queryByText("Response Cache")).not.toBeInTheDocument();+ expect(screen.queryByText("Cache Key")).not.toBeInTheDocument();+ });+it("should display LiteLLM Overhead when litellm_overhead_time_ms is in metadata", () => {render(<LogDetailContentdiff --git a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsxindex 12c4d8ccaef..4c5c7b7b43f 100644--- a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx@@ -347,6 +347,8 @@ function getUncachedInputTextTokens(metadata: Record<string, any>): number | undconst RESPONSE_CACHE_TOOLTIP ="Whether this request was served from LiteLLM's response cache (e.g. Redis / in-memory), skipping the LLM provider call entirely. This is separate from provider prompt caching; a Miss here does not mean prompt caching failed.";const RESPONSE_CACHE_DOCS_URL = "https://docs.litellm.ai/docs/proxy/caching";+const CACHE_KEY_TOOLTIP =+ "The key LiteLLM computed for this request in the response cache. Requests with the same cache key share a cached response; a different key means the request content did not match any cached entry.";const PROMPT_CACHE_DOCS_URL = "https://docs.litellm.ai/docs/completion/prompt_caching";function MetricLabel({ label, tooltip, docsUrl }: { label: string; tooltip: string; docsUrl: string }) {@@ -380,8 +382,9 @@ function MetricsSection({ logEntry, metadata }: { logEntry: LogEntry; metadata:: null;const responseCacheValue = String(logEntry.cache_hit ?? "").toLowerCase();+ const responseCacheKey = logEntry.cache_key && logEntry.cache_key !== "Cache OFF" ? logEntry.cache_key : undefined;const isResponseCacheHit = responseCacheValue === "true";- const showResponseCache = isResponseCacheHit || responseCacheValue === "false";+ const showResponseCache = isResponseCacheHit || responseCacheValue === "false" || responseCacheKey != null;const promptCacheReadTokens = Number(metadata?.additional_usage_values?.cache_read_input_tokens) || 0;const promptCacheCreationTokens = Number(metadata?.additional_usage_values?.cache_creation_input_tokens) || 0;@@ -436,6 +439,13 @@ function MetricsSection({ logEntry, metadata }: { logEntry: LogEntry; metadata:</Badge></DescriptionItem>)}+ {responseCacheKey && (+ <DescriptionItem+ label={<MetricLabel label="Cache Key" tooltip={CACHE_KEY_TOOLTIP} docsUrl={RESPONSE_CACHE_DOCS_URL} />}+ >+ <TruncatedValue value={responseCacheKey} />+ </DescriptionItem>+ )}{promptCacheReadTokens > 0 && (<DescriptionItemlabel={diff --git a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailsDrawer.tsx b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailsDrawer.tsxindex 0d36427aaa6..f677a66cc54 100644--- a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailsDrawer.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailsDrawer.tsx@@ -278,6 +278,7 @@ export function LogDetailsDrawer({).length;const agentCount = sessionLogs.filter((row) => AGENT_CALL_TYPES.includes(row.call_type)).length;const mcpCount = sessionLogs.filter((row) => MCP_CALL_TYPES.includes(row.call_type)).length;+ const cacheHitCount = sessionLogs.filter((row) => String(row.cache_hit ?? "").toLowerCase() === "true").length;const logsForList = isSessionMode ? sessionLogs : currentLog ? [currentLog] : [];const leftPanelId = isSessionMode ? sessionId || "" : currentLog?.request_id || "";const leftPanelDisplayId = leftPanelId.length > 14 ? `${leftPanelId.slice(0, 11)}...` : leftPanelId;@@ -387,6 +388,11 @@ export function LogDetailsDrawer({</>)}</div>+ {isSessionMode && (+ <div className="text-[11px] text-muted-foreground font-mono whitespace-nowrap">+ {cacheHitCount}/{logsForList.length} cached+ </div>+ )}{isSessionMode && sessionTruncated && (<div className="mt-1 text-[11px] text-warning font-mono">Showing most recent {logsForList.length} of {sessionTotalCount}diff --git a/ui/litellm-dashboard/src/components/view_logs/RequestLogsTableColumns.tsx b/ui/litellm-dashboard/src/components/view_logs/RequestLogsTableColumns.tsxindex fc7d1cf0a71..cf776515bd4 100644--- a/ui/litellm-dashboard/src/components/view_logs/RequestLogsTableColumns.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/RequestLogsTableColumns.tsx@@ -90,6 +90,7 @@ export const getRequestLogsTableColumns = ({sessionLlmCount > 0 && `${sessionLlmCount} LLM`,sessionAgentCount > 0 && `${sessionAgentCount} Agent`,sessionMcpCount > 0 && `${sessionMcpCount} MCP`,+ log.session_cache_hit_count != null && `${log.session_cache_hit_count} cache hit`,].filter(Boolean);return <CellTooltip content={tooltipParts.join(" • ")} trigger={sessionTypeBadge} />;},diff --git a/ui/litellm-dashboard/src/components/view_logs/columns.tsx b/ui/litellm-dashboard/src/components/view_logs/columns.tsxindex d4f784bf165..eef957922d7 100644--- a/ui/litellm-dashboard/src/components/view_logs/columns.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/columns.tsx@@ -42,6 +42,7 @@ export type LogEntry = {request_duration_ms?: number;session_total_count?: number;session_total_spend?: number;+ session_cache_hit_count?: number;mcp_tool_call_count?: number;mcp_tool_call_spend?: number;session_llm_count?: number;