Skip to content

fix(anthropic): handle non-streaming responses without a usage object - #44756

Open
apex-mochen wants to merge 2 commits into
BerriAI:mainfrom
apex-mochen:fix/anthropic-missing-usage-transform
Open

apex-mochen wants to merge 2 commits into
BerriAI:mainfrom
apex-mochen:fix/anthropic-missing-usage-transform

Conversation

@apex-mochen

Copy link
Copy Markdown
Contributor

Fixes #44535

Some Anthropic non-streaming responses omit the usage object; transform_parsed_response indexed completion_response["usage"] directly, raising KeyError('usage'), which the router mapped to a 500 and retried num_retries times before surfacing a final 500.

Fix: a missing usage keeps the request successful, but unlike an injected 0/0 the usage stays absent in the response path and the logging payload records usage=None with a marker in standard_logging_object, so spend tracking and budgets can distinguish "no usage reported" from a genuine zero (per review feedback on this thread).

AI-assisted disclosure: generated with AI assistance.

Regression test covers both a missing usage key and usage: None (fails with KeyError before the fix).

@greptile-apps

greptile-apps Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

[Medium risk] Handles missing usage data in Anthropic API responses.

The PR should not merge until missing Anthropic usage remains distinguishable from genuine zero usage for cost accounting.

Findings

  1. P1 Missing usage becomes zero cost ▶

Summary

The PR prevents a missing or null usage object from raising KeyError in non-streaming Anthropic responses and adds a regression test. Its fallback currently reports unknown usage as zero tokens.

Reviews (1) · Last reviewed commit: "[Bugfix][Anthropic] Handle non-streaming..."

@@ -2675,7 +2675,7 @@ def transform_parsed_response(
)

usage: Final = self.calculate_usage(
usage_object=completion_response["usage"],
usage_object=completion_response.get("usage") or {},

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.

P1 Missing usage becomes zero cost When a non-streaming Anthropic response contains generated text but omits usage or sets it to None, this fallback creates a real usage object with zero tokens. Response-based cost calculation uses those zeros without counting the returned text, so spend tracking can record a generated response as costing nothing. The response and logging payload also lack the missing-usage marker described in the PR, leaving unknown usage indistinguishable from genuine zero usage.

@codecov

codecov Bot commented Oct 6, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing apex-mochen:fix/anthropic-missing-usage-transform (54f757b) with main (5b8f0a4)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (883e321) during the generation of this report, so 5b8f0a4 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

# "no usage reported" apart from a genuine zero, otherwise a
# response that omits usage would be recorded as free even though
# the upstream consumed tokens.
setattr(model_response, "usage", None)

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.

Low: Spend budget bypass for missing usage

When a billable upstream with token-based pricing omits/nulls usage, a virtual-key holder can now repeatedly receive successful completions without consuming their spend budget: completion_cost() converts usage=None into empty usage and zero token counts (litellm/cost_calculator.py:1476–1511), and the spend callback reconciles any reservation against that zero cost. Nothing downstream reads usage_missing, so wire this case into accounting and budget enforcement—for example, retain a conservative estimated charge or reject unmetered responses for budgeted requests rather than recording them as free.

@veria-ai

veria-ai Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

PR overview

The PR updates Anthropic response handling to support non-streaming completions when the upstream response omits or nulls the usage object.

One accounting issue remains open: when a billable upstream omits usage, successful completions can be recorded at zero cost, allowing a virtual-key holder to repeatedly obtain completions without consuming their spend budget. This undermines budget enforcement for affected responses, and no issues have been addressed yet.

Open issues (1)

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

@apex-mochen apex-mochen changed the title [Bugfix][Anthropic] Handle non-streaming responses without a usage object fix(anthropic): handle non-streaming responses without a usage object Oct 6, 2026
…4535)

Instead of injecting `{}` so calculate_usage fabricates a 0/0 usage, a
successful non-streaming response that carries no usage object now keeps
`model_response.usage` as None and marks `_hidden_params["usage_missing"]`,
so spend tracking and budgets can distinguish "no usage reported" from a
genuine zero instead of recording the call as free.

Signed-off-by: apex-mochen <2756823972@qq.com>
@apex-mochen
apex-mochen force-pushed the fix/anthropic-missing-usage-transform branch from 866b5eb to b5132b7 Compare October 9, 2026 08:21
@apex-mochen

Copy link
Copy Markdown
Contributor Author

Rebased onto the latest main (a3236ba9). The branch previously sat on a stale base which made the merge dirty.

Resolution notes:

  • transformation.py: clean 3-way merge (our change is preserved in the new context).
  • test_anthropic_chat_transformation.py: one overlap between the test_transform_parsed_response_without_usage regression test and the newer anthropic_chunk_list streaming fixtures added upstream; kept both (our test follows the earlier fixture in the file).
  • Verified: both files compile, ruff check clean under the repo's ruff.toml / ruff-tests.toml, no conflict markers, LF endings.

Could you take another look when the checks finish?

@apex-mochen

Copy link
Copy Markdown
Contributor Author

The only failing check on this head is the lint job — everything else (unit, smoke, codecov, and the 28 provider/runtime jobs) is green. Could this be the same repo-level environment failure that hit other PRs today (#44759, #45569, #45531, #44514)? Locally ruff check and ruff format --check pass on this exact diff, and the full unit suite for the touched module is green.

If it reproduces on re-run I'll dig into the failing log, but this looks like the shared lint/uv environment rather than the change itself. Could the lint job be re-run?

The rebase side failed CI at the first lint step, so the later gates had
never run; running them locally surfaced three more. All four are
mechanical:

1. ruff I001: the rebase resolution left the anthropic transformation
   import groups different from upstream's layout; restore upstream's own
   grouping (third-party block, then litellm).
2. ruff-strict B010: the usage change replaced one setattr with two, so
   the file counted one more B010 than the merge-base.
3. type-discipline LIT011 / basedpyright reportAttributeAccessIssue:
   writing `model_response.usage = ...` is an in-place store on a
   parameter; the two stores added 2 LIT011 and 2 attribute-access
   diagnostics over the merge-base ceilings.
4. basedpyright unknown-type rules: reading
   `completion_response.get("usage")` into a `Final` local added
   reportUnknownMemberType and reportUnknownVariableType. A Final name
   takes its inferred type, so an annotation cannot widen it away; the
   value has to stop flowing out of an unknown dict into a new local.

Resolved as one shape rather than four patches: compute the value with a
conditional expression and write it back through the single `setattr`
upstream already used on that line, so the B010, LIT011, attribute-access
and basedpyright rule counts all stay at their merge-base totals, with no
suppression comment anywhere.

No behavior change: a missing key and an explicit null both still mean
"no usage reported" (asserted by
test_transform_parsed_response_without_usage, both variants).

Signed-off-by: apex-mochen <2756823972@qq.com>

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]: Anthropic response without a usage object leads to a retry and HTTP 500 on /chat/completions

1 participant