Skip to content

fix(cost): honor per-second custom pricing on chat completions for every provider - #42403

Merged
mateo-berri merged 5 commits into
mainfrom
litellm_per_second_chat_pricing
Sep 22, 2026
Merged

mateo-berri merged 5 commits into
mainfrom
litellm_per_second_chat_pricing

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • A chat deployment priced only per second bills $0 on every request
  • Providers with their own cost calculator never saw the per-second rates
  • The call duration was read before it was stamped, so it was always 0

How it solves it:

  • Per-second rates are checked once, before any provider calculator runs
  • The duration is stamped before the cost is computed
  • Streams and other unstamped results bill the logged start-to-end window
  • Media-mode entries keep their per-second rates on their own calculators

User Flow

Before: a proxy admin prices an openai/gpt-5.4-nano deployment per second and every chat completion on it is logged at $0 spend

  1. The admin adds per-second-priced-chat (openai/gpt-5.4-nano with input_cost_per_second: 0.000420 and output_cost_per_second: 0.000420) to config.yaml and starts the proxy
  2. A developer sends POST https://litellm-domain/v1/chat/completions with {"model": "per-second-priced-chat", "messages": [{"role": "user", "content": "Say hi in three words"}]}
  3. 200 comes back with real usage (11 prompt and 7 completion tokens) and x-litellm-response-duration-ms: 1133.85, but x-litellm-response-cost-input: 0.0 and x-litellm-response-cost-output: 0.0
  4. The same request with "stream": true also ends with every cost header at 0.0
  5. GET https://litellm-domain/spend/logs?request_id={x-litellm-call-id} shows "spend": 0.0 next to those token counts, so the deployment bills nothing and no budget ever moves

After: the same deployment bills its per-second rates times the call's duration

  1. The admin adds per-second-priced-chat (openai/gpt-5.4-nano with input_cost_per_second: 0.000420 and output_cost_per_second: 0.000420) to config.yaml and starts the proxy
  2. A developer sends POST https://litellm-domain/v1/chat/completions with {"model": "per-second-priced-chat", "messages": [{"role": "user", "content": "Say hi in three words"}]}
  3. 200 comes back with x-litellm-response-duration-ms: 941.86 and x-litellm-response-cost: 0.00079116, which is 0.000420 × 0.94186 s on each of the input and output sides
  4. The same request with "stream": true ends with a non-zero cost header and is logged at 0.000341, the rate times the full stream's duration
  5. GET https://litellm-domain/spend/logs?request_id={x-litellm-call-id} shows "spend": 0.0007911589622497559, so the deployment bills and budgets move

Design 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_second under model_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 before

The 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_time argument 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 error

Two 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/... and 6-month-commitment/..., 28 rows, all mode: chat with only per-second rates, listed by python3 -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 custom input_cost_per_second now bills the input side too, where the azure calculator used to price only output_cost_per_second and drop the input rate

The shared branch bills wall-clock seconds only for entries whose mode is chat, 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 on vertex_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 in NON_INFERENCE_CALL_TYPES was 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 carries

One 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 diagnostic

The 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

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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
  • 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
  • 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)

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 with prisma db push, booted with DISABLE_SCHEMA_UPDATE=true). OPENAI_API_KEY, DATABASE_URL, and LITELLM_MASTER_KEY=sk-lit8315 come from the environment, and LITELLM_LOCAL_MODEL_COST_MAP=True so both legs read the checked-in cost map. Spend is read back through GET /spend/logs?request_id=<x-litellm-call-id> on the same proxy

config.yaml (the first deployment is the ticket's shape, the second carries the same rates under model_info as the docs show, the third is a per-token control, the fourth is an embedding deployment with the same per-second rates):

model_list:
  - model_name: per-second-priced-chat
    litellm_params:
      model: openai/gpt-5.4-nano
      api_key: os.environ/OPENAI_API_KEY
      input_cost_per_second: 0.000420
      output_cost_per_second: 0.000420
  - model_name: per-second-priced-chat-model-info
    litellm_params:
      model: openai/gpt-5.4-nano
      api_key: os.environ/OPENAI_API_KEY
    model_info:
      input_cost_per_second: 0.000420
      output_cost_per_second: 0.000420
  - model_name: per-token-priced-chat
    litellm_params:
      model: openai/gpt-5.4-nano
      api_key: os.environ/OPENAI_API_KEY
  - model_name: per-second-priced-embedding
    litellm_params:
      model: openai/text-embedding-3-small
      api_key: os.environ/OPENAI_API_KEY
      input_cost_per_second: 0.000420
      output_cost_per_second: 0.000420

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY

Proxy, one worktree per leg on its own port (52947 for Before, 44082 for After):

python litellm/proxy/proxy_cli.py --config config.yaml --port $PORT --num_workers 2 --detailed_debug

Every 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:

H=(-H "Authorization: Bearer sk-lit8315" -H "Content-Type: application/json")
FILTER='^x-litellm-response-cost|^x-litellm-response-duration-ms|^x-litellm-call-id'
ROW='import json,sys; print([{k: r.get(k) for k in ("model","call_type","spend","total_tokens","prompt_tokens","completion_tokens")} for r in json.load(sys.stdin)])'

Before (5cf17f9)

POST /v1/chat/completions, per-second rates in litellm_params

  1. 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"
  2. Observed: every cost header is 0.0 next to a real duration
x-litellm-call-id: 3bd8991b-57d2-4459-a2e8-8bacd0b5d19d
x-litellm-response-cost-original: 0.0
x-litellm-response-cost-input: 0.0
x-litellm-response-cost-output: 0.0
x-litellm-response-duration-ms: 1133.8469982147217
  1. curl -s "http://localhost:52947/spend/logs?request_id=3bd8991b-57d2-4459-a2e8-8bacd0b5d19d" "${H[@]}" | python3 -c "$ROW"
  2. Observed: $0 spend next to real token counts
[{'model': 'openai/gpt-5.4-nano', 'call_type': 'acompletion', 'spend': 0.0, 'total_tokens': 18, 'prompt_tokens': 11, 'completion_tokens': 7}]

POST /v1/chat/completions, per-second rates in model_info

  1. 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"
  2. Observed: 0.0 again
x-litellm-call-id: 1493825a-c29c-44b2-9228-25976e1fa589
x-litellm-response-cost-original: 0.0
x-litellm-response-cost-input: 0.0
x-litellm-response-cost-output: 0.0
x-litellm-response-duration-ms: 516.010046005249
  1. curl -s "http://localhost:52947/spend/logs?request_id=1493825a-c29c-44b2-9228-25976e1fa589" "${H[@]}" | python3 -c "$ROW"
  2. Observed: $0 spend
[{'model': 'openai/gpt-5.4-nano', 'call_type': 'acompletion', 'spend': 0.0, 'total_tokens': 18, 'prompt_tokens': 11, 'completion_tokens': 7}]

POST /v1/chat/completions, per-token control deployment

  1. 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"
  2. Observed: per-token pricing works, so the $0 is specific to per-second rates
x-litellm-call-id: 6bec60f4-3379-4a2b-9d98-f0856d1b5e11
x-litellm-response-cost: 1.3450000000000002e-05
x-litellm-response-cost-input: 2.2e-06
x-litellm-response-cost-output: 1.125e-05
x-litellm-response-duration-ms: 909.1670513153076
  1. curl -s "http://localhost:52947/spend/logs?request_id=6bec60f4-3379-4a2b-9d98-f0856d1b5e11" "${H[@]}" | python3 -c "$ROW"
  2. Observed: the per-token spend is logged
[{'model': 'openai/gpt-5.4-nano', 'call_type': 'acompletion', 'spend': 1.345e-05, 'total_tokens': 20, 'prompt_tokens': 11, 'completion_tokens': 9}]

POST /v1/chat/completions with stream: true, per-second deployment

  1. 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"
  2. Observed: cost headers 0.0
x-litellm-call-id: 56f8c9ad-9050-4f37-868e-f8f5bdc87ec1
x-litellm-response-cost-original: 0.0
x-litellm-response-cost-input: 0.0
x-litellm-response-cost-output: 0.0
x-litellm-response-duration-ms: 411.82994842529297
  1. curl -s "http://localhost:52947/spend/logs?request_id=56f8c9ad-9050-4f37-868e-f8f5bdc87ec1" "${H[@]}" | python3 -c "$ROW"
  2. Observed: the finished stream is logged at $0
[{'model': 'openai/gpt-5.4-nano', 'call_type': 'acompletion', 'spend': 0.0, 'total_tokens': 18, 'prompt_tokens': 11, 'completion_tokens': 7}]

POST /v1/chat/completions with stream: true, per-token control deployment

  1. 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"
  2. Observed: headers 0.0 (usage only arrives with the last chunk)
x-litellm-call-id: 8ce821de-7058-49c2-99cc-0d1a32eb6f1a
x-litellm-response-cost-original: 0.0
x-litellm-response-cost-input: 0.0
x-litellm-response-cost-output: 0.0
x-litellm-response-duration-ms: 418.11490058898926
  1. curl -s "http://localhost:52947/spend/logs?request_id=8ce821de-7058-49c2-99cc-0d1a32eb6f1a" "${H[@]}" | python3 -c "$ROW"
  2. Observed: the per-token spend is logged once the stream finished
[{'model': 'openai/gpt-5.4-nano', 'call_type': 'acompletion', 'spend': 9.700000000000002e-06, 'total_tokens': 17, 'prompt_tokens': 11, 'completion_tokens': 6}]

POST /v1/responses, per-second deployment

  1. curl -s -D - http://localhost:52947/v1/responses "${H[@]}" -d '{"model": "per-second-priced-chat", "input": "Say hi in three words"}' | grep -iE "$FILTER"
  2. Observed: billed at gpt-5.4-nano's per-token rates, the deployment's per-second rates are not consulted
x-litellm-call-id: f6141f44-3d1e-41cd-a02f-2d1c9181e6ba
x-litellm-response-cost: 1.2200000000000002e-05
x-litellm-response-cost-input: 2.2e-06
x-litellm-response-cost-output: 1e-05
x-litellm-response-duration-ms: 1217.0758247375488
  1. curl -s "http://localhost:52947/spend/logs?request_id=f6141f44-3d1e-41cd-a02f-2d1c9181e6ba" "${H[@]}" | python3 -c "$ROW"
  2. Observed: the per-token spend is logged
[{'model': 'openai/gpt-5.4-nano', 'call_type': 'aresponses', 'spend': 1.22e-05, 'total_tokens': 19, 'prompt_tokens': 11, 'completion_tokens': 8}]

POST /v1/embeddings, per-second deployment

  1. curl -s -D - http://localhost:52947/v1/embeddings "${H[@]}" -d '{"model": "per-second-priced-embedding", "input": "Say hi in three words"}' | grep -iE "$FILTER"
  2. Observed: 0.0 on an embedding deployment with per-second rates too
x-litellm-call-id: 80777808-380a-44e9-9436-304ffa8f8926
x-litellm-response-cost-original: 0.0
x-litellm-response-cost-input: 0.0
x-litellm-response-cost-output: 0.0
x-litellm-response-duration-ms: 376.143217086792
  1. curl -s "http://localhost:52947/spend/logs?request_id=80777808-380a-44e9-9436-304ffa8f8926" "${H[@]}" | python3 -c "$ROW"
  2. Observed: $0 spend
[{'model': 'openai/text-embedding-3-small', 'call_type': 'aembedding', 'spend': 0.0, 'total_tokens': 5, 'prompt_tokens': 5, 'completion_tokens': 0}]

POST /v1/messages, per-second deployment

  1. 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"
  2. Observed: same as /v1/responses, per-token rates of the base model
x-litellm-call-id: 81f8769c-3a65-42b8-b073-d41e197b04d8
x-litellm-response-cost: 1.4700000000000002e-05
x-litellm-response-cost-input: 2.2e-06
x-litellm-response-cost-output: 1.25e-05
x-litellm-response-duration-ms: 1952.2430896759033
  1. curl -s "http://localhost:52947/spend/logs?request_id=81f8769c-3a65-42b8-b073-d41e197b04d8" "${H[@]}" | python3 -c "$ROW"
  2. Observed: the per-token spend is logged
[{'model': 'openai/gpt-5.4-nano', 'call_type': 'anthropic_messages', 'spend': 1.47e-05, 'total_tokens': 21, 'prompt_tokens': 11, 'completion_tokens': 10}]

After (a56166d)

POST /v1/chat/completions, per-second rates in litellm_params

  1. 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"
  2. Observed: 0.000420 × 0.9418559 s = 0.00039558 on each side, 0.00079116 total
x-litellm-call-id: 88dc379f-e050-42b4-9a73-e7f99cda6162
x-litellm-response-cost: 0.0007911589622497559
x-litellm-response-cost-original: 0.0007911589622497559
x-litellm-response-cost-input: 0.00039557948112487796
x-litellm-response-cost-output: 0.00039557948112487796
x-litellm-response-duration-ms: 941.8559074401855
  1. curl -s "http://localhost:44082/spend/logs?request_id=88dc379f-e050-42b4-9a73-e7f99cda6162" "${H[@]}" | python3 -c "$ROW"
  2. Observed: the same non-zero spend is logged
[{'model': 'openai/gpt-5.4-nano', 'call_type': 'acompletion', 'spend': 0.0007911589622497559, 'total_tokens': 19, 'prompt_tokens': 11, 'completion_tokens': 8}]

POST /v1/chat/completions, per-second rates in model_info

  1. 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"
  2. Observed: 0.000420 × 0.5005319 s = 0.00021022 on each side
x-litellm-call-id: 20485306-2d43-4c10-99e7-1e9e6c9ffe1d
x-litellm-response-cost: 0.0004204468059539795
x-litellm-response-cost-original: 0.0004204468059539795
x-litellm-response-cost-input: 0.00021022340297698975
x-litellm-response-cost-output: 0.00021022340297698975
x-litellm-response-duration-ms: 500.5319118499756
  1. curl -s "http://localhost:44082/spend/logs?request_id=20485306-2d43-4c10-99e7-1e9e6c9ffe1d" "${H[@]}" | python3 -c "$ROW"
  2. Observed: logged at that spend
[{'model': 'openai/gpt-5.4-nano', 'call_type': 'acompletion', 'spend': 0.0004204468059539795, 'total_tokens': 17, 'prompt_tokens': 11, 'completion_tokens': 6}]

POST /v1/chat/completions, per-token control deployment

  1. 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"
  2. Observed: still per-token (the output side differs from Before only because the model answered with 8 tokens instead of 9)
x-litellm-call-id: d784e900-caff-4bbe-8ed6-c77839c25692
x-litellm-response-cost: 1.2200000000000002e-05
x-litellm-response-cost-input: 2.2e-06
x-litellm-response-cost-output: 1e-05
x-litellm-response-duration-ms: 506.9310665130615
  1. curl -s "http://localhost:44082/spend/logs?request_id=d784e900-caff-4bbe-8ed6-c77839c25692" "${H[@]}" | python3 -c "$ROW"
  2. Observed: unchanged per-token spend
[{'model': 'openai/gpt-5.4-nano', 'call_type': 'acompletion', 'spend': 1.22e-05, 'total_tokens': 19, 'prompt_tokens': 11, 'completion_tokens': 8}]

POST /v1/chat/completions with stream: true, per-second deployment

  1. 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"
  2. Observed: the headers carry the cost of the window elapsed when they were sent (0.000420 × 0.3357 s per side)
x-litellm-call-id: a3b30563-7607-4bf0-9bf4-7090c0c8a99a
x-litellm-response-cost: 0.0002814234638214111
x-litellm-response-cost-original: 0.0002814234638214111
x-litellm-response-cost-input: 0.00014071173191070556
x-litellm-response-cost-output: 0.00014071173191070556
x-litellm-response-duration-ms: 335.7410430908203
  1. curl -s "http://localhost:44082/spend/logs?request_id=a3b30563-7607-4bf0-9bf4-7090c0c8a99a" "${H[@]}" | python3 -c "$ROW"
  2. Observed: the spend row carries the full stream's duration (0.000420 × 0.4060 s per side)
[{'model': 'openai/gpt-5.4-nano', 'call_type': 'acompletion', 'spend': 0.0003410054683685303, 'total_tokens': 18, 'prompt_tokens': 11, 'completion_tokens': 7}]

POST /v1/chat/completions with stream: true, per-token control deployment

  1. 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"
  2. Observed: unchanged from Before, headers 0.0
x-litellm-call-id: d3155e91-c78d-46f1-882e-cfc5d3e486ef
x-litellm-response-cost-original: 0.0
x-litellm-response-cost-input: 0.0
x-litellm-response-cost-output: 0.0
x-litellm-response-duration-ms: 445.0531005859375
  1. curl -s "http://localhost:44082/spend/logs?request_id=d3155e91-c78d-46f1-882e-cfc5d3e486ef" "${H[@]}" | python3 -c "$ROW"
  2. Observed: per-token spend as Before (8 completion tokens this run, 6 in Before)
[{'model': 'openai/gpt-5.4-nano', 'call_type': 'acompletion', 'spend': 1.22e-05, 'total_tokens': 19, 'prompt_tokens': 11, 'completion_tokens': 8}]

POST /v1/responses, per-second deployment

  1. curl -s -D - http://localhost:44082/v1/responses "${H[@]}" -d '{"model": "per-second-priced-chat", "input": "Say hi in three words"}' | grep -iE "$FILTER"
  2. Observed: unchanged, still the base model's per-token rates (see the Medium caveat)
x-litellm-call-id: c32f54ad-a670-4274-9d62-030b9bf9538f
x-litellm-response-cost: 1.3450000000000002e-05
x-litellm-response-cost-input: 2.2e-06
x-litellm-response-cost-output: 1.125e-05
x-litellm-response-duration-ms: 853.8408279418945
  1. curl -s "http://localhost:44082/spend/logs?request_id=c32f54ad-a670-4274-9d62-030b9bf9538f" "${H[@]}" | python3 -c "$ROW"
  2. Observed: per-token spend at the same rates as Before
[{'model': 'openai/gpt-5.4-nano', 'call_type': 'aresponses', 'spend': 1.345e-05, 'total_tokens': 20, 'prompt_tokens': 11, 'completion_tokens': 9}]

POST /v1/embeddings, per-second deployment

  1. curl -s -D - http://localhost:44082/v1/embeddings "${H[@]}" -d '{"model": "per-second-priced-embedding", "input": "Say hi in three words"}' | grep -iE "$FILTER"
  2. Observed: 0.000420 × 0.3722391 s = 0.00015634 on each side
x-litellm-call-id: 86cb7cdf-b8be-4c29-aace-c3a5f561d0a9
x-litellm-response-cost: 0.0003126808547973633
x-litellm-response-cost-original: 0.0003126808547973633
x-litellm-response-cost-input: 0.00015634042739868164
x-litellm-response-cost-output: 0.00015634042739868164
x-litellm-response-duration-ms: 372.2391128540039
  1. curl -s "http://localhost:44082/spend/logs?request_id=86cb7cdf-b8be-4c29-aace-c3a5f561d0a9" "${H[@]}" | python3 -c "$ROW"
  2. Observed: logged at that spend
[{'model': 'openai/text-embedding-3-small', 'call_type': 'aembedding', 'spend': 0.0003126808547973633, 'total_tokens': 5, 'prompt_tokens': 5, 'completion_tokens': 0}]

POST /v1/messages, per-second deployment

  1. 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"
  2. Observed: unchanged, still the base model's per-token rates (see the Medium caveat)
x-litellm-call-id: bda0e9a9-dc73-436b-bde9-0199d86c5731
x-litellm-response-cost: 1.595e-05
x-litellm-response-cost-input: 2.2e-06
x-litellm-response-cost-output: 1.375e-05
x-litellm-response-duration-ms: 926.7199039459229
  1. curl -s "http://localhost:44082/spend/logs?request_id=bda0e9a9-dc73-436b-bde9-0199d86c5731" "${H[@]}" | python3 -c "$ROW"
  2. Observed: per-token spend at the same rates as Before
[{'model': 'openai/gpt-5.4-nano', 'call_type': 'anthropic_messages', 'spend': 1.595e-05, 'total_tokens': 22, 'prompt_tokens': 11, 'completion_tokens': 11}]

Observations from the run:

  • Stream cost headers cover elapsed window, spend log full duration
  • Per-token stream headers read 0.0 on both legs, pre-existing
  • /v1/responses and /v1/messages ignore per-second rates, pre-existing
  • Per-second embedding deployments were $0 too and now bill

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • /v1/responses and /v1/messages still ignore this deployment's per-second rates
    • Both bill the base model's per-token rates, before and after
    • Tracked separately as LIT-8323
  • Bedrock commitment cost-map entries now bill per-second × duration, not $0
  • Azure custom input_cost_per_second now bills the input side too
  • SDK completion_cost(total_time=...) now outranks the logging window
  • /v1/completions and /v1/embeddings on a per-second deployment now bill too
    • Live A/B: no cost header on base, 0.000425 and 0.000290 on head
  • Budgeted keys on a per-second deployment now get 422 once over budget
    • Live A/B: base stayed 200 with key spend 0.0, head answered budget_exceeded after one call
    • This is the ticket's ask (spend must move); the four items above are the design decisions named in that section, shipped on this run's call with no separate human sign-off

Low

  • Per-second stream cost headers cover only the window elapsed at send time
    • The spend log carries the full stream's duration
  • Per-token stream headers still read 0.0, unchanged
  • Anthropic, bedrock, and azure per-second paths are unit-tested only
  • Pass-through routes and background spend consumers not exercised live
  • Bedrock commitment entries measured in the SDK, not on a live proxy
  • Video status polls on per-second video models stay $0, proven in the SDK
  • /spend/calculate ignores a deployment's per-second rates, before and after
  • Unmapped Replicate through the proxy now bills LiteLLM's measured duration
    • Base priced the provider's created/ended window; SDK parity only, not verified live
  • Admin UI writes input_cost_per_second only and shows output_cost_per_second only
    • Pre-existing; a UI-created per-second deployment now bills but renders -
  • SDK litellm.max_budget accumulator passes seconds where it expects milliseconds
    • Pre-existing unit bug, SDK only, per-second models under-count 1000×
  • Fallback retries may reuse a stale logged end_time for unstamped results
    • Inferred from the code, not verified live
  • Rust bridge finalize() and topaz per-second path not exercised live
  • CircleCI reds at the tip (pipeline 90047) are fleet-wide, red on main too
    • local_testing_part1 bedrock parity, llm_translation_testing fireworks/hosted_vllm/moonshot, unit secret-detection timing
    • Same tests red on main pipelines 90036, 90023, 90021, and 89979
    • e2e_ui_testing and using_litellm_on_windows fail at the same steps as main 90023
  • litellm_router_unit_testing stream count flaked across a minute boundary at the tip
    • Green on every main pipeline, unchanged since the merge base, passes locally 3/3, green on the CircleCI rerun (job 2200301)
  • tests/unit test_detailed_timing_pre_processing_uses_receive_anchor fails on a non-UTC laptop at base and head alike

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

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_second on chat-style calls.

Per-second billing is centralized in _per_second_pricing_cost and applied in cost_per_token before 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_ms first, then explicit total_time, then the logging object’s start/end window. response_metadata now stamps timing before computing response_cost in hidden params, and get_response_ms accepts mixed float/datetime timestamps.

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.

@devin-ai-integration

devin-ai-integration Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@greptile-apps

greptile-apps Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

The PR appears safe to merge; no outstanding correctness or repository-rule violations were identified.

Findings

  1. P2 Duplicate mapped test file ▶

Summary

This PR fixes duration-based cost accounting by resolving response duration before pricing and applying per-second-only rates ahead of provider-specific calculators.

  • Adds shared per-second pricing for eligible completion modes while preserving token and tiered pricing precedence.
  • Resolves duration from stamped response metadata, explicit caller timing, or the logging window.
  • Supports mixed datetime and numeric logging timestamps.
  • Reorders response metadata updates so pricing sees the stamped duration.
  • Adds regression coverage across providers, streaming fallbacks, media-mode exclusions, logging timestamps, and response metadata.
  • Moves the response metadata regression test into the repository’s mapped tests/unit file, fully addressing the previous review finding.

Reviews (3) · Last reviewed commit: "fix(cost_calculator): keep media-mode pe..."

Comment on lines +12 to +68
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)

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.

P2 Duplicate mapped test file

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!

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.

Moved into the mapped tests/unit/litellm_core_utils/llm_response_utils/test_response_metadata.py in cd493dd and dropped the duplicate file.

@codspeed

codspeed Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_per_second_chat_pricing (a56166d) with main (19c13ac)

Open in CodSpeed

@codecov

codecov Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.91837% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/cost_calculator.py 94.44% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

…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
@mateo-berri mateo-berri added run-ci and removed run-ci labels Sep 22, 2026
@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri mateo-berri added run-ci and removed run-ci labels Sep 22, 2026

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

Stale Bugbot comment from a previous run.

@chilkotiKartik

Copy link
Copy Markdown

Review for PR #42403: Honor per-second custom pricing on chat completions for every provider

Architecture & Precision Verification

  1. Duration Precision:
    When computing custom duration-based pricing (time_to_first_token or total_request_duration_seconds), ensure duration values from async streaming chunks are measured using monotonic clocks (time.perf_counter()) to prevent clock skew or NTP adjustments from corrupting billable units.

  2. Custom Pricing Precedence:
    Validate that custom_pricing dictionaries override default provider rates in litellm.completion_cost() without clobbering model cache lookups for token usage.

# 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.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri mateo-berri added run-ci and removed run-ci labels Sep 22, 2026
@mateo-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 a56166d. Configure here.

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

LGTM

@mateo-berri
mateo-berri merged commit 8603d6e into main Sep 22, 2026
145 of 151 checks passed
@mateo-berri
mateo-berri deleted the litellm_per_second_chat_pricing branch September 22, 2026 05:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants