Skip to content

fix(cost): price a non-streamed reply without usage from counted tokens - #50442

Open
zuraiz-anjum wants to merge 2 commits into
BerriAI:mainfrom
zuraiz-anjum:fix-no-usage-cost
Open

zuraiz-anjum wants to merge 2 commits into
BerriAI:mainfrom
zuraiz-anjum:fix-no-usage-cost

Conversation

@zuraiz-anjum

@zuraiz-anjum zuraiz-anjum commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

[insert handwritten description here]

Details

TLDR

Problem this solves:

  • A non-streamed chat reply with no usage is priced at $0
  • Key budgets never close and spend logs show $0 for that traffic
  • The zero-cost warning also stays quiet, so nobody notices

How it solves it:

  • completion() now leaves its placeholder usage as the existing UnreportedUsage marker
  • Cost tracking prices a reply still carrying that marker from locally counted tokens
  • Same estimate streams already get, and a warning is logged once per reply

Intentional product change: a reply with no usage is now charged an estimate instead of $0. The response body still shows the same 0/0 usage it shows today

User Flow

Before: a key with a hard budget keeps serving an upstream that leaves usage out, and every call is free

  1. The proxy admin adds an OpenAI-compatible model with per-token prices whose server omits usage from replies
  2. They create a key with max_budget: 0.0005
  3. A developer sends POST https://litellm-domain/v1/chat/completions with that key, twenty times
  4. All twenty return 200 with x-litellm-response-cost: 0.0, and GET https://litellm-domain/key/info shows spend 0.0

After: the same calls are charged an estimate, so the budget closes

  1. The proxy admin adds an OpenAI-compatible model with per-token prices whose server omits usage from replies
  2. They create a key with max_budget: 0.0005
  3. A developer sends POST https://litellm-domain/v1/chat/completions with that key, twenty times
  4. The first few return 200 with a non-zero x-litellm-response-cost, then the key gets 400 budget exceeded, and GET https://litellm-domain/key/info shows the spend

Relevant issues

Fixes #50124

This is the non-streamed side of #44230, which restored the token estimate for streams that send no usage

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

No major provider leaves usage out of a normal reply, so the upstream here is a small OpenAI-compatible stub that answers every chat completion with a fixed reply and no usage key, streamed or not. With --usage it sends a 12/9 usage block, which is the control. The proxy ran with one worker and no Redis, since the change is in how a single reply is priced and not in shared counters. The budget case used a throwaway Postgres

Shared setup, the stub, the config and the requests
"""Tiny OpenAI-compatible upstream for the #50124 proof. Answers every chat completion with a fixed reply.

python stub_upstream.py --port 8999            -> replies with no "usage" key (the bug)
python stub_upstream.py --port 8999 --usage    -> replies with usage 12/9 (control)

"stream": true gets SSE chunks, again with no usage unless --usage is set. Any other path is a 404.
"""

import argparse
import json
import time
from http.server import BaseHTTPRequestHandler, HTTPServer

REPLY = "A budget is a promise you keep to yourself"
USAGE = {"prompt_tokens": 12, "completion_tokens": 9, "total_tokens": 21}


def make_handler(with_usage: bool) -> type[BaseHTTPRequestHandler]:
    class Handler(BaseHTTPRequestHandler):
        def send(self, status: int, content_type: str, raw: bytes) -> None:
            self.send_response(status)
            self.send_header("content-type", content_type)
            self.send_header("content-length", str(len(raw)))
            self.end_headers()
            self.wfile.write(raw)

        def do_POST(self) -> None:
            request = json.loads(self.rfile.read(int(self.headers.get("content-length") or 0)) or b"{}")
            if not self.path.endswith("/chat/completions"):
                self.send(404, "application/json", json.dumps({"error": {"message": "not served by the stub"}}).encode())
                return
            base = {"id": f"chatcmpl-stub-{time.time_ns()}", "created": int(time.time()), "model": "stub-model"}
            if request.get("stream"):
                chunks = [
                    {"index": 0, "delta": {"role": "assistant", "content": REPLY}, "finish_reason": None},
                    {"index": 0, "delta": {}, "finish_reason": "stop"},
                ]
                events = [{**base, "object": "chat.completion.chunk", "choices": [c]} for c in chunks]
                if with_usage and (request.get("stream_options") or {}).get("include_usage"):
                    events.append({**base, "object": "chat.completion.chunk", "choices": [], "usage": USAGE})
                body = "".join(f"data: {json.dumps(e)}\n\n" for e in events) + "data: [DONE]\n\n"
                self.send(200, "text/event-stream", body.encode())
                return
            message = {"role": "assistant", "content": REPLY}
            body = {**base, "object": "chat.completion", "choices": [{"index": 0, "message": message, "finish_reason": "stop"}]}
            if with_usage:
                body["usage"] = USAGE
            self.send(200, "application/json", json.dumps(body).encode())

        def log_message(self, format: str, *args: object) -> None:
            print("stub:", self.command, self.path, flush=True)

    return Handler


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--port", type=int, default=8999)
    parser.add_argument("--usage", action="store_true")
    args = parser.parse_args()
    print(f"stub upstream on 127.0.0.1:{args.port}, usage={'on' if args.usage else 'omitted'}", flush=True)
    HTTPServer(("127.0.0.1", args.port), make_handler(args.usage)).serve_forever()
model_list:
  - model_name: no-usage-model
    litellm_params:
      model: openai/stub-model
      api_base: http://127.0.0.1:53079/v1
      api_key: stub
      input_cost_per_token: 0.000003
      output_cost_per_token: 0.000007
general_settings:
  proxy_batch_write_at: 2

The response cost case ran without a database and with the same config minus general_settings. Env var names are LITELLM_MASTER_KEY, LITELLM_LOCAL_MODEL_COST_MAP=True and, for the budget case only, DATABASE_URL

python stub_upstream.py --port $STUB_PORT
python litellm/proxy/proxy_cli.py --config config.yaml --port $PORT --num_workers 1 --detailed_debug

curl -sD - http://localhost:$PORT/v1/chat/completions \
  -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" \
  -d '{"model": "no-usage-model", "messages": [{"role": "user", "content": "Write one line about budgets"}]}'

curl -sN http://localhost:$PORT/v1/chat/completions \
  -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" \
  -d '{"model": "no-usage-model", "messages": [{"role": "user", "content": "Write one line about budgets"}], "stream": true, "stream_options": {"include_usage": true}}'

KEY=$(curl -s http://localhost:$PORT/key/generate -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
  -H "Content-Type: application/json" -d '{"max_budget": 0.0005}' | python -c "import json,sys; print(json.load(sys.stdin)['key'])")
for i in $(seq 1 20); do
  curl -s -o /dev/null -w "%{http_code} " http://localhost:$PORT/v1/chat/completions -H "Authorization: Bearer $KEY" \
    -H "Content-Type: application/json" \
    -d '{"model": "no-usage-model", "messages": [{"role": "user", "content": "Write one line about budgets"}]}'
  sleep 1
done
sleep 12
curl -s "http://localhost:$PORT/key/info?key=$KEY" -H "Authorization: Bearer $LITELLM_MASTER_KEY"

Before (2a4f8b1)

Response cost

  1. The curl returns 200 with x-litellm-response-cost: 0.0 and usage {"completion_tokens": 0, "prompt_tokens": 0, "total_tokens": 0}
  2. Nothing about the missing usage in the proxy log
  3. With "stream": true and include_usage the last chunk is {"id":"chatcmpl-stub-1794006257060714784","created":1794006257,"model":"no-usage-model","object":"chat.completion.chunk","choices":[],"usage":{"completion_tokens":9,"prompt_tokens":12,"total_tokens":21,"completion_tokens_details":{"reasoning_tokens":0,"text_tokens":9},"cost":0.000099}}

Key budget

  1. A key with max_budget: 0.0005 answers the 20 calls with 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200
  2. /key/info shows spend 0.0, max_budget 0.0005

After (fa9664a)

Response cost

  1. The same curl returns 200 with x-litellm-response-cost: 9.9e-05, and the body still says {"completion_tokens": 0, "prompt_tokens": 0, "total_tokens": 0}
  2. The proxy log has stub-model returned no token usage, so it is priced from locally counted tokens (12 prompt, 9 completion)
  3. With "stream": true and include_usage the last chunk is {"id":"chatcmpl-stub-1794006326184869702","created":1794006326,"model":"no-usage-model","object":"chat.completion.chunk","choices":[],"usage":{"completion_tokens":9,"prompt_tokens":12,"total_tokens":21,"completion_tokens_details":{"reasoning_tokens":0,"text_tokens":9},"cost":0.000099}}, so the stream path is unchanged
  4. Control with the stub sending usage 12/9 gives x-litellm-response-cost: 9.9e-05 and no warning

Key budget

  1. A fresh key with max_budget: 0.0005 answers the 20 calls with 200 200 200 200 200 200 422 422 422 422 422 422 422 422 422 422 422 422 422 422
  2. The first refused call returns
{"error":{"message":"Budget has been exceeded! Key=key (sk-...HZvA) Current cost: 0.0005940000000000098, Max budget: 0.0005","type":"budget_exceeded","param":null,"code":"422"}}
  1. /key/info shows spend 0.0005939999999999999, max_budget 0.0005

Tests

uv run pytest tests/unit/litellm_core_utils/test_litellm_logging.py -k "without_usage or reports_zero_tokens or omits_usage" gives 3 failed, 1 passed, 773 deselected, 18 warnings in 30.30s at the merge base with only the tests added and 4 passed, 773 deselected, 18 warnings in 23.29s at the tip. Three fail at the merge base because the reply is priced at 0.0, the fourth checks that a provider's explicit 0/0 still prices at $0

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • Callers relying on $0 for usage-less replies now get charged
  • The estimate is a local token count, so it can be off
    • Same counter and tokenizer choice the stream path uses
    • Tool-call arguments are counted, and an image in the prompt gets token_counter's default count, since accounting must not fetch a caller's URL

Low

  • Spend log rows keep 0 prompt and 0 completion tokens next to the estimated spend
    • The tokens show what the provider reported, the spend is the estimate
    • Can follow up if you'd rather log the estimated counts too
  • Malformed usage (the 500 case in the issue) is not covered here, it fails before cost tracking runs
  • response.usage == litellm.Usage() is now False for these replies, since pydantic compares the class

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

@veria-ai

veria-ai Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No open security issues remain on this pull request.

Fixed/addressed: 1 · PR risk: 0/10

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Key budget is not charged when the provider's response has missing or malformed usage

1 participant