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): build per-chunk Delta directly instead of setattr/delattr churn (#33992)

Yassin Kortame906dbe4a1bf
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index 5b98e8be8d2..9eba7c1277c 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -1272,6 +1272,19 @@ class Message(SafeAttributeModel, OpenAIObject):
class Delta(SafeAttributeModel, OpenAIObject):
+ if TYPE_CHECKING:
+ # Stored in __pydantic_extra__ at runtime (extra='allow'), set directly in
+ # __init__ rather than via self.<attr> = .... Declared here only so type
+ # checkers still see them as attributes for consumers that read delta.content
+ # etc.; the runtime branch is skipped so pydantic does not treat them as fields.
+ content: Optional[str]
+ role: Optional[str]
+ function_call: Optional[FunctionCall]
+ tool_calls: Optional[List[ChatCompletionDeltaToolCall]]
+ audio: Optional[ChatCompletionAudioResponse]
+ images: Optional[List[ImageURLListItem]]
+ annotations: Optional[List[ChatCompletionAnnotation]]
+
reasoning_content: Optional[str] = None
thinking_blocks: Optional[List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]]] = None
reasoning_items: Optional[List[ChatCompletionReasoningItem]] = None
@@ -1300,14 +1313,55 @@ class Delta(SafeAttributeModel, OpenAIObject):
super(Delta, self).__init__(**params)
add_provider_specific_fields(self, params.get("provider_specific_fields", {}))
- self.content = content
- self.role = role
- # Set default values and correct types
- self.function_call: Optional[Union[FunctionCall, Any]] = None
- self.tool_calls: Optional[List[Union[ChatCompletionDeltaToolCall, Any]]] = None
- self.audio: Optional[ChatCompletionAudioResponse] = None
- self.images: Optional[List[ImageURLListItem]] = None
- self.annotations: Optional[List[ChatCompletionAnnotation]] = None
+
+ if function_call is not None and isinstance(function_call, dict):
+ function_call = FunctionCall(**function_call)
+
+ if tool_calls is not None and isinstance(tool_calls, list):
+ coerced_tool_calls: List[ChatCompletionDeltaToolCall] = []
+ current_index = 0
+ for tool_call in tool_calls:
+ if isinstance(tool_call, dict):
+ if tool_call.get("index", None) is None:
+ tool_call["index"] = current_index
+ current_index += 1
+ if tool_call.get("type", None) is None:
+ tool_call["type"] = "function"
+ coerced_tool_calls.append(ChatCompletionDeltaToolCall(**tool_call))
+ elif isinstance(tool_call, ChatCompletionDeltaToolCall):
+ coerced_tool_calls.append(tool_call)
+ tool_calls = coerced_tool_calls
+
+ # Build the per-chunk state directly instead of round-tripping every
+ # field through pydantic's __setattr__/__delattr__ (the dominant
+ # streaming cost). These keys are not declared model fields, so they
+ # live in __pydantic_extra__; the slow path set each of content, role,
+ # function_call, tool_calls, audio, images and annotations (marking them
+ # in __pydantic_fields_set__) and then deleted the ones OpenAI omits.
+ extra = self.__pydantic_extra__
+ if extra is None: # pragma: no cover - extra='allow' guarantees a dict
+ extra = self.__pydantic_extra__ = {}
+ fields_set = self.__pydantic_fields_set__
+ fields_set.update(
+ (
+ "content",
+ "role",
+ "function_call",
+ "tool_calls",
+ "audio",
+ "images",
+ "annotations",
+ )
+ )
+ extra["content"] = content
+ extra["role"] = role
+ extra["function_call"] = function_call
+ extra["tool_calls"] = tool_calls
+ extra["audio"] = audio
+ if images is not None and len(images) > 0:
+ extra["images"] = images
+ if annotations is not None:
+ extra["annotations"] = annotations
if reasoning_content is not None:
self.reasoning_content = reasoning_content
@@ -1328,39 +1382,6 @@ class Delta(SafeAttributeModel, OpenAIObject):
if hasattr(self, "reasoning_items"):
del self.reasoning_items
- # Add annotations to the delta, ensure they are only on Delta if they exist (Match OpenAI spec)
- if annotations is not None:
- self.annotations = annotations
- else:
- del self.annotations
-
- if images is not None and len(images) > 0:
- self.images = images
- else:
- del self.images
-
- if function_call is not None and isinstance(function_call, dict):
- self.function_call = FunctionCall(**function_call)
- else:
- self.function_call = function_call
- if tool_calls is not None and isinstance(tool_calls, list):
- self.tool_calls = []
- current_index = 0
- for tool_call in tool_calls:
- if isinstance(tool_call, dict):
- if tool_call.get("index", None) is None:
- tool_call["index"] = current_index
- current_index += 1
- if tool_call.get("type", None) is None:
- tool_call["type"] = "function"
- self.tool_calls.append(ChatCompletionDeltaToolCall(**tool_call))
- elif isinstance(tool_call, ChatCompletionDeltaToolCall):
- self.tool_calls.append(tool_call)
- else:
- self.tool_calls = tool_calls
-
- self.audio = audio
-
def __contains__(self, key):
# Define custom behavior for the 'in' operator
return hasattr(self, key)
diff --git a/tests/test_litellm/types/test_types_utils.py b/tests/test_litellm/types/test_types_utils.py
index 4147ce47ae5..98820d657b5 100644
--- a/tests/test_litellm/types/test_types_utils.py
+++ b/tests/test_litellm/types/test_types_utils.py
@@ -416,3 +416,113 @@ def test_message_accepts_thinking_block_with_null_signature():
)
assert choice.message.thinking_blocks is not None
assert choice.message.thinking_blocks[0]["signature"] is None
+
+
+def test_delta_serialization_contract():
+ """
+ Lock the exact per-chunk serialization shape that the streaming path emits.
+
+ Delta is built once per streaming chunk and serialized via
+ ModelResponseStream.model_dump(), which defaults to exclude_unset=True.
+ The construction therefore has to mark content/role/function_call/
+ tool_calls/audio as "set" (so they survive exclude_unset) while keeping
+ OpenAI-omitted fields (reasoning_content, thinking_blocks, reasoning_items,
+ images, annotations) absent unless explicitly provided. This guards that
+ contract for both the default dump and the exclude_unset dump.
+ """
+ from litellm.types.utils import Delta
+
+ base_keys = {"content", "role", "function_call", "tool_calls", "audio"}
+
+ # Plain content delta: only the OpenAI-compatible keys appear, nothing extra
+ delta = Delta(content="hi", role="assistant")
+ assert set(delta.model_dump(exclude_unset=True).keys()) == base_keys
+ assert set(delta.model_dump().keys()) == base_keys | {"provider_specific_fields"}
+ assert delta.model_dump(exclude_unset=True) == {
+ "content": "hi",
+ "role": "assistant",
+ "function_call": None,
+ "tool_calls": None,
+ "audio": None,
+ }
+
+ # Empty delta still emits the base keys (used for the trailing chunk)
+ assert set(Delta().model_dump(exclude_unset=True).keys()) == base_keys
+
+ # model_fields_set is part of the contract. The legacy setattr-then-delattr
+ # path marked content/role/function_call/tool_calls/audio/images/annotations
+ # as set (pydantic's __delattr__ does not clear __pydantic_fields_set__), so
+ # images/annotations remain in model_fields_set even though they are omitted
+ # from the dump when absent. Lock that exact set so a pydantic change to
+ # fields_set handling fails here rather than silently shifting the contract.
+ expected_fields_set = base_keys | {"images", "annotations"}
+ assert Delta(content="hi", role="assistant").model_fields_set == expected_fields_set
+ assert Delta().model_fields_set == expected_fields_set
+ assert (
+ Delta(
+ content="x",
+ images=[{"type": "image_url", "image_url": {"url": "http://x"}}],
+ ).model_fields_set
+ == expected_fields_set
+ )
+
+ # Optional fields only show up when provided
+ for kwargs, expected_extra in [
+ ({"reasoning_content": "t"}, "reasoning_content"),
+ (
+ {
+ "thinking_blocks": [
+ {"type": "thinking", "thinking": "a", "signature": "s"}
+ ]
+ },
+ "thinking_blocks",
+ ),
+ ({"reasoning_items": []}, "reasoning_items"),
+ (
+ {"images": [{"type": "image_url", "image_url": {"url": "http://x"}}]},
+ "images",
+ ),
+ (
+ {
+ "annotations": [
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "start_index": 0,
+ "end_index": 1,
+ "title": "t",
+ "url": "u",
+ },
+ }
+ ]
+ },
+ "annotations",
+ ),
+ ]:
+ present = Delta(content="x", **kwargs)
+ assert expected_extra in present.model_dump(exclude_unset=True)
+ absent = Delta(content="x")
+ assert expected_extra not in absent.model_dump(exclude_unset=True)
+ assert not hasattr(absent, expected_extra)
+
+ # tool_calls dicts are coerced and back-filled with index/type
+ tc_delta = Delta(
+ tool_calls=[{"id": "1", "function": {"name": "f", "arguments": "{}"}}]
+ )
+ dumped = tc_delta.model_dump(exclude_unset=True)["tool_calls"]
+ assert dumped == [
+ {
+ "id": "1",
+ "function": {"arguments": "{}", "name": "f"},
+ "type": "function",
+ "index": 0,
+ }
+ ]
+
+ # Extra provider params survive (extra='allow') and, because super().__init__
+ # populates them before the base keys are appended, order ahead of "content".
+ extra_delta = Delta(content="x", custom_field="v")
+ extra_dump = extra_delta.model_dump(exclude_unset=True)
+ keys = list(extra_dump.keys())
+ assert extra_dump["custom_field"] == "v"
+ assert keys.index("custom_field") < keys.index("content")