Repository navigation
fix: prevent doubled thinking text in streaming reasoning reassembly (#43010) - #43196
PrimeFoldTools wants to merge 1 commit into
Conversation
|
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
9904958 to
5e37f5b
Compare
VANDRANKI
left a comment
There was a problem hiding this comment.
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: appendinto[d1, d2, d3], joined = full text. The signature entry then hitsif thinking_text and thinking_text != "".join(current_thinking_text_parts):— since its text equals what's already joined, the condition isFalse, so nothing is appended a second time. Result: exactly one copy of the text, matchingtest_responses_reasoning_thinking_text_is_not_doubled. - Signature-only (no separate deltas, full text arrives solely on the signature entry):
current_thinking_text_partsis still empty when the signature entry arrives, sothinking_text != ""isTrueand it gets appended. Matchestest_signature_only_stream_text_preserved. - Bedrock-style (deltas carry the text, the closing entry has
thinking=""): the closing entry'sthinking_textis falsy, so both the first append condition and the second (if thinking_text and ...) short-circuit toFalseregardless of the join comparison. No truncation, no doubling. Matchestest_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.
|
Thanks for the reproduction. #40673 covers the same duplication plus signature-only blocks, repeated deltas, and replay payloads. Happy to coordinate |
|
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. |
|
Thanks. Your four regression cases pass on #40673, and the baseline still reproduces duplication. Happy to coordinate with maintainers |
|
@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! |
|
@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. |
|
Thanks for coordinating and sharing your regression cases. They pass on #40673, and I've linked your contribution in the description |
Fixes #43010
Problem
On the streaming
/v1/responsespath with Anthropic, the reassembled reasoningblock (and its
encrypted_content) contained the model's thinking text twice.Non-streaming and
/v1/chat/completionswere unaffected.Root cause
ChunkProcessor._build_thinking_blocks(streaming_chunk_builder_utils.py)accumulates the
thinkingtext of everythinking_blocksentry and flushes thejoined result when it sees a signature.
The Anthropic stream handler emits, on the
signature_delta, athinking_blocksentry whose
thinkingfield is set to the full block text — the join of everyprior delta (
anthropic/chat/handler.py, thesignaturebranch), plus thesignature. So the builder assembled
(sum of deltas == full text)+(signature entry == full text again)= the text doubled. This reassembly onlyruns 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.pysets
thinking=""). The signature entry's text is therefore used only when it isthe 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_parserover raw SSE(
content_block_start→ 3thinking_delta→signature_delta) and the realChunkProcessor; asserts the reassembledthinkingequals 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 neithertruncated nor doubled.
All four pass with this change; the existing
test_streaming_chunk_builder_utils.pysuite (51 tests) remains green. No API keyor network needed.
Scope boundary
Only the streaming reasoning-reassembly de-dup. Does not touch the handler's
emission contract or the non-streaming paths.