Repository navigation
refactor(cost): price generic_cost_per_token with the native calculate - #52816
Merged
Merged
Conversation
This was referenced Nov 19, 2026
Merged
feat(cost): price native /v1/messages calls in the Rust route and hand the receipt to logging
#52624
Merged
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
maciej-berri
force-pushed
the
litellm_cost_generic_on_main
branch
from
November 20, 2026 20:30
524ef7c to
7d43c5b
Compare
maciej-berri
marked this pull request as ready for review
November 20, 2026 20:59
Contributor
maciej-berri
force-pushed
the
litellm_cost_generic_on_main
branch
from
November 20, 2026 21:10
7d43c5b to
471b635
Compare
Contributor
Author
|
rust-test and rust-wheel fail on main code this PR doesn't touch: marshal_boundary flags db_repository/user.rs (#52756), and stubtest flags main-only names. Generated by Claude Code |
This was referenced Nov 22, 2026
narmstrong-berri
approved these changes
Nov 23, 2026
narmstrong-berri
left a comment
Contributor
There was a problem hiding this comment.
Minor comment changes, but the shape looks great. Thanks Maciej!
Contributor
Author
|
rust-test fails twice on a callbacks-budgets seeding test. That crate and its dependencies are unchanged from main here, so it comes from main. Generated by Claude Code |
narmstrong-berri
force-pushed
the
litellm_cost_generic_on_main
branch
2 times, most recently
from
November 23, 2026 20:37
ae72103 to
4464926
Compare
narmstrong-berri
enabled stacked auto-merge (squash)
November 23, 2026 20:47
litellm-cost gains Schedule::is_open, Quote and calculate, and generic_cost_per_token now lowers the row into NativePrices and prices the billed quantities there. Quote is the single rate rule: band pick, service tier fallback, tiered_pricing, off-peak, cache read and write, modality and reasoning rates, unit meters. calculate multiplies usage over it, sums each side in the order Python did and applies the residency, FedRAMP and regional endpoint uplifts Python keeps reading provider usage into counts (billed_quantities), the provider wrappers, custom pricing, the Anthropic and Bedrock geo and speed multipliers and the batch path. get_billed_token_rates, calculate_prompt_caching_savings and the Perplexity and Dashscope cost files read rates from quote. The Python rate functions, the Fireworks cache-read default module and the price lookup reference fixture are deleted model-catalog adds billed_prices, a lowering for billing that never fails, because a deployment that overrides a flat-priced row with tiered_pricing holds both spellings and Prices::try_from rejects it. Prices::try_from stays strict for the catalog guard
The first cut of the native pricing path changed the bill for a few row shapes no catalog row has. Each one now has a test that failed first and passes on main billed_prices returns BilledPrices, Flat or Tiered. A row whose token tiers price input bills an empty prompt from its flat prices, since main picks no tier for it, so a tier-only row bills it nothing. A tier's missing cache and reasoning rates are that tier's input and output rate, filled before any off-peak swap, which also stops a Fireworks row with tiers from reading its cache at half price. A token tier starts where the one before it ends, so a ladder written with a one token gap bills the next tier from its first token. Result tiers are left to the search calculator. A modality input token price that does not parse is 0 again The off-peak reader reports a malformed window or weekday and keeps the well-formed ones, where it used to drop the whole block A batch or decisions call, or one with custom pricing, gets a quote with no rates instead of online rates, and the speed and geo uplifts apply when the row carries them NativeTokenUsage names its quantities input_*, cached_*, cache_write_* and output_*, and billed_cache_read_rate is the one place that picks the explicit or implicit cache-read rate
Main now bills an image-only row's output at output_cost_per_image_token for the request's service tier, falling back to the standard image rate. Quote::text_output read only the standard image rate, so a priority call kept billing the standard price after the rebase
narmstrong-berri
force-pushed
the
litellm_cost_generic_on_main
branch
from
November 23, 2026 21:47
4464926 to
9778a16
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Handwritten 1-3 sentence description
Moves the python cost_calculator calculate math function to rust.
Details
This PR carries #51566 by @yujonglee-berri, rebased onto current main so the cost tracking stack (#52472 and up) sits on main. The two commits from #51566 keep their original author. The latest rebase, onto main at 74bc0f8, hit two conflicts. In
python-bridge/Cargo.tomlthe pyo3 features now carry main'schrononext to this PR'sjiff-02. Inllm_cost_calc/utils.pymain had changed one line of the Python rate code this PR deletes (#52972, which bills an image-only row's output at the image token rate of the request's service tier), so the deletion stands and a third commit ports that change toQuote, which read only the standard image rate. It now reads the call tier's image rate first and falls back to the standard one, with a test per case. The TLDR, user flow, live proof, sweeps and caveats come from #51566, and its proof was run at its original commit 5f51b4a. The tests rerun at this tip are listed under Screenshots / Proof of Fix.TLDR
Problem this solves:
How it solves it:
litellm-costgetsSchedule::is_open,Quoteandcalculategeneric_cost_per_tokennow callsNativePrices(...).calculate(...)get_billed_token_rates, savings, Perplexity, Dashscope) readquoteWhat moved to Rust:
tiered_pricing, off-peak schedule and rate swapWhat stays in Python:
billed_quantities)cost_per_token,completion_cost, custom pricing, discount and marginNot in the original plan:
billed_pricesreturnsBilledPrices, a lowering for billing that never failsPrices::try_fromrejects a row that holds both flat and tiered prices, which a deployment override producesFlat(Prices), orTiered { tiers, empty_prompt }for a row whose token tiers price inputPrices::try_fromstays strict for the catalog guardcalculatereturnsUnpricedfor a batch or decisions call or one with custom pricingNativeQuote.uplift, so rate readers stop calling the Python uplift gettersUser Flow
Before: a developer reads the cost of a chat call from the response header
"model": "deepseek-flash"usageblock andx-litellm-response-cost: 2.55e-05x-litellm-response-cost-cache-readAfter: the same calls return the same costs
"model": "deepseek-flash"usageblock andx-litellm-response-cost: 2.55e-05x-litellm-response-cost-cache-readRelevant issues
Carries #51566 onto current main.
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or moreDelays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
The live proof below is #51566's, run at its original commit 5f51b4a against its merge base 27e9a04. It was not rerun at this branch's tip because no provider keys were available here. What changed since is the rebases onto main and the image rate port, so the tip was checked with the tests listed under "Rerun at the new tip".
Rerun at the new tip (471b635)
The native extension was rebuilt from the tip. The rerun covers what the rebase touched, and CI covers the rest.
The ruff strict, type discipline and test quality gates pass against main, ruff check and format are clean on the changed files, and CI's rust-lint (clippy and fmt) and typecheck jobs pass at this tip. CI's rust-test job fails on
marshal_boundary, which flagsserde_json::from_strinpython-bridge/src/db_repository/user.rs, and rust-wheel fails on the same 5 stubtest errors listed above. Both come from main code this PR does not touch.Overhead of pricing in Rust
generic_cost_per_tokennow buildsNativePrices(row, provider)on every call, which copies the wholeget_model_inforow into Rust and lowers it before pricing. Main read only the keys it needed straight from the dict. This PR does not cache the lowered row, so the cost was measured at main 74bc0f8 and at this PR's tip 471b635 (built from 7d43c5b, which has the same tree), with release wheels built from each commit, on an Apple M5 with Python 3.12 andLITELLM_LOCAL_MODEL_COST_MAP=True. Every cost matched main to the last digit.The row is copied once per request, never per chunk. A request copies it 2 times without streaming and 3 times with streaming, sync or async, and a streamed response of 501 chunks still copies it 3 times. One copy costs about 7µs for a 25 field row and about 17µs for a 50 field row, so a request pays about 15 to 50µs. Against the 1 to 3ms LiteLLM itself spends on a mocked request that is 2 to 6%, and against a real provider call of 300ms or more it is under 0.02%. Rows with an off-peak schedule got faster, since main's Python schedule check cost more than the copy.
generic_cost_per_tokenmain -> tipcompletion_costmain -> tiplitellm.completionwithmock_responseEach number is the median of 5 batches (3000 calls per batch for the cost functions, 300 for
litellm.completion), and each leg ran twice, alternating main and tip. The cost function numbers agree within 1µs between runs, the end-to-end ones within about 30µs. The usage in the first table is a 4978 token prompt with 4736 cached tokens and 120 completion tokens, 40 of them reasoning.How it was run
bench_cost.pytimesgeneric_cost_per_tokenwith the row passed in and looked up, andcompletion_coston aModelResponse, for each row above.bench_request.pywrapsNativePricesin a counter where the module imports it, sendslitellm.completionandlitellm.acompletionwithmock_response, streaming and not, and counts the constructions per request after the logging threads settle. Both scripts are below.The 501 chunk check ran the same counter with
mock_response=" ".join(["word"] * 300)andstream=True.Proof from #51566 at 5f51b4a
Two proxies ran side by side against the real DeepSeek API at 2026-11-13T07:10:42Z, the merge base on port 4001 and #51566 on port 4000. Each proxy loaded its own
_native.abi3.so, checked withlsof -p <pid> | grep _native. DeepSeek returns slightly different completion and reasoning token counts per call, so each case ran five times per proxy, and rows with the same usage are comparedShared setup
DEEPSEEK_API_KEY,LITELLM_MASTER_KEY,LITELLM_MODE=PRODUCTION(so neither proxy reads a.env)--port 4001for the merge base and--port 4000for the branchconfig.yamlrun.outRequest bodies and the curl loop
Before (27e9a04)
Plain call
grep '^plain :4001' run.out | sort -k3 | uniq -cCached prompt
grep '^cached :4001' run.out | sort -k3 | uniq -cReasoning call
grep '^reasoning :4001' run.out | sort -k3 | uniq -cAfter (5f51b4a)
Plain call
grep '^plain :4000' run.out | sort -k3 | uniq -c. The 13 completion token rows match Before to the last digitCached prompt
grep '^cached :4000' run.out | sort -k3 | uniq -c. The 12 and 16 completion token rows match Before to the last digit, cache read includedReasoning call
grep '^reasoning :4000' run.out | sort -k3 | uniq -c. The 18 completion token rows match Before to the last digitSweeps: old Python against native (from #51566)
Throwaway scripts (not committed) loaded the Python cost files from the merge base and compared them with #51566, with
==on the floatsflex,priority,fast,ultrafast,balanced,auto,PRIORITYeu,US,fedramp), Vertex location and peak and off-peak instants on the rows that price themgeneric_cost_per_token: 1,709,392 checks, none differ beyond the last bitget_billed_token_rates: 359,872 checks, 0 differencescalculate_prompt_caching_savings: 359,872 checks, 0 differencescost_per_token: 16,896 checks, 0 differencescost_per_token: 8,712 checks, 0 differencesType
🧹 Refactoring
Caveats (if any)
Medium
Low
service_tier: priorityabove 200k tokens bill 1h writes at the base 1h rate_above_Nk_tokensprices on this pathlitellm-costonlyquote.rs,calculate.rs,Schedule::is_openandAdjustments::for_callwas caughtmodel-cataloglowering was not mutation testedFinal Attestation