Repository navigation
fix(anthropic): handle non-streaming responses without a usage object - #44756
apex-mochen wants to merge 2 commits into
Conversation
|
| @@ -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 {}, | |||
There was a problem hiding this comment.
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 Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
| # "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) |
There was a problem hiding this comment.
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.
PR overviewThe 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 |
…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>
866b5eb to
b5132b7
Compare
|
Rebased onto the latest Resolution notes:
Could you take another look when the checks finish? |
|
The only failing check on this head is the 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>
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).