Skip to content

refactor(cost): price generic_cost_per_token with the native calculate - #52816

Merged
narmstrong-berri merged 4 commits into
mainfrom
litellm_cost_generic_on_main
Nov 23, 2026
Merged

narmstrong-berri merged 4 commits into
mainfrom
litellm_cost_generic_on_main

Conversation

@maciej-berri

@maciej-berri maciej-berri commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

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.toml the pyo3 features now carry main's chrono next to this PR's jiff-02. In llm_cost_calc/utils.py main 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 to Quote, 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:

  • Token pricing rules lived in Python only
  • The Rust gateway could not price a call the same way
  • About 900 lines of rate resolution had no single rule

How it solves it:

  • litellm-cost gets Schedule::is_open, Quote and calculate
  • generic_cost_per_token now calls NativePrices(...).calculate(...)
  • Rate readers (get_billed_token_rates, savings, Perplexity, Dashscope) read quote
  • The Python rate functions and their reference fixture are deleted

What moved to Rust:

  • Band pick, service tier fallback, tiered_pricing, off-peak schedule and rate swap
  • Cache read (implicit, explicit, per modality) and cache write by TTL
  • Modality token rates, reasoning rate, the image token fallback for output
  • Characters, image count, audio and video seconds, queries
  • Residency, FedRAMP and Vertex regional uplifts

What stays in Python:

  • Reading provider usage into counts (billed_quantities)
  • The provider wrappers, cost_per_token, completion_cost, custom pricing, discount and margin
  • Anthropic and Bedrock geo and speed multipliers
  • The batch path

Not in the original plan:

  • billed_prices returns BilledPrices, a lowering for billing that never fails
    • Prices::try_from rejects a row that holds both flat and tiered prices, which a deployment override produces
    • Flat(Prices), or Tiered { tiers, empty_prompt } for a row whose token tiers price input
      • An empty prompt picks no tier, so it reads the flat prices
      • A tier's missing cache and reasoning rates are that tier's input and output rate
      • A token tier starts where the one before it ends
    • Prices::try_from stays strict for the catalog guard
  • The off-peak reader keeps well-formed windows and weekdays when one is malformed
    • The catalog guard still reports the malformed one
  • calculate returns Unpriced for a batch or decisions call or one with custom pricing
    • Pricing them at online rates would be silently wrong, and Python still prices those
  • NativeQuote.uplift, so rate readers stop calling the Python uplift getters

User Flow

Before: a developer reads the cost of a chat call from the response header

  1. They send POST http://localhost:4000/v1/chat/completions with "model": "deepseek-flash"
  2. The response comes back 200 with a usage block and x-litellm-response-cost: 2.55e-05
  3. A prompt served from cache comes back with a lower cost and x-litellm-response-cost-cache-read

After: the same calls return the same costs

  1. They send POST http://localhost:4000/v1/chat/completions with "model": "deepseek-flash"
  2. The response comes back 200 with the same usage block and x-litellm-response-cost: 2.55e-05
  3. A prompt served from cache comes back with the same lower cost and x-litellm-response-cost-cache-read

Relevant issues

Carries #51566 onto current main.

Pre-Submission checklist

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

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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 more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

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

cd litellm/rust
cargo test -p litellm-cost
cargo test -p litellm-model-catalog
cargo fmt --all -- --check
cargo build -p litellm-python-bridge --lib --features extension-module
cd ../..
python -m mypy.stubtest --mypy-config-file tests/unit/rust_bridge/stubtest.ini litellm.rust_bridge._native
PYTHONPATH=litellm/enterprise LITELLM_LOCAL_MODEL_COST_MAP=True python -m pytest -q -n 3 tests/unit/test_cost_calculator.py tests/unit/litellm_core_utils/llm_cost_calc tests/unit/rust_bridge
PYTHONPATH=litellm/enterprise LITELLM_LOCAL_MODEL_COST_MAP=True python -m pytest -q tests/unit/llms/dashscope tests/unit/llms/perplexity
litellm-cost: 177 passed, 0 failed (3 new cases for the image rate port)
litellm-model-catalog: 309 passed, 0 failed
cargo fmt --check: clean
stubtest: 5 errors, all on names only main added (AuthObject, NativeActiveTeams, NativeSensitiveRoutePins)
pytest (cost, llm_cost_calc, rust_bridge): 2616 passed
pytest (dashscope, perplexity): 746 passed

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 flags serde_json::from_str in python-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_token now builds NativePrices(row, provider) on every call, which copies the whole get_model_info row 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 and LITELLM_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.

Row (fields) generic_cost_per_token main -> tip completion_cost main -> tip
gpt-5.5 (50) 54 -> 71µs 128 -> 136µs
gemini/gemini-2.5-pro (53) 54 -> 70µs 121 -> 128µs
claude-sonnet-5-5 (38) 51 -> 64µs 124 -> 132µs
gpt-4o (25) 52 -> 59µs 125 -> 125µs
deepseek/deepseek-flash (25, off-peak) 136 -> 63µs 218 -> 122µs
litellm.completion with mock_response non-stream main -> tip stream main -> tip
gpt-5.5 ~1080 -> ~1150µs ~2880 -> ~3070µs
anthropic/claude-sonnet-5-5 ~930 -> ~955µs ~2700 -> ~2820µs
gemini/gemini-2.5-pro ~915 -> ~940µs ~2770 -> ~2865µs

Each 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
git worktree add --detach ../main-74bc 74bc0f8431
for dir in ../main-74bc .; do (cd $dir && uv build --python 3.12 --wheel --out-dir "$OLDPWD/wheels-$(basename $dir)"); done
UV_PROJECT_ENVIRONMENT=bench-venv uv sync --python 3.12 --frozen --no-install-project
uv pip install --python bench-venv/bin/python --no-deps --target site-main wheels-main-74bc/*.whl
uv pip install --python bench-venv/bin/python --no-deps --target site-tip wheels-./*.whl
for leg in main tip main tip; do PYTHONPATH=site-$leg bench-venv/bin/python bench_cost.py $leg; done
for leg in tip main tip main; do PYTHONPATH=site-$leg bench-venv/bin/python bench_request.py $leg; done

bench_cost.py times generic_cost_per_token with the row passed in and looked up, and completion_cost on a ModelResponse, for each row above. bench_request.py wraps NativePrices in a counter where the module imports it, sends litellm.completion and litellm.acompletion with mock_response, streaming and not, and counts the constructions per request after the logging threads settle. Both scripts are below.

# bench_cost.py
import json, os, statistics, sys, time

os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
import litellm
from litellm import completion_cost
from litellm.litellm_core_utils.llm_cost_calc.utils import generic_cost_per_token
from litellm.types.utils import Choices, CompletionTokensDetailsWrapper, Message, ModelResponse, PromptTokensDetailsWrapper, Usage

CASES = [("gpt-5.5", "openai"), ("gpt-4o", "openai"), ("claude-sonnet-5-5", "anthropic"),
         ("gemini/gemini-2.5-pro", "gemini"), ("deepseek/deepseek-flash", "deepseek")]

def usage():
    return Usage(prompt_tokens=4978, completion_tokens=120, total_tokens=5098,
                 prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=4736, text_tokens=242),
                 completion_tokens_details=CompletionTokensDetailsWrapper(reasoning_tokens=40, text_tokens=80))

def timed(fn, n):
    for _ in range(200):
        fn()
    runs = []
    for _ in range(5):
        start = time.perf_counter()
        for _ in range(n):
            fn()
        runs.append((time.perf_counter() - start) / n * 1e6)
    return statistics.median(runs)

results = {}
for model, provider in CASES:
    info = litellm.get_model_info(model=model, custom_llm_provider=provider)
    u = usage()
    r = ModelResponse(model=model, usage=usage(),
                      choices=[Choices(index=0, finish_reason="stop", message=Message(role="assistant", content="ready"))])
    results[model] = {
        "generic_row_given_us": timed(lambda: generic_cost_per_token(model=model, usage=u, custom_llm_provider=provider, model_info=info), 3000),
        "generic_lookup_us": timed(lambda: generic_cost_per_token(model=model, usage=u, custom_llm_provider=provider), 3000),
        "completion_cost_us": timed(lambda: completion_cost(completion_response=r, model=model, custom_llm_provider=provider), 1000),
        "cost": sum(generic_cost_per_token(model=model, usage=u, custom_llm_provider=provider)),
    }
print(json.dumps({"label": sys.argv[1], "results": results}))
# bench_request.py
import asyncio, json, os, statistics, sys, time

os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
import litellm
import litellm.litellm_core_utils.llm_cost_calc.utils as cost_utils

counts = {"constructed": 0}
original = getattr(cost_utils, "NativePrices", None)
if original is not None:
    def counting(*args, **kwargs):
        counts["constructed"] += 1
        return original(*args, **kwargs)
    cost_utils.NativePrices = counting

MESSAGES = [{"role": "user", "content": "Reply with the single word: ready"}]

def sync_call(model, stream):
    response = litellm.completion(model=model, messages=MESSAGES, mock_response="ready", stream=stream)
    if stream:
        for _ in response:
            pass

async def async_call(model, stream):
    response = await litellm.acompletion(model=model, messages=MESSAGES, mock_response="ready", stream=stream)
    if stream:
        async for _ in response:
            pass

def run(model, kind, stream):
    sync_call(model, stream) if kind == "sync" else asyncio.run(async_call(model, stream))

def per_request(model, kind, stream):
    for _ in range(5):
        run(model, kind, stream)
    time.sleep(1.0)
    before = counts["constructed"]
    for _ in range(50):
        run(model, kind, stream)
    time.sleep(2.0)
    return (counts["constructed"] - before) / 50

def timed(model, stream):
    for _ in range(50):
        sync_call(model, stream)
    runs = []
    for _ in range(5):
        start = time.perf_counter()
        for _ in range(300):
            sync_call(model, stream)
        runs.append((time.perf_counter() - start) / 300 * 1e6)
    return statistics.median(runs)

result = {}
for model in ["gpt-5.5", "anthropic/claude-sonnet-5-5", "gemini/gemini-2.5-pro"]:
    for stream in (False, True):
        result[f"{model} stream={stream}"] = {
            "sync_per_request": per_request(model, "sync", stream) if original else None,
            "async_per_request": per_request(model, "async", stream) if original else None,
            "sync_completion_us": timed(model, stream),
        }
print(json.dumps({"label": sys.argv[1], "result": result}))

The 501 chunk check ran the same counter with mock_response=" ".join(["word"] * 300) and stream=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 with lsof -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 compared

Shared setup

  • Env vars: DEEPSEEK_API_KEY, LITELLM_MASTER_KEY, LITELLM_MODE=PRODUCTION (so neither proxy reads a .env)
  • Proxy start, once in each checkout, with --port 4001 for the merge base and --port 4000 for the branch
python litellm/proxy/proxy_cli.py --config config.yaml --port 4000
  • config.yaml
model_list:
  - model_name: deepseek-flash
    litellm_params:
      model: deepseek/deepseek-flash
      api_key: os.environ/DEEPSEEK_API_KEY
  - model_name: deepseek-v4-pro
    litellm_params:
      model: deepseek/deepseek-v4-pro
      api_key: os.environ/DEEPSEEK_API_KEY

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  • Client commands, run once, output saved to run.out
Request bodies and the curl loop
RULES=$(for i in $(seq 1 260); do printf 'Rule %s: every invoice line must name its meter, its quantity and its unit price. ' $i; done)
jq -n '{model:"deepseek-flash",temperature:0,max_tokens:16,messages:[{role:"user",content:"Reply with the single word: ready"}]}' > plain.json
jq -n --arg rules "$RULES" '{model:"deepseek-flash",temperature:0,max_tokens:16,messages:[{role:"system",content:$rules},{role:"user",content:"Reply with the single word: ready"}]}' > cached.json
jq -n '{model:"deepseek-v4-pro",temperature:0,max_tokens:64,messages:[{role:"user",content:"What is 17 + 25? Answer with the number only."}]}' > reasoning.json

for body in plain cached reasoning; do
  for try in 1 2 3 4 5; do
    for port in 4001 4000; do
      usage=$(curl -s -D headers.txt http://localhost:$port/v1/chat/completions \
        -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d @$body.json \
        | jq -c '.usage | {prompt_tokens, cached: .prompt_tokens_details.cached_tokens, completion_tokens, reasoning: .completion_tokens_details.reasoning_tokens}')
      costs=$(grep -iE '^x-litellm-response-cost(-input|-output|-cache-read|-reasoning)?:' headers.txt | sed -E 's/x-litellm-response-//; s/: /=/' | tr -d '\r' | tr '\n' ' ')
      echo "$body :$port $usage $costs"
    done
  done
done > run.out
  • Check that no usage was billed two different ways across the two proxies. It prints nothing
cut -d' ' -f1,3- run.out | sort -u | cut -d' ' -f1,2 | uniq -d

Before (27e9a04)

Plain call

  1. grep '^plain :4001' run.out | sort -k3 | uniq -c
   4 plain :4001 {"prompt_tokens":37,"cached":0,"completion_tokens":13,"reasoning":11} cost=2.67e-05 cost-input=1.1099999999999999e-05 cost-output=1.56e-05 cost-reasoning=1.3199999999999999e-05
   1 plain :4001 {"prompt_tokens":37,"cached":0,"completion_tokens":16,"reasoning":16} cost=3.0299999999999998e-05 cost-input=1.1099999999999999e-05 cost-output=1.92e-05 cost-reasoning=1.92e-05

Cached prompt

  1. grep '^cached :4001' run.out | sort -k3 | uniq -c
   3 cached :4001 {"prompt_tokens":4978,"cached":4736,"completion_tokens":12,"reasoning":10} cost=0.000115416 cost-input=7.26e-05 cost-output=1.4400000000000001e-05 cost-cache-read=2.8416e-05 cost-reasoning=1.2e-05
   2 cached :4001 {"prompt_tokens":4978,"cached":4736,"completion_tokens":16,"reasoning":16} cost=0.000120216 cost-input=7.26e-05 cost-output=1.92e-05 cost-cache-read=2.8416e-05 cost-reasoning=1.92e-05

Reasoning call

  1. grep '^reasoning :4001' run.out | sort -k3 | uniq -c
   3 reasoning :4001 {"prompt_tokens":97,"cached":0,"completion_tokens":18,"reasoning":16} cost=0.00019932 cost-input=0.00012804 cost-output=7.128000000000001e-05 cost-reasoning=6.336e-05
   1 reasoning :4001 {"prompt_tokens":97,"cached":0,"completion_tokens":28,"reasoning":26} cost=0.00023892 cost-input=0.00012804 cost-output=0.00011088000000000001 cost-reasoning=0.00010296
   1 reasoning :4001 {"prompt_tokens":97,"cached":0,"completion_tokens":42,"reasoning":40} cost=0.00029436 cost-input=0.00012804 cost-output=0.00016632 cost-reasoning=0.0001584

After (5f51b4a)

Plain call

  1. grep '^plain :4000' run.out | sort -k3 | uniq -c. The 13 completion token rows match Before to the last digit
   2 plain :4000 {"prompt_tokens":37,"cached":0,"completion_tokens":12,"reasoning":10} cost=2.55e-05 cost-input=1.1099999999999999e-05 cost-output=1.4400000000000001e-05 cost-reasoning=1.2e-05
   3 plain :4000 {"prompt_tokens":37,"cached":0,"completion_tokens":13,"reasoning":11} cost=2.67e-05 cost-input=1.1099999999999999e-05 cost-output=1.56e-05 cost-reasoning=1.3199999999999999e-05

Cached prompt

  1. grep '^cached :4000' run.out | sort -k3 | uniq -c. The 12 and 16 completion token rows match Before to the last digit, cache read included
   4 cached :4000 {"prompt_tokens":4978,"cached":4736,"completion_tokens":12,"reasoning":10} cost=0.000115416 cost-input=7.26e-05 cost-output=1.4400000000000001e-05 cost-cache-read=2.8416e-05 cost-reasoning=1.2e-05
   1 cached :4000 {"prompt_tokens":4978,"cached":4736,"completion_tokens":16,"reasoning":16} cost=0.000120216 cost-input=7.26e-05 cost-output=1.92e-05 cost-cache-read=2.8416e-05 cost-reasoning=1.92e-05

Reasoning call

  1. grep '^reasoning :4000' run.out | sort -k3 | uniq -c. The 18 completion token rows match Before to the last digit
   2 reasoning :4000 {"prompt_tokens":97,"cached":0,"completion_tokens":18,"reasoning":16} cost=0.00019932 cost-input=0.00012804 cost-output=7.128000000000001e-05 cost-reasoning=6.336e-05
   2 reasoning :4000 {"prompt_tokens":97,"cached":0,"completion_tokens":20,"reasoning":18} cost=0.00020724000000000003 cost-input=0.00012804 cost-output=7.920000000000001e-05 cost-reasoning=7.128000000000001e-05
   1 reasoning :4000 {"prompt_tokens":97,"cached":0,"completion_tokens":41,"reasoning":39} cost=0.0002904 cost-input=0.00012804 cost-output=0.00016236 cost-reasoning=0.00015444000000000002

Sweeps: 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 floats

  • Every catalog row: 5,977 rows, 2,401 distinct price shapes
    • Service tiers: none, flex, priority, fast, ultrafast, balanced, auto, PRIORITY
    • Prompt sizes: 0, 1, 1,000, 10,000,000, plus every band and tier edge and the token after it
    • 19 usage shapes: plain, cached, cached by modality, explicit cache, cache writes (flat, 5m and 1h, 30m and 12h, details only), double counted, input modalities, units, characters, reasoning, output modalities, no completion
    • Residency (eu, US, fedramp), Vertex location and peak and off-peak instants on the rows that price them
    • generic_cost_per_token: 1,709,392 checks, none differ beyond the last bit
      • 4,081 differ in the last bit only, all in one synthetic shape: unattributed cache writes next to 30m writes, which Rust adds before multiplying
    • get_billed_token_rates: 359,872 checks, 0 differences
    • calculate_prompt_caching_savings: 359,872 checks, 0 differences
  • Deployment overrides: 4 tier ladders (two tiers, input only, with cache and reasoning, with a one token gap) laid over 9 catalog rows, OpenAI, Anthropic, Gemini, DeepSeek with off-peak, Dashscope, xAI and Fireworks among them
    • 102,752 cost, 21,632 rate and 21,632 savings checks, 0 differences
  • Provider cost files
    • Dashscope cost_per_token: 16,896 checks, 0 differences
    • Perplexity cost_per_token: 8,712 checks, 0 differences

Type

🧹 Refactoring

Caveats (if any)

Medium

  • Input audio and video seconds can differ from main at the 10th significant digit
    • Rust holds a duration in whole nanoseconds, Python multiplied the float
    • 8,799 of 8,800 random durations differ, by at most 2e-10 relative
  • Values Python billed and the Rust types refuse are ignored
    • A negative token count bills 0, Python billed a negative amount
    • A multiplier below 1 or a negative price is left out

Low

  • The live proof and sweeps ran at refactor(cost): price generic_cost_per_token with the native calculate #51566's commit, not at this tip
    • The rebases changed only conflict lines and the image rate port, listed in the first paragraph
  • Python behavior kept on purpose, worth a follow-up
    • A 1h or 12h cache write under a service tier ignores the standard band price
      • Anthropic rows with service_tier: priority above 200k tokens bill 1h writes at the base 1h rate
    • Characters, images, audio and video seconds ignore _above_Nk_tokens prices on this path
    • Image and video input tokens fall back to the text input rate
  • Tier ladders whose tiers price different meters can differ from main
    • A meter one tier leaves out reads the tier below, main read the flat price
  • The live proof covers one provider in its peak window
    • No live call exercised off-peak, cache writes, explicit cache, a service tier or an uplift
    • The sweeps and tests cover those rules
  • Mutation testing ran on litellm-cost only
    • Every viable mutant in quote.rs, calculate.rs, Schedule::is_open and Adjustments::for_call was caught
    • 23 missed mutants are older weekday parsing, serde and schema code the default-feature tests skip
    • The model-catalog lowering was not mutation tested

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

@codecov

codecov Bot commented Nov 19, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@maciej-berri
maciej-berri force-pushed the litellm_cost_generic_on_main branch from 524ef7c to 7d43c5b Compare November 20, 2026 20:30
@CLAassistant

CLAassistant commented Nov 20, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@maciej-berri maciej-berri added the rust-tests label Nov 20, 2026 — with Claude
@maciej-berri
maciej-berri marked this pull request as ready for review November 20, 2026 20:59
@veria-ai

veria-ai Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

@maciej-berri
maciej-berri force-pushed the litellm_cost_generic_on_main branch from 7d43c5b to 471b635 Compare November 20, 2026 21:10

Copy link
Copy Markdown
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

@narmstrong-berri narmstrong-berri 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.

Minor comment changes, but the shape looks great. Thanks Maciej!

Copy link
Copy Markdown
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
narmstrong-berri force-pushed the litellm_cost_generic_on_main branch 2 times, most recently from ae72103 to 4464926 Compare November 23, 2026 20:37
@narmstrong-berri
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
maciej-berri and others added 2 commits November 23, 2026 13:44
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
narmstrong-berri force-pushed the litellm_cost_generic_on_main branch from 4464926 to 9778a16 Compare November 23, 2026 21:47
@narmstrong-berri
narmstrong-berri merged commit 0ba2d79 into main Nov 23, 2026
64 of 66 checks passed
@narmstrong-berri
narmstrong-berri deleted the litellm_cost_generic_on_main branch November 23, 2026 22:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants