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): toggle internal health check visibility in request logs
mateo-berri41192ef08541
diff --git a/litellm/proxy/spend_tracking/spend_management_endpoints.py b/litellm/proxy/spend_tracking/spend_management_endpoints.pyindex 06395a3c3cc..26da42a2f5c 100644--- a/litellm/proxy/spend_tracking/spend_management_endpoints.py+++ b/litellm/proxy/spend_tracking/spend_management_endpoints.py@@ -23,6 +23,7 @@ from typing_extensions import ReadOnlyimport litellmfrom litellm._logging import verbose_proxy_logger+from litellm.constants import LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAMEfrom litellm.proxy._types import *from litellm.proxy._types import ProviderBudgetResponse, ProviderBudgetResponseObjectfrom litellm.proxy.auth.user_api_key_auth import user_api_key_auth@@ -54,6 +55,11 @@ router: Final = APIRouter()SPEND_LOGS_PAGINATION_COUNT_CAP: Final = 10000+_INTERNAL_HEALTH_CHECK_API_KEYS: Final = (+ LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME,+ hash_token(token=LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME),+)+_RowT = TypeVar("_RowT")@@ -2259,6 +2265,10 @@ async def ui_view_spend_logs(default="desc",description="Sort order: asc or desc",),+ exclude_internal_health_checks: bool = fastapi.Query(+ default=False,+ description="Exclude LiteLLM internal health check requests from results",+ ),):"""View spend logs with pagination support.@@ -2551,6 +2561,11 @@ async def ui_view_spend_logs(sql_params.append(status_filter)p += 1+ if exclude_internal_health_checks:+ sql_conditions.append(f"api_key NOT IN (${p}, ${p + 1})")+ sql_params.extend(_INTERNAL_HEALTH_CHECK_API_KEYS)+ p += 2 # rebind-ok: advances the file's shared $N placeholder counter+# Spend rangeif min_spend is not None:sql_conditions.append(f"spend >= ${p}")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 8c15ead8983..752894087dc 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@@ -1,6 +1,7 @@import asyncioimport collectionsimport datetime+import hashlibimport jsonimport refrom datetime import timezone@@ -96,6 +97,7 @@ def _reconstruct_ui_where_from_sql(sql_query, params):msg = re.search(r"error_message' LIKE \$(\d+)", cond)sess = re.fullmatch(r"session_id LIKE \$(\d+)", cond)status = re.fullmatch(r"status = \$(\d+)", cond)+ api_key_not_in = re.fullmatch(r"api_key NOT IN \(\$(\d+), \$(\d+)\)", cond)if gte:date_bounds["gte"] = _iso(params[int(gte.group(1)) - 1])elif lte:@@ -108,6 +110,11 @@ def _reconstruct_ui_where_from_sql(sql_query, params):where["session_id"] = {"contains": str(params[int(sess.group(1)) - 1]).strip("%")}elif status:where["status"] = {"equals": params[int(status.group(1)) - 1]}+ elif api_key_not_in:+ where["api_key_not_in"] = [+ params[int(api_key_not_in.group(1)) - 1],+ params[int(api_key_not_in.group(2)) - 1],+ ]elif alias:metadata_conds.append({@@ -196,6 +203,7 @@ def make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_fn, team_lookup_fn=Noreturn MockPrismaClient()+from litellm.constants import LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAMEfrom litellm.proxy._types import (LitellmUserRoles,Member,@@ -1256,6 +1264,140 @@ async def test_ui_view_spend_logs_with_team_id(client, monkeypatch):app.dependency_overrides.pop(ps.user_api_key_auth, None)+_HEALTH_CHECK_HASHED_API_KEY = hashlib.sha256(LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME.encode()).hexdigest()+++def _spend_logs_with_health_check_rows():+ now = datetime.datetime.now(timezone.utc).isoformat()+ return [+ {+ "id": "log1",+ "request_id": "req1",+ "api_key": "sk-test-key",+ "user": "test_user_1",+ "team_id": None,+ "spend": 0.05,+ "startTime": now,+ "model": "gpt-4",+ },+ {+ "id": "log2",+ "request_id": "req2",+ "api_key": _HEALTH_CHECK_HASHED_API_KEY,+ "user": None,+ "team_id": LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME,+ "spend": 0.0,+ "startTime": now,+ "model": "gpt-4",+ },+ {+ "id": "log3",+ "request_id": "req3",+ "api_key": LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME,+ "user": None,+ "team_id": LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME,+ "spend": 0.0,+ "startTime": now,+ "model": "gpt-4",+ },+ ]+++async def test_ui_view_spend_logs_exclude_internal_health_checks(client, monkeypatch):+ mock_spend_logs = _spend_logs_with_health_check_rows()++ def filter_health_checks(where):+ excluded = where.get("api_key_not_in")+ if excluded is None:+ return mock_spend_logs+ return [log for log in mock_spend_logs if log["api_key"] not in excluded]++ observed_queries = []++ def observe_query(sql_query, params):+ if 'FROM "LiteLLM_SpendLogs"' in sql_query:+ observed_queries.append((sql_query, params))++ monkeypatch.setattr(+ "litellm.proxy.proxy_server.prisma_client",+ make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_health_checks, query_observer=observe_query),+ )+ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"+ )++ try:+ start_date, end_date = _default_date_range()+ response = client.get(+ "/spend/logs/ui",+ params={+ "exclude_internal_health_checks": "true",+ "start_date": start_date,+ "end_date": end_date,+ },+ headers={"Authorization": "Bearer sk-test"},+ )++ assert response.status_code == 200+ data = response.json()+ assert data["total"] == 1+ assert [row["request_id"] for row in data["data"]] == ["req1"]++ page_sql, page_params = next((sql, params) for sql, params in observed_queries if "ORDER BY" in sql)+ not_in = re.search(r"api_key NOT IN \(\$(\d+), \$(\d+)\)", page_sql)+ assert not_in is not None+ assert LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME not in page_sql+ assert _HEALTH_CHECK_HASHED_API_KEY not in page_sql+ assert {+ page_params[int(not_in.group(1)) - 1],+ page_params[int(not_in.group(2)) - 1],+ } == {LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME, _HEALTH_CHECK_HASHED_API_KEY}+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)+++async def test_ui_view_spend_logs_includes_internal_health_checks_by_default(client, monkeypatch):+ mock_spend_logs = _spend_logs_with_health_check_rows()++ def filter_health_checks(where):+ excluded = where.get("api_key_not_in")+ if excluded is None:+ return mock_spend_logs+ return [log for log in mock_spend_logs if log["api_key"] not in excluded]++ observed_queries = []++ def observe_query(sql_query, params):+ if 'FROM "LiteLLM_SpendLogs"' in sql_query:+ observed_queries.append((sql_query, params))++ monkeypatch.setattr(+ "litellm.proxy.proxy_server.prisma_client",+ make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_health_checks, query_observer=observe_query),+ )+ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"+ )++ try:+ start_date, end_date = _default_date_range()+ response = client.get(+ "/spend/logs/ui",+ params={"start_date": start_date, "end_date": end_date},+ headers={"Authorization": "Bearer sk-test"},+ )++ assert response.status_code == 200+ data = response.json()+ assert data["total"] == 3+ assert [row["request_id"] for row in data["data"]] == ["req1", "req2", "req3"]+ assert all("NOT IN" not in sql for sql, _ in observed_queries)+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)++@pytest.mark.asyncioasync def test_ui_view_spend_logs_internal_user_scoped_without_user_id(client, monkeypatchdiff --git a/ui/litellm-dashboard/src/components/networking.test.ts b/ui/litellm-dashboard/src/components/networking.test.tsindex f12a52a0bcf..cd22935a66f 100644--- a/ui/litellm-dashboard/src/components/networking.test.ts+++ b/ui/litellm-dashboard/src/components/networking.test.ts@@ -459,6 +459,64 @@ describe("teamInfoCall", () => {});});+describe("uiSpendLogsCall exclude_internal_health_checks serialization", () => {+ const originalFetch = global.fetch;++ beforeEach(() => {+ vi.clearAllMocks();+ });++ afterEach(() => {+ global.fetch = originalFetch;+ });++ const mockOkFetch = () => {+ const mockFetch = vi.fn().mockResolvedValue({+ ok: true,+ json: vi.fn().mockResolvedValue({ data: [], total: 0, page: 1, page_size: 50, total_pages: 0 }),+ } as any);+ global.fetch = mockFetch as any;+ return mockFetch;+ };++ const callWith = (params: Parameters<typeof Networking.uiSpendLogsCall>[0]["params"]) =>+ Networking.uiSpendLogsCall({+ accessToken: "token",+ start_date: "2026-01-01 00:00:00",+ end_date: "2026-01-02 00:00:00",+ params,+ });++ const lastUrl = (mockFetch: ReturnType<typeof vi.fn>) => {+ const [url] = mockFetch.mock.calls.at(-1) ?? [];+ return new URL(url as string, "http://example.com");+ };++ it("appends exclude_internal_health_checks=true when the toggle is on", async () => {+ const mockFetch = mockOkFetch();++ await callWith({ exclude_internal_health_checks: true });++ expect(lastUrl(mockFetch).searchParams.get("exclude_internal_health_checks")).toBe("true");+ });++ it("omits exclude_internal_health_checks when the toggle is off", async () => {+ const mockFetch = mockOkFetch();++ await callWith({ exclude_internal_health_checks: false });++ expect(lastUrl(mockFetch).searchParams.has("exclude_internal_health_checks")).toBe(false);+ });++ it("omits exclude_internal_health_checks when the param is absent", async () => {+ const mockFetch = mockOkFetch();++ await callWith({});++ expect(lastUrl(mockFetch).searchParams.has("exclude_internal_health_checks")).toBe(false);+ });+});+describe("sessionSpendLogsCall", () => {const originalFetch = global.fetch;diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsxindex 5b6d70b4771..c7868a5f039 100644--- a/ui/litellm-dashboard/src/components/networking.tsx+++ b/ui/litellm-dashboard/src/components/networking.tsx@@ -2013,6 +2013,7 @@ interface UiSpendLogsParams {sort_order?: "asc" | "desc";min_spend?: number;max_spend?: number;+ exclude_internal_health_checks?: boolean;}interface UiSpendLogsCallOptions {@@ -2047,6 +2048,8 @@ export const uiSpendLogsCall = async ({if (value == null) continue;if (key === "min_spend" || key === "max_spend") {queryParams.append(key, value.toString());+ } else if (typeof value === "boolean") {+ if (value) queryParams.append(key, "true");} else if (typeof value === "string" && value !== "") {queryParams.append(key, String(value));}diff --git a/ui/litellm-dashboard/src/components/view_logs/LogsTableToolbar.tsx b/ui/litellm-dashboard/src/components/view_logs/LogsTableToolbar.tsxindex 7cd339f1d48..cb7836d603f 100644--- a/ui/litellm-dashboard/src/components/view_logs/LogsTableToolbar.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/LogsTableToolbar.tsx@@ -23,6 +23,8 @@ interface LogsTableToolbarProps {onSelectedTimeIntervalChange: (value: { value: number; unit: string }) => void;isLiveTail: boolean;onIsLiveTailChange: (value: boolean) => void;+ excludeInternalHealthChecks: boolean;+ onExcludeInternalHealthChecksChange: (value: boolean) => void;onResetToFirstPage: () => void;onResetFilters: () => void;}@@ -38,6 +40,8 @@ export function LogsTableToolbar({onSelectedTimeIntervalChange,isLiveTail,onIsLiveTailChange,+ excludeInternalHealthChecks,+ onExcludeInternalHealthChecksChange,onResetToFirstPage,onResetFilters,}: LogsTableToolbarProps) {@@ -125,6 +129,15 @@ export function LogsTableToolbar({<Switch checked={isLiveTail} onCheckedChange={onIsLiveTailChange} aria-label="Live Tail" /></div>+ <div className="flex items-center gap-2">+ <span className="text-sm font-medium">Hide Health Checks</span>+ <Switch+ checked={excludeInternalHealthChecks}+ onCheckedChange={onExcludeInternalHealthChecksChange}+ aria-label="Hide Health Checks"+ />+ </div>+<Button variant="outline" size="sm" onClick={onResetFilters}>Reset Filters</Button>diff --git a/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.test.tsx b/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.test.tsxindex b68e12b9c3d..593bebdbdae 100644--- a/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.test.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.test.tsx@@ -434,6 +434,35 @@ describe("RequestLogsPanel", () => {});});+ describe("hide health checks", () => {+ const toggle = () => screen.getByRole("switch", { name: "Hide Health Checks" });++ it("defaults to showing health checks and refetches without them from page 1 when toggled on", async () => {+ const user = userEvent.setup();+ renderPanel();++ await waitFor(() => expect(uiSpendLogsCall).toHaveBeenCalled());+ expect(lastCall()?.params?.exclude_internal_health_checks).toBe(false);+ expect(toggle()).not.toBeChecked();++ await user.click(toggle());++ await waitFor(() => expect(lastCall()?.params?.exclude_internal_health_checks).toBe(true));+ expect(lastCall()?.page).toBe(1);+ expect(toggle()).toBeChecked();+ expect(sessionStorage.getItem("excludeInternalHealthChecks")).toBe("true");+ });++ it("restores the persisted toggle from sessionStorage", async () => {+ sessionStorage.setItem("excludeInternalHealthChecks", "true");+ renderPanel();++ await waitFor(() => expect(uiSpendLogsCall).toHaveBeenCalled());+ expect(lastCall()?.params?.exclude_internal_health_checks).toBe(true);+ expect(toggle()).toBeChecked();+ });+ });+describe("live tail", () => {it("shows the auto-refresh banner on the first page and hides it once stopped", async () => {const user = userEvent.setup();diff --git a/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsx b/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsxindex b6f61cb3c6b..4e424904d40 100644--- a/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/RequestLogsPanel.tsx@@ -72,6 +72,15 @@ export default function RequestLogsPanel({ accessToken, token, userRole, userID,sessionStorage.setItem("isLiveTail", JSON.stringify(isLiveTail));}, [isLiveTail]);+ const [excludeInternalHealthChecks, setExcludeInternalHealthChecks] = useState<boolean>(() => {+ const storedValue = sessionStorage.getItem("excludeInternalHealthChecks");+ return storedValue !== null ? JSON.parse(storedValue) : false;+ });++ useEffect(() => {+ sessionStorage.setItem("excludeInternalHealthChecks", JSON.stringify(excludeInternalHealthChecks));+ }, [excludeInternalHealthChecks]);+const { logsQuery, filteredLogs, allTeams } = useLogFilterLogic({accessToken,token,@@ -80,6 +89,7 @@ export default function RequestLogsPanel({ accessToken, token, userRole, userID,columnFilters,activeTab: isActive ? "request logs" : "inactive",isLiveTail,+ excludeInternalHealthChecks,startTime,endTime,pagination,@@ -219,6 +229,14 @@ export default function RequestLogsPanel({ accessToken, token, userRole, userID,setPagination((previous) => ({ ...previous, pageIndex: 0 }));}, []);+ const handleExcludeInternalHealthChecksChange = useCallback(+ (value: boolean) => {+ setExcludeInternalHealthChecks(value);+ resetToFirstPage();+ },+ [resetToFirstPage],+ );+const handleResetFilters = useCallback(() => {setColumnFilters([]);setStartTime(moment().subtract(24, "hours").format("YYYY-MM-DDTHH:mm"));@@ -313,6 +331,8 @@ export default function RequestLogsPanel({ accessToken, token, userRole, userID,onSelectedTimeIntervalChange={setSelectedTimeInterval}isLiveTail={isLiveTail}onIsLiveTailChange={setIsLiveTail}+ excludeInternalHealthChecks={excludeInternalHealthChecks}+ onExcludeInternalHealthChecksChange={handleExcludeInternalHealthChecksChange}onResetToFirstPage={resetToFirstPage}onResetFilters={handleResetFilters}/>diff --git a/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.test.tsx b/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.test.tsxindex 26c5bda1593..b61461dc4d7 100644--- a/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.test.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.test.tsx@@ -47,6 +47,7 @@ const defaultProps = {columnFilters: [] as ColumnFiltersState,activeTab: "request logs",isLiveTail: false,+ excludeInternalHealthChecks: false,startTime: "2025-01-01T00:00:00",endTime: "2025-01-01T23:59:59",pagination: FIRST_PAGE,@@ -152,6 +153,7 @@ describe("useLogFilterLogic", () => {["pagination", { pagination: { pageIndex: 1, pageSize: 50 } }],["startTime", { startTime: "2025-02-02T00:00:00" }],["columnFilters", { columnFilters: [{ id: LOG_FILTER_IDS.TEAM_ID, value: "team-2" }] }],+ ["excludeInternalHealthChecks", { excludeInternalHealthChecks: true }],])("refetches when %s changes", async (_label, nextProps) => {const { rerender } = renderHook((props: HookOverrides) => useLogFilterLogic({ ...defaultProps, ...props }), {wrapper,@@ -164,6 +166,22 @@ describe("useLogFilterLogic", () => {});});+ describe("hide health checks toggle", () => {+ it("passes exclude_internal_health_checks when the toggle is on", async () => {+ renderFilterHook({ excludeInternalHealthChecks: true });++ await waitFor(() => expect(uiSpendLogsCall).toHaveBeenCalled());+ expect(lastCallParams()?.params).toMatchObject({ exclude_internal_health_checks: true });+ });++ it("passes exclude_internal_health_checks as false when the toggle is off", async () => {+ renderFilterHook();++ await waitFor(() => expect(uiSpendLogsCall).toHaveBeenCalled());+ expect(lastCallParams()?.params).toMatchObject({ exclude_internal_health_checks: false });+ });+ });+describe("query enablement", () => {it("does not query when the request logs tab is inactive", async () => {renderFilterHook({ activeTab: "audit logs" });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.tsxindex 474f51e93b3..9b6666dc9ee 100644--- a/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.tsx+++ b/ui/litellm-dashboard/src/components/view_logs/log_filter_logic.tsx@@ -101,6 +101,7 @@ export function useLogFilterLogic({columnFilters,activeTab,isLiveTail,+ excludeInternalHealthChecks,startTime,endTime,pagination,@@ -114,6 +115,7 @@ export function useLogFilterLogic({columnFilters: ColumnFiltersState;activeTab: string;isLiveTail: boolean;+ excludeInternalHealthChecks: boolean;startTime: string;endTime: string;pagination: PaginationState;@@ -137,6 +139,7 @@ export function useLogFilterLogic({columnFilters,sortBy,sortOrder,+ excludeInternalHealthChecks,],queryFn: async () => {if (!accessToken || !token || !userRole || !userID) {@@ -174,6 +177,7 @@ export function useLogFilterLogic({error_message: getFilterValue(columnFilters, LOG_FILTER_IDS.ERROR_MESSAGE),sort_by: sortBy,sort_order: sortOrder,+ exclude_internal_health_checks: excludeInternalHealthChecks,},});},diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex 3d657ea53a7..04873dd5dc9 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -53256,6 +53256,8 @@ export interface operations {sort_by?: string;/** @description Sort order: asc or desc */sort_order?: string | null;+ /** @description Exclude LiteLLM internal health check requests from results */+ exclude_internal_health_checks?: boolean;};header?: never;path?: never;@@ -53364,6 +53366,8 @@ export interface operations {sort_by?: string;/** @description Sort order: asc or desc */sort_order?: string | null;+ /** @description Exclude LiteLLM internal health check requests from results */+ exclude_internal_health_checks?: boolean;};header?: never;path?: never;