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: emit content_block_start for every block in the rebuilt stream

mateo-berri0485b3fcd42a
diff --git a/litellm/integrations/websearch_interception/ARCHITECTURE.md b/litellm/integrations/websearch_interception/ARCHITECTURE.md
index 0cce648003e..b1485b9b680 100644
--- a/litellm/integrations/websearch_interception/ARCHITECTURE.md
+++ b/litellm/integrations/websearch_interception/ARCHITECTURE.md
@@ -244,8 +244,9 @@ buys. Where the refused call was the only block left, the turn comes back with n
Non-streaming is not a limitation on the client here, because a client that asked for a stream gets the same
treatment. Interception converts an intercepted `stream=True` request to non-streaming before the loop runs and
rebuilds the SSE stream from the finalized turn afterwards, so the ceiling is always reached on a response the
-client has not seen yet. The guard is written against the flag anyway, so a caller added later that reaches the
-loop with a stream already open keeps raising rather than replacing a turn that is halfway to the client.
+client has not seen yet. `AgenticStreamingIterator` is the one caller that reaches the loop with its events
+already on the wire, and it keeps raising, because a finalized turn would arrive there as a second message
+rather than as a replacement.
Two other surfaces do not get that treatment yet. `/v1/responses` returns its own shape that the finalizer does
not rewrite, so it still hands back the internal call. And `/v1/chat/completions` runs its own copy of these
diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/fake_stream_iterator.py b/litellm/llms/anthropic/experimental_pass_through/messages/fake_stream_iterator.py
index 215d4a5b42b..14f1b7697cf 100644
--- a/litellm/llms/anthropic/experimental_pass_through/messages/fake_stream_iterator.py
+++ b/litellm/llms/anthropic/experimental_pass_through/messages/fake_stream_iterator.py
@@ -113,6 +113,14 @@ class FakeAnthropicMessagesStreamIterator:
}
chunks.append(f"event: content_block_delta\ndata: {json.dumps(content_block_delta)}\n\n".encode())
+ else:
+ passthrough_start: Final = {
+ "type": "content_block_start",
+ "index": index,
+ "content_block": block_dict,
+ }
+ chunks.append(f"event: content_block_start\ndata: {json.dumps(passthrough_start)}\n\n".encode())
+
content_block_stop: Final = {"type": "content_block_stop", "index": index}
chunks.append(f"event: content_block_stop\ndata: {json.dumps(content_block_stop)}\n\n".encode())
return chunks
diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py
index 0aae700dc04..ebc76e6c7ea 100644
--- a/litellm/llms/custom_httpx/llm_http_handler.py
+++ b/litellm/llms/custom_httpx/llm_http_handler.py
@@ -5190,12 +5190,13 @@ class BaseLLMHTTPHandler:
pydantic model the finalizer does not rewrite, so it keeps raising, which
is what every surface did before this path learned to end the turn.
- Every call site passes ``stream=False`` today, because interception
- converts an intercepted stream to non-streaming before the loop runs and
- rebuilds the SSE stream from the finalized turn afterwards. The flag is
- still checked so a streaming call site added later cannot replace a turn
- already on the wire, which would reach the client as a second message
- rather than as a replacement.
+ The messages and responses call sites pass ``stream=False``, because
+ interception converts an intercepted stream to non-streaming before the
+ loop runs and rebuilds the SSE stream from the finalized turn
+ afterwards. ``AgenticStreamingIterator`` passes ``stream=True``, and
+ that path keeps raising: its events are already on the wire, so a
+ finalized turn would reach the client as a second message rather than
+ as a replacement.
"""
return not stream and api_surface == "anthropic_messages"
diff --git a/tests/test_litellm/integrations/websearch_interception/test_websearch_agentic_loop_cap.py b/tests/test_litellm/integrations/websearch_interception/test_websearch_agentic_loop_cap.py
index de3fba51eec..91148f7cf6d 100644
--- a/tests/test_litellm/integrations/websearch_interception/test_websearch_agentic_loop_cap.py
+++ b/tests/test_litellm/integrations/websearch_interception/test_websearch_agentic_loop_cap.py
@@ -559,3 +559,96 @@ class TestMaxAgenticLoopsConfigKnob:
assert "max_agentic_loops" not in updated
_, max_loops, _ = BaseLLMHTTPHandler._get_agentic_loop_settings(kwargs=updated)
assert max_loops == 3
+
+
+def _stream_events(response: dict) -> list[dict]:
+ events: list[dict] = []
+ for chunk in FakeAnthropicMessagesStreamIterator(response=response):
+ for line in chunk.decode().splitlines():
+ if line.startswith("data: "):
+ events.append(json.loads(line[len("data: ") :]))
+ return events
+
+
+class TestRebuiltStreamIsWellFormed:
+ """
+ A capped turn is rebuilt into SSE by FakeAnthropicMessagesStreamIterator.
+
+ Anthropic's SDK accumulator appends on content_block_start and then indexes
+ content[event.index] on content_block_delta, so a block that stops without
+ ever starting shifts every later index and the accumulator raises
+ IndexError. A web search turn carries server_tool_use and
+ web_search_tool_result blocks, which is exactly where that used to happen.
+ """
+
+ @staticmethod
+ def _capped_search_turn() -> dict:
+ return {
+ "id": "msg_01",
+ "type": "message",
+ "role": "assistant",
+ "model": "claude-sonnet-4-5",
+ "stop_reason": "end_turn",
+ "content": [
+ {
+ "type": "server_tool_use",
+ "id": "srvtoolu_01",
+ "name": "web_search",
+ "input": {"query": "on-demand H100 hourly price"},
+ },
+ {
+ "type": "web_search_tool_result",
+ "tool_use_id": "srvtoolu_01",
+ "content": [
+ {
+ "type": "web_search_result",
+ "url": "https://example.com/h100",
+ "title": "H100 pricing",
+ }
+ ],
+ },
+ {"type": "text", "text": "AWS lists the H100 at $12.29 an hour."},
+ ],
+ "usage": {"input_tokens": 100, "output_tokens": 20},
+ }
+
+ def test_every_content_block_stop_has_a_matching_start(self):
+ events = _stream_events(self._capped_search_turn())
+
+ started = [event["index"] for event in events if event["type"] == "content_block_start"]
+ stopped = [event["index"] for event in events if event["type"] == "content_block_stop"]
+
+ assert started == [0, 1, 2]
+ assert stopped == [0, 1, 2]
+
+ def test_no_delta_indexes_past_the_blocks_started_before_it(self):
+ events = _stream_events(self._capped_search_turn())
+
+ blocks_started = 0
+ for event in events:
+ if event["type"] == "content_block_start":
+ blocks_started += 1
+ elif event["type"] == "content_block_delta":
+ assert event["index"] < blocks_started
+
+ def test_search_blocks_reach_the_client(self):
+ events = _stream_events(self._capped_search_turn())
+
+ started_types = [
+ event["content_block"]["type"] for event in events if event["type"] == "content_block_start"
+ ]
+
+ assert started_types == ["server_tool_use", "web_search_tool_result", "text"]
+
+ def test_the_search_result_survives_the_rebuild_intact(self):
+ events = _stream_events(self._capped_search_turn())
+
+ result_block = next(
+ event["content_block"]
+ for event in events
+ if event["type"] == "content_block_start"
+ and event["content_block"]["type"] == "web_search_tool_result"
+ )
+
+ assert result_block["tool_use_id"] == "srvtoolu_01"
+ assert result_block["content"][0]["url"] == "https://example.com/h100"