Skip to content

feat(cost-optimization): add spend-by-tool and cache leakage views - #33978

Merged
tin-berri merged 3 commits into
litellm_internal_stagingfrom
litellm_cost_optimization_tools
Jul 23, 2026
Merged

tin-berri merged 3 commits into
litellm_internal_stagingfrom
litellm_cost_optimization_tools

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Relevant issues

  • Adds 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 range
  • Adds a "Spend by tool" chart to the Cost Optimization Usage tab, and a cache leakage table to the Prompt Caching tab next to the setting it tells you to turn on, with a By virtual key / By model toggle (the model view is scoped to Anthropic Claude models) sortable metric columns, and an info tooltip explaining each leakage column
  • Cache leakage treats litellm's normalized prompt_tokens as 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 table

Linear ticket

Resolves LIT-4689

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to 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 joins LiteLLM_SpendLogToolIndex (which tool names ran on which request) to LiteLLM_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_spend is 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 Postgres

GET /v1/tool/spend?start_date=YYYY-MM-DD&end_date=YYYY-MM-DD
-> { by_tool: [{ tool_name, spend, call_count, total_tokens }],
     daily:   [{ date, tool_name, spend, call_count }],
     total_spend, start_date, end_date }

Frontend 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 useDailyActivityRange hook owned by CostOptimizationView and 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 normalized prompt_tokens includes cache read and cache creation tokens for every provider, so uncached tokens are computed as prompt_tokens - cache_read_input_tokens - cache_creation_input_tokens (clamped at zero) and the cache hit ratio is cache_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 secret

QA 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" | jq returns 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 with Invalid date format: 07/01/2026. Expected: 'YYYY-MM-DD'
  • calling the endpoint with a non-admin principal returns 403 (a bare virtual key is already rejected by the auth layer with 401)
  • open http://localhost:4000/ui/?page=cost-optimization, stay on the default "Usage" tab, pick a date range, and confirm the "Spend by tool" chart renders
  • switch to the "Prompt Caching" tab and confirm the cache leakage table renders below the settings panel, sorted by potential savings, over the same date range you picked on the Usage tab, with an info tooltip on each metric column and no raw key values shown; toggle it from By virtual key to By model and confirm it re-groups the same metrics by model, listing only Anthropic (Claude) models; click the Uncached input tokens, Cache hit rate, and Potential savings headers and confirm each re-sorts the table, with cache hit rate opening worst-first

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

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/spend for 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 deduplicated total_spend. The route sits ahead of dynamic /v1/tool/{tool_name} paths, validates YYYY-MM-DD dates (400 on bad input), and returns 403 for non-admin callers.

On the dashboard, useDailyActivityRange lifts paginated daily activity (and one shared date range) into CostOptimizationView so 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 getToolSpend and 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.

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment, CI, and merge conflict monitoring

@CLAassistant

CLAassistant commented Jul 20, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@greptile-apps

greptile-apps Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds GET /v1/tool/spend (admin-only, 400 on malformed dates, two raw SQL queries with proper date binding) and extends the Cost Optimization UI with a "Spend by tool" chart on the Usage tab and a sortable "Cache leakage" table on the Prompt Caching tab.

  • Backend: joins LiteLLM_SpendLogToolIndex to LiteLLM_SpendLogs for per-tool attributed spend; a separate deduplicated totals query avoids double-counting; route is registered before the /{tool_name:path} wildcard; admin-role and DB-null guards in place; comprehensive mock-only tests cover edge cases.
  • Frontend: useDailyActivityRange lifts date state to CostOptimizationView so both tabs share one fetch and one date picker; computeCacheLeakage correctly subtracts cache_read and cache_creation tokens from prompt_tokens (cache-inclusive as of the previous fix); sortable columns, by-key/by-model toggle, and info tooltips are implemented cleanly.
  • Minor concern: isAnthropicModel hard-codes a provider-specific regex in the frontend rather than reading a capability flag from the model registry, which may silently exclude future Anthropic models with different naming conventions.

Confidence Score: 5/5

Safe 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 that has no runtime impact today.

costOptimizationUtils.ts — the isAnthropicModel regex may need revisiting when new Anthropic model names are released that don't contain "claude" or "anthropic".

Important Files Changed

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

codecov Bot commented Jul 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_cost_optimization_tools (090fd49) with litellm_internal_staging (b5bc363)1

Open in CodSpeed

Footnotes

  1. No successful run was found on litellm_internal_staging (df3050f) during the generation of this report, so b5bc363 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@tin-berri

Copy link
Copy Markdown
Contributor

QA output against a live proxy on localhost:4000, Postgres backed, seeded with two spend logs where request qa-tool-spend-2 called two tools

Before 543ece0 every call to the endpoint failed on a real Postgres, because prisma binds query_raw params as text and the query compared them to a timestamp column without a cast (the unit tests mock query_raw, so they could not catch this):

$ curl -s -H "Authorization: Bearer sk-1234" "http://localhost:4000/v1/tool/spend?start_date=2026-06-20&end_date=2026-07-17"
{"error":{"message":"Internal server error","type":"internal_server_error"}}

# proxy log:
prisma.errors.RawQueryError: ERROR: operator does not exist: timestamp without time zone >= text

After 543ece0 the aggregation and the documented multi-tool attribution work:

$ curl -s -H "Authorization: Bearer sk-1234" "http://localhost:4000/v1/tool/spend?start_date=2026-07-15&end_date=2026-07-15" | jq
{
  "by_tool": [
    { "tool_name": "qa/search", "spend": 3.75, "call_count": 2, "total_tokens": 1400 },
    { "tool_name": "qa/read_file", "spend": 2.5, "call_count": 1, "total_tokens": 900 }
  ],
  "daily": [
    { "date": "2026-07-15", "tool_name": "qa/search", "spend": 3.75, "call_count": 2 },
    { "date": "2026-07-15", "tool_name": "qa/read_file", "spend": 2.5, "call_count": 1 }
  ],
  "total_spend": 6.25,
  "start_date": "2026-07-15",
  "end_date": "2026-07-15"
}

qa/search gets 1.25 + 2.50 because the second request used both tools, and total_spend is the sum of attributions as documented

Malformed dates now fail loudly instead of silently applying the default 30 day window:

$ curl -s -w "\nHTTP %{http_code}\n" -H "Authorization: Bearer sk-1234" "http://localhost:4000/v1/tool/spend?start_date=07/01/2026"
{"detail":"Invalid date format: 07/01/2026. Expected: 'YYYY-MM-DD'"}
HTTP 400

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

@tin-berri

Copy link
Copy Markdown
Contributor

@greptileai

@tin-berri

Copy link
Copy Markdown
Contributor

bugbot run

@tin-berri

Copy link
Copy Markdown
Contributor

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:

$ curl -s -H "Authorization: Bearer sk-1234" "http://localhost:4000/v1/tool/spend?start_date=2026-07-15&end_date=2026-07-15" | jq '{total_spend, by_tool: [.by_tool[] | {tool_name, spend}]}'
{
  "total_spend": 3.75,
  "by_tool": [
    { "tool_name": "qa/search", "spend": 3.75 },
    { "tool_name": "qa/read_file", "spend": 2.5 }
  ]
}

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

@tin-berri

Copy link
Copy Markdown
Contributor

@greptileai

@tin-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.

@tin-berri

Copy link
Copy Markdown
Contributor

@greptileai

1 similar comment
@tin-berri

Copy link
Copy Markdown
Contributor

@greptileai

@tin-berri

Copy link
Copy Markdown
Contributor

bugbot run

@tin-berri

Copy link
Copy Markdown
Contributor

@greptileai

@tin-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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)).
@tin-berri
tin-berri force-pushed the litellm_cost_optimization_tools branch from ea160cb to bd73ca8 Compare July 23, 2026 17:48
…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
@tin-berri

Copy link
Copy Markdown
Contributor

bugbot run

@tin-berri

Copy link
Copy Markdown
Contributor

@greptileai rereview

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.

@tin-berri
tin-berri merged commit 43e7b96 into litellm_internal_staging Jul 23, 2026
81 checks passed
@tin-berri
tin-berri deleted the litellm_cost_optimization_tools branch July 23, 2026 20:43
yuneng-berri added a commit that referenced this pull request Jul 28, 2026
…nd_0727

chore(release): backport #33899, #33978, #34582, #34675 to rc/1.94.0 and bump litellm-proxy-extras to 0.4.79.post2
ap-anton-r-susilo pushed a commit to ap-anton-r-susilo/litellm that referenced this pull request Jul 29, 2026
…on_tools

feat(cost-optimization): add spend-by-tool and cache leakage views

(cherry picked from commit 43e7b96)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants