Skip to content

fix(cost): charge key budget when usage is missing or malformed - #50469

Open
Nafay-0 wants to merge 6 commits into
BerriAI:mainfrom
Nafay-0:cursor/fix-missing-malformed-usage-budget-3bbf
Open

Nafay-0 wants to merge 6 commits into
BerriAI:mainfrom
Nafay-0:cursor/fix-missing-malformed-usage-budget-3bbf

Conversation

@Nafay-0

@Nafay-0 Nafay-0 commented Nov 6, 2026 •

Copy link
Copy Markdown

Handwritten 1-3 sentence description

When an OpenAI-compatible upstream omits usage or returns it malformed, LiteLLM priced the reply at $0 (or 500'd on malformed values), so a key's max_budget never closed on that traffic. This marks missing or unparseable usage the same way streams already mark unreported usage, so cost tracking prices the reply from locally counted tokens while the response body still reports 0/0.

Details

TLDR

Problem this solves:

  • An OpenAI-compatible upstream that omits usage is priced at $0
  • A key's max_budget never closes on that traffic
  • Malformed usage ("oops", null) 500s the client even though the upstream already billed

How it solves it:

  • Missing or unparseable usage is marked the same way streams already mark unreported usage
  • Cost tracking prices that reply from locally counted prompt and completion tokens
  • A warning is logged, and the response body still shows 0/0 usage

Intentional product change: a reply with no usable usage is now charged an estimate instead of $0. The JSON body still reports 0 prompt and 0 completion tokens

User Flow

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

  1. The proxy admin adds an OpenAI-compatible model with per-token prices whose server omits usage, or returns {"prompt_tokens":"oops","completion_tokens":null}
  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 omitted-usage calls return 200 with x-litellm-response-cost: 0.0, GET https://litellm-domain/key/info shows spend 0.0, and a malformed-usage call returns 500 Invalid response object

After: the same omitted or malformed calls are charged an estimate, so the budget closes, and malformed usage no longer 500s

  1. The proxy admin adds the same OpenAI-compatible model
  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 422 budget exceeded, GET https://litellm-domain/key/info shows the spend, and a malformed-usage call also returns 200 with a non-zero cost

Relevant issues

Fixes #50124

This is the non-streamed side of the stream path that already estimates tokens when usage is missing. Open PR #50442 covers omitted usage only. This change also covers malformed usage so that case no longer 500s

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

Verification below was automated through the running proxy HTTP API; no manual UI verification was performed.

Before ran on current upstream main (709b27e) and After on this PR's tip (0c3f3f1), with the same command, config, client and Redis, each on a fresh Postgres 17 database. The proxy applied its own migrations at boot.

The proxy ran two workers (two Started server process lines, two worker processes) against one local Redis 7.4 used by both router_settings and general_settings.coordination_redis, flushed before each run. That way the key's spend and budget check go through the shared counters.

The upstream is a small local OpenAI-compatible stub. For model stub-nousage it answers with a normal chat completion and no usage key. For stub-malformed it sends "usage": {"prompt_tokens": "oops", "completion_tokens": null}. No real provider was called, see Caveats.

Proxy command, config.yaml, the stub and the client

Env var name: DATABASE_URL. sk-local-test is a throwaway master key for this local run.

python stub.py      # on :9100
python litellm/proxy/proxy_cli.py --config config.yaml --port 4000 --num_workers 2 --detailed_debug --reload --use_v2_migration_resolver
python client.py client.log
model_list:
  - model_name: no-usage
    litellm_params:
      model: openai/stub-nousage
      api_base: http://127.0.0.1:9100/v1
      api_key: fake-upstream-key
      input_cost_per_token: 0.00001
      output_cost_per_token: 0.00003
  - model_name: bad-usage
    litellm_params:
      model: openai/stub-malformed
      api_base: http://127.0.0.1:9100/v1
      api_key: fake-upstream-key
      input_cost_per_token: 0.00001
      output_cost_per_token: 0.00003
general_settings:
  master_key: sk-local-test
  database_url: os.environ/DATABASE_URL
  proxy_batch_write_at: 2
  coordination_redis:
    host: 127.0.0.1
    port: 6390
router_settings:
  redis_host: 127.0.0.1
  redis_port: 6390
"""OpenAI-compatible upstream that omits usage (model stub-nousage) or returns malformed usage (stub-malformed)."""
import json, time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer


class H(BaseHTTPRequestHandler):
    def do_POST(self):
        body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        reply = {
            "id": "chatcmpl-stub", "object": "chat.completion", "created": int(time.time()), "model": body["model"],
            "choices": [{"index": 0, "finish_reason": "stop",
                         "message": {"role": "assistant", "content": "Here is a fairly long answer " * 20}}],
        }
        if body["model"] == "stub-malformed":
            reply["usage"] = {"prompt_tokens": "oops", "completion_tokens": None}
        out = json.dumps(reply).encode()
        self.send_response(200); self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(out))); self.end_headers(); self.wfile.write(out)

    def log_message(self, *a):
        pass


ThreadingHTTPServer(("127.0.0.1", 9100), H).serve_forever()
import json, sys, time
import httpx

LOG = sys.argv[1]
out = open(LOG, "w")
def log(*a):
    line = " ".join(str(x) for x in a); print(line); out.write(line + "\n"); out.flush()

admin = httpx.Client(base_url="http://127.0.0.1:4000", headers={"Authorization": "Bearer sk-local-test"}, timeout=60)
r = admin.post("/key/generate", json={"max_budget": 0.0005, "key_alias": "budget-e2e"})
key = r.json()["key"]
log("POST /key/generate max_budget=0.0005 ->", r.status_code)
dev = httpx.Client(base_url="http://127.0.0.1:4000", headers={"Authorization": f"Bearer {key}"}, timeout=60)
msg = {"messages": [{"role": "user", "content": "Explain how budgets work in one paragraph please."}]}
for i in range(1, 21):
    r = dev.post("/v1/chat/completions", json={"model": "no-usage", **msg})
    usage = r.json().get("usage") if r.status_code == 200 else None
    log(f"call {i:2d} no-usage -> {r.status_code} x-litellm-response-cost={r.headers.get('x-litellm-response-cost')} "
        f"body.usage={json.dumps(usage) if usage else r.text[:110]}")
    time.sleep(0.3)
time.sleep(5)
info = admin.get("/key/info", params={"key": key}).json()["info"]
log("GET /key/info -> spend", info.get("spend"), "max_budget", info.get("max_budget"))
r = admin.post("/v1/chat/completions", json={"model": "bad-usage", **msg})
log("malformed usage call (admin key) ->", r.status_code, "x-litellm-response-cost=", r.headers.get("x-litellm-response-cost"),
    r.text[:160] if r.status_code != 200 else "body.usage=" + json.dumps(r.json().get("usage")))

Before (709b27e)

Key budget

  1. POST /key/generate with max_budget: 0.0005 returns 200
  2. All 20 POST /v1/chat/completions calls on no-usage return 200 with x-litellm-response-cost: 0.0 and usage {"completion_tokens": 0, "prompt_tokens": 0, "total_tokens": 0}
  3. GET /key/info shows spend 0.0, max_budget 0.0005

Malformed usage

  1. POST /v1/chat/completions on bad-usage returns 500
{"error":{"message":"litellm.InternalServerError: InternalServerError: OpenAIException - Invalid response object","type":"internal_server_error", ...

After (0c3f3f1)

Key budget

  1. POST /key/generate with max_budget: 0.0005 returns 200
  2. Call 1 returns 200 with x-litellm-response-cost: 0.0038, and the body still says {"completion_tokens": 0, "prompt_tokens": 0, "total_tokens": 0}
  3. Calls 2 to 20 return 422
{"error":{"message":"Budget has been exceeded! Key=budget-e2e (sk-...) Current cost: 0.0038, Max budget: 0.0005 ...
  1. GET /key/info shows spend 0.0038, max_budget 0.0005

The stub's reply is long enough that one call costs more than the whole budget, so the key closes after the first call.

Malformed usage

  1. POST /v1/chat/completions on bad-usage returns 200 with x-litellm-response-cost: 0.0038, and the body usage is still 0/0

Tests

uv run pytest tests/unit/litellm_core_utils/llm_response_utils/test_convert_dict_to_response.py \
  tests/unit/litellm_core_utils/test_litellm_logging.py -q \
  -k "usage_still_returns or reported_usage_is_kept or a_reply_with or a_reply_without or reports_zero_tokens"

8 passed at 0c3f3f1:

  • test_missing_usage_still_returns_a_response
  • test_malformed_usage_still_returns_a_response
  • test_reported_usage_is_kept
  • test_a_reply_without_usage_is_priced_from_locally_counted_tokens
  • test_a_reply_with_malformed_usage_is_priced_from_locally_counted_tokens
  • test_a_reply_with_empty_usage_is_priced_from_locally_counted_tokens
  • test_a_reply_with_null_token_counts_is_priced_from_locally_counted_tokens
  • test_a_reply_whose_provider_reports_zero_tokens_stays_at_zero

With the base versions of the two source files swapped in, the cost tests price the reply at 0.0 and malformed usage fails before cost tracking runs. The last test checks that a provider's explicit 0/0 still prices at $0. Both test files passed in full locally (903 tests).

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • Callers relying on $0 for usage-less replies now get charged
    • Only replies that reached cost tracking with no usage, or usage that could not be parsed
    • A provider's explicit 0/0 is still treated as reported
  • The estimate is a local token count, so it can be off
    • Same counter and tokenizer choice the stream path uses
    • An image in the prompt gets token_counter's default count, since accounting must not fetch a caller's URL
  • The live run used a local OpenAI-compatible stub, not a real provider
    • A real provider that omits usage would hit the same code path

Low

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

Copilot AI balanced review requested due to automatic review settings November 6, 2026 23:15
@CLAassistant

CLAassistant commented Nov 6, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@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: 4 · PR risk: 0/10

Reviews

Price replies with missing or malformed usage from locally counted tokens so key max_budget still applies.
@cursor
cursor Bot force-pushed the cursor/fix-missing-malformed-usage-budget-3bbf branch from 5757855 to 83531b0 Compare November 6, 2026 23:23
…lback

Treat empty or null token counts as unreported, include tools and reasoning in the local count, and keep charging completion tokens when the prompt counter raises.
…malformed-usage-budget-3bbf

# Conflicts:
#	tests/unit/litellm_core_utils/test_litellm_logging.py

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

3 participants