Skip to content

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]

fix(anthropic): split mixed stream chunks by payload kind (#35289)

yucheng-berri1018d18e6b20
diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py
index 853bea636af..d9bcfa19a7f 100644
--- a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py
+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py
@@ -28,7 +28,7 @@ from litellm.types.llms.anthropic import (
UsageDelta,
UsageIteration,
)
-from litellm.types.utils import AdapterCompletionStreamWrapper
+from litellm.types.utils import AdapterCompletionStreamWrapper, Delta
if TYPE_CHECKING:
from litellm.types.utils import ModelResponseStream
@@ -96,6 +96,90 @@ class _CombinedChunkSplitter:
or getattr(delta, "thinking_blocks", None)
)
+ _PAYLOAD_FIELD_GROUPS: "tuple[tuple[str, ...], ...]" = (
+ ("reasoning_content", "thinking_blocks"),
+ ("content",),
+ ("tool_calls",),
+ )
+
+ @staticmethod
+ def _clear_usage(chunk: "ModelResponseStream") -> None:
+ if hasattr(chunk, "usage"):
+ chunk.usage = None
+ hidden_params = getattr(chunk, "_hidden_params", None)
+ if isinstance(hidden_params, dict) and "usage" in hidden_params:
+ chunk._hidden_params = {key: value for key, value in hidden_params.items() if key != "usage"}
+
+ @staticmethod
+ def _split_by_payload_kind(chunk: "ModelResponseStream") -> "tuple[ModelResponseStream, ...]":
+ """Return ``(chunk,)``, or one piece per payload kind it carries.
+
+ Each piece's delta is rebuilt as a fresh ``Delta`` carrying exactly one
+ payload kind (reasoning, text, tool calls), in native Anthropic block
+ order: thinking, then text, then tool_use. Runs downstream of
+ ``_split``, which has already peeled ``finish_reason`` and usage onto
+ their own finish chunk.
+
+ Chunks that must not be split pass through unchanged: multi-choice
+ chunks (the translators read every choice, so slicing one would drop
+ or repeat payload) and tool-argument continuations (splitting one
+ would close the in-flight ``tool_use`` block mid-arguments). A
+ reasoning piece whose ``thinking_blocks`` carry no signature is
+ normalized to ``reasoning_content`` so the synthesized block start
+ stays empty and the thinking text is emitted exactly once.
+ """
+ choices = getattr(chunk, "choices", None)
+ if not choices or len(choices) != 1:
+ return (chunk,)
+ delta = getattr(choices[0], "delta", None)
+ if delta is None:
+ return (chunk,)
+ tool_calls = getattr(delta, "tool_calls", None)
+ if tool_calls and not any(
+ getattr(getattr(tool_call, "function", None), "name", None) for tool_call in tool_calls
+ ):
+ return (chunk,)
+ present_groups = tuple(
+ group
+ for group in _CombinedChunkSplitter._PAYLOAD_FIELD_GROUPS
+ if any(getattr(delta, field, None) for field in group)
+ )
+ if len(present_groups) <= 1:
+ return (chunk,)
+
+ pieces = tuple(copy.deepcopy(chunk) for _ in present_groups)
+ for index, (piece, group) in enumerate(zip(pieces, present_groups)):
+ copied_delta = piece.choices[0].delta
+ fields = {field: value for field in group if (value := getattr(copied_delta, field, None))}
+ fields = _CombinedChunkSplitter._normalize_reasoning_fields(fields)
+ role = getattr(copied_delta, "role", None) if index == 0 else None
+ piece.choices[0].delta = Delta(role=role, **fields)
+ return pieces
+
+ @staticmethod
+ def _normalize_reasoning_fields(fields: "dict[str, Any]") -> "dict[str, Any]":
+ """Collapse signature-less ``thinking_blocks`` into ``reasoning_content``.
+
+ The block opener seeds a ``thinking_blocks`` start body with the full
+ thinking text while the delta re-emits it, so SSE accumulators would
+ collect it twice; the ``reasoning_content`` branch opens an empty body.
+ Signature-carrying blocks are kept intact so ``signature_delta``
+ suppression of the full-text snapshot still applies.
+ """
+ thinking_blocks = fields.get("thinking_blocks")
+ if not thinking_blocks:
+ return fields
+ if any(block.get("signature") for block in thinking_blocks if isinstance(block, dict)):
+ return fields
+ thinking_text = "".join(
+ block.get("thinking") or ""
+ for block in thinking_blocks
+ if isinstance(block, dict) and block.get("type") == "thinking"
+ )
+ if not thinking_text:
+ return fields
+ return {"reasoning_content": thinking_text}
+
@staticmethod
def _split(chunk: Any) -> List[Any]:
"""Return ``[chunk]``, or ``[content_chunk, finish_chunk]`` if combined."""
@@ -105,6 +189,7 @@ class _CombinedChunkSplitter:
# Content chunk: keep the delta payload, clear the finish_reason.
content_chunk = copy.deepcopy(chunk)
content_chunk.choices[0].finish_reason = None
+ _CombinedChunkSplitter._clear_usage(content_chunk)
# Finish chunk: keep finish_reason (and usage), clear the delta payload.
finish_chunk = copy.deepcopy(chunk)
@@ -127,7 +212,11 @@ class _CombinedChunkSplitter:
if self._sync_iter is None:
self._sync_iter = iter(self._stream)
chunk = next(self._sync_iter) # propagates StopIteration when exhausted
- self._buffer.extend(self._split(chunk))
+ self._buffer.extend(
+ split_chunk
+ for combined_chunk in self._split(chunk)
+ for split_chunk in self._split_by_payload_kind(combined_chunk)
+ )
return self._buffer.popleft()
def __aiter__(self) -> "AsyncIterator[Any]":
@@ -139,7 +228,11 @@ class _CombinedChunkSplitter:
if self._async_iter is None:
self._async_iter = self._stream.__aiter__()
chunk = await self._async_iter.__anext__() # propagates StopAsyncIteration
- self._buffer.extend(self._split(chunk))
+ self._buffer.extend(
+ split_chunk
+ for combined_chunk in self._split(chunk)
+ for split_chunk in self._split_by_payload_kind(combined_chunk)
+ )
return self._buffer.popleft()
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.py
index 17a57d974de..2eb8e077320 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
@@ -65,9 +65,7 @@ def _thinking_chunk(thinking: str, signature: str = "") -> MagicMock:
return _make_chunk(Delta(content=None, thinking_blocks=[block]))
-def _tool_chunk(
- call_id: str, name: Optional[str], arguments: Optional[str]
-) -> MagicMock:
+def _tool_chunk(call_id: str, name: Optional[str], arguments: Optional[str]) -> MagicMock:
return _make_chunk(
Delta(
content=None,
@@ -109,8 +107,7 @@ def _text_deltas(events: List[dict]) -> List[str]:
return [
e["delta"]["text"]
for e in events
- if e.get("type") == "content_block_delta"
- and e["delta"].get("type") == "text_delta"
+ if e.get("type") == "content_block_delta" and e["delta"].get("type") == "text_delta"
]
@@ -118,8 +115,7 @@ def _input_json_deltas(events: List[dict]) -> List[str]:
return [
e["delta"]["partial_json"]
for e in events
- if e.get("type") == "content_block_delta"
- and e["delta"].get("type") == "input_json_delta"
+ if e.get("type") == "content_block_delta" and e["delta"].get("type") == "input_json_delta"
]
@@ -127,8 +123,7 @@ def _thinking_deltas(events: List[dict]) -> List[str]:
return [
e["delta"]["thinking"]
for e in events
- if e.get("type") == "content_block_delta"
- and e["delta"].get("type") == "thinking_delta"
+ if e.get("type") == "content_block_delta" and e["delta"].get("type") == "thinking_delta"
]
@@ -136,8 +131,7 @@ def _signature_deltas(events: List[dict]) -> List[str]:
return [
e["delta"]["signature"]
for e in events
- if e.get("type") == "content_block_delta"
- and e["delta"].get("type") == "signature_delta"
+ if e.get("type") == "content_block_delta" and e["delta"].get("type") == "signature_delta"
]
@@ -228,9 +222,7 @@ async def test_first_text_delta_after_tool_use_is_not_dropped_async():
_make_chunk(Delta(content=" Bye.")),
_make_chunk(Delta(content=None), finish_reason="stop"),
]
- wrapper = AnthropicStreamWrapper(
- completion_stream=_AsyncStream(chunks), model="claude-x"
- )
+ wrapper = AnthropicStreamWrapper(completion_stream=_AsyncStream(chunks), model="claude-x")
events = await _drain_async(wrapper)
assert _input_json_deltas(events) == ['{"city": "NY"}']
@@ -665,3 +657,262 @@ def test_finish_first_chunk_is_not_deferred_sync():
"message_delta",
"message_stop",
]
+
+
+def _mixed_reasoning_and_text_chunks() -> List[MagicMock]:
+ return [
+ _make_chunk(Delta(content=None, reasoning_content="First thought.")),
+ _make_chunk(
+ Delta(content="Answer.", reasoning_content=" Last thought."),
+ finish_reason="stop",
+ ),
+ ]
+
+
+def _assert_mixed_reasoning_and_text_chunk_is_split(events: List[dict]) -> None:
+ _assert_deltas_match_their_block_type(events)
+ assert _thinking_deltas(events) == ["First thought.", " Last thought."]
+ assert _text_deltas(events) == ["Answer."]
+ assert [event["type"] for event in events].count("message_delta") == 1
+
+
+def test_mixed_reasoning_and_text_chunk_is_split_sync():
+ wrapper = AnthropicStreamWrapper(
+ completion_stream=iter(_mixed_reasoning_and_text_chunks()),
+ model="claude-x",
+ )
+
+ _assert_mixed_reasoning_and_text_chunk_is_split(_drain_sync(wrapper))
+
+
+async def test_mixed_reasoning_and_text_chunk_is_split_async():
+ wrapper = AnthropicStreamWrapper(
+ completion_stream=_AsyncStream(_mixed_reasoning_and_text_chunks()),
+ model="claude-x",
+ )
+
+ _assert_mixed_reasoning_and_text_chunk_is_split(await _drain_async(wrapper))
+
+
+def _mixed_chunk_with_tool_call() -> List[MagicMock]:
+ return [
+ _make_chunk(
+ Delta(
+ content="Answer.",
+ reasoning_content="Thought.",
+ tool_calls=[
+ ChatCompletionDeltaToolCall(
+ id="call_1",
+ function=Function(name="get_weather", arguments='{"city": "NY"}'),
+ type="function",
+ index=0,
+ )
+ ],
+ ),
+ finish_reason="tool_calls",
+ )
+ ]
+
+
+def _assert_each_payload_kind_emitted_once_in_anthropic_order(events: List[dict]) -> None:
+ starts = [(e["index"], e["content_block"]["type"]) for e in events if e.get("type") == "content_block_start"]
+ assert [block_type for _, block_type in starts] == ["thinking", "text", "tool_use"], starts
+ assert _thinking_deltas(events) == ["Thought."]
+ assert _text_deltas(events) == ["Answer."]
+ assert _input_json_deltas(events) == ['{"city": "NY"}']
+ assert [e["type"] for e in events].count("message_delta") == 1
+ _assert_deltas_match_their_block_type(events)
+
+
+def test_mixed_chunk_with_tool_call_emits_tool_use_once_sync():
+ """A collapsed chunk carrying reasoning, text, AND a tool call must emit the
+ tool_use block exactly once. The previous split cleared only the fields it
+ knew about, so ``tool_calls`` survived on both pieces and the tool_use block
+ (same id) was emitted twice; clients executed the tool twice or rejected the
+ follow-up turn.
+ """
+ wrapper = AnthropicStreamWrapper(
+ completion_stream=iter(_mixed_chunk_with_tool_call()),
+ model="claude-x",
+ )
+ _assert_each_payload_kind_emitted_once_in_anthropic_order(_drain_sync(wrapper))
+
+
+async def test_mixed_chunk_with_tool_call_emits_tool_use_once_async():
+ wrapper = AnthropicStreamWrapper(
+ completion_stream=_AsyncStream(_mixed_chunk_with_tool_call()),
+ model="claude-x",
+ )
+ _assert_each_payload_kind_emitted_once_in_anthropic_order(await _drain_async(wrapper))
+
+
+def test_mixed_thinking_blocks_and_text_chunk_is_split_sync():
+ """A mixed chunk whose reasoning arrives as ``thinking_blocks`` with no
+ ``reasoning_content`` must split too. The previous predicate gated on
+ ``reasoning_content`` only, so this shape skipped the split and emitted a
+ ``thinking_delta`` inside a text block while dropping the answer text.
+ """
+ chunks = [
+ _make_chunk(
+ Delta(
+ content="Answer.",
+ thinking_blocks=[{"type": "thinking", "thinking": "Thought."}],
+ )
+ ),
+ _make_chunk(Delta(content=None), finish_reason="stop"),
+ ]
+ wrapper = AnthropicStreamWrapper(completion_stream=iter(chunks), model="claude-x")
+ events = _drain_sync(wrapper)
+
+ assert _thinking_deltas(events) == ["Thought."]
+ assert _text_deltas(events) == ["Answer."]
+ _assert_deltas_match_their_block_type(events)
+
+
+def test_mixed_chunk_with_both_reasoning_fields_keeps_text_sync():
+ """LiteLLM bridges often set ``reasoning_content`` AND ``thinking_blocks``
+ together. Both fields are one payload kind, so the split must emit the
+ thinking once and still deliver the text; the previous split cleared only
+ ``reasoning_content`` on the text piece, so the surviving ``thinking_blocks``
+ won the translator's priority and the answer text was dropped.
+ """
+ chunks = [
+ _make_chunk(
+ Delta(
+ content="Answer.",
+ reasoning_content="Thought.",
+ thinking_blocks=[{"type": "thinking", "thinking": "Thought."}],
+ )
+ ),
+ _make_chunk(Delta(content=None), finish_reason="stop"),
+ ]
+ wrapper = AnthropicStreamWrapper(completion_stream=iter(chunks), model="claude-x")
+ events = _drain_sync(wrapper)
+
+ assert _thinking_deltas(events) == ["Thought."]
+ assert _text_deltas(events) == ["Answer."]
+ _assert_deltas_match_their_block_type(events)
+
+
+def test_mixed_thinking_start_body_is_empty_and_thinking_not_doubled_sync():
+ """SSE accumulators seed a block from the ``content_block_start`` body and
+ append every delta, so a thinking start body that already carries the text
+ doubles it client-side. A signature-less thinking_blocks piece must open
+ with an empty body and deliver the text exactly once, via the delta.
+ """
+ chunks = [
+ _make_chunk(
+ Delta(
+ content="Answer.",
+ thinking_blocks=[{"type": "thinking", "thinking": "Thought.", "signature": ""}],
+ )
+ ),
+ _make_chunk(Delta(content=None), finish_reason="stop"),
+ ]
+ wrapper = AnthropicStreamWrapper(completion_stream=iter(chunks), model="claude-x")
+ events = _drain_sync(wrapper)
+
+ accumulated = ""
+ for event in events:
+ if event.get("type") == "content_block_start" and event["content_block"].get("type") == "thinking":
+ assert not event["content_block"].get("thinking"), event["content_block"]
+ accumulated += event["content_block"].get("thinking") or ""
+ if event.get("type") == "content_block_delta" and event["delta"].get("type") == "thinking_delta":
+ accumulated += event["delta"]["thinking"]
+ assert accumulated == "Thought."
+ assert _text_deltas(events) == ["Answer."]
+
+
+def test_mixed_chunk_with_tool_argument_continuation_is_not_split_sync():
+ """Streaming providers send a tool call's name only on its first chunk;
+ later chunks carry argument fragments with ``name=None``. Splitting a
+ mixed chunk around such a continuation would close the in-flight tool_use
+ block mid-arguments and fabricate a second block with truncated JSON, so
+ continuation chunks must pass through the splitter untouched.
+ """
+ chunks = [
+ _tool_chunk("call_1", "get_weather", '{"ci'),
+ _make_chunk(
+ Delta(
+ content="Answer.",
+ tool_calls=[
+ ChatCompletionDeltaToolCall(
+ id=None,
+ function=Function(name=None, arguments='ty": "NY"}'),
+ type="function",
+ index=0,
+ )
+ ],
+ )
+ ),
+ _make_chunk(Delta(content=None), finish_reason="tool_calls"),
+ ]
+ wrapper = AnthropicStreamWrapper(completion_stream=iter(chunks), model="claude-x")
+ events = _drain_sync(wrapper)
+
+ starts = [e["content_block"]["type"] for e in events if e.get("type") == "content_block_start"]
+ assert starts.count("tool_use") == 1, starts
+ assert "".join(_input_json_deltas(events)) == '{"city": "NY"}'
+
+
+def test_multi_choice_mixed_chunk_is_not_split_sync():
+ """The translators read every choice, so slicing a multi-choice chunk into
+ per-kind pieces would drop or repeat the secondary choices' payload. A
+ chunk with more than one choice must pass through the splitter untouched.
+ """
+ chunk = MagicMock()
+ chunk.choices = [
+ StreamingChoices(
+ finish_reason=None,
+ index=0,
+ delta=Delta(content="Answer.", reasoning_content="Thought."),
+ logprobs=None,
+ ),
+ StreamingChoices(
+ finish_reason=None,
+ index=1,
+ delta=Delta(
+ content=None,
+ tool_calls=[
+ ChatCompletionDeltaToolCall(
+ id="call_1",
+ function=Function(name="get_weather", arguments='{"city": "NY"}'),
+ type="function",
+ index=0,
+ )
+ ],
+ ),
+ logprobs=None,
+ ),
+ ]
+ chunk.usage = None
+ chunk._hidden_params = {}
+ chunks = [chunk, _make_chunk(Delta(content=None), finish_reason="stop")]
+ wrapper = AnthropicStreamWrapper(completion_stream=iter(chunks), model="claude-x")
+ events = _drain_sync(wrapper)
+
+ assert _input_json_deltas(events) == ['{"city": "NY"}']
+
+
+def test_mixed_finish_chunk_emits_usage_once_sync():
+ """Usage riding on a mixed finish chunk must surface exactly once, on the
+ final ``message_delta``, never duplicated onto the intermediate pieces.
+ """
+ chunks = [
+ _make_chunk(Delta(content=None, reasoning_content="T.")),
+ _make_chunk(
+ Delta(content="Hi", reasoning_content=" T2."),
+ finish_reason="stop",
+ ),
+ ]
+ chunks[1].usage = Usage(prompt_tokens=5, completion_tokens=7, total_tokens=12)
+ wrapper = AnthropicStreamWrapper(completion_stream=iter(chunks), model="claude-x")
+ events = _drain_sync(wrapper)
+
+ message_deltas = [e for e in events if e.get("type") == "message_delta"]
+ assert len(message_deltas) == 1
+ assert message_deltas[0]["usage"]["output_tokens"] == 7
+ assert _text_deltas(events) == ["Hi"]
+ _assert_deltas_match_their_block_type(events)