Repository navigation
fix(cost): honor per-second custom pricing on chat completions for every provider - #42403
Conversation
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
| def test_update_response_metadata_prices_per_second_deployment_from_its_stamped_duration(monkeypatch): | ||
| """ | ||
| The cost cached on ``_hidden_params`` is computed after ``_response_ms`` is stamped, so a | ||
| deployment priced only per second bills the response window it was given rather than 0 or | ||
| whatever wider window the logging object holds. | ||
| """ | ||
| monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True") | ||
| monkeypatch.setattr(litellm, "model_cost", litellm.get_model_cost_map(url="")) | ||
|
|
||
| deployment_id: Final = "per-second-deployment-response-metadata" | ||
| litellm.register_model( | ||
| model_cost={ | ||
| deployment_id: { | ||
| "input_cost_per_second": 0.02, | ||
| "output_cost_per_second": 0.04, | ||
| "litellm_provider": "openai", | ||
| "mode": "chat", | ||
| } | ||
| } | ||
| ) | ||
| start_time: Final = datetime.datetime(2026, 9, 21, 12, 0, 0) | ||
| logging_obj: Final = Logging( | ||
| model="gpt-5.4-nano", | ||
| messages=[{"role": "user", "content": "Hello"}], | ||
| stream=False, | ||
| call_type="completion", | ||
| start_time=start_time, | ||
| litellm_call_id="per-second-response-metadata", | ||
| function_id="f", | ||
| ) | ||
| logging_obj.update_environment_variables( | ||
| model="gpt-5.4-nano", | ||
| litellm_params={ | ||
| "input_cost_per_second": 0.02, | ||
| "output_cost_per_second": 0.04, | ||
| "metadata": {"model_info": {"id": deployment_id}}, | ||
| }, | ||
| optional_params={}, | ||
| custom_llm_provider="openai", | ||
| ) | ||
| logging_obj.model_call_details["end_time"] = start_time + datetime.timedelta(seconds=10) | ||
| result: Final = ModelResponse( | ||
| model="gpt-5.4-nano", | ||
| usage=Usage(prompt_tokens=11, completion_tokens=7, total_tokens=18), | ||
| ) | ||
|
|
||
| update_response_metadata( | ||
| result=result, | ||
| logging_obj=logging_obj, | ||
| model="gpt-5.4-nano", | ||
| kwargs={"model_info": {"id": deployment_id}}, | ||
| start_time=start_time, | ||
| end_time=start_time + datetime.timedelta(seconds=2), | ||
| ) | ||
|
|
||
| assert result._response_ms == pytest.approx(2000) | ||
| assert result._hidden_params["response_cost"] == pytest.approx((0.02 + 0.04) * 2) |
There was a problem hiding this comment.
This bug fix creates a second test file for response_metadata.py. Repository rules require bug-fix regressions to extend the existing mapped file, so this test must move to tests/unit/litellm_core_utils/llm_response_utils/test_response_metadata.py before merging
Context Used: AGENTS.md (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
There was a problem hiding this comment.
Moved into the mapped tests/unit/litellm_core_utils/llm_response_utils/test_response_metadata.py in cd493dd and dropped the duplicate file.
Merging this PR will not alter performance
Comparing |
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
…m_per_second_chat_pricing
…aying at $0 The zero-cost diagnostic tests from #42345 used a per-second-only entry as their misconfigured fixture, which this branch now bills. Switch that fixture to a per-query-only entry, which is still selected as the deployment's own pricing and still prices chat usage at $0, and add a per-second test asserting the call duration is billed with no diagnostic Also let a caller's explicit total_time outrank the logging window in completion_cost, so the SDK precedence stays stamped response, caller, logging
…the mapped tests/unit file
|
bugbot run |
|
Review for PR #42403: Honor per-second custom pricing on chat completions for every provider Architecture & Precision Verification
# Verification pattern for duration-based cost calculation
if "per_second_cost" in model_pricing:
elapsed_seconds = max(0.0, response_duration_seconds)
total_cost += elapsed_seconds * model_pricing["per_second_cost"]The logic cleanly unifies time-based compute billing with standard token-based telemetry. |
…lock path A video, transcription, speech, or realtime entry's per-second rates price media seconds, which their dedicated cost paths bill from the media itself. The generic per-second branch now skips those modes, so a video status poll on a per-second video model bills nothing instead of the seconds the poll took to answer.
|
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 a56166d. Configure here.
TLDR
Problem this solves:
How it solves it:
User Flow
Before: a proxy admin prices an
openai/gpt-5.4-nanodeployment per second and every chat completion on it is logged at $0 spendper-second-priced-chat(openai/gpt-5.4-nanowithinput_cost_per_second: 0.000420andoutput_cost_per_second: 0.000420) to config.yaml and starts the proxy{"model": "per-second-priced-chat", "messages": [{"role": "user", "content": "Say hi in three words"}]}x-litellm-response-duration-ms: 1133.85, butx-litellm-response-cost-input: 0.0andx-litellm-response-cost-output: 0.0"stream": truealso ends with every cost header at0.0"spend": 0.0next to those token counts, so the deployment bills nothing and no budget ever movesAfter: the same deployment bills its per-second rates times the call's duration
per-second-priced-chat(openai/gpt-5.4-nanowithinput_cost_per_second: 0.000420andoutput_cost_per_second: 0.000420) to config.yaml and starts the proxy{"model": "per-second-priced-chat", "messages": [{"role": "user", "content": "Say hi in three words"}]}x-litellm-response-duration-ms: 941.86andx-litellm-response-cost: 0.00079116, which is 0.000420 × 0.94186 s on each of the input and output sides"stream": trueends with a non-zero cost header and is logged at 0.000341, the rate times the full stream's duration"spend": 0.0007911589622497559, so the deployment bills and budgets moveDesign decisions
Honor per-second rates on chat completions rather than reject them at config load. The docs' "Cost Per Second (e.g. Sagemaker)" section on the custom pricing page shows exactly this shape, a chat deployment carrying
input_cost_per_secondundermodel_info, so rejecting it would break every config written from the docs. The two alternatives were patching each provider branch to look at the per-second keys (the same check duplicated everywhere) and adding the check inside the shared generic per-token helper (it never receives the response time). The chosen shape is one branch ahead of the provider dispatch that returns the per-second cost whenever the model carries a per-second rate and no per-token or tiered rate, so a model with both keeps billing per token exactly as beforeThe duration is the whole call's wall clock, from the request going out to the response completing, and both the input and the output rate are multiplied by that same duration. Splitting it into time to first token for the input side and generation time for the output side was considered and dropped, since nothing records that split today and the docs do not define it. The duration is resolved in a fixed order: a non-streaming response carries its own stamped duration; otherwise an SDK caller's explicit
total_timeargument applies, as it always did for replicate; otherwise a stream is priced when it finishes, from the logged start and end of the call; and with none of those the cost is $0 rather than an errorTwo side effects of the shared branch are deliberate and named here so nobody has to guess. The bedrock commitment entries in the cost map (
bedrock/*/1-month-commitment/...and6-month-commitment/..., 28 rows, allmode: chatwith only per-second rates, listed bypython3 -c 'import json; m=json.load(open("model_prices_and_context_window.json")); print("\n".join(k for k,v in m.items() if "commitment" in k and v.get("input_cost_per_second") and not v.get("input_cost_per_token")))') billed $0 through the bedrock calculator and now bill their per-second rate times the call duration. An azure deployment with a custominput_cost_per_secondnow bills the input side too, where the azure calculator used to price onlyoutput_cost_per_secondand drop the input rateThe shared branch bills wall-clock seconds only for entries whose
modeischat,completion,embedding,responses, or unset. A per-second rate on a media-mode entry (audio_transcription,audio_speech,video_generation,realtime) prices media seconds, and the dedicated calculators for those modes already read it, so the generic branch leaves them alone. The live risk pass caught why that gate matters: without it a video status poll onvertex_ai/veo-3.1-generate-001(mode: video_generation,output_cost_per_second: 0.4) billed 0.4 × the poll's own wall-clock seconds, $0.80 for a two second poll, where the base logs $0. Marking the video read call types unbilled inNON_INFERENCE_CALL_TYPESwas considered and dropped, since that zeroes the spend row and the OTel usage for those calls instead of fixing the rate lookup, and so was gating on the call type, which would have to list every media call type while the mode is one field the entry already carriesOne test expectation flipped on purpose. The zero-cost diagnostic tests from #42345 used a per-second-only deployment as their "misconfigured, bills $0" fixture, which is exactly the input this PR makes bill. That fixture is now a per-query-only entry (
input_cost_per_query, a rerank-style rate that still prices chat usage at $0 and still reports the two missing per-token keys), and a new test asserts that a per-second-priced deployment bills the call duration and raises no diagnosticThe timing swap (stamp the duration, then compute the cost) is the same one #31558 by @ptempier proposes, credited here; that PR covers only the timing half and has been conflicting since June
Relevant issues
No GitHub issue. Overlaps with #31558, which makes the same timing swap and none of the pricing change
Affected release
Linear ticket
Resolves LIT-8315
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/test_litellm/<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@greptileaito re-request a review after pushing changes)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
Shared setup for both legs. Real OpenAI calls, no mocks. One proxy per leg with two uvicorn workers (
--num_workers 2), both legs sharing one fresh Postgres database (litellm_lit8315_qa, schema pushed withprisma db push, booted withDISABLE_SCHEMA_UPDATE=true).OPENAI_API_KEY,DATABASE_URL, andLITELLM_MASTER_KEY=sk-lit8315come from the environment, andLITELLM_LOCAL_MODEL_COST_MAP=Trueso both legs read the checked-in cost map. Spend is read back throughGET /spend/logs?request_id=<x-litellm-call-id>on the same proxyconfig.yaml(the first deployment is the ticket's shape, the second carries the same rates undermodel_infoas the docs show, the third is a per-token control, the fourth is an embedding deployment with the same per-second rates):Proxy, one worktree per leg on its own port (
52947for Before,44082for After):python litellm/proxy/proxy_cli.py --config config.yaml --port $PORT --num_workers 2 --detailed_debugEvery case below runs the curl shown, keeps the call id, cost, and duration headers, then reads the spend row for that call id back through the spend API:
Before (5cf17f9)
POST /v1/chat/completions, per-second rates in litellm_params
curl -s -D - http://localhost:52947/v1/chat/completions "${H[@]}" -d '{"model": "per-second-priced-chat", "messages": [{"role": "user", "content": "Say hi in three words"}]}' | grep -iE "$FILTER"0.0next to a real durationcurl -s "http://localhost:52947/spend/logs?request_id=3bd8991b-57d2-4459-a2e8-8bacd0b5d19d" "${H[@]}" | python3 -c "$ROW"POST /v1/chat/completions, per-second rates in model_info
curl -s -D - http://localhost:52947/v1/chat/completions "${H[@]}" -d '{"model": "per-second-priced-chat-model-info", "messages": [{"role": "user", "content": "Say hi in three words"}]}' | grep -iE "$FILTER"0.0againcurl -s "http://localhost:52947/spend/logs?request_id=1493825a-c29c-44b2-9228-25976e1fa589" "${H[@]}" | python3 -c "$ROW"POST /v1/chat/completions, per-token control deployment
curl -s -D - http://localhost:52947/v1/chat/completions "${H[@]}" -d '{"model": "per-token-priced-chat", "messages": [{"role": "user", "content": "Say hi in three words"}]}' | grep -iE "$FILTER"curl -s "http://localhost:52947/spend/logs?request_id=6bec60f4-3379-4a2b-9d98-f0856d1b5e11" "${H[@]}" | python3 -c "$ROW"POST /v1/chat/completions with stream: true, per-second deployment
curl -s -N -D - http://localhost:52947/v1/chat/completions "${H[@]}" -d '{"model": "per-second-priced-chat", "messages": [{"role": "user", "content": "Say hi in three words"}], "stream": true, "stream_options": {"include_usage": true}}' | grep -iE "$FILTER"0.0curl -s "http://localhost:52947/spend/logs?request_id=56f8c9ad-9050-4f37-868e-f8f5bdc87ec1" "${H[@]}" | python3 -c "$ROW"POST /v1/chat/completions with stream: true, per-token control deployment
curl -s -N -D - http://localhost:52947/v1/chat/completions "${H[@]}" -d '{"model": "per-token-priced-chat", "messages": [{"role": "user", "content": "Say hi in three words"}], "stream": true, "stream_options": {"include_usage": true}}' | grep -iE "$FILTER"0.0(usage only arrives with the last chunk)curl -s "http://localhost:52947/spend/logs?request_id=8ce821de-7058-49c2-99cc-0d1a32eb6f1a" "${H[@]}" | python3 -c "$ROW"POST /v1/responses, per-second deployment
curl -s -D - http://localhost:52947/v1/responses "${H[@]}" -d '{"model": "per-second-priced-chat", "input": "Say hi in three words"}' | grep -iE "$FILTER"curl -s "http://localhost:52947/spend/logs?request_id=f6141f44-3d1e-41cd-a02f-2d1c9181e6ba" "${H[@]}" | python3 -c "$ROW"POST /v1/embeddings, per-second deployment
curl -s -D - http://localhost:52947/v1/embeddings "${H[@]}" -d '{"model": "per-second-priced-embedding", "input": "Say hi in three words"}' | grep -iE "$FILTER"0.0on an embedding deployment with per-second rates toocurl -s "http://localhost:52947/spend/logs?request_id=80777808-380a-44e9-9436-304ffa8f8926" "${H[@]}" | python3 -c "$ROW"POST /v1/messages, per-second deployment
curl -s -D - http://localhost:52947/v1/messages "${H[@]}" -d '{"model": "per-second-priced-chat", "max_tokens": 32, "messages": [{"role": "user", "content": "Say hi in three words"}]}' | grep -iE "$FILTER"curl -s "http://localhost:52947/spend/logs?request_id=81f8769c-3a65-42b8-b073-d41e197b04d8" "${H[@]}" | python3 -c "$ROW"After (a56166d)
POST /v1/chat/completions, per-second rates in litellm_params
curl -s -D - http://localhost:44082/v1/chat/completions "${H[@]}" -d '{"model": "per-second-priced-chat", "messages": [{"role": "user", "content": "Say hi in three words"}]}' | grep -iE "$FILTER"curl -s "http://localhost:44082/spend/logs?request_id=88dc379f-e050-42b4-9a73-e7f99cda6162" "${H[@]}" | python3 -c "$ROW"POST /v1/chat/completions, per-second rates in model_info
curl -s -D - http://localhost:44082/v1/chat/completions "${H[@]}" -d '{"model": "per-second-priced-chat-model-info", "messages": [{"role": "user", "content": "Say hi in three words"}]}' | grep -iE "$FILTER"curl -s "http://localhost:44082/spend/logs?request_id=20485306-2d43-4c10-99e7-1e9e6c9ffe1d" "${H[@]}" | python3 -c "$ROW"POST /v1/chat/completions, per-token control deployment
curl -s -D - http://localhost:44082/v1/chat/completions "${H[@]}" -d '{"model": "per-token-priced-chat", "messages": [{"role": "user", "content": "Say hi in three words"}]}' | grep -iE "$FILTER"curl -s "http://localhost:44082/spend/logs?request_id=d784e900-caff-4bbe-8ed6-c77839c25692" "${H[@]}" | python3 -c "$ROW"POST /v1/chat/completions with stream: true, per-second deployment
curl -s -N -D - http://localhost:44082/v1/chat/completions "${H[@]}" -d '{"model": "per-second-priced-chat", "messages": [{"role": "user", "content": "Say hi in three words"}], "stream": true, "stream_options": {"include_usage": true}}' | grep -iE "$FILTER"curl -s "http://localhost:44082/spend/logs?request_id=a3b30563-7607-4bf0-9bf4-7090c0c8a99a" "${H[@]}" | python3 -c "$ROW"POST /v1/chat/completions with stream: true, per-token control deployment
curl -s -N -D - http://localhost:44082/v1/chat/completions "${H[@]}" -d '{"model": "per-token-priced-chat", "messages": [{"role": "user", "content": "Say hi in three words"}], "stream": true, "stream_options": {"include_usage": true}}' | grep -iE "$FILTER"0.0curl -s "http://localhost:44082/spend/logs?request_id=d3155e91-c78d-46f1-882e-cfc5d3e486ef" "${H[@]}" | python3 -c "$ROW"POST /v1/responses, per-second deployment
curl -s -D - http://localhost:44082/v1/responses "${H[@]}" -d '{"model": "per-second-priced-chat", "input": "Say hi in three words"}' | grep -iE "$FILTER"curl -s "http://localhost:44082/spend/logs?request_id=c32f54ad-a670-4274-9d62-030b9bf9538f" "${H[@]}" | python3 -c "$ROW"POST /v1/embeddings, per-second deployment
curl -s -D - http://localhost:44082/v1/embeddings "${H[@]}" -d '{"model": "per-second-priced-embedding", "input": "Say hi in three words"}' | grep -iE "$FILTER"curl -s "http://localhost:44082/spend/logs?request_id=86cb7cdf-b8be-4c29-aace-c3a5f561d0a9" "${H[@]}" | python3 -c "$ROW"POST /v1/messages, per-second deployment
curl -s -D - http://localhost:44082/v1/messages "${H[@]}" -d '{"model": "per-second-priced-chat", "max_tokens": 32, "messages": [{"role": "user", "content": "Say hi in three words"}]}' | grep -iE "$FILTER"curl -s "http://localhost:44082/spend/logs?request_id=bda0e9a9-dc73-436b-bde9-0199d86c5731" "${H[@]}" | python3 -c "$ROW"Observations from the run:
0.0on both legs, pre-existing/v1/responsesand/v1/messagesignore per-second rates, pre-existingType
🐛 Bug Fix
Caveats (if any)
Medium
/v1/responsesand/v1/messagesstill ignore this deployment's per-second ratesinput_cost_per_secondnow bills the input side toocompletion_cost(total_time=...)now outranks the logging window/v1/completionsand/v1/embeddingson a per-second deployment now bill toobudget_exceededafter one callLow
0.0, unchanged/spend/calculateignores a deployment's per-second rates, before and afterinput_cost_per_secondonly and showsoutput_cost_per_secondonly-litellm.max_budgetaccumulator passes seconds where it expects millisecondsend_timefor unstamped resultsfinalize()and topaz per-second path not exercised livelocal_testing_part1bedrock parity,llm_translation_testingfireworks/hosted_vllm/moonshot,unitsecret-detection timinge2e_ui_testingandusing_litellm_on_windowsfail at the same steps as main 90023litellm_router_unit_testingstream count flaked across a minute boundary at the tiptests/unittest_detailed_timing_pre_processing_uses_receive_anchorfails on a non-UTC laptop at base and head alikeFinal Attestation
Note
Medium Risk
Changes core spend calculation and ordering of provider dispatch, which can alter logged costs for Bedrock commitment entries, Azure per-second input, and embeddings; timing fixes affect all duration-based billing paths.
Overview
Fixes $0 spend for proxy deployments priced only with
input_cost_per_second/output_cost_per_secondon chat-style calls.Per-second billing is centralized in
_per_second_pricing_costand applied incost_per_tokenbefore provider-specific calculators (OpenAI, Bedrock, Azure, etc.), so custom per-second rates win when there is no per-token or tiered pricing. Wall-clock modes (chat,completion,embedding,responses) bill duration × both rates; media modes (video_generation, transcription, etc.) are excluded so status polls are not charged on HTTP latency.Duration is resolved via
_response_time_ms_for_cost: stamped_response_msfirst, then explicittotal_time, then the logging object’s start/end window.response_metadatanow stamps timing before computingresponse_costin hidden params, andget_response_msaccepts mixedfloat/datetimetimestamps.Zero-cost diagnostic tests swap the “misconfigured” fixture from per-second-only to per-query-only pricing, with new coverage for per-second deployments and provider parametrization.
Reviewed by Cursor Bugbot for commit a56166d. Bugbot is set up for automated code reviews on this repo. Configure here.