Skip to content

fix: prevent doubled thinking text in streaming reasoning reassembly (#43010) - #43196

Closed
PrimeFoldTools wants to merge 1 commit into
BerriAI:mainfrom
PrimeFoldTools:fix/43010-doubled-thinking-streaming
Closed

PrimeFoldTools wants to merge 1 commit into
BerriAI:mainfrom
PrimeFoldTools:fix/43010-doubled-thinking-streaming

Conversation

@PrimeFoldTools

Copy link
Copy Markdown

Fixes #43010

Problem

On the streaming /v1/responses path with Anthropic, the reassembled reasoning
block (and its encrypted_content) contained the model's thinking text twice.
Non-streaming and /v1/chat/completions were unaffected.

Root cause

ChunkProcessor._build_thinking_blocks (streaming_chunk_builder_utils.py)
accumulates the thinking text of every thinking_blocks entry and flushes the
joined result when it sees a signature.

The Anthropic stream handler emits, on the signature_delta, a thinking_blocks
entry whose thinking field is set to the full block text — the join of every
prior delta (anthropic/chat/handler.py, the signature branch), plus the
signature. So the builder assembled (sum of deltas == full text) +
(signature entry == full text again) = the text doubled. This reassembly only
runs on the streaming Responses path, which is why other paths were unaffected.

Fix

Accumulate text from delta entries, and on the signature entry keep its text only
when it differs from what the deltas already accumulated. In practice no
provider sends new reasoning text on the signature entry — Anthropic repeats the
full text (skipped as a duplicate), Bedrock sends it empty (invoke_handler.py
sets thinking=""). The signature entry's text is therefore used only when it is
the sole source (a stream that carried the full text solely on the signed entry),
so the change neither doubles (Anthropic) nor truncates (any deltas-present shape).
~13 lines in one function; the handler's emission contract is unchanged.

Testing

Adds tests/test_litellm/litellm_core_utils/test_streaming_thinking_doubling_43010.py:

  • drives the real Anthropic handler chunk_parser over raw SSE

    (content_block_start → 3 thinking_delta → signature_delta) and the real
    ChunkProcessor; asserts the reassembled thinking equals the model text once
    (fails on main — returns the doubled text);

  • documents the handler emitting the full text on the signature entry;

  • fallback: full text arriving solely on the signature entry is preserved;

  • Bedrock-style signature entry with thinking="" alongside deltas is neither

    truncated nor doubled.

All four pass with this change; the existing
test_streaming_chunk_builder_utils.py suite (51 tests) remains green. No API key
or network needed.

Scope boundary

Only the streaming reasoning-reassembly de-dup. Does not touch the handler's
emission contract or the non-streaming paths.

@PrimeFoldTools
PrimeFoldTools requested a review from a team September 25, 2026 18:49
@CLAassistant

CLAassistant commented Sep 25, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@greptile-apps

greptile-apps Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Fixes doubled reasoning text in streaming response assembly.

The PR appears safe to merge; no actionable regression was identified.

Summary

The PR prevents Anthropic’s full-text signature entry from being appended after its thinking deltas during streaming reassembly.

  • Adds regression coverage for the Anthropic handler and signed-entry fallback shapes.

Reviews (1) · Last reviewed commit: "fix: prevent doubled thinking text in st..."

@codecov

codecov Bot commented Sep 25, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

…erriAI#43010)

_build_thinking_blocks appended the thinking text of every chunk entry,
including the signature entry whose 'thinking' field re-transmits the full
block text. On the streaming /v1/responses path this doubled the reasoning
content in the reassembled block (and its encrypted_content).

Only accumulate text from delta entries; treat the signature entry as
closing the block, with a fallback to the signature entry's text when no
deltas were seen. Adds a regression test driving the real Anthropic handler
chunk_parser + ChunkProcessor over raw SSE.

Fixes BerriAI#43010
@PrimeFoldTools
PrimeFoldTools force-pushed the fix/43010-doubled-thinking-streaming branch from 9904958 to 5e37f5b Compare September 25, 2026 19:02
@codspeed

codspeed Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing PrimeFoldTools:fix/43010-doubled-thinking-streaming (5e37f5b) with main (081f73f)1

Open in CodSpeed

Footnotes

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

@VANDRANKI VANDRANKI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I traced all four new tests by hand against the actual fix in streaming_chunk_builder_utils.py, plus checked _flush_thinking_block to confirm it resets state between blocks.

The bug (litellm#43010): Anthropic's stream handler emits one thinking_blocks entry per thinking_delta (each carrying just that delta's text), then on signature_delta emits a closing entry whose own thinking field repeats the FULL concatenated text of the block, not just an empty string or a final fragment. The old code unconditionally appended every entry's thinking text before flushing on the signature:

thinking_text = thinking_block.get("thinking", None)
if thinking_text:
    current_thinking_text_parts.append(thinking_text)
signature = thinking_block.get("signature", None)
if signature:
    current_signature = signature
    _flush_thinking_block()

So for Anthropic: sum of deltas (== full text) + the signature entry's full text again == the text twice in the final reassembled block.

The fix reorders this so the plain-delta append only happens when there's no signature on that entry, and adds a second, conditional append for the signature entry: only if its thinking_text differs from what's already been accumulated.

I traced the three shapes the new tests cover against the actual code:

  • Anthropic (3 deltas + signature entry carrying the full text): the 3 deltas accumulate via if thinking_text and not signature: append into [d1, d2, d3], joined = full text. The signature entry then hits if thinking_text and thinking_text != "".join(current_thinking_text_parts): — since its text equals what's already joined, the condition is False, so nothing is appended a second time. Result: exactly one copy of the text, matching test_responses_reasoning_thinking_text_is_not_doubled.
  • Signature-only (no separate deltas, full text arrives solely on the signature entry): current_thinking_text_parts is still empty when the signature entry arrives, so thinking_text != "" is True and it gets appended. Matches test_signature_only_stream_text_preserved.
  • Bedrock-style (deltas carry the text, the closing entry has thinking=""): the closing entry's thinking_text is falsy, so both the first append condition and the second (if thinking_text and ...) short-circuit to False regardless of the join comparison. No truncation, no doubling. Matches test_bedrock_style_empty_signature_entry_does_not_truncate.

I also checked _flush_thinking_block() itself resets current_thinking_text_parts = [] and current_signature = None after building the finished block, so a stream with multiple sequential thinking blocks won't leak state from one block's accumulated text into the next.

The regression test test_handler_signature_entry_repeats_full_thinking_text is a good addition beyond the fix itself: it drives the actual Anthropic ModelResponseIterator.chunk_parser on raw SSE events (not a mock of the builder's input) to document that the handler really does repeat the full text on the signature entry, which is the premise the whole fix depends on, rather than just asserting it in a comment.

I traced this end to end against the real code paths and I'm confident in it.

Community review, doesn't clear the merge gate by itself.

@jinwukong

Copy link
Copy Markdown

Thanks for the reproduction. #40673 covers the same duplication plus signature-only blocks, repeated deltas, and replay payloads. Happy to coordinate

@PrimeFoldTools

Copy link
Copy Markdown
Author

Thanks for flagging #40673 — I hadn't found it when reproducing #43010.

I took a look at the overlap. My patch is narrowly scoped to the duplication path, while #40673 handles the broader stream/replay lifecycle. In particular, its snapshot-vs-delta distinction looks important for preserving genuinely repeated deltas, which my equality-based de-dup doesn't distinguish.

Happy to defer to whichever scope/approach the maintainers prefer. My reproduction and regression test may still be useful as independent coverage of the Anthropic handler → reassembler path.

@jinwukong

Copy link
Copy Markdown

Thanks. Your four regression cases pass on #40673, and the baseline still reproduces duplication. Happy to coordinate with maintainers

@krrish-berri-2

Copy link
Copy Markdown
Contributor

@PrimeFoldTools — could you add a screenshot or short video showing that this change works as expected (e.g. a streamed Anthropic/Bedrock response with thinking, before vs. after, showing the reasoning text is no longer doubled)? It really helps reviewers verify the fix quickly. Thanks!

@jinwukong

jinwukong commented Sep 27, 2026 •

Copy link
Copy Markdown

This earlier video records #40673 at 1571ad12. #44127 now fixes duplication upstream; #40673 has been narrowed to reasoning done replay data

litellm-pr-40673-live-demo-1571ad12.mp4

@PrimeFoldTools

Copy link
Copy Markdown
Author

@krrish-berri-2 thanks! #40673 is the more complete fix and already has a demo, so I'm happy for maintainers to go with that — I'll close this in its favor. Glad the regression tests are useful as coverage there.

@jinwukong

Copy link
Copy Markdown

Thanks for coordinating and sharing your regression cases. They pass on #40673, and I've linked your contribution in the description

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]: /v1/responses streaming with Anthropic doubles thinking text in reasoning encrypted_content

5 participants