The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(anthropic-adapter): open the first content block with the real upstream type so reasoning-first streams start with thinking (#34433)
Napuh2f7574d7c176
diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.pyindex f02333c34c8..853bea636af 100644--- a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py@@ -393,24 +393,25 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):if compaction_event is not None:return compaction_event- if self.sent_content_block_start is False:- self.sent_content_block_start = True- self.sent_content_block_finish = False- self.chunk_queue.append(- {- "type": "content_block_start",- "index": self.current_content_block_index,- "content_block": {"type": "text", "text": ""},- }- )- return self.chunk_queue.popleft()-for chunk in self.completion_stream:if chunk == "None" or chunk is None:raise Exceptionshould_start_new_block = self._should_start_new_content_block(chunk)- if should_start_new_block:+ is_opening_first_block = self.sent_content_block_start is False+ if is_opening_first_block and self._is_blank_delta(chunk):+ continue+ if is_opening_first_block:+ self.sent_content_block_start = True+ self.sent_content_block_finish = False+ self.chunk_queue.append(+ {+ "type": "content_block_start",+ "index": self.current_content_block_index,+ "content_block": self.current_content_block_start,+ }+ )+ elif should_start_new_block:self._increment_content_block_index()# applied_edits only needs to flow to the final message_delta@@ -447,7 +448,7 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):# ``not self.queued_usage_chunk``.continue- if should_start_new_block and not self.sent_content_block_finish:+ if should_start_new_block and not is_opening_first_block and not self.sent_content_block_finish:# Queue the sequence: content_block_stop -> content_block_start# -> (optionally) the trigger chunk's delta.#@@ -615,25 +616,25 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):if compaction_event is not None:return compaction_event- if self.sent_content_block_start is False:- self.sent_content_block_start = True- self.sent_content_block_finish = False- self.chunk_queue.append(- {- "type": "content_block_start",- "index": self.current_content_block_index,- "content_block": {"type": "text", "text": ""},- }- )- return self.chunk_queue.popleft()-async for chunk in self.completion_stream:if chunk == "None" or chunk is None:raise Exception- # Check if we need to start a new content blockshould_start_new_block = self._should_start_new_content_block(chunk)- if should_start_new_block:+ is_opening_first_block = self.sent_content_block_start is False+ if is_opening_first_block and self._is_blank_delta(chunk):+ continue+ if is_opening_first_block:+ self.sent_content_block_start = True+ self.sent_content_block_finish = False+ self.chunk_queue.append(+ {+ "type": "content_block_start",+ "index": self.current_content_block_index,+ "content_block": self.current_content_block_start,+ }+ )+ elif should_start_new_block:self._increment_content_block_index()# applied_edits only needs to flow to the final message_delta@@ -664,7 +665,7 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):# Check if this processed chunk has a stop_reason - hold it for next chunkif not self.queued_usage_chunk:- if should_start_new_block and not self.sent_content_block_finish:+ if should_start_new_block and not is_opening_first_block and not self.sent_content_block_finish:# Queue the sequence: content_block_stop -> content_block_start# -> (optionally) the trigger chunk's delta.#@@ -875,6 +876,22 @@ class AnthropicStreamWrapper(AdapterCompletionStreamWrapper):return Falsereturn bool(delta.get(_delta_payload_field(delta_type)))+ @staticmethod+ def _is_blank_delta(chunk: "ModelResponseStream") -> bool:+ choice = chunk.choices[0]+ if choice.finish_reason is not None:+ return False+ delta = choice.delta+ if getattr(delta, "tool_calls", None):+ return False+ if getattr(delta, "content", None):+ return False+ if getattr(delta, "reasoning_content", None):+ return False+ if getattr(delta, "thinking_blocks", None):+ return False+ return True+def _should_start_new_content_block(self, chunk: "ModelResponseStream") -> bool:"""Determine if we should start a new content block based on the processed chunk.diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_streaming_iterator_first_delta.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_streaming_iterator_first_delta.pyindex 19ec1a04b45..17a57d974de 100644--- a/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_streaming_iterator_first_delta.py+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/adapters/test_streaming_iterator_first_delta.py@@ -506,3 +506,162 @@ def test_empty_content_chunk_mid_text_block_is_suppressed_sync():assert _text_deltas(events) == ["Hi", " there"]_assert_deltas_match_their_block_type(events)+++def _thinking_first_chunks() -> List[MagicMock]:+ return [+ _thinking_chunk("Let me think"),+ _thinking_chunk("about it."),+ _make_chunk(Delta(content="42")),+ _make_chunk(Delta(content=None), finish_reason="stop"),+ ]+++def _assert_thinking_first_block_opens_at_index_zero(events: List[dict]) -> None:+ starts = [+ (e["index"], e["content_block"]["type"])+ for e in events+ if e.get("type") == "content_block_start"+ ]+ assert starts == [(0, "thinking"), (1, "text")], starts+ assert "" not in _text_deltas(events)+ assert _thinking_deltas(events) == ["Let me think", "about it."]+ assert _text_deltas(events) == ["42"]+ _assert_deltas_match_their_block_type(events)+++def test_thinking_first_stream_opens_thinking_block_at_index_zero_sync():+ """Bug A regression: when the model's first output is reasoning the adapter+ must open the first content block as ``thinking`` at index 0. The previous+ code pre-emitted a hardcoded empty ``text`` block at index 0 before+ inspecting any upstream chunk, then opened ``thinking`` at index 1; strict+ Anthropic SDK clients with thinking enabled reject that stream with+ "Content block is not a thinking block".+ """+ wrapper = AnthropicStreamWrapper(+ completion_stream=iter(_thinking_first_chunks()),+ model="claude-x",+ )+ _assert_thinking_first_block_opens_at_index_zero(_drain_sync(wrapper))+++async def test_thinking_first_stream_opens_thinking_block_at_index_zero_async():+ """Async twin of the Bug A regression; the proxy serves the async iterator,+ so the first block must be ``thinking`` at index 0 on this path too.+ """+ wrapper = AnthropicStreamWrapper(+ completion_stream=_AsyncStream(_thinking_first_chunks()),+ model="claude-x",+ )+ _assert_thinking_first_block_opens_at_index_zero(await _drain_async(wrapper))+++def _reasoning_content_chunk(reasoning: str) -> MagicMock:+ return _make_chunk(Delta(content=None, reasoning_content=reasoning))+++def _reasoning_first_chunks() -> List[MagicMock]:+ return [+ _reasoning_content_chunk("Let me think"),+ _reasoning_content_chunk("about it."),+ _make_chunk(Delta(content="42")),+ _make_chunk(Delta(content=None), finish_reason="stop"),+ ]+++def test_reasoning_content_first_stream_opens_thinking_block_at_index_zero_sync():+ """The reported backend (hosted_vllm; vLLM and SGLang reasoning parsers)+ surfaces reasoning as OpenAI ``reasoning_content`` with no+ ``thinking_blocks``. Such a stream must also open the first content block as+ ``thinking`` at index 0, exercising the reasoning_content branch of the+ chunk translator rather than the thinking_blocks branch the other twins use.+ """+ wrapper = AnthropicStreamWrapper(+ completion_stream=iter(_reasoning_first_chunks()),+ model="claude-x",+ )+ _assert_thinking_first_block_opens_at_index_zero(_drain_sync(wrapper))+++def _blank_lead_chunks() -> List[MagicMock]:+ return [+ _make_chunk(Delta(content=None)),+ _thinking_chunk("Let me think"),+ _thinking_chunk("about it."),+ _make_chunk(Delta(content="42")),+ _make_chunk(Delta(content=None), finish_reason="stop"),+ ]+++def _role_only_reasoning_content_lead_chunks() -> List[MagicMock]:+ return [+ _make_chunk(Delta(role="assistant", content=None, tool_calls=[])),+ _reasoning_content_chunk("Let me think"),+ _reasoning_content_chunk("about it."),+ _make_chunk(Delta(content="42")),+ _make_chunk(Delta(content=None), finish_reason="stop"),+ ]+++def test_contentless_lead_chunk_does_not_open_text_block_before_thinking_sync():+ """OpenAI-compatible streaming backends open the response with a contentless+ priming chunk (an empty delta, e.g. the {role: assistant} lead-in) before the+ first real token. Such a lead chunk must NOT commit index 0 to an empty text+ block; the following thinking chunk must still open thinking at index 0, or+ strict Anthropic SDK clients reject the stream.+ """+ wrapper = AnthropicStreamWrapper(+ completion_stream=iter(_blank_lead_chunks()),+ model="claude-x",+ )+ _assert_thinking_first_block_opens_at_index_zero(_drain_sync(wrapper))+++def test_role_only_lead_chunk_does_not_open_text_block_before_reasoning_content_sync():+ wrapper = AnthropicStreamWrapper(+ completion_stream=iter(_role_only_reasoning_content_lead_chunks()),+ model="claude-x",+ )+ _assert_thinking_first_block_opens_at_index_zero(_drain_sync(wrapper))+++async def test_contentless_lead_chunk_does_not_open_text_block_before_thinking_async():+ """Async twin; the proxy serves the async iterator, so the contentless lead+ chunk must be skipped on this path too.+ """+ wrapper = AnthropicStreamWrapper(+ completion_stream=_AsyncStream(_blank_lead_chunks()),+ model="claude-x",+ )+ _assert_thinking_first_block_opens_at_index_zero(await _drain_async(wrapper))+++async def test_role_only_lead_chunk_does_not_open_text_block_before_reasoning_content_async():+ wrapper = AnthropicStreamWrapper(+ completion_stream=_AsyncStream(_role_only_reasoning_content_lead_chunks()),+ model="claude-x",+ )+ _assert_thinking_first_block_opens_at_index_zero(await _drain_async(wrapper))+++def test_finish_first_chunk_is_not_deferred_sync():+ """A stream whose first upstream chunk is already the finish event must not+ be skipped by the blank-delta deferral. ``_is_blank_delta`` returns False+ for a finish chunk so the message_delta still flows (with an empty text+ block opened and closed first); without that guard the deferral would drop+ the terminal event entirely.+ """+ chunks = [_make_chunk(Delta(content=None), finish_reason="stop")]+ wrapper = AnthropicStreamWrapper(completion_stream=iter(chunks), model="claude-x")+ events = _drain_sync(wrapper)++ assert [e["type"] for e in events] == [+ "message_start",+ "content_block_start",+ "content_block_stop",+ "message_delta",+ "message_stop",+ ]diff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_parallel_tool_calls.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_parallel_tool_calls.pyindex e44413cf837..6d7cd2f88be 100644--- a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_parallel_tool_calls.py+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_parallel_tool_calls.py@@ -134,13 +134,6 @@ def test_anthropic_stream_wrapper_single_tool_call():# Verify the expected sequence of chunk typesexpected_types = ["message_start", # Initial message start- # TODO: for future contributors: if the initial content_block_start- # respects the upstream's starting chunk, the initial empty text block- # should be removed (and this test should be updated accordingly)- # ---------------------------------------------------------------------- "content_block_start", # Initial empty text block start- "content_block_stop", # End of empty text block- # ---------------------------------------------------------------------"content_block_start", # Start of first tool_use content block"content_block_delta", # {"city":"content_block_delta", # "NY"}@@ -196,13 +189,6 @@ def test_anthropic_stream_wrapper_back_to_back_tool_calls():# Verify the expected sequence of chunk typesexpected_types = ["message_start", # Initial message start- # TODO: for future contributors: if the initial content_block_start- # respects the upstream's starting chunk, the initial empty text block- # should be removed (and this test should be updated accordingly)- # ---------------------------------------------------------------------- "content_block_start", # Initial empty text block start- "content_block_stop", # End of empty text block- # ---------------------------------------------------------------------"content_block_start", # Start of first tool_use content block"content_block_delta", # {"city":"content_block_delta", # "NY"}@@ -267,13 +253,6 @@ def test_anthropic_stream_wrapper_interleaved_tool_calls_and_text():# Verify the expected sequence of chunk typesexpected_types = ["message_start", # Initial message start- # TODO: for future contributors: if the initial content_block_start- # respects the upstream's starting chunk, the initial empty text block- # should be removed (and this test should be updated accordingly)- # ---------------------------------------------------------------------- "content_block_start", # Initial empty text block start- "content_block_stop", # End of empty text block- # ---------------------------------------------------------------------"content_block_start", # Start of first tool_use content block"content_block_delta", # {"city":"content_block_delta", # "NY"}