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
perf(streaming): add shared JSONFragmentAccumulator for Vertex and Anthropic (#36610)
Deepanshu Lulla6684bb343b0b
diff --git a/litellm/litellm_core_utils/json_fragment_accumulator.py b/litellm/litellm_core_utils/json_fragment_accumulator.pynew file mode 100644index 00000000000..81d18dd0119--- /dev/null+++ b/litellm/litellm_core_utils/json_fragment_accumulator.py@@ -0,0 +1,97 @@+import json+from typing import Final, cast # noqa: TID251 # raw_decode returns tuple[Any, int]; no cast-free unpack+++class JSONFragmentAccumulator:+ """+ Buffers a JSON value that arrives piecemeal over a stream (SSE data split+ across TCP packets, one shard per network read, etc) without the O(n^2)+ cost of repeated `buffer += fragment` string concatenation, and without+ the O(n^2) cost of re-copying the unconsumed remainder on every peeled+ value when one payload holds many concatenated JSON values.++ Fragments are appended to a list in O(1). The buffer is only rebuilt into+ a single string, and only decoded, when a caller asks for a value via+ `pop_next_value`, and `could_close_json` lets callers skip that rebuild+ entirely for fragments that plainly cannot close a JSON value yet. Once+ rebuilt, consumed values are dropped by advancing a cursor rather than+ slicing a new string, so draining N concatenated values already sitting+ in the buffer costs O(n) total, not O(n^2).+ """++ def __init__(self) -> None:+ self._chunks: list[str] = [] # mutable-ok: O(1) append; string concat would copy the buffer each time+ self._buffer: str = (+ "" # mutable-ok: lazily materialized join of _chunks, rebuilt only when _chunks is non-empty+ )+ self._offset: int = 0 # mutable-ok: cursor past already-consumed values; avoids re-slicing on every pop+ self._could_close: bool = False # mutable-ok: cached heuristic; rescanning past fragments was itself O(n^2)++ def __bool__(self) -> bool:+ return bool(self._chunks) or self._offset < len(self._buffer)++ def append(self, fragment: str) -> None:+ self._chunks.append(fragment) # mutable-ok: see __init__+ stripped: Final = fragment.rstrip()+ if stripped:+ self._could_close = stripped[-1] in ("}", "]") # mutable-ok: see __init__++ def could_close_json(self) -> bool:+ """+ Whether the buffer's logical last non-whitespace byte is "}" or "]",+ i.e. whether a JSON value could plausibly be complete. Tracked+ incrementally in `append` rather than rescanned here, so a run of+ blank keepalive fragments (e.g. from a malformed upstream stream)+ can't make this, or the join+parse it gates, cost O(n^2).+ """+ return self._could_close++ def _materialize(self) -> None:+ if not self._chunks:+ return+ unconsumed: Final = self._buffer[self._offset :]+ self._buffer = unconsumed + "".join(self._chunks) # mutable-ok: merge pending fragments, once per append batch+ self._offset = 0 # mutable-ok: see __init__+ self._chunks = [] # mutable-ok: see __init__++ def pop_next_value(self) -> tuple[bool, object]:+ """+ Attempt to decode one complete JSON value from the front of the+ buffer. On success, advances a cursor past that value (keeping any+ unconsumed tail, e.g. a second concatenated value, in place rather+ than copying it) and returns (True, value). If the buffer is empty+ or holds no complete value yet, it is left untouched and this+ returns (False, None).+ """+ self._materialize()+ length: Final = len(self._buffer)+ start = self._offset+ while start < length and self._buffer[start].isspace():+ start += 1+ if start >= length:+ self._offset = start # mutable-ok: see __init__+ return False, None+ decoder: Final = json.JSONDecoder()+ try:+ raw_value: Final = decoder.raw_decode(self._buffer, start)+ except json.JSONDecodeError:+ return False, None+ decoded, end_index = cast("tuple[object, int]", raw_value) # cast-ok: raw_decode returns tuple[Any, int]+ self._offset = end_index # mutable-ok: see __init__+ if self._offset >= len(self._buffer):+ self._buffer = "" # mutable-ok: see __init__+ self._offset = 0 # mutable-ok: see __init__+ self._could_close = False # mutable-ok: buffer is empty, nothing can close+ return True, decoded++ def snapshot(self) -> str:+ self._materialize()+ return self._buffer[self._offset :]++ def set(self, value: str) -> None:+ """Replace the buffer's contents with a single fragment."""+ self._chunks = [] # mutable-ok: see __init__+ self._buffer = value # mutable-ok: see __init__+ self._offset = 0 # mutable-ok: see __init__+ stripped: Final = value.rstrip()+ self._could_close = bool(stripped) and stripped[-1] in ("}", "]") # mutable-ok: see __init__diff --git a/litellm/llms/anthropic/chat/handler.py b/litellm/llms/anthropic/chat/handler.pyindex d9bb0d7abff..5842cc2679d 100644--- a/litellm/llms/anthropic/chat/handler.py+++ b/litellm/llms/anthropic/chat/handler.py@@ -18,6 +18,7 @@ from litellm.anthropic_beta_headers_manager import ()from litellm.constants import RESPONSE_FORMAT_TOOL_NAMEfrom litellm.litellm_core_utils.core_helpers import map_finish_reason+from litellm.litellm_core_utils.json_fragment_accumulator import JSONFragmentAccumulatorfrom litellm.llms.custom_httpx.http_handler import (AsyncHTTPHandler,HTTPHandler,@@ -654,7 +655,7 @@ class ModelResponseIterator:# For handling partial JSON chunks from fragmentation# See: https://github.com/BerriAI/litellm/issues/17473- self.accumulated_json: str = ""+ self._json_buffer = JSONFragmentAccumulator()self.chunk_type: Literal["valid_json", "accumulated_json"] = "valid_json"# Track current content block type to avoid emitting tool calls for non-tool blocks@@ -678,6 +679,14 @@ class ModelResponseIterator:self._current_server_tool_id: str | None = Noneself._container_id: str | None = None+ @property+ def accumulated_json(self) -> str:+ return self._json_buffer.snapshot()++ @accumulated_json.setter+ def accumulated_json(self, value: str) -> None:+ self._json_buffer.set(value)+def check_empty_tool_call_args(self) -> bool:"""Check if the tool call block so far has been an empty string@@ -1149,31 +1158,39 @@ class ModelResponseIterator:container: Final = message_delta["delta"].get("container")return finish_reason, usage, container- def _handle_accumulated_json_chunk(self, data_str: str) -> ModelResponseStream | None:+ def _handle_accumulated_json_chunk(self, data_str: str, is_final: bool = False) -> ModelResponseStream | None:"""Handle partial JSON chunks by accumulating them until valid JSON is received.This fixes network fragmentation issues where SSE data chunks may be splitacross TCP packets. See: https://github.com/BerriAI/litellm/issues/17473+ Mid-stream, defer parsing until the buffer's last byte can close a value:+ attempting a parse after every fragment of one large object is O(n^2) and+ holds the GIL, freezing the event loop. At end of stream (is_final) no more+ data is coming, so drain whatever complete values remain regardless of the+ trailing byte.+Args:data_str: The JSON string to parse (without "data:" prefix)+ is_final: True when called from the end-of-stream drain, where the+ trailing-byte heuristic no longer appliesReturns:ModelResponseStream if JSON is complete, None if still accumulating"""- # Accumulate JSON data- self.accumulated_json += data_str+ self._json_buffer.append(data_str)- # Try to parse the accumulated JSON- try:- data_json: Final = json.loads(self.accumulated_json)- self.accumulated_json = "" # Reset after successful parsing- return self.chunk_parser(chunk=data_json)- except json.JSONDecodeError:- # If it's not valid JSON yet, continue to the next chunk+ if not is_final and not self._json_buffer.could_close_json():return None+ while True:+ found, decoded = self._json_buffer.pop_next_value()+ if not found:+ return None+ if isinstance(decoded, dict):+ return self.chunk_parser(chunk=decoded)+def _parse_sse_data(self, str_line: str) -> ModelResponseStream | None:"""Parse SSE data line, handling both complete and partial JSON chunks.@@ -1209,13 +1226,10 @@ class ModelResponseIterator:chunk = self.response_iterator.__next__()except StopIteration:# If we have accumulated JSON when stream ends, try to parse it- if self.accumulated_json:- try:- data_json = json.loads(self.accumulated_json)- self.accumulated_json = ""- return self.chunk_parser(chunk=data_json)- except json.JSONDecodeError:- pass+ if self._json_buffer:+ result = self._handle_accumulated_json_chunk(data_str="", is_final=True)+ if result is not None:+ return resultraise StopIterationexcept ValueError as e:raise RuntimeError(f"Error receiving chunk from stream: {e}")@@ -1258,13 +1272,10 @@ class ModelResponseIterator:chunk = await self.async_response_iterator.__anext__()except StopAsyncIteration:# If we have accumulated JSON when stream ends, try to parse it- if self.accumulated_json:- try:- data_json = json.loads(self.accumulated_json)- self.accumulated_json = ""- return self.chunk_parser(chunk=data_json)- except json.JSONDecodeError:- pass+ if self._json_buffer:+ result = self._handle_accumulated_json_chunk(data_str="", is_final=True)+ if result is not None:+ return resultraise StopAsyncIterationexcept ValueError as e:raise RuntimeError(f"Error receiving chunk from stream: {e}")diff --git a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.pyindex d298670aa7a..d12ba24eda4 100644--- a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py+++ b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py@@ -23,6 +23,7 @@ from litellm.constants import (DEFAULT_REASONING_EFFORT_MINIMAL_THINKING_BUDGET_GEMINI_2_5_FLASH_LITE,DEFAULT_REASONING_EFFORT_MINIMAL_THINKING_BUDGET_GEMINI_2_5_PRO,)+from litellm.litellm_core_utils.json_fragment_accumulator import JSONFragmentAccumulatorfrom litellm.litellm_core_utils.prompt_templates.factory import (_encode_tool_call_id_with_signature,)@@ -3087,7 +3088,7 @@ class ModelResponseIterator:self.streaming_response = streaming_responseself.response = responseself.chunk_type: Literal["valid_json", "accumulated_json"] = "valid_json"- self.accumulated_json = ""+ self._json_buffer = JSONFragmentAccumulator()self.sent_first_chunk = Falseself.logging_obj = logging_objself.response_headers = response_headers or {}@@ -3095,6 +3096,14 @@ class ModelResponseIterator:self.cumulative_tool_call_index: int = 0self.has_seen_tool_calls: bool = False+ @property+ def accumulated_json(self) -> str:+ return self._json_buffer.snapshot()++ @accumulated_json.setter+ def accumulated_json(self, value: str) -> None:+ self._json_buffer.set(value)+@staticmethoddef _check_streaming_error(chunk: dict) -> None:"""Detect embedded errors (e.g. 429 RESOURCE_EXHAUSTED) in streaming chunks and raise VertexAIError."""@@ -3298,8 +3307,8 @@ class ModelResponseIterator:return self.chunk_parser(chunk=json_chunk)def handle_accumulated_json_chunk(self, chunk: str, is_final: bool = False) -> Optional["ModelResponseStream"]:- message: Final = litellm.CustomStreamWrapper._strip_sse_data_from_chunk(chunk) or ""- self.accumulated_json = (self.accumulated_json + message.replace("\n\n", "")).strip()+ message: Final = (litellm.CustomStreamWrapper._strip_sse_data_from_chunk(chunk) or "").replace("\n\n", "")+ self._json_buffer.append(message)# Mid-stream, defer parsing until the buffer's last byte can close a value:# attempting a parse after every fragment of one large object is O(n^2) and@@ -3307,27 +3316,23 @@ class ModelResponseIterator:# data is coming, so drain whatever complete values remain regardless of the# trailing byte, otherwise a complete leading value sitting behind a truncated# trailing one would be silently dropped.- if not is_final and (not self.accumulated_json or self.accumulated_json[-1] not in "}]"):+ if not is_final and not self._json_buffer.could_close_json():return None# Peel one complete JSON value from the front of the buffer and keep the# unconsumed tail. Running json.loads over the whole buffer would fail# forever once it held more than one concatenated value ("Extra data") while# never resetting the buffer, so the buffer grew without bound and pinned the- # core. raw_decode reports where the value ended, so concatenated values drain- # one call at a time. A leading non-dict value (never emitted by Gemini in- # practice) is consumed and skipped so it cannot block the dict values behind it.- decoder: Final = json.JSONDecoder()- while self.accumulated_json:- try:- raw_value = decoder.raw_decode(self.accumulated_json)- except json.JSONDecodeError:+ # core. pop_next_value reports where the value ended, so concatenated values+ # drain one call at a time. A leading non-dict value (never emitted by Gemini+ # in practice) is consumed and skipped so it cannot block the dict values+ # behind it.+ while True:+ found, decoded = self._json_buffer.pop_next_value()+ if not found:return None- decoded, end_index = cast("tuple[object, int]", raw_value) # cast-ok: raw_decode -> tuple[Any,int]- self.accumulated_json = self.accumulated_json[end_index:].strip()if isinstance(decoded, dict):return self.chunk_parser(chunk=decoded)- return Nonedef _common_chunk_parsing_logic(self, chunk: str) -> Optional["ModelResponseStream"]:try:@@ -3351,7 +3356,7 @@ class ModelResponseIterator:try:chunk: Final = self.response_iterator.__next__()except StopIteration:- if self.chunk_type == "accumulated_json" and self.accumulated_json:+ if self.chunk_type == "accumulated_json" and self._json_buffer:result: Final = self.handle_accumulated_json_chunk(chunk="", is_final=True)if result is not None:return result@@ -3375,7 +3380,7 @@ class ModelResponseIterator:try:chunk: Final = await self.async_response_iterator.__anext__()except StopAsyncIteration:- if self.chunk_type == "accumulated_json" and self.accumulated_json:+ if self.chunk_type == "accumulated_json" and self._json_buffer:result: Final = self.handle_accumulated_json_chunk(chunk="", is_final=True)if result is not None:return resultdiff --git a/tests/test_litellm/litellm_core_utils/test_json_fragment_accumulator.py b/tests/test_litellm/litellm_core_utils/test_json_fragment_accumulator.pynew file mode 100644index 00000000000..d16230afe3a--- /dev/null+++ b/tests/test_litellm/litellm_core_utils/test_json_fragment_accumulator.py@@ -0,0 +1,236 @@+import json+import time+from unittest.mock import patch++from litellm.litellm_core_utils.json_fragment_accumulator import JSONFragmentAccumulator+++def test_initial_state_is_empty():+ accumulator = JSONFragmentAccumulator()+ assert not accumulator+ assert accumulator.could_close_json() is False+ assert accumulator.snapshot() == ""+++def test_could_close_json_true_only_when_last_fragment_closes_a_value():+ accumulator = JSONFragmentAccumulator()+ accumulator.append('{"a": ')+ assert accumulator.could_close_json() is False++ accumulator.append("1}")+ assert accumulator.could_close_json() is True+++def test_could_close_json_looks_past_trailing_blank_fragments():+ """A whitespace-only or empty fragment (e.g. the flush call at end of+ stream) must not mask a real closing byte in an earlier fragment."""+ accumulator = JSONFragmentAccumulator()+ accumulator.append('{"a": 1}')+ accumulator.append("")+ accumulator.append(" \n")+ assert accumulator.could_close_json() is True+++def test_pop_next_value_on_empty_buffer_returns_false_without_touching_state():+ accumulator = JSONFragmentAccumulator()+ found, value = accumulator.pop_next_value()+ assert found is False+ assert value is None+++def test_pop_next_value_on_incomplete_buffer_leaves_buffer_untouched():+ accumulator = JSONFragmentAccumulator()+ accumulator.append('{"candidates": [{"content":')++ found, value = accumulator.pop_next_value()++ assert found is False+ assert value is None+ assert accumulator.snapshot() == '{"candidates": [{"content":'+++def test_pop_next_value_decodes_single_complete_object_and_clears_buffer():+ accumulator = JSONFragmentAccumulator()+ accumulator.append('{"candidates": [{"content": {"parts": [{"text": "hi"}]}}]}')++ found, value = accumulator.pop_next_value()++ assert found is True+ assert value == {"candidates": [{"content": {"parts": [{"text": "hi"}]}}]}+ assert accumulator.snapshot() == ""+ assert not accumulator+++def test_pop_next_value_reassembles_a_value_split_across_many_fragments():+ obj = {"candidates": [{"content": {"parts": [{"text": "x" * 5000}]}}]}+ blob = json.dumps(obj)+ fragments = [blob[i : i + 37] for i in range(0, len(blob), 37)]+ assert len(fragments) > 10, "need a genuinely multi-fragment payload"++ accumulator = JSONFragmentAccumulator()+ found = False+ value = None+ for fragment in fragments:+ accumulator.append(fragment)+ if accumulator.could_close_json():+ found, value = accumulator.pop_next_value()++ assert found is True+ assert value == obj+++def test_pop_next_value_peels_one_value_and_keeps_remainder():+ """Two concatenated envelopes in the buffer must both surface, one per+ call, instead of json.loads's "Extra data" failure wedging the buffer."""+ obj = '{"a": 1}'+ accumulator = JSONFragmentAccumulator()+ accumulator.append(obj + obj)++ first_found, first_value = accumulator.pop_next_value()+ assert first_found is True+ assert first_value == {"a": 1}+ assert accumulator.snapshot() == obj, "second value must remain buffered"++ second_found, second_value = accumulator.pop_next_value()+ assert second_found is True+ assert second_value == {"a": 1}+ assert not accumulator+++def test_pop_next_value_skips_non_ascii_whitespace_between_concatenated_values():+ """A separator like U+00A0 (non-breaking space) between two concatenated+ values must not strand the second value forever. `raw_decode` only skips+ the narrow `json.decoder.WHITESPACE` set, so the accumulator's own+ whitespace skip must be as tolerant as `str.strip()` was before this+ class replaced it, not merely match `raw_decode`'s narrower set."""+ accumulator = JSONFragmentAccumulator()+ accumulator.append('{"a": 1}' + "\xa0" + '{"a": 2}')++ first_found, first_value = accumulator.pop_next_value()+ assert first_found is True+ assert first_value == {"a": 1}++ second_found, second_value = accumulator.pop_next_value()+ assert second_found is True, "the second value must not be permanently stranded"+ assert second_value == {"a": 2}+ assert not accumulator+++def test_pop_next_value_advances_past_a_non_dict_leading_value():+ accumulator = JSONFragmentAccumulator()+ accumulator.append("[1, 2]" + '{"a": 1}')++ first_found, first_value = accumulator.pop_next_value()+ assert first_found is True+ assert first_value == [1, 2]++ second_found, second_value = accumulator.pop_next_value()+ assert second_found is True+ assert second_value == {"a": 1}+++def test_set_and_snapshot_roundtrip():+ accumulator = JSONFragmentAccumulator()+ accumulator.set('{"a": 1}')+ assert accumulator.snapshot() == '{"a": 1}'+ assert accumulator++ accumulator.set("")+ assert accumulator.snapshot() == ""+ assert not accumulator+++def test_append_never_calls_raw_decode(): # test-quality-ok: TQ002 - laziness contract has no caller-observable proxy other than spying on the stdlib call it must defer+ """Appending must be O(1) bookkeeping only; the O(n) join+decode is+ deferred entirely to pop_next_value."""+ accumulator = JSONFragmentAccumulator()+ with patch.object(json.JSONDecoder, "raw_decode", autospec=True, side_effect=json.JSONDecoder.raw_decode) as spy:+ for fragment in ['{"a":', " 1", "}"]:+ accumulator.append(fragment)+ assert spy.call_count == 0+++def test_pop_next_value_calls_raw_decode_at_most_once_per_value():+ accumulator = JSONFragmentAccumulator()+ accumulator.append('{"a": 1}' * 3)++ with patch.object(json.JSONDecoder, "raw_decode", autospec=True, side_effect=json.JSONDecoder.raw_decode) as spy:+ for _ in range(3):+ found, _ = accumulator.pop_next_value()+ assert found is True+ assert spy.call_count == 3+++def test_accumulation_of_many_fragments_is_not_quadratic():+ """Regression guard: appending 1000 shards must stay O(n) total, not the+ O(n^2) cost of repeated `buffer += fragment` string concatenation."""+ accumulator = JSONFragmentAccumulator()+ shard = "x" * 2048++ start = time.perf_counter()+ for _ in range(1000):+ accumulator.append(shard)+ elapsed_ms = (time.perf_counter() - start) * 1000++ assert elapsed_ms < 50, f"1000-fragment append took {elapsed_ms:.1f} ms (expected < 50 ms); O(n^2) regression?"+++def test_draining_many_concatenated_values_is_not_quadratic():+ """+ Regression guard: peeling N JSON values already sitting in one buffer,+ one pop_next_value() call per value with no new fragments in between,+ must be O(n) total. Re-copying the shrinking remainder on every pop+ (slicing a new string instead of advancing a cursor) makes total drain+ time scale with the square of the buffer size.++ Uses a doubling ratio rather than an absolute ms budget so it isn't+ flaky on a slower or busier CI runner: doubling the input should+ roughly double an O(n) drain's time but roughly quadruple an O(n^2)+ drain's time, and that ratio holds regardless of machine speed.+ """++ def drain_time_ms(n: int) -> float:+ accumulator = JSONFragmentAccumulator()+ accumulator.append('{"a": 1}' * n)+ start = time.perf_counter()+ drained = 0+ while True:+ found, _ = accumulator.pop_next_value()+ if not found:+ break+ drained += 1+ assert drained == n+ return (time.perf_counter() - start) * 1000++ small_ms = drain_time_ms(40_000)+ large_ms = drain_time_ms(80_000)++ ratio = large_ms / max(small_ms, 0.001)+ assert ratio < 3.0, (+ f"doubling drained values scaled time by {ratio:.2f}x ({small_ms:.1f} ms -> {large_ms:.1f} ms); "+ "expected roughly 2x for O(n); O(n^2) regression?"+ )+++def test_could_close_json_after_many_blank_fragments_is_not_quadratic():+ """+ Regression test: a hostile upstream can send malformed JSON that never+ closes, followed by thousands of blank keepalive fragments. Rescanning+ every blank fragment on each could_close_json() call would make N calls+ cost O(n^2) total; it must be O(1) regardless of how many blank+ fragments preceded it.+ """+ accumulator = JSONFragmentAccumulator()+ accumulator.append('{"a": ') # never closes++ start = time.perf_counter()+ for _ in range(20_000):+ accumulator.append("")+ accumulator.could_close_json()+ elapsed_ms = (time.perf_counter() - start) * 1000++ assert accumulator.could_close_json() is False+ assert elapsed_ms < 300, (+ f"20000 blank-fragment could_close_json() calls took {elapsed_ms:.1f} ms "+ "(expected < 300 ms); quadratic rescan regression?"+ )diff --git a/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_handler.py b/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_handler.pyindex f6cd6ac6734..bd750a47f63 100644--- a/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_handler.py+++ b/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_handler.py@@ -1008,6 +1008,143 @@ def test_multiple_partial_chunks_accumulation():assert result3.choices[0].delta.content == "Hello"+def test_accumulated_json_partial_fragment_returns_none_without_parsing():+ """+ Regression test: before the shared JSONFragmentAccumulator, every partial+ fragment triggered a `json.loads` attempt over the whole growing buffer,+ unlike Vertex which already deferred parsing until the buffer could close.+ A fragment that can't close a JSON value must not trigger a decode attempt.+ """+ iterator = ModelResponseIterator(+ streaming_response=MagicMock(), sync_stream=True, json_mode=False+ )+ iterator.chunk_type = "accumulated_json"++ with patch.object(+ json.JSONDecoder, "raw_decode", autospec=True, side_effect=json.JSONDecoder.raw_decode+ ) as spy:+ result = iterator._handle_accumulated_json_chunk(+ '{"type":"content_block_delta","index":0,"delta":'+ )+ assert result is None+ assert spy.call_count == 0, "incomplete buffer should not be parsed"+++def test_accumulated_json_does_not_reparse_every_fragment():+ """+ Regression test for the O(n^2) json.loads-per-fragment anti-pattern: a+ payload split across many fragments must be parsed ~once, not once per+ fragment.+ """+ text = "x" * 200_000+ blob = json.dumps(+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": text}}+ )+ fragments = [blob[i : i + 4096] for i in range(0, len(blob), 4096)]+ assert len(fragments) > 10, "need a multi-fragment payload to exercise the bug"++ iterator = ModelResponseIterator(+ streaming_response=MagicMock(), sync_stream=True, json_mode=False+ )+ iterator.chunk_type = "accumulated_json"++ parsed = None+ with patch.object(+ json.JSONDecoder, "raw_decode", autospec=True, side_effect=json.JSONDecoder.raw_decode+ ) as spy:+ for fragment in fragments:+ out = iterator._handle_accumulated_json_chunk(fragment)+ if out is not None:+ parsed = out+ parse_calls = spy.call_count++ assert parsed is not None, "the reassembled chunk must still parse"+ assert parsed.choices[0].delta.content == text+ assert parse_calls <= 2, (+ f"raw_decode was called {parse_calls} times for {len(fragments)} fragments; "+ "the O(n^2) per-fragment re-parse has regressed"+ )+++def test_accumulated_json_concatenated_envelopes_do_not_wedge():+ """+ Regression test: Anthropic's single `json.loads(self.accumulated_json)`+ call raised "Extra data" on two concatenated envelopes and, since the+ buffer was never reset on that failure, returned None forever while+ growing without bound. The shared accumulator peels one value at a time+ and keeps the remainder, so both values surface across two calls.+ """+ obj = '{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"a"}}'+ iterator = ModelResponseIterator(+ streaming_response=MagicMock(), sync_stream=True, json_mode=False+ )+ iterator.chunk_type = "accumulated_json"++ first = iterator._handle_accumulated_json_chunk(obj + obj)+ assert first is not None+ assert first.choices[0].delta.content == "a"++ second = iterator._handle_accumulated_json_chunk("")+ assert second is not None+ assert second.choices[0].delta.content == "a"++ assert iterator.accumulated_json == ""+++def test_accumulated_json_heuristic_passes_but_value_still_incomplete():+ """+ A buffer whose newest fragment ends in '}' can still be genuinely+ incomplete (an inner object closed, the outer one didn't). The+ heuristic must let the parse attempt through, and pop_next_value+ finding nothing must propagate as None rather than raising.+ """+ iterator = ModelResponseIterator(+ streaming_response=MagicMock(), sync_stream=True, json_mode=False+ )+ iterator.chunk_type = "accumulated_json"++ result = iterator._handle_accumulated_json_chunk('{"type": {"nested": 1}')+ assert result is None+++def test_accumulated_json_setter_and_sync_end_of_stream_drain():+ """+ The accumulated_json setter and __next__'s StopIteration drain branch:+ a buffered partial JSON must still parse and return when the+ underlying stream ends, instead of being silently dropped.+ """+ obj = '{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"a"}}'+ iterator = ModelResponseIterator(+ streaming_response=iter([]), sync_stream=True, json_mode=False+ )+ iterator.chunk_type = "accumulated_json"+ iterator.accumulated_json = obj # exercises the setter++ result = iterator.__next__()+ assert result is not None+ assert result.choices[0].delta.content == "a"+++def test_accumulated_json_async_end_of_stream_drain():+ """Async twin of the sync end-of-stream drain test: __anext__'s+ StopAsyncIteration branch must also parse a buffered value."""+ import asyncio++ obj = '{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"a"}}'+ iterator = ModelResponseIterator(+ streaming_response=MagicMock(), sync_stream=False, json_mode=False+ )+ iterator.chunk_type = "accumulated_json"+ iterator.accumulated_json = obj+ mock_async_iterator = MagicMock()+ mock_async_iterator.__anext__ = AsyncMock(side_effect=StopAsyncIteration)+ iterator.async_response_iterator = mock_async_iterator++ result = asyncio.run(iterator.__anext__())+ assert result is not None+ assert result.choices[0].delta.content == "a"++def test_web_search_tool_result_no_extra_tool_calls():"""Test that web_search_tool_result blocks don't emit tool call chunks.diff --git a/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py b/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.pyindex 3d882deeb52..790a32506f2 100644--- a/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py+++ b/tests/test_litellm/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py@@ -3002,8 +3002,11 @@ def test_accumulated_json_does_not_reparse_every_fragment():The buffer only becomes a complete JSON object on the final fragment, so acorrect implementation parses it ~once, not once per fragment. We assert the- full chunk still parses correctly AND that json.loads is not called on every- fragment (which is what made it quadratic).+ full chunk still parses correctly AND that the buffer is not decoded on+ every fragment (which is what made it quadratic). Post-migration to the+ shared JSONFragmentAccumulator, decoding goes through+ `json.JSONDecoder.raw_decode`, not `json.loads` (see the equivalent+ Anthropic tests) so the spy targets that call, not `json.loads`."""from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import (ModelResponseIterator,@@ -3024,7 +3027,9 @@ def test_accumulated_json_does_not_reparse_every_fragment():assert len(fragments) > 10, "need a multi-fragment payload to exercise the bug"parsed = None- with patch("json.loads", wraps=json.loads) as spy:+ with patch.object(+ json.JSONDecoder, "raw_decode", autospec=True, side_effect=json.JSONDecoder.raw_decode+ ) as spy:for fragment in fragments:out = iterator.handle_accumulated_json_chunk(chunk=fragment)if out is not None:@@ -3035,14 +3040,16 @@ def test_accumulated_json_does_not_reparse_every_fragment():assert parsed.choices[0].delta.content == text, "content must be preserved intact"assert parse_calls <= 2, (- f"json.loads was called {parse_calls} times for {len(fragments)} "+ f"raw_decode was called {parse_calls} times for {len(fragments)} ""fragments; the O(n^2) per-fragment re-parse has regressed")def test_accumulated_json_partial_fragment_returns_none_without_parsing():- """A fragment that cannot complete the JSON must not trigger a json.loads- parse of the whole growing buffer (issue #26181)."""+ """A fragment that cannot complete the JSON must not trigger a decode+ attempt over the whole growing buffer (issue #26181). Decoding goes+ through `json.JSONDecoder.raw_decode` post-JSONFragmentAccumulator+ migration, not `json.loads`."""from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import (ModelResponseIterator,)@@ -3054,7 +3061,9 @@ def test_accumulated_json_partial_fragment_returns_none_without_parsing():)iterator.chunk_type = "accumulated_json"- with patch("json.loads", wraps=json.loads) as spy:+ with patch.object(+ json.JSONDecoder, "raw_decode", autospec=True, side_effect=json.JSONDecoder.raw_decode+ ) as spy:result = iterator.handle_accumulated_json_chunk(chunk='{"candidates": [{"content": {"parts": [{"text": "partial')@@ -5552,3 +5561,21 @@ def test_accumulated_json_skips_non_dict_leading_value():assert len(out) == 1assert out[0].choices[0].delta.content == "a"+++def test_accumulated_json_async_end_of_stream_drains_buffered_value():+ """Async twin of test_accumulated_json_end_of_stream_drains_all_buffered_values:+ __anext__'s StopAsyncIteration branch must also parse a buffered value."""+ import asyncio+ from unittest.mock import AsyncMock, MagicMock++ obj = '{"candidates":[{"content":{"parts":[{"text":"a"}]}}],"usageMetadata":{}}'+ iterator = _accumulating_gemini_iterator()+ iterator.accumulated_json = obj+ mock_async_iterator = MagicMock()+ mock_async_iterator.__anext__ = AsyncMock(side_effect=StopAsyncIteration)+ iterator.async_response_iterator = mock_async_iterator++ result = asyncio.run(iterator.__anext__())+ assert result is not None+ assert result.choices[0].delta.content == "a"