Skip to content

fix(anthropic): log 0 output tokens when an error frame follows message_start - #53914

Merged
mateo-berri merged 3 commits into
mainfrom
litellm_anthropic_error_frame_partial_usage
Nov 23, 2026
Merged

mateo-berri merged 3 commits into
mainfrom
litellm_anthropic_error_frame_partial_usage

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

When Anthropic sends an error in the middle of a streamed reply before any text arrived, the failed attempt was logged with one output token that was never generated. It now logs zero, the same as when the connection simply drops at that point, so failed attempts are costed the same way whichever way they fail

Details

Link to Devin session: https://app.devin.ai/sessions/fcfafbe746ed40609bc6395f0854cdbb
Open in Devin Desktop: https://app.devin.ai/desktop/session/fcfafbe746ed40609bc6395f0854cdbb?variant=devin
Requested by: @mateo-berri

TLDR

Problem this solves:

How it solves it:

  • Leaves upstream error events out before the stream is assembled for logging
  • Both failure shapes now take the same path and report the same usage and cost
  • Text received before an error frame is now counted, as it already was for a drop
  • Works whether logging hands over whole SSE frames or the stream already split into lines

User Flow

Before: a failed attempt that Anthropic ended with an error frame shows one output token nobody received

  1. A developer sends POST https://litellm-domain/v1/messages with "stream": true to an Anthropic model with num_retries: 1
  2. Anthropic sends message_start and then event: error, and the gateway retries and completes the reply
  3. Their logging callback receives the failed attempt with 5 input and 1 output tokens

After: the same failed attempt shows zero output tokens

  1. The developer sends the same POST https://litellm-domain/v1/messages with "stream": true
  2. Anthropic sends message_start and then event: error, and the gateway retries and completes the reply
  3. Their logging callback receives the failed attempt with 5 input and 0 output tokens, the same as after a dropped connection

Relevant issues

Follow-up to #53394 and #53885

Pre-Submission checklist

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

Screenshots / Proof of Fix

Both runs are tests/integration/run.py providers --workers 2 tests/integration/messages_endpoint/providers/anthropic/test_anthropic_messages_pre_content_retry_wire.py with this PR's tests

Before (551a18b, product files from main)

  1. 1 failed, 38 passed
  2. test_superseded_attempt_and_its_retry_each_log_their_own_usage[recoverable-error-frame] fails with AssertionError: (('failure', 5, 1), ('success', 5, 3))

After (529d421)

  1. 39 passed

Mutation: reverting the two files under litellm/ turns the unit tests named test_upstream_error_frame_... red in all four of their cases (4 failed), and restoring them turns them green (236 passed for the file). Reverting only 08fe119's change to the filter turns the two cases that pass the stream as separate lines red (2 failed, 2 passed)

Type

🐛 Bug Fix

Caveats (if any)

Low

  • An error frame after content used to log only the message_start placeholder as output. It now logs the output tokens estimated from the text that arrived, matching a dropped connection after content, so those failed attempts cost slightly more in the logs than before
  • The integration file does not run on this PR's CI without the run-ci label, so it first runs on main after merge. It was run locally as shown above

Note

Medium Risk
Adjusts token and cost accounting on Anthropic streaming failure paths used by spend logs and callbacks; behavior for failures after some content may bill slightly more output than before (more accurate).

Overview
Anthropic streaming failures that end with an upstream error SSE frame (e.g. right after message_start) were logged with a phantom output token from the message_start placeholder, while a connection drop at the same point logged 0 output tokens.

This change adds anthropic_sse_events_before_upstream_error, which strips upstream error events before stream assembly, and wires it into AnthropicPassthroughLoggingHandler._assemble_streaming_response so partial-failure logging follows the same path for error frames and transport drops. Integration and unit tests now assert matching usage/cost for both failure shapes (including when chunks are split into lines).

Reviewed by Cursor Bugbot for commit 529d421. Bugbot is set up for automated code reviews on this repo. Configure here.

…ge_start

A /v1/messages stream that ended with an upstream error event right after
message_start logged the message_start placeholder as 1 output token on the
failed attempt, while the same stream cut by a dropped connection logged 0.
Assembly raised on the error event and fell back to usage-only parsing, which
copies the placeholder. The error events are now left out before assembly, so
both failure shapes report the same usage and cost

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration

Copy link
Copy Markdown
Contributor

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

@veria-ai

veria-ai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@greptile-apps

greptile-apps Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with no new actionable issues found.

Summary

The PR removes upstream error frames before building responses for logging. Failed streams can retain received text without counting a placeholder output token before content arrives.

  • Anthropic error frames no longer add phantom output tokens to failure logs.

Reviews (3) · Last reviewed commit: "refactor(anthropic): one loop per compre..." · Reviewed by Greptile

try:
assembled: Final = AnthropicPassthroughLoggingHandler.build_complete_streaming_response(
all_chunks=all_chunks,
all_chunks=anthropic_sse_events_before_upstream_error(all_chunks),

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 Required live proof is missing

This changes how provider errors become logged responses, but the supplied proof uses only synthetic upstreams and unit tests. The repository requires before/after requests through a running proxy to real providers. Add reproducible commands, commit hashes, and actual outputs, with the after run at dd6827970ba6942999030610a0309d17cd70ec9f. This requirement must be satisfied before merging.

Rule Used: Apply this rule only to PRs that fix LLM translation bugs or add LLM translation features. LLM translation means converting requests, responses, streaming events, tool calls, and errors between the API a caller uses on LiteLLM (any endpoint or SDK fu... (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.

Anthropic cannot be made to send an error frame right after message_start on demand, so the proof is the real proxy run against a scripted upstream, rerun at 08fe119 with 39 passed

… split into lines

The logging path for a stream that ran to its end hands assembly the SSE
lines one by one, with no blank lines between frames, so the frame scan
found no error event and returned the lines unchanged. The filter now
looks at each event it splits out, so both input shapes drop the error

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

… error-free streams

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

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 529d421. Configure here.

@mateo-berri
mateo-berri enabled auto-merge (squash) November 23, 2026 21:25
@mateo-berri
mateo-berri requested review from ryan-crabbe-berri and yucheng-berri and removed request for yucheng-berri November 23, 2026 21:25
@mateo-berri
mateo-berri merged commit 6088120 into main Nov 23, 2026
56 checks passed
@mateo-berri
mateo-berri deleted the litellm_anthropic_error_frame_partial_usage branch November 23, 2026 23:10
mateo-berri added a commit that referenced this pull request Nov 23, 2026
…08_x

fix(anthropic): log 0 output tokens when an error frame follows message_start on lts/1.108.x (#53914)
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.

2 participants