Repository navigation
feat(cost-optimization): add spend-by-tool and cache leakage views - #33978
Conversation
🤖 Devin AI EngineerI'll be helping with this pull request! Here's what you should know: ✅ I will automatically:
Note: I can only respond to comments from users who have write access to this repository. ⚙️ Control Options:
|
Greptile SummaryThis PR adds
Confidence Score: 5/5Safe to merge — the new backend endpoint is correctly guarded, date validation is strict, and the dashboard changes are purely additive. The backend SQL uses parameterised date binds, the admin-role check is explicit, malformed dates return 400 before any DB query fires, and the route order prevents wildcard shadowing — all verified by mock-only unit tests. The frontend changes are isolated to the cost-optimisation page, share state cleanly via the new hook, and carry no regressions in the daily-activity or caching tabs. The only open item is a hardcoded provider regex in costOptimizationUtils.ts — the isAnthropicModel regex may need revisiting when new Anthropic model names are released that don't contain "claude" or "anthropic".
|
| Filename | Overview |
|---|---|
| litellm/proxy/management_endpoints/tool_management_endpoints.py | Adds GET /v1/tool/spend with proper admin-role guard, 400 on malformed dates, and two raw SQL queries (per-tool attributed spend and deduplicated total). Route is registered before the dynamic path so it is not shadowed. |
| litellm/types/tool_management.py | Adds ToolSpendEntry, ToolSpendDailyEntry, and ToolSpendResponse pydantic models; clean types with documented attribution semantics. |
| tests/test_litellm/proxy/management_endpoints/test_tool_management_endpoints.py | New tests cover route non-shadowing, aggregation/sort, 500 on missing DB, inclusive end-date bounds, parametrized malformed-date 400s, and 403 for non-admin; all use mocks, no real network calls. |
| ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/costOptimizationUtils.ts | Implements computeCacheLeakage (correct cache-inclusive prompt_tokens formula), buildDailyToolSeries, and topToolsBySpend. Contains a hardcoded isAnthropicModel regex that could miss future Anthropic models with different naming conventions. |
| ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/CacheLeakageCard.tsx | New cache leakage table component with sortable columns, by-key/by-model toggle, and info tooltips; correctly uses shared DailyActivityRange for date state. |
| ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.tsx | Refactored to accept shared DailyActivityRange; adds spend-by-tool section with bar charts and a properly-cancelled useEffect for the tool spend API call. |
| ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/useDailyActivityRange.ts | Extracts daily activity fetching into a shared hook so CostOptimizationView fetches once and both tabs share the same date range and data. |
| ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/CostOptimizationView.tsx | Minimal change: lifts daily activity state into useDailyActivityRange and passes the activity object to UsageTab and PromptCachingTab. |
| ui/litellm-dashboard/src/components/networking.tsx | Adds ToolSpendEntry, ToolSpendDailyEntry, ToolSpendResponse interfaces and getToolSpend API function; clean addition using the existing apiClient pattern. |
| ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/PromptCachingTab.tsx | Accepts shared activity prop and renders CacheLeakageCard below the existing settings panel. |
Reviews (7): Last reviewed commit: "feat(cost-optimization): sortable cache ..." | Re-trigger Greptile
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
|
QA output against a live proxy on localhost:4000, Postgres backed, seeded with two spend logs where request Before 543ece0 every call to the endpoint failed on a real Postgres, because prisma binds After 543ece0 the aggregation and the documented multi-tool attribution work:
Malformed dates now fail loudly instead of silently applying the default 30 day window: Since the endpoint reports deployment-wide spend it is now limited to proxy admin roles. A bare virtual key was already rejected by the auth layer (verified live, 401); a non-admin logged-in role now gets 403 from the endpoint, pinned in unit tests |
|
bugbot run |
|
135e7fc tightens the backend implementation without changing the endpoint's shape Query rows are now validated at the boundary with a pydantic TypeAdapter that returns typed rows or raises, replacing the TypedDict with per-field or-defaults; a malformed row now fails loudly instead of being silently coerced. by_tool is built in one groupby pass instead of rescanning all rows once per tool total_spend semantics changed: it previously summed per-tool attributed spend, so it exceeded real spend whenever one request used several tools. It is now the deduplicated spend of every request that called at least one tool in the window, via a second aggregate query. Per-tool spend stays attributed as documented. Live output on the same seeded data, where request qa-tool-spend-2 called both tools: 3.75 is the real 1.25 + 2.50; the attributed per-tool sum of 6.25 is no longer presented as a total. The UI never rendered total_spend, so nothing changes visually. Both semantics are documented as field descriptions on the response schema and the regenerated schema.d.ts carries them as JSDoc |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 135e7fc. Configure here.
1 similar comment
|
bugbot run |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit ea160cb. Configure here.
Adds GET /v1/tool/spend returning per-tool and daily tool spend with a deduplicated request total, and a cache leakage breakdown on the Prompt Caching tab of the Cost Optimization page. Tool-spend rows are validated at the boundary with pydantic, the endpoint is scoped to proxy admins, date params are cast to timestamptz for real-Postgres query_raw, and the leakage math treats litellm-normalized prompt_tokens as cache-inclusive (uncached = max(0, prompt - cache_read - cache_creation)).
ea160cb to
bd73ca8
Compare
…h plain-language columns Adds a By virtual key / By model toggle to the cache leakage table. The model view aggregates the daily activity model breakdown and is scoped to Anthropic (Claude) models, which support prompt caching. Renames the columns to plain language: Uncached input, Cache hit rate, and Potential savings (replacing Realized caching savings and Est. savings left), with a tooltip on Potential savings that spells out how it is calculated
…oken column name Makes the three metric columns on the cache leakage table sortable, each with a sensible first-click direction: most uncached tokens and biggest potential savings first, worst cache hit rate first. Repeat clicks toggle the direction. Renames Uncached input to Uncached input tokens, since the column is a token count
|
bugbot run |
|
@greptileai rereview |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 090fd49. Configure here.
…on_tools feat(cost-optimization): add spend-by-tool and cache leakage views (cherry picked from commit 43e7b96)
Relevant issues
GET /v1/tool/spend(proxy-admin only): joins the spend-log tool index to spend logs and returns per-tool attributed spend, daily series, and a deduplicated total over a date rangeprompt_tokensas cache-inclusive: uncached = prompt - cache_read - cache_creation, priced at the realized cache-read discount to estimate the potential savings each key or model is leaving on the tableLinear ticket
Resolves LIT-4689
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
@greptileaito re-request a review after pushing changes)Screenshots / Proof of Fix
Live proxy proof is posted as a PR comment: before and after curl output against localhost:4000 backed by a real Postgres with seeded spend log and tool index rows
Type
🆕 New Feature
Changes
This adds two optimization views to the Cost Optimization dashboard motivated by a customer workflow: estimating missed prompt-caching savings per virtual key, and attributing spend to the tools that ran
Backend adds
GET /v1/tool/spend, which joinsLiteLLM_SpendLogToolIndex(which tool names ran on which request) toLiteLLM_SpendLogs(what the request cost) and aggregates spend, call count, and tokens per tool over a date range. Because a single request can invoke several tools, per-tool spend is attributed rather than partitioned: a request that used multiple tools counts its full spend toward each tool present.total_spendis the deduplicated spend of every request that called at least one tool in the window (a second aggregate query), so it never double counts; both semantics are documented on the response schema. Query rows are validated at the boundary with a pydantic TypeAdapter and grouped in a single pass. The route is registered before the dynamic/v1/tool/{tool_name:path}routes so it is not shadowed. The endpoint is limited to proxy admin roles (403 otherwise) since it reports deployment-wide spend, malformed date params return 400 (Expected: 'YYYY-MM-DD') instead of silently falling back to the default window, the end date is inclusive via a half-open next-day bound, and the query binds its date params with$n::timestamptz AT TIME ZONE 'UTC'casts, matching the other raw spend queries, so it runs on a real PostgresFrontend adds a "Spend by tool" chart (top tools by attributed spend plus a stacked daily view) to the Usage tab of the Cost Optimization page, and a cache leakage table to the Prompt Caching tab, beneath the caching settings panel so the diagnosis sits next to the control that fixes it. The table carries a By virtual key / By model toggle; the model view aggregates the daily-activity model breakdown and is scoped to Anthropic (Claude) models, which support prompt caching, so it never shows a savings figure for a model that cannot cache. The daily-activity query and the date range live in a
useDailyActivityRangehook owned byCostOptimizationViewand are passed to both tabs, so the page fetches that data once regardless of which tabs are opened and both pickers stay on one range. Cache leakage reuses the existing daily-activity per-key breakdown. litellm's normalizedprompt_tokensincludes cache read and cache creation tokens for every provider, so uncached tokens are computed asprompt_tokens - cache_read_input_tokens - cache_creation_input_tokens(clamped at zero) and the cache hit ratio iscache_read / prompt_tokens. The columns read in plain language: Uncached input tokens, Cache hit rate, and Potential savings, which prices those uncached tokens at the realized cache-read discount (uncached input tokens times realized cache savings over cache-read tokens) and carries a tooltip spelling out that calculation. All three metric columns are sortable, each opening in the direction that surfaces the worst offenders first: most uncached tokens and biggest potential savings first, lowest cache hit rate first, with repeat clicks toggling direction. That estimate is explicitly approximate, since the system cannot know whether a given uncached prompt would have been cacheable. Keys are shown by alias or a truncated hash, never a raw secretQA runbook
Run a proxy with a Postgres DB that has spend logs and tool-index rows, then:
curl -s -H "Authorization: Bearer sk-1234" "http://localhost:4000/v1/tool/spend?start_date=2026-06-01&end_date=2026-07-19" | jqreturns per-tool spend sorted descending, a daily array, and a total_spend that is at most the sum of by_tool spend (strictly less whenever a request used several tools)curl -s -H "Authorization: Bearer sk-1234" "http://localhost:4000/v1/tool/spend?start_date=07/01/2026"returns 400 withInvalid date format: 07/01/2026. Expected: 'YYYY-MM-DD'http://localhost:4000/ui/?page=cost-optimization, stay on the default "Usage" tab, pick a date range, and confirm the "Spend by tool" chart rendersFinal Attestation
Link to Devin session: https://app.devin.ai/sessions/e5a21acd37294315a9a82370b78fe63a
Requested by: @krrish-berri-2
Note
Medium Risk
New deployment-wide spend SQL and admin-only API touch spend logs; dashboard changes are additive but rely on correct multi-tool attribution semantics for cost decisions.
Overview
Adds proxy-admin
GET /v1/tool/spendfor the Cost Optimization dashboard: it joins spend-log tool index rows to spend logs, returns per-tool attributed spend (multi-tool requests count full cost toward each tool), a daily series, and a deduplicatedtotal_spend. The route sits ahead of dynamic/v1/tool/{tool_name}paths, validatesYYYY-MM-DDdates (400 on bad input), and returns 403 for non-admin callers.On the dashboard,
useDailyActivityRangelifts paginated daily activity (and one shared date range) intoCostOptimizationViewso Usage and Prompt Caching tabs do not refetch when switching tabs. The Usage tab loads tool spend for the selected range and shows spend-by-tool bar charts. The Prompt Caching tab adds a cache leakage table (by virtual key or Anthropic-only model) with sortable uncached tokens, cache hit rate, and approximate potential savings from existing daily-activity breakdowns.Client
getToolSpendand OpenAPI/schema snapshots are updated; backend and UI tests cover aggregation, auth, routing, and leakage math.Reviewed by Cursor Bugbot for commit 090fd49. Bugbot is set up for automated code reviews on this repo. Configure here.