Skip to content

fix(anthropic-adapter): open the first content block with the real upstream type so reasoning-first streams start with thinking - #34433

Merged
yucheng-berri merged 2 commits into
BerriAI:litellm_internal_stagingfrom
Napuh:litellm_fix_anthropic_thinking_first_block
Jul 29, 2026
Merged

yucheng-berri merged 2 commits into
BerriAI:litellm_internal_stagingfrom
Napuh:litellm_fix_anthropic_thinking_first_block

Conversation

@Napuh

@Napuh Napuh commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • The Anthropic /v1/messages pass-through adapter emitted a hardcoded empty text block at index 0 before reading any upstream chunk
  • When a reasoning model led with thinking, thinking then opened at index 1, leaving a spurious empty text block at index 0 that strict Anthropic SDK clients with extended thinking reject with "Content block is not a thinking block"

How it solves it:

  • Defer the first content_block_start until the first upstream chunk arrives, and open index 0 with that chunk's real type (text, thinking, or tool_use)
  • Mirror the change across the sync __next__ and async __anext__ paths

Relevant issues

Fixes #29518. Relates to #30043, the umbrella report for Claude Code to vLLM streaming through this adapter.

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review

Proof of Fix

Reproduce against a live proxy fronting a reasoning backend. Launch the proxy, then stream a thinking-enabled request:

curl -sS -N http://localhost:4000/v1/messages \
-H "x-api-key: <key>" \
-H "anthropic-version: 2023-06-01" \
-H "content-type:application/json" \
-d '{"model":"<reasoning-model>","max_tokens":2048,"stream":true,"thinking":{"type":"enabled","budget_tokens":1024},"messages":[{"role":"user","content":"Write a python function that adds two numbers."}]}'

Before the fix the content_block_start order is text at index 0 (empty, followed by an empty text_delta and a content_block_stop), then thinking at index 1, then the answer text at index 2. After the fix the first content_block_start is thinking at index 0 with no leading text block, and the answer text follows at index 1.

Type

🐛 Bug Fix

Changes

In litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py, AnthropicStreamWrapper previously unconditionally queued a content_block_start with a hardcoded {"type": "text", "text": ""} body before the main loop consumed any upstream chunk. That committed the first block to text regardless of what the model actually emitted first.

The fix removes that pre-emit gate. The main loop now opens the first content block lazily on the first real upstream chunk, using that chunk's translated type at index 0, with no preceding content_block_stop and no index increment. The existing block-transition branch is additionally guarded with not is_opening_first_block so the first block is never emitted a second time as a transition. The same change is applied to both the sync __next__ and async __anext__ paths.

This preserves every adjacent behaviour. The _delta_has_content re-emit still returns the first token of each block (#30014), empty deltas are still suppressed (#33315), the compaction block still owns its own index lifecycle ahead of the main loop, and text-first, tool_use-first, and thinking-first responses each still open the correct block type at index 0.

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

Maintainer live verification

A/B against a live proxy at the merge base (712136d) and at this head (4279e14), each side launched from its own worktree with the loaded litellm module path asserted, fronting real gemini/gemini-2.5-flash with no mocks. Observed /v1/messages streaming block orderings:

thinking enabled   base: text@0 (empty) -> thinking@1 -> text@2    head: thinking@0 -> text@1
forced tool call   base: text@0 (empty) -> tool_use@1              head: tool_use@0
plain text         base: text@0                                    head: text@0 (unchanged)

The head ordering matches the real Anthropic API captured the same day: claude-sonnet-4-6 with thinking enabled streams thinking@0 -> text@1 and a forced tool call streams tool_use@0, and Claude on Bedrock produces the same shapes. The anthropic Python SDK (0.120.2) pointed at the head proxy accepts the stream and assembles the thinking and text blocks with stop_reason and usage intact

A second pass with a dedicated Postgres per side shows spend rows written identically for every leg (streaming and non-streaming, plus chat completions), and key create -> use -> info -> delete -> 401 behaves the same on both sides. Merging current litellm_internal_staging into this head is conflict free and the same scenarios behave identically on the merged tree. The changed lines in streaming_iterator.py all sit inside the mapped unit suite's coverage (542 tests passing at head)

One adjacent observation, present on the merge base as well as on this head and therefore unrelated to this PR: a Bedrock guardrail in post_call mode applied to a streaming /v1/messages request on this adapter path returns 500 because the guardrail streaming hook passes SSE bytes into stream_chunk_builder; tracked separately


Note

Medium Risk
Changes core streaming SSE ordering for the Anthropic pass-through adapter, but scope is limited to first-block handling with broad regression tests; wrong edge-case handling could still break Claude Code or tool-call streams.

Overview
Fixes reasoning-first and tool-first /v1/messages streams where the adapter used to always emit an empty text content_block_start at index 0 before reading upstream chunks, pushing real thinking or tool_use blocks to index 1 and breaking strict Anthropic SDK clients.

AnthropicStreamWrapper (sync __next__ and async __anext__) now opens the first block lazily on the first meaningful upstream chunk, using current_content_block_start from translation instead of a hardcoded empty text block. Blank priming deltas (empty content, role-only lead-ins) are skipped via new _is_blank_delta so they do not lock index 0 to text. The block-transition path is gated with not is_opening_first_block so the first block is not closed/re-opened as a spurious transition.

Tests cover thinking-first (thinking_blocks and reasoning_content), contentless leads, finish-only first chunks, and updated parallel tool-call expectations (no leading empty text block).

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

@greptile-apps

greptile-apps Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR safely completes the prior fix by deferring the initial Anthropic content block until meaningful upstream output identifies its actual type.

  • Applies equivalent lazy first-block handling to synchronous and asynchronous streams.
  • Skips contentless lead-in chunks while preserving terminal chunks.
  • Adds regression coverage for thinking-first, reasoning-first, metadata-leading, tool-use-first, and finish-first streams.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failures remain in the fix for contentless lead chunks and first-block type selection.

Important Files Changed

Filename Overview
litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py Lazily opens the first translated content block in both iterator paths and avoids committing contentless lead-in chunks to an empty text block.
tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_streaming_iterator_first_delta.py Adds focused sync and async regression tests covering reasoning-first streams, contentless lead chunks, and an immediately terminal stream.
tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_parallel_tool_calls.py Updates tool-call stream expectations to reflect removal of the obsolete leading empty text block.

Reviews (2): Last reviewed commit: "fix(anthropic): defer blank leading stre..." | Re-trigger Greptile

@codecov

codecov Bot commented Jul 23, 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 Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing Napuh:litellm_fix_anthropic_thinking_first_block (4279e14) with litellm_internal_staging (b9b27c2)

Open in CodSpeed

@Napuh

Napuh commented Jul 25, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai re-review

@Napuh

Napuh commented Jul 27, 2026

Copy link
Copy Markdown
Contributor Author

@yucheng-berri

Copy link
Copy Markdown
Contributor

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.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Want higher recall? High effort reviews run extra passes and find more bugs. A team admin can switch effort levels in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 4279e14. Configure here.

"index": self.current_content_block_index,
"content_block": self.current_content_block_start,
}
)

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.

First thinking token duplicated

Medium Severity

When the first upstream chunk uses thinking_blocks, the lazy first-block open emits a content_block_start whose body already includes that chunk's thinking text, then also emits the matching thinking_delta. Anthropic SDK clients accumulate with +=, so the first thinking segment is duplicated. The reasoning_content path is unaffected because its start body stays empty.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 4279e14. Configure here.

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.

The duplication is real but predates this PR; it comes from the translate layer, not the lazy first-block open. _translate_streaming_openai_chunk_to_anthropic_content_block builds the thinking block start with the chunk's thinking text (transformation.py, thinking_blocks branch), and the merge base already consumed that same non-empty start body on the mid-stream transition path

Executable A/B at the merge base 712136d vs this head 4279e14, feeding the wrapper a thinking_blocks-first stream (T1, T2, then text, then finish) and accumulating start bodies plus thinking_deltas the way SDK accumulators do:

base: start:text@0, start:thinking@1 (body 'T1.'), tdelta@1 'T1.', tdelta@1 ' T2.'  -> accumulated 'T1.T1. T2.'
head: start:thinking@0 (body 'T1.'), tdelta@0 'T1.', tdelta@0 ' T2.'                -> accumulated 'T1.T1. T2.'

Byte-identical duplication on both sides; this PR only moves the block from index 1 to index 0 and drops the leading empty text block. The decisive case is a mid-stream transition (a text chunk, then a thinking_blocks chunk), which never executes this PR's new lines: the base emits start body 'T1.' plus a 'T1.' delta and accumulates 'T1.T1.' the same way. reasoning_content streams are clean on both sides because that branch opens with an empty body, matching your note. Async paths behave identically to sync on both sides

The fix belongs in the translate layer as a follow-up: open the thinking_blocks start with thinking="" the way the reasoning_content branch does, which corrects the pre-existing transition path and the first block in one place. Tracking that separately from this PR

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/messages adapter drops reasoning_content → thinking blocks for OpenAI-compatible chat-completions backends (streaming)

2 participants