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]

perf(streaming): group tool-call fragments once instead of rescanning per index

mateo-berri1dad33749c0c
diff --git a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
index 1f22f241452..029a18d7514 100644
--- a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
+++ b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
@@ -1,6 +1,8 @@
import base64
import time
from collections.abc import Iterator, Mapping, Sequence
+from itertools import groupby
+from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Union, cast
from litellm._logging import verbose_logger
@@ -237,6 +239,20 @@ class ChunkProcessor:
if getattr(custom, "input", None):
yield index, "custom_input", custom.input
+ @staticmethod
+ def _join_fragments_by_index_and_field(
+ fragment_records: Iterator[tuple[int, str, str]],
+ ) -> Mapping[tuple[int, str], str]:
+ def group_key(record: tuple[int, str, str]) -> tuple[int, str]:
+ return record[0], record[1]
+
+ return MappingProxyType(
+ {
+ key: "".join(fragment for _, _, fragment in group)
+ for key, group in groupby(sorted(fragment_records, key=group_key), key=group_key)
+ }
+ )
+
def get_combined_tool_content(
self, tool_call_chunks: Sequence[Mapping[str, Any]]
) -> list[
@@ -344,7 +360,7 @@ class ChunkProcessor:
if isinstance(provider_fields, dict):
tool_call_map[index]["provider_specific_fields"].update(provider_fields)
- fragment_records = tuple(self._iter_tool_call_fragments(tool_call_chunks))
+ joined_fragments = self._join_fragments_by_index_and_field(self._iter_tool_call_fragments(tool_call_chunks))
# Convert the map to a list of tool calls
for index in sorted(tool_call_map.keys()):
@@ -355,23 +371,12 @@ class ChunkProcessor:
id=tool_call_data["id"],
custom=ChatCompletionCustomToolCallPayload(
name=tool_call_data["custom_name"],
- input="".join(
- fragment
- for fragment_index, field, fragment in fragment_records
- if fragment_index == index and field == "custom_input"
- ),
+ input=joined_fragments.get((index, "custom_input"), ""),
),
)
)
elif tool_call_data["id"] and tool_call_data["name"]:
- combined_arguments = (
- "".join(
- fragment
- for fragment_index, field, fragment in fragment_records
- if fragment_index == index and field == "arguments"
- )
- or "{}"
- )
+ combined_arguments = joined_fragments.get((index, "arguments"), "") or "{}"
# Build function - provider_specific_fields should be on tool_call level, not function level
function = Function(
diff --git a/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py b/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py
index cfa566428d0..0114db381cf 100644
--- a/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py
+++ b/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py
@@ -1066,7 +1066,7 @@ def test_get_combined_tool_content_custom_tool_call_without_type_field():
}
-def _tool_call_delta_chunk(tool_call):
+def _tool_call_delta_chunk(tool_call: dict[str, object] | ChatCompletionDeltaToolCall) -> dict[str, object]:
return {"choices": [{"delta": {"tool_calls": [tool_call]}}]}
@@ -1095,6 +1095,28 @@ def test_get_combined_tool_content_joins_many_dict_shaped_argument_fragments_in_
assert combined[2].function.arguments == "{}"
+def test_get_combined_tool_content_joins_fragments_across_many_parallel_tool_calls():
+ processor = ChunkProcessor.__new__(ChunkProcessor)
+ indexes = range(40)
+ header_chunks = [
+ _tool_call_delta_chunk(
+ {"index": index, "id": f"call_{index}", "type": "function", "function": {"name": f"tool_{index}"}}
+ )
+ for index in indexes
+ ]
+ fragment_chunks = [
+ _tool_call_delta_chunk({"index": index, "function": {"arguments": f"{index}.{position};"}})
+ for position in range(5)
+ for index in indexes
+ ]
+
+ combined = processor.get_combined_tool_content(header_chunks + fragment_chunks)
+
+ assert [tool_call.id for tool_call in combined] == [f"call_{index}" for index in indexes]
+ for index, tool_call in zip(indexes, combined):
+ assert tool_call.function.arguments == "".join(f"{index}.{position};" for position in range(5))
+
+
def test_get_combined_tool_content_joins_many_object_shaped_argument_fragments_in_order():
processor = ChunkProcessor.__new__(ChunkProcessor)
first_fragments = [f"x{i}|" for i in range(300)]