Repository navigation
fix(responses): emit sequence_number, text.format, and usage details on Responses API stream - #28899
mateo-berri wants to merge 10 commits into
Conversation
…on Responses API stream
The /v1/responses streaming surface had three OpenAI-spec violations that
strict deserializers (Grok Build CLI, OpenAI SDK) reject:
1. sequence_number was dropped from the wire. The completion-transformation
streaming iterator set event.__dict__["sequence_number"] = N after
constructing the Pydantic model, but that mutates the instance dict
without updating __pydantic_extra__, so model_dump() silently omits the
field. 13 mutation sites converted to constructor kwargs; an additional
5 event constructors that never set sequence_number at all (OutputTextDone,
ContentPartDone, OutputTextAnnotationAdded, ReasoningSummaryTextDelta,
ResponseCompleted) now do.
2. response.completed.response.text was hardcoded to {}. The spec requires
text.format to be present. Default to {"format": {"type": "text"}}
when the request didn't supply a text config; honor the request value
otherwise.
3. usage.input_tokens_details and usage.output_tokens_details were dropped
when upstream didn't provide prompt_tokens_details / completion_tokens_details.
The spec requires both fields on every response.completed.usage. Both now
always emit, defaulting to zero-valued details (cached_tokens=0,
reasoning_tokens=0). This unblocks Anthropic chat-completion routes,
which omit completion_tokens_details on tool-only function-call responses.
Verified end-to-end with Grok Build CLI 0.2.2 → LiteLLM → claude-haiku-4-5:
grok -p 'hi' --model litellm-haiku --output-format json returns clean JSON
with exit=0 and zero stderr errors. Confirmed across single-word, arithmetic,
multi-line, and 'grok models' catalog probes.
Tests:
- 4 contract-pinning usage tests updated to assert the new always-emit shape.
- 1 streaming-tool-call test that asserted the buggy __dict__ pattern updated
to read sequence_number from model_dump() (the actual wire payload).
- 1 new regression test pins the Grok contract: every streaming event must
carry sequence_number in model_dump() output, monotonic and unique.
Greptile SummaryThis PR fixes three OpenAI Responses API spec violations in LiteLLM's
Confidence Score: 5/5Safe to merge — all changes are strictly additive on the wire: previously-absent fields are now always populated with spec-compliant defaults, and no existing field is removed or changed in a breaking way. The three fixes are well-scoped to the litellm_completion_transformation bridge path. Each fix is verified by the 162-test suite and an end-to-end Grok Build CLI run. The previous hardcoded sequence_number=1 in create_output_item_done_event is correctly fixed. No auth, DB, or critical-path logic is touched. No files require special attention.
|
| Filename | Overview |
|---|---|
| litellm/responses/litellm_completion_transformation/streaming_iterator.py | Converts 13 post-construction dict mutations and 5 events that never set sequence_number into proper constructor kwargs; adds missing increment calls for OutputTextDone, ContentPartDone, OutputItemDone, ReasoningSummaryTextDelta, and ResponseCompleted. |
| litellm/responses/litellm_completion_transformation/transformation.py | Replaces hardcoded text={} with request-aware default; always emits input_tokens_details and output_tokens_details with zero defaults. |
| litellm/types/llms/openai.py | Adds sequence_number: int = 0 as a declared field to 11 event types so model_dump() serializes it correctly. |
| litellm/responses/streaming_iterator.py | Adds a post-pass that assigns monotonic sequence_number to all synthetic response events. |
| litellm/responses/mcp/mcp_streaming_iterator.py | Adds sequence_number=sequence_start + 4 to OutputItemDoneEvent, consistent with the existing offset pattern in that function. |
| tests/test_litellm/responses/litellm_completion_transformation/test_tool_call_streaming_transformation.py | Updates assertions from dict check to model_dump(); adds regression test for monotonic sequence_number serialization. |
| tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py | Updates test to assert always-present detail objects with zero defaults instead of None. |
| tests/test_litellm/test_responses_api_bridge_non_stream.py | Updates three tests to assert always-present InputTokensDetails/OutputTokensDetails with zero defaults. |
Reviews (8): Last reviewed commit: "fix(responses): start synthetic stream s..." | Re-trigger Greptile
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Co-authored-by: Yassin Kortam <yassin@berri.ai>
|
|
Annotation events were assigned a sequence_number when queued, but emitted later (after text/reasoning/tool deltas from subsequent chunks). This caused the queued annotation events to have lower sequence numbers than events emitted before them, breaking the monotonic ordering guarantee for strict clients. Defer assignment to emit time so sequence_number reflects actual emission order. Co-authored-by: Yassin Kortam <yassin@berri.ai>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
Autofix Details
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: Usage details missing on early-return when usage is None
- Added input_tokens_details=InputTokensDetails(cached_tokens=0) and output_tokens_details=OutputTokensDetails(reasoning_tokens=0) to the early-return ResponseAPIUsage so both paths emit the always-present detail fields required by strict deserializers.
Preview (a8c00601e7)
diff --git a/litellm/responses/litellm_completion_transformation/streaming_iterator.py b/litellm/responses/litellm_completion_transformation/streaming_iterator.py
--- a/litellm/responses/litellm_completion_transformation/streaming_iterator.py
+++ b/litellm/responses/litellm_completion_transformation/streaming_iterator.py
@@ -219,8 +219,8 @@
"status": "in_progress",
}
),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
self._pending_tool_events.append(event)
if fn_args_delta:
@@ -232,16 +232,19 @@
for i in range(0, len(fn_args_delta), chunk_size):
delta_chunk = fn_args_delta[i : i + chunk_size]
self._sequence_number += 1
+ # sequence_number is passed via constructor so it lands in
+ # __pydantic_extra__ (BaseLiteLLMOpenAIResponseObject allows extra
+ # fields). Setting it via __dict__ afterward is silently dropped
+ # by model_dump() and breaks strict OpenAI Responses-API clients.
delta_event: BaseLiteLLMOpenAIResponseObject = (
FunctionCallArgumentsDeltaEvent(
type=ResponsesAPIStreamEvents.FUNCTION_CALL_ARGUMENTS_DELTA,
item_id=call_id,
output_index=output_index,
delta=delta_chunk,
+ sequence_number=self._sequence_number,
)
)
- # Add sequence_number as extra field (BaseLiteLLMOpenAIResponseObject allows extra fields)
- delta_event.__dict__["sequence_number"] = self._sequence_number
self._pending_tool_events.append(delta_event)
def _queue_final_tool_call_done_events(
@@ -306,8 +309,8 @@
"status": "in_progress",
}
),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
self._pending_tool_events.append(event)
final_args = fn_args or self._tool_args_by_call_id.get(call_id, "")
@@ -328,8 +331,8 @@
item_id=call_id,
output_index=output_index,
delta=delta_chunk,
+ sequence_number=self._sequence_number,
)
- delta_event.__dict__["sequence_number"] = self._sequence_number
self._pending_tool_events.append(delta_event)
self._sequence_number += 1
@@ -338,8 +341,8 @@
item_id=call_id,
output_index=output_index,
arguments=final_args,
+ sequence_number=self._sequence_number,
)
- done_event.__dict__["sequence_number"] = self._sequence_number
self._pending_tool_events.append(done_event)
self._sequence_number += 1
@@ -424,30 +427,28 @@
"""
response_created_event_data = self._default_response_created_event_data()
self._sequence_number += 1
- event = ResponseCreatedEvent(
+ return ResponseCreatedEvent(
type=ResponsesAPIStreamEvents.RESPONSE_CREATED,
response=ResponsesAPIResponse(**response_created_event_data),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
- return event
def create_response_in_progress_event(self) -> ResponseInProgressEvent:
response_in_progress_event_data = self._default_response_created_event_data()
response_in_progress_event_data["status"] = "in_progress"
self._sequence_number += 1
- event = ResponseInProgressEvent(
+ return ResponseInProgressEvent(
type=ResponsesAPIStreamEvents.RESPONSE_IN_PROGRESS,
response=ResponsesAPIResponse(**response_in_progress_event_data),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
- return event
def create_output_item_added_event(self) -> OutputItemAddedEvent:
if self._cached_item_id is None:
self._cached_item_id = f"msg_{str(uuid.uuid4())}"
self._sequence_number += 1
- event = OutputItemAddedEvent(
+ return OutputItemAddedEvent(
type=ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED,
output_index=0,
item=BaseLiteLLMOpenAIResponseObject(
@@ -459,16 +460,15 @@
"content": [],
}
),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
- return event
def create_content_part_added_event(self) -> ContentPartAddedEvent:
if self._cached_item_id is None:
self._cached_item_id = f"msg_{str(uuid.uuid4())}"
self._sequence_number += 1
- event = ContentPartAddedEvent(
+ return ContentPartAddedEvent(
type=ResponsesAPIStreamEvents.CONTENT_PART_ADDED,
item_id=self._cached_item_id,
output_index=0,
@@ -476,9 +476,8 @@
part=BaseLiteLLMOpenAIResponseObject(
**{"type": "output_text", "text": "", "annotations": []}
),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
- return event
def _merge_provider_specific_fields(self, src: dict) -> None:
"""Merge provider_specific_fields using last-value-wins for lists.
@@ -599,6 +598,7 @@
if self._cached_item_id is None:
self._cached_item_id = f"msg_{str(uuid.uuid4())}"
+ self._sequence_number += 1
return OutputTextDoneEvent(
type=ResponsesAPIStreamEvents.OUTPUT_TEXT_DONE,
item_id=self._cached_item_id,
@@ -606,6 +606,7 @@
content_index=0,
text=getattr(litellm_complete_object.choices[0].message, "content", "") # type: ignore
or "",
+ sequence_number=self._sequence_number,
)
def create_output_content_part_done_event(
@@ -636,12 +637,14 @@
logprobs=None,
)
+ self._sequence_number += 1
return ContentPartDoneEvent(
type=ResponsesAPIStreamEvents.CONTENT_PART_DONE,
item_id=self._cached_item_id,
output_index=0,
content_index=0,
part=part,
+ sequence_number=self._sequence_number,
)
def create_output_item_done_event(
@@ -656,10 +659,11 @@
response_annotations = LiteLLMCompletionResponsesConfig._transform_chat_completion_annotations_to_response_output_annotations(
annotations=annotations
)
+ self._sequence_number += 1
return OutputItemDoneEvent(
type=ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE,
output_index=0,
- sequence_number=1,
+ sequence_number=self._sequence_number,
item=BaseLiteLLMOpenAIResponseObject(
**{
"id": self._cached_item_id,
@@ -817,8 +821,8 @@
"summary": None,
}
),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
self._pending_response_events.append(event)
return
@@ -842,8 +846,8 @@
"content": [],
}
),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
self._pending_response_events.append(event)
# Emit content_part.added immediately after output_item.added for message
@@ -1075,6 +1079,9 @@
if hasattr(annotation, "model_dump")
else dict(annotation)
)
+ # Sequence number is assigned at emit time (see Priority 4
+ # below) to preserve monotonic ordering relative to
+ # higher-priority events from later chunks.
event = OutputTextAnnotationAddedEvent(
type=ResponsesAPIStreamEvents.OUTPUT_TEXT_ANNOTATION_ADDED,
item_id=item_id,
@@ -1092,11 +1099,13 @@
):
reasoning_content = chunk.choices[0].delta.reasoning_content
+ self._sequence_number += 1
return ReasoningSummaryTextDeltaEvent(
type=ResponsesAPIStreamEvents.REASONING_SUMMARY_TEXT_DELTA,
item_id=f"rs_{hash(str(reasoning_content))}",
output_index=0,
delta=reasoning_content,
+ sequence_number=self._sequence_number,
)
# Priority 2: Handle text deltas
@@ -1109,8 +1118,8 @@
output_index=0,
content_index=0,
delta=delta_content,
+ sequence_number=self._sequence_number,
)
- text_delta_event.__dict__["sequence_number"] = self._sequence_number
return text_delta_event
# Priority 3: Handle tool call deltas (if any) -> queue events and emit them
@@ -1126,12 +1135,16 @@
return self._pending_tool_events.pop(0)
# Priority 4: If we have pending annotation events, emit the next one
- # This happens when the current chunk has no text/reasoning content
+ # This happens when the current chunk has no text/reasoning content.
+ # Assign the sequence number here (at emit time) so it stays monotonic
+ # relative to other events emitted from intervening chunks.
if (
hasattr(self, "_pending_annotation_events")
and self._pending_annotation_events
):
event = self._pending_annotation_events.pop(0)
+ self._sequence_number += 1
+ event.sequence_number = self._sequence_number
return event
# Priority 5: If we have pending tool events (from earlier chunk), emit the next one
@@ -1191,9 +1204,11 @@
litellm_metadata=self.litellm_metadata,
)
+ self._sequence_number += 1
return ResponseCompletedEvent(
type=ResponsesAPIStreamEvents.RESPONSE_COMPLETED,
response=encoded_response,
+ sequence_number=self._sequence_number,
)
else:
return None
diff --git a/litellm/responses/litellm_completion_transformation/transformation.py b/litellm/responses/litellm_completion_transformation/transformation.py
--- a/litellm/responses/litellm_completion_transformation/transformation.py
+++ b/litellm/responses/litellm_completion_transformation/transformation.py
@@ -1692,7 +1692,10 @@
status=LiteLLMCompletionResponsesConfig._map_chat_completion_finish_reason_to_responses_status(
finish_reason
),
- text={},
+ # OpenAI Responses spec requires `text.format` to be present. Honor the
+ # request's `text` config when supplied; otherwise default to plain text.
+ # Strict deserializers (Grok Build CLI, OpenAI SDK) reject `text: {}`.
+ text=responses_api_request.get("text") or {"format": {"type": "text"}},
truncation=getattr(chat_completion_response, "truncation", None),
usage=LiteLLMCompletionResponsesConfig._transform_chat_completion_usage_to_responses_usage(
chat_completion_response=chat_completion_response
@@ -2079,6 +2082,8 @@
input_tokens=0,
output_tokens=0,
total_tokens=0,
+ input_tokens_details=InputTokensDetails(cached_tokens=0),
+ output_tokens_details=OutputTokensDetails(reasoning_tokens=0),
)
response_usage = ResponseAPIUsage(
@@ -2091,21 +2096,18 @@
if hasattr(usage, "cost") and usage.cost is not None:
setattr(response_usage, "cost", usage.cost)
- # Translate prompt_tokens_details to input_tokens_details
- if (
- hasattr(usage, "prompt_tokens_details")
- and usage.prompt_tokens_details is not None
- ):
- prompt_details = usage.prompt_tokens_details
- input_details_dict: Dict[str, int] = {}
-
+ # Translate prompt_tokens_details -> input_tokens_details.
+ # OpenAI's Responses spec requires this field to always be present on
+ # response.completed.usage, so we emit it with defaults if upstream
+ # omitted prompt_tokens_details entirely.
+ prompt_details = getattr(usage, "prompt_tokens_details", None)
+ input_details_dict: Dict[str, int] = {"cached_tokens": 0}
+ if prompt_details is not None:
if (
hasattr(prompt_details, "cached_tokens")
and prompt_details.cached_tokens is not None
):
input_details_dict["cached_tokens"] = prompt_details.cached_tokens
- else:
- input_details_dict["cached_tokens"] = 0
if (
hasattr(prompt_details, "text_tokens")
@@ -2119,18 +2121,14 @@
):
input_details_dict["audio_tokens"] = prompt_details.audio_tokens
- if input_details_dict:
- response_usage.input_tokens_details = InputTokensDetails(
- **input_details_dict
- )
+ response_usage.input_tokens_details = InputTokensDetails(**input_details_dict)
- # Translate completion_tokens_details to output_tokens_details
- if (
- hasattr(usage, "completion_tokens_details")
- and usage.completion_tokens_details is not None
- ):
- completion_details = usage.completion_tokens_details
- output_details_dict: Dict[str, int] = {}
+ # Translate completion_tokens_details -> output_tokens_details. Same
+ # always-present requirement; strict deserializers (Grok Build CLI, the
+ # OpenAI SDK) reject a usage object without it.
+ completion_details = getattr(usage, "completion_tokens_details", None)
+ output_details_dict: Dict[str, int] = {"reasoning_tokens": 0}
+ if completion_details is not None:
if (
hasattr(completion_details, "reasoning_tokens")
and completion_details.reasoning_tokens is not None
@@ -2138,8 +2136,6 @@
output_details_dict["reasoning_tokens"] = (
completion_details.reasoning_tokens
)
- else:
- output_details_dict["reasoning_tokens"] = 0
if (
hasattr(completion_details, "text_tokens")
@@ -2153,10 +2149,9 @@
):
output_details_dict["image_tokens"] = completion_details.image_tokens
- if output_details_dict:
- response_usage.output_tokens_details = OutputTokensDetails(
- **output_details_dict
- )
+ response_usage.output_tokens_details = OutputTokensDetails(
+ **output_details_dict
+ )
return response_usage
diff --git a/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py b/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py
--- a/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py
+++ b/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py
@@ -1601,7 +1601,13 @@
assert response_usage.input_tokens_details.text_tokens == 9
def test_transform_usage_without_details(self):
- """Test transformation when prompt_tokens_details and completion_tokens_details are None"""
+ """Test transformation when prompt_tokens_details and completion_tokens_details are None.
+
+ Per the OpenAI Responses spec, `input_tokens_details` and
+ `output_tokens_details` must always be present on the response.completed
+ usage object; strict deserializers (Grok Build CLI, OpenAI SDK) reject
+ the event when either is missing. We emit them with zero defaults.
+ """
# Setup: Usage without details (basic usage only)
usage = Usage(
prompt_tokens=9,
@@ -1629,12 +1635,14 @@
chat_completion_response=chat_completion_response
)
- # Assert: Basic usage should still be transformed, but details should be None
+ # Assert: basic counts transformed, and details always present with zero defaults
assert response_usage.input_tokens == 9
assert response_usage.output_tokens == 27
assert response_usage.total_tokens == 36
- assert response_usage.input_tokens_details is None
- assert response_usage.output_tokens_details is None
+ assert response_usage.input_tokens_details is not None
+ assert response_usage.input_tokens_details.cached_tokens == 0
+ assert response_usage.output_tokens_details is not None
+ assert response_usage.output_tokens_details.reasoning_tokens == 0
def test_transform_usage_with_image_tokens(self):
"""Test that image_tokens from Vertex AI/Gemini are properly transformed to output_tokens_details"""
diff --git a/tests/test_litellm/responses/litellm_completion_transformation/test_tool_call_streaming_transformation.py b/tests/test_litellm/responses/litellm_completion_transformation/test_tool_call_streaming_transformation.py
--- a/tests/test_litellm/responses/litellm_completion_transformation/test_tool_call_streaming_transformation.py
+++ b/tests/test_litellm/responses/litellm_completion_transformation/test_tool_call_streaming_transformation.py
@@ -187,11 +187,15 @@
# Process the chunk once - it queues all events internally
evt = iterator._transform_chat_completion_chunk_to_response_api_chunk(chunk)
- # First event should be OUTPUT_ITEM_ADDED
+ # First event should be OUTPUT_ITEM_ADDED, carrying a serialized sequence_number.
+ # `sequence_number` is passed through the constructor so it lands in
+ # __pydantic_extra__ (BaseLiteLLMOpenAIResponseObject allows extras); a raw
+ # __dict__ assignment would be silently dropped by model_dump(). We assert on
+ # the dump because that is what hits the wire as SSE.
assert evt is not None
assert evt.type == ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED
assert evt.output_index == 1
- assert hasattr(evt, "__dict__") and "sequence_number" in evt.__dict__
+ assert "sequence_number" in evt.model_dump()
# Collect all remaining delta events from the pending queue by creating empty chunks
delta_events = []
@@ -220,19 +224,21 @@
# Verify multiple delta events were created (at least 6 chunks for 67 chars)
assert len(delta_events) >= 6 # 67 chars split into chunks of max 10 chars each
- # Verify each delta is at most 10 characters
+ # Verify each delta is at most 10 characters and carries a serializable
+ # sequence_number (the value lives in __pydantic_extra__, not __dict__).
for evt in delta_events:
assert len(evt.delta) <= 10
assert evt.item_id == "call_test"
assert evt.output_index == 1
- assert hasattr(evt, "__dict__") and "sequence_number" in evt.__dict__
+ assert "sequence_number" in evt.model_dump()
# Verify all deltas concatenated equal the original arguments
concatenated = "".join(evt.delta for evt in delta_events)
assert concatenated == large_arguments
- # Verify sequence numbers are increasing
- sequence_numbers = [evt.__dict__["sequence_number"] for evt in delta_events]
+ # Verify sequence numbers are increasing and unique (read from the dumped
+ # payload, which is what actually hits the wire).
+ sequence_numbers = [evt.model_dump()["sequence_number"] for evt in delta_events]
assert sequence_numbers == sorted(sequence_numbers)
assert len(set(sequence_numbers)) == len(sequence_numbers) # All unique
@@ -397,3 +403,40 @@
assert arguments_by_call_id["call_b"] == '{"b":'
assert arguments_by_call_id["call_a"] != '{"a":1}'
assert arguments_by_call_id["call_b"] != '{"b":1}'
+
+
+def test_streaming_events_serialize_sequence_number_for_strict_clients():
+ """Pin the Grok Build CLI / OpenAI SDK contract: every emitted streaming
+ event must carry `sequence_number` in its on-wire JSON payload.
+
+ Earlier code set `event.__dict__["sequence_number"] = N` after construction,
+ which silently dropped the field during Pydantic's `model_dump()` and broke
+ strict deserializers. The fix routes the value through the constructor so it
+ lands in `__pydantic_extra__` and survives serialization.
+ """
+ iterator = LiteLLMCompletionStreamingIterator(
+ model="test-model",
+ litellm_custom_stream_wrapper=AsyncMock(),
+ request_input="hi",
+ responses_api_request={},
+ )
+
+ created = iterator.create_response_created_event()
+ in_progress = iterator.create_response_in_progress_event()
+ item_added = iterator.create_output_item_added_event()
+ part_added = iterator.create_content_part_added_event()
+
+ for evt in (created, in_progress, item_added, part_added):
+ dumped = evt.model_dump()
+ assert (
+ "sequence_number" in dumped
+ ), f"{type(evt).__name__} dropped sequence_number"
+ assert isinstance(dumped["sequence_number"], int)
+
+ # And the values must be monotonic — strict clients enforce ordering.
+ seqs = [
+ evt.model_dump()["sequence_number"]
+ for evt in (created, in_progress, item_added, part_added)
+ ]
+ assert seqs == sorted(seqs), seqs
+ assert len(set(seqs)) == len(seqs), seqs
diff --git a/tests/test_litellm/test_responses_api_bridge_non_stream.py b/tests/test_litellm/test_responses_api_bridge_non_stream.py
--- a/tests/test_litellm/test_responses_api_bridge_non_stream.py
+++ b/tests/test_litellm/test_responses_api_bridge_non_stream.py
@@ -131,7 +131,11 @@
"""
Test that transformation works when completion response has NO token details.
- This simulates providers that don't return detailed token breakdowns.
+ This simulates providers that don't return detailed token breakdowns. Per the
+ OpenAI Responses spec, `input_tokens_details` and `output_tokens_details` must
+ always be present on `response.completed.usage`; strict deserializers (Grok
+ Build CLI, OpenAI SDK) reject the event when either is missing. Defaults are
+ zeros.
"""
completion_response = create_mock_completion_response(
model="gpt-4",
@@ -150,9 +154,11 @@
assert responses_usage.output_tokens == 20
assert responses_usage.total_tokens == 30
- # Token details should not be present when not provided
- assert responses_usage.input_tokens_details is None
- assert responses_usage.output_tokens_details is None
+ # Token details are always emitted, defaulting to zeros when upstream omits them.
+ assert isinstance(responses_usage.input_tokens_details, InputTokensDetails)
+ assert responses_usage.input_tokens_details.cached_tokens == 0
+ assert isinstance(responses_usage.output_tokens_details, OutputTokensDetails)
+ assert responses_usage.output_tokens_details.reasoning_tokens == 0
print("✓ Transformation works with no token details")
@@ -186,8 +192,10 @@
assert isinstance(responses_usage.input_tokens_details, InputTokensDetails)
assert responses_usage.input_tokens_details.cached_tokens == 80
- # Output details should not be present (no reasoning_tokens provided)
- assert responses_usage.output_tokens_details is None
+ # Output details are always emitted (defaulting reasoning_tokens to 0) to match
+ # the OpenAI Responses spec — strict deserializers require the field.
+ assert isinstance(responses_usage.output_tokens_details, OutputTokensDetails)
+ assert responses_usage.output_tokens_details.reasoning_tokens == 0
print("✓ Transformation works with cached_tokens only")
@@ -216,8 +224,10 @@
assert responses_usage.output_tokens == 100
assert responses_usage.total_tokens == 150
- # Input details should not be present (no cached_tokens provided)
- assert responses_usage.input_tokens_details is None
+ # Input details are always emitted (defaulting cached_tokens to 0) to match
+ # the OpenAI Responses spec.
+ assert isinstance(responses_usage.input_tokens_details, InputTokensDetails)
+ assert responses_usage.input_tokens_details.cached_tokens == 0
# Output details should be present with reasoning_tokens
assert responses_usage.output_tokens_details is not NoneYou can send follow-ups to the cloud agent here.
…None Co-authored-by: Yassin Kortam <yassin@berri.ai>
Pydantic-extra storage works at runtime but mypy (with pydantic.mypy) treats undeclared constructor kwargs as call-arg errors. Declare sequence_number explicitly on the event classes used by the Responses API streaming iterator so the type checker accepts the kwarg and allows setattr on OutputTextAnnotationAddedEvent.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.
Autofix Details
Bugbot Autofix prepared fixes for both issues found in the latest run.
- ✅ Fixed:
OutputTextDoneEventmissing declaredsequence_numberfield unlike peers- Added
sequence_number: int = 0as a declared Pydantic field onOutputTextDoneEventto match its sibling event classes.
- Added
- ✅ Resolved by another fix:
OutputTextDoneEventmissing declaredsequence_numberfield- Same single-line addition of the declared
sequence_number: int = 0default onOutputTextDoneEventalso fixes this duplicate report.
- Same single-line addition of the declared
Preview (1a6a908a72)
diff --git a/litellm/responses/litellm_completion_transformation/streaming_iterator.py b/litellm/responses/litellm_completion_transformation/streaming_iterator.py
--- a/litellm/responses/litellm_completion_transformation/streaming_iterator.py
+++ b/litellm/responses/litellm_completion_transformation/streaming_iterator.py
@@ -219,8 +219,8 @@
"status": "in_progress",
}
),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
self._pending_tool_events.append(event)
if fn_args_delta:
@@ -232,16 +232,19 @@
for i in range(0, len(fn_args_delta), chunk_size):
delta_chunk = fn_args_delta[i : i + chunk_size]
self._sequence_number += 1
+ # sequence_number is passed via constructor so it lands in
+ # __pydantic_extra__ (BaseLiteLLMOpenAIResponseObject allows extra
+ # fields). Setting it via __dict__ afterward is silently dropped
+ # by model_dump() and breaks strict OpenAI Responses-API clients.
delta_event: BaseLiteLLMOpenAIResponseObject = (
FunctionCallArgumentsDeltaEvent(
type=ResponsesAPIStreamEvents.FUNCTION_CALL_ARGUMENTS_DELTA,
item_id=call_id,
output_index=output_index,
delta=delta_chunk,
+ sequence_number=self._sequence_number,
)
)
- # Add sequence_number as extra field (BaseLiteLLMOpenAIResponseObject allows extra fields)
- delta_event.__dict__["sequence_number"] = self._sequence_number
self._pending_tool_events.append(delta_event)
def _queue_final_tool_call_done_events(
@@ -306,8 +309,8 @@
"status": "in_progress",
}
),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
self._pending_tool_events.append(event)
final_args = fn_args or self._tool_args_by_call_id.get(call_id, "")
@@ -328,8 +331,8 @@
item_id=call_id,
output_index=output_index,
delta=delta_chunk,
+ sequence_number=self._sequence_number,
)
- delta_event.__dict__["sequence_number"] = self._sequence_number
self._pending_tool_events.append(delta_event)
self._sequence_number += 1
@@ -338,8 +341,8 @@
item_id=call_id,
output_index=output_index,
arguments=final_args,
+ sequence_number=self._sequence_number,
)
- done_event.__dict__["sequence_number"] = self._sequence_number
self._pending_tool_events.append(done_event)
self._sequence_number += 1
@@ -424,30 +427,28 @@
"""
response_created_event_data = self._default_response_created_event_data()
self._sequence_number += 1
- event = ResponseCreatedEvent(
+ return ResponseCreatedEvent(
type=ResponsesAPIStreamEvents.RESPONSE_CREATED,
response=ResponsesAPIResponse(**response_created_event_data),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
- return event
def create_response_in_progress_event(self) -> ResponseInProgressEvent:
response_in_progress_event_data = self._default_response_created_event_data()
response_in_progress_event_data["status"] = "in_progress"
self._sequence_number += 1
- event = ResponseInProgressEvent(
+ return ResponseInProgressEvent(
type=ResponsesAPIStreamEvents.RESPONSE_IN_PROGRESS,
response=ResponsesAPIResponse(**response_in_progress_event_data),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
- return event
def create_output_item_added_event(self) -> OutputItemAddedEvent:
if self._cached_item_id is None:
self._cached_item_id = f"msg_{str(uuid.uuid4())}"
self._sequence_number += 1
- event = OutputItemAddedEvent(
+ return OutputItemAddedEvent(
type=ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED,
output_index=0,
item=BaseLiteLLMOpenAIResponseObject(
@@ -459,16 +460,15 @@
"content": [],
}
),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
- return event
def create_content_part_added_event(self) -> ContentPartAddedEvent:
if self._cached_item_id is None:
self._cached_item_id = f"msg_{str(uuid.uuid4())}"
self._sequence_number += 1
- event = ContentPartAddedEvent(
+ return ContentPartAddedEvent(
type=ResponsesAPIStreamEvents.CONTENT_PART_ADDED,
item_id=self._cached_item_id,
output_index=0,
@@ -476,9 +476,8 @@
part=BaseLiteLLMOpenAIResponseObject(
**{"type": "output_text", "text": "", "annotations": []}
),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
- return event
def _merge_provider_specific_fields(self, src: dict) -> None:
"""Merge provider_specific_fields using last-value-wins for lists.
@@ -599,6 +598,7 @@
if self._cached_item_id is None:
self._cached_item_id = f"msg_{str(uuid.uuid4())}"
+ self._sequence_number += 1
return OutputTextDoneEvent(
type=ResponsesAPIStreamEvents.OUTPUT_TEXT_DONE,
item_id=self._cached_item_id,
@@ -606,6 +606,7 @@
content_index=0,
text=getattr(litellm_complete_object.choices[0].message, "content", "") # type: ignore
or "",
+ sequence_number=self._sequence_number,
)
def create_output_content_part_done_event(
@@ -636,12 +637,14 @@
logprobs=None,
)
+ self._sequence_number += 1
return ContentPartDoneEvent(
type=ResponsesAPIStreamEvents.CONTENT_PART_DONE,
item_id=self._cached_item_id,
output_index=0,
content_index=0,
part=part,
+ sequence_number=self._sequence_number,
)
def create_output_item_done_event(
@@ -656,10 +659,11 @@
response_annotations = LiteLLMCompletionResponsesConfig._transform_chat_completion_annotations_to_response_output_annotations(
annotations=annotations
)
+ self._sequence_number += 1
return OutputItemDoneEvent(
type=ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE,
output_index=0,
- sequence_number=1,
+ sequence_number=self._sequence_number,
item=BaseLiteLLMOpenAIResponseObject(
**{
"id": self._cached_item_id,
@@ -817,8 +821,8 @@
"summary": None,
}
),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
self._pending_response_events.append(event)
return
@@ -842,8 +846,8 @@
"content": [],
}
),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
self._pending_response_events.append(event)
# Emit content_part.added immediately after output_item.added for message
@@ -1075,6 +1079,9 @@
if hasattr(annotation, "model_dump")
else dict(annotation)
)
+ # Sequence number is assigned at emit time (see Priority 4
+ # below) to preserve monotonic ordering relative to
+ # higher-priority events from later chunks.
event = OutputTextAnnotationAddedEvent(
type=ResponsesAPIStreamEvents.OUTPUT_TEXT_ANNOTATION_ADDED,
item_id=item_id,
@@ -1092,11 +1099,13 @@
):
reasoning_content = chunk.choices[0].delta.reasoning_content
+ self._sequence_number += 1
return ReasoningSummaryTextDeltaEvent(
type=ResponsesAPIStreamEvents.REASONING_SUMMARY_TEXT_DELTA,
item_id=f"rs_{hash(str(reasoning_content))}",
output_index=0,
delta=reasoning_content,
+ sequence_number=self._sequence_number,
)
# Priority 2: Handle text deltas
@@ -1109,8 +1118,8 @@
output_index=0,
content_index=0,
delta=delta_content,
+ sequence_number=self._sequence_number,
)
- text_delta_event.__dict__["sequence_number"] = self._sequence_number
return text_delta_event
# Priority 3: Handle tool call deltas (if any) -> queue events and emit them
@@ -1126,12 +1135,16 @@
return self._pending_tool_events.pop(0)
# Priority 4: If we have pending annotation events, emit the next one
- # This happens when the current chunk has no text/reasoning content
+ # This happens when the current chunk has no text/reasoning content.
+ # Assign the sequence number here (at emit time) so it stays monotonic
+ # relative to other events emitted from intervening chunks.
if (
hasattr(self, "_pending_annotation_events")
and self._pending_annotation_events
):
event = self._pending_annotation_events.pop(0)
+ self._sequence_number += 1
+ event.sequence_number = self._sequence_number
return event
# Priority 5: If we have pending tool events (from earlier chunk), emit the next one
@@ -1191,9 +1204,11 @@
litellm_metadata=self.litellm_metadata,
)
+ self._sequence_number += 1
return ResponseCompletedEvent(
type=ResponsesAPIStreamEvents.RESPONSE_COMPLETED,
response=encoded_response,
+ sequence_number=self._sequence_number,
)
else:
return None
diff --git a/litellm/responses/litellm_completion_transformation/transformation.py b/litellm/responses/litellm_completion_transformation/transformation.py
--- a/litellm/responses/litellm_completion_transformation/transformation.py
+++ b/litellm/responses/litellm_completion_transformation/transformation.py
@@ -1692,7 +1692,10 @@
status=LiteLLMCompletionResponsesConfig._map_chat_completion_finish_reason_to_responses_status(
finish_reason
),
- text={},
+ # OpenAI Responses spec requires `text.format` to be present. Honor the
+ # request's `text` config when supplied; otherwise default to plain text.
+ # Strict deserializers (Grok Build CLI, OpenAI SDK) reject `text: {}`.
+ text=responses_api_request.get("text") or {"format": {"type": "text"}},
truncation=getattr(chat_completion_response, "truncation", None),
usage=LiteLLMCompletionResponsesConfig._transform_chat_completion_usage_to_responses_usage(
chat_completion_response=chat_completion_response
@@ -2079,6 +2082,8 @@
input_tokens=0,
output_tokens=0,
total_tokens=0,
+ input_tokens_details=InputTokensDetails(cached_tokens=0),
+ output_tokens_details=OutputTokensDetails(reasoning_tokens=0),
)
response_usage = ResponseAPIUsage(
@@ -2091,21 +2096,18 @@
if hasattr(usage, "cost") and usage.cost is not None:
setattr(response_usage, "cost", usage.cost)
- # Translate prompt_tokens_details to input_tokens_details
- if (
- hasattr(usage, "prompt_tokens_details")
- and usage.prompt_tokens_details is not None
- ):
- prompt_details = usage.prompt_tokens_details
- input_details_dict: Dict[str, int] = {}
-
+ # Translate prompt_tokens_details -> input_tokens_details.
+ # OpenAI's Responses spec requires this field to always be present on
+ # response.completed.usage, so we emit it with defaults if upstream
+ # omitted prompt_tokens_details entirely.
+ prompt_details = getattr(usage, "prompt_tokens_details", None)
+ input_details_dict: Dict[str, int] = {"cached_tokens": 0}
+ if prompt_details is not None:
if (
hasattr(prompt_details, "cached_tokens")
and prompt_details.cached_tokens is not None
):
input_details_dict["cached_tokens"] = prompt_details.cached_tokens
- else:
- input_details_dict["cached_tokens"] = 0
if (
hasattr(prompt_details, "text_tokens")
@@ -2119,18 +2121,14 @@
):
input_details_dict["audio_tokens"] = prompt_details.audio_tokens
- if input_details_dict:
- response_usage.input_tokens_details = InputTokensDetails(
- **input_details_dict
- )
+ response_usage.input_tokens_details = InputTokensDetails(**input_details_dict)
- # Translate completion_tokens_details to output_tokens_details
- if (
- hasattr(usage, "completion_tokens_details")
- and usage.completion_tokens_details is not None
- ):
- completion_details = usage.completion_tokens_details
- output_details_dict: Dict[str, int] = {}
+ # Translate completion_tokens_details -> output_tokens_details. Same
+ # always-present requirement; strict deserializers (Grok Build CLI, the
+ # OpenAI SDK) reject a usage object without it.
+ completion_details = getattr(usage, "completion_tokens_details", None)
+ output_details_dict: Dict[str, int] = {"reasoning_tokens": 0}
+ if completion_details is not None:
if (
hasattr(completion_details, "reasoning_tokens")
and completion_details.reasoning_tokens is not None
@@ -2138,8 +2136,6 @@
output_details_dict["reasoning_tokens"] = (
completion_details.reasoning_tokens
)
- else:
- output_details_dict["reasoning_tokens"] = 0
if (
hasattr(completion_details, "text_tokens")
@@ -2153,10 +2149,9 @@
):
output_details_dict["image_tokens"] = completion_details.image_tokens
- if output_details_dict:
- response_usage.output_tokens_details = OutputTokensDetails(
- **output_details_dict
- )
+ response_usage.output_tokens_details = OutputTokensDetails(
+ **output_details_dict
+ )
return response_usage
diff --git a/litellm/types/llms/openai.py b/litellm/types/llms/openai.py
--- a/litellm/types/llms/openai.py
+++ b/litellm/types/llms/openai.py
@@ -1448,16 +1448,19 @@
class ResponseCreatedEvent(BaseLiteLLMOpenAIResponseObject):
type: Literal[ResponsesAPIStreamEvents.RESPONSE_CREATED]
response: ResponsesAPIResponse
+ sequence_number: int = 0
class ResponseInProgressEvent(BaseLiteLLMOpenAIResponseObject):
type: Literal[ResponsesAPIStreamEvents.RESPONSE_IN_PROGRESS]
response: ResponsesAPIResponse
+ sequence_number: int = 0
class ResponseCompletedEvent(BaseLiteLLMOpenAIResponseObject):
type: Literal[ResponsesAPIStreamEvents.RESPONSE_COMPLETED]
response: ResponsesAPIResponse
+ sequence_number: int = 0
_hidden_params: dict = PrivateAttr(default_factory=dict)
@@ -1484,6 +1487,7 @@
output_index: int
summary_index: int = 0
delta: str
+ sequence_number: int = 0
class ReasoningSummaryTextDoneEvent(BaseLiteLLMOpenAIResponseObject):
@@ -1508,6 +1512,7 @@
type: Literal[ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED]
output_index: int
item: Optional[BaseLiteLLMOpenAIResponseObject]
+ sequence_number: int = 0
class OutputItemDoneEvent(BaseLiteLLMOpenAIResponseObject):
@@ -1536,6 +1541,7 @@
output_index: int
content_index: int
part: BaseLiteLLMOpenAIResponseObject
+ sequence_number: int = 0
class ContentPartDonePartOutputText(BaseLiteLLMOpenAIResponseObject):
@@ -1568,6 +1574,7 @@
output_index: int
content_index: int
part: PART_UNION_TYPES
+ sequence_number: int = 0
class OutputTextDeltaEvent(BaseLiteLLMOpenAIResponseObject):
@@ -1576,6 +1583,7 @@
output_index: int
content_index: int
delta: str
+ sequence_number: int = 0
class OutputTextAnnotationAddedEvent(BaseLiteLLMOpenAIResponseObject):
@@ -1585,6 +1593,7 @@
content_index: int
annotation_index: int
annotation: dict
+ sequence_number: int = 0
class OutputTextDoneEvent(BaseLiteLLMOpenAIResponseObject):
@@ -1593,6 +1602,7 @@
output_index: int
content_index: int
text: str
+ sequence_number: int = 0
class RefusalDeltaEvent(BaseLiteLLMOpenAIResponseObject):
@@ -1616,6 +1626,7 @@
item_id: str
output_index: int
delta: str
+ sequence_number: int = 0
class FunctionCallArgumentsDoneEvent(BaseLiteLLMOpenAIResponseObject):
@@ -1623,6 +1634,7 @@
item_id: str
output_index: int
arguments: str
+ sequence_number: int = 0
class FileSearchCallInProgressEvent(BaseLiteLLMOpenAIResponseObject):
diff --git a/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py b/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py
--- a/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py
+++ b/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py
@@ -1601,7 +1601,13 @@
assert response_usage.input_tokens_details.text_tokens == 9
def test_transform_usage_without_details(self):
- """Test transformation when prompt_tokens_details and completion_tokens_details are None"""
+ """Test transformation when prompt_tokens_details and completion_tokens_details are None.
+
+ Per the OpenAI Responses spec, `input_tokens_details` and
+ `output_tokens_details` must always be present on the response.completed
+ usage object; strict deserializers (Grok Build CLI, OpenAI SDK) reject
+ the event when either is missing. We emit them with zero defaults.
+ """
# Setup: Usage without details (basic usage only)
usage = Usage(
prompt_tokens=9,
@@ -1629,12 +1635,14 @@
chat_completion_response=chat_completion_response
)
- # Assert: Basic usage should still be transformed, but details should be None
+ # Assert: basic counts transformed, and details always present with zero defaults
assert response_usage.input_tokens == 9
assert response_usage.output_tokens == 27
assert response_usage.total_tokens == 36
- assert response_usage.input_tokens_details is None
- assert response_usage.output_tokens_details is None
+ assert response_usage.input_tokens_details is not None
+ assert response_usage.input_tokens_details.cached_tokens == 0
+ assert response_usage.output_tokens_details is not None
+ assert response_usage.output_tokens_details.reasoning_tokens == 0
def test_transform_usage_with_image_tokens(self):
"""Test that image_tokens from Vertex AI/Gemini are properly transformed to output_tokens_details"""
diff --git a/tests/test_litellm/responses/litellm_completion_transformation/test_tool_call_streaming_transformation.py b/tests/test_litellm/responses/litellm_completion_transformation/test_tool_call_streaming_transformation.py
--- a/tests/test_litellm/responses/litellm_completion_transformation/test_tool_call_streaming_transformation.py
+++ b/tests/test_litellm/responses/litellm_completion_transformation/test_tool_call_streaming_transformation.py
@@ -187,11 +187,15 @@
# Process the chunk once - it queues all events internally
evt = iterator._transform_chat_completion_chunk_to_response_api_chunk(chunk)
- # First event should be OUTPUT_ITEM_ADDED
+ # First event should be OUTPUT_ITEM_ADDED, carrying a serialized sequence_number.
+ # `sequence_number` is passed through the constructor so it lands in
+ # __pydantic_extra__ (BaseLiteLLMOpenAIResponseObject allows extras); a raw
+ # __dict__ assignment would be silently dropped by model_dump(). We assert on
+ # the dump because that is what hits the wire as SSE.
assert evt is not None
assert evt.type == ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED
assert evt.output_index == 1
- assert hasattr(evt, "__dict__") and "sequence_number" in evt.__dict__
+ assert "sequence_number" in evt.model_dump()
# Collect all remaining delta events from the pending queue by creating empty chunks
delta_events = []
@@ -220,19 +224,21 @@
# Verify multiple delta events were created (at least 6 chunks for 67 chars)
assert len(delta_events) >= 6 # 67 chars split into chunks of max 10 chars each
- # Verify each delta is at most 10 characters
+ # Verify each delta is at most 10 characters and carries a serializable
+ # sequence_number (the value lives in __pydantic_extra__, not __dict__).
for evt in delta_events:
assert len(evt.delta) <= 10
assert evt.item_id == "call_test"
assert evt.output_index == 1
- assert hasattr(evt, "__dict__") and "sequence_number" in evt.__dict__
+ assert "sequence_number" in evt.model_dump()
# Verify all deltas concatenated equal the original arguments
concatenated = "".join(evt.delta for evt in delta_events)
assert concatenated == large_arguments
- # Verify sequence numbers are increasing
- sequence_numbers = [evt.__dict__["sequence_number"] for evt in delta_events]
+ # Verify sequence numbers are increasing and unique (read from the dumped
+ # payload, which is what actually hits the wire).
+ sequence_numbers = [evt.model_dump()["sequence_number"] for evt in delta_events]
assert sequence_numbers == sorted(sequence_numbers)
assert len(set(sequence_numbers)) == len(sequence_numbers) # All unique
@@ -397,3 +403,40 @@
assert arguments_by_call_id["call_b"] == '{"b":'
assert arguments_by_call_id["call_a"] != '{"a":1}'
assert arguments_by_call_id["call_b"] != '{"b":1}'
+
+
+def test_streaming_events_serialize_sequence_number_for_strict_clients():
+ """Pin the Grok Build CLI / OpenAI SDK contract: every emitted streaming
+ event must carry `sequence_number` in its on-wire JSON payload.
+
+ Earlier code set `event.__dict__["sequence_number"] = N` after construction,
+ which silently dropped the field during Pydantic's `model_dump()` and broke
+ strict deserializers. The fix routes the value through the constructor so it
+ lands in `__pydantic_extra__` and survives serialization.
+ """
+ iterator = LiteLLMCompletionStreamingIterator(
+ model="test-model",
+ litellm_custom_stream_wrapper=AsyncMock(),
+ request_input="hi",
+ responses_api_request={},
+ )
+
+ created = iterator.create_response_created_event()
+ in_progress = iterator.create_response_in_progress_event()
+ item_added = iterator.create_output_item_added_event()
+ part_added = iterator.create_content_part_added_event()
+
+ for evt in (created, in_progress, item_added, part_added):
+ dumped = evt.model_dump()
+ assert (
+ "sequence_number" in dumped
+ ), f"{type(evt).__name__} dropped sequence_number"
+ assert isinstance(dumped["sequence_number"], int)
+
+ # And the values must be monotonic — strict clients enforce ordering.
+ seqs = [
+ evt.model_dump()["sequence_number"]
+ for evt in (created, in_progress, item_added, part_added)
+ ]
+ assert seqs == sorted(seqs), seqs
+ assert len(set(seqs)) == len(seqs), seqs
diff --git a/tests/test_litellm/test_responses_api_bridge_non_stream.py b/tests/test_litellm/test_responses_api_bridge_non_stream.py
--- a/tests/test_litellm/test_responses_api_bridge_non_stream.py
+++ b/tests/test_litellm/test_responses_api_bridge_non_stream.py
@@ -131,7 +131,11 @@
"""
Test that transformation works when completion response has NO token details.
- This simulates providers that don't return detailed token breakdowns.
+ This simulates providers that don't return detailed token breakdowns. Per the
+ OpenAI Responses spec, `input_tokens_details` and `output_tokens_details` must
+ always be present on `response.completed.usage`; strict deserializers (Grok
+ Build CLI, OpenAI SDK) reject the event when either is missing. Defaults are
+ zeros.
"""
completion_response = create_mock_completion_response(
model="gpt-4",
@@ -150,9 +154,11 @@
assert responses_usage.output_tokens == 20
assert responses_usage.total_tokens == 30
- # Token details should not be present when not provided
- assert responses_usage.input_tokens_details is None
- assert responses_usage.output_tokens_details is None
+ # Token details are always emitted, defaulting to zeros when upstream omits them.
+ assert isinstance(responses_usage.input_tokens_details, InputTokensDetails)
+ assert responses_usage.input_tokens_details.cached_tokens == 0
+ assert isinstance(responses_usage.output_tokens_details, OutputTokensDetails)
+ assert responses_usage.output_tokens_details.reasoning_tokens == 0
print("✓ Transformation works with no token details")
@@ -186,8 +192,10 @@
assert isinstance(responses_usage.input_tokens_details, InputTokensDetails)
assert responses_usage.input_tokens_details.cached_tokens == 80
- # Output details should not be present (no reasoning_tokens provided)
- assert responses_usage.output_tokens_details is None
+ # Output details are always emitted (defaulting reasoning_tokens to 0) to match
+ # the OpenAI Responses spec — strict deserializers require the field.
+ assert isinstance(responses_usage.output_tokens_details, OutputTokensDetails)
+ assert responses_usage.output_tokens_details.reasoning_tokens == 0
print("✓ Transformation works with cached_tokens only")
@@ -216,8 +224,10 @@
assert responses_usage.output_tokens == 100
assert responses_usage.total_tokens == 150
- # Input details should not be present (no cached_tokens provided)
- assert responses_usage.input_tokens_details is None
+ # Input details are always emitted (defaulting cached_tokens to 0) to match
+ # the OpenAI Responses spec.
+ assert isinstance(responses_usage.input_tokens_details, InputTokensDetails)
+ assert responses_usage.input_tokens_details.cached_tokens == 0
# Output details should be present with reasoning_tokens
assert responses_usage.output_tokens_details is not NoneYou can send follow-ups to the cloud agent here.
…sistency Co-authored-by: Yassin Kortam <yassin@berri.ai>
create_mcp_call_events relied on OutputItemDoneEvent's default sequence_number, which was previously 1 but is now 0. Pass an explicit value so the event matches the streaming sequence order emitted by the surrounding MCP call events.
Several Responses API event types now declare sequence_number with a default of 0. The native synthetic streaming path constructed many events without explicitly passing sequence_number, which caused them to serialize as 0 and break the strict monotonic ordering guarantee expected by some clients (e.g. Grok Build CLI). Assign sequence_number to every event after the list is built so the stream is guaranteed monotonic regardless of which helper produced each event. Co-authored-by: Yassin Kortam <yassin@berri.ai>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: Synthetic stream path uses 0-based sequence numbers
- Changed enumerate(events) to enumerate(events, start=1) so synthetic/cached response stream events use 1-based sequence numbers, matching the litellm_completion_transformation streaming path and OpenAI's observed behavior.
Preview (7f52f18118)
diff --git a/litellm/responses/litellm_completion_transformation/streaming_iterator.py b/litellm/responses/litellm_completion_transformation/streaming_iterator.py
--- a/litellm/responses/litellm_completion_transformation/streaming_iterator.py
+++ b/litellm/responses/litellm_completion_transformation/streaming_iterator.py
@@ -219,8 +219,8 @@
"status": "in_progress",
}
),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
self._pending_tool_events.append(event)
if fn_args_delta:
@@ -232,16 +232,19 @@
for i in range(0, len(fn_args_delta), chunk_size):
delta_chunk = fn_args_delta[i : i + chunk_size]
self._sequence_number += 1
+ # sequence_number is passed via constructor so it lands in
+ # __pydantic_extra__ (BaseLiteLLMOpenAIResponseObject allows extra
+ # fields). Setting it via __dict__ afterward is silently dropped
+ # by model_dump() and breaks strict OpenAI Responses-API clients.
delta_event: BaseLiteLLMOpenAIResponseObject = (
FunctionCallArgumentsDeltaEvent(
type=ResponsesAPIStreamEvents.FUNCTION_CALL_ARGUMENTS_DELTA,
item_id=call_id,
output_index=output_index,
delta=delta_chunk,
+ sequence_number=self._sequence_number,
)
)
- # Add sequence_number as extra field (BaseLiteLLMOpenAIResponseObject allows extra fields)
- delta_event.__dict__["sequence_number"] = self._sequence_number
self._pending_tool_events.append(delta_event)
def _queue_final_tool_call_done_events(
@@ -306,8 +309,8 @@
"status": "in_progress",
}
),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
self._pending_tool_events.append(event)
final_args = fn_args or self._tool_args_by_call_id.get(call_id, "")
@@ -328,8 +331,8 @@
item_id=call_id,
output_index=output_index,
delta=delta_chunk,
+ sequence_number=self._sequence_number,
)
- delta_event.__dict__["sequence_number"] = self._sequence_number
self._pending_tool_events.append(delta_event)
self._sequence_number += 1
@@ -338,8 +341,8 @@
item_id=call_id,
output_index=output_index,
arguments=final_args,
+ sequence_number=self._sequence_number,
)
- done_event.__dict__["sequence_number"] = self._sequence_number
self._pending_tool_events.append(done_event)
self._sequence_number += 1
@@ -424,30 +427,28 @@
"""
response_created_event_data = self._default_response_created_event_data()
self._sequence_number += 1
- event = ResponseCreatedEvent(
+ return ResponseCreatedEvent(
type=ResponsesAPIStreamEvents.RESPONSE_CREATED,
response=ResponsesAPIResponse(**response_created_event_data),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
- return event
def create_response_in_progress_event(self) -> ResponseInProgressEvent:
response_in_progress_event_data = self._default_response_created_event_data()
response_in_progress_event_data["status"] = "in_progress"
self._sequence_number += 1
- event = ResponseInProgressEvent(
+ return ResponseInProgressEvent(
type=ResponsesAPIStreamEvents.RESPONSE_IN_PROGRESS,
response=ResponsesAPIResponse(**response_in_progress_event_data),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
- return event
def create_output_item_added_event(self) -> OutputItemAddedEvent:
if self._cached_item_id is None:
self._cached_item_id = f"msg_{str(uuid.uuid4())}"
self._sequence_number += 1
- event = OutputItemAddedEvent(
+ return OutputItemAddedEvent(
type=ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED,
output_index=0,
item=BaseLiteLLMOpenAIResponseObject(
@@ -459,16 +460,15 @@
"content": [],
}
),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
- return event
def create_content_part_added_event(self) -> ContentPartAddedEvent:
if self._cached_item_id is None:
self._cached_item_id = f"msg_{str(uuid.uuid4())}"
self._sequence_number += 1
- event = ContentPartAddedEvent(
+ return ContentPartAddedEvent(
type=ResponsesAPIStreamEvents.CONTENT_PART_ADDED,
item_id=self._cached_item_id,
output_index=0,
@@ -476,9 +476,8 @@
part=BaseLiteLLMOpenAIResponseObject(
**{"type": "output_text", "text": "", "annotations": []}
),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
- return event
def _merge_provider_specific_fields(self, src: dict) -> None:
"""Merge provider_specific_fields using last-value-wins for lists.
@@ -599,6 +598,7 @@
if self._cached_item_id is None:
self._cached_item_id = f"msg_{str(uuid.uuid4())}"
+ self._sequence_number += 1
return OutputTextDoneEvent(
type=ResponsesAPIStreamEvents.OUTPUT_TEXT_DONE,
item_id=self._cached_item_id,
@@ -606,6 +606,7 @@
content_index=0,
text=getattr(litellm_complete_object.choices[0].message, "content", "") # type: ignore
or "",
+ sequence_number=self._sequence_number,
)
def create_output_content_part_done_event(
@@ -636,12 +637,14 @@
logprobs=None,
)
+ self._sequence_number += 1
return ContentPartDoneEvent(
type=ResponsesAPIStreamEvents.CONTENT_PART_DONE,
item_id=self._cached_item_id,
output_index=0,
content_index=0,
part=part,
+ sequence_number=self._sequence_number,
)
def create_output_item_done_event(
@@ -656,10 +659,11 @@
response_annotations = LiteLLMCompletionResponsesConfig._transform_chat_completion_annotations_to_response_output_annotations(
annotations=annotations
)
+ self._sequence_number += 1
return OutputItemDoneEvent(
type=ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE,
output_index=0,
- sequence_number=1,
+ sequence_number=self._sequence_number,
item=BaseLiteLLMOpenAIResponseObject(
**{
"id": self._cached_item_id,
@@ -817,8 +821,8 @@
"summary": None,
}
),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
self._pending_response_events.append(event)
return
@@ -842,8 +846,8 @@
"content": [],
}
),
+ sequence_number=self._sequence_number,
)
- event.__dict__["sequence_number"] = self._sequence_number
self._pending_response_events.append(event)
# Emit content_part.added immediately after output_item.added for message
@@ -1075,6 +1079,9 @@
if hasattr(annotation, "model_dump")
else dict(annotation)
)
+ # Sequence number is assigned at emit time (see Priority 4
+ # below) to preserve monotonic ordering relative to
+ # higher-priority events from later chunks.
event = OutputTextAnnotationAddedEvent(
type=ResponsesAPIStreamEvents.OUTPUT_TEXT_ANNOTATION_ADDED,
item_id=item_id,
@@ -1092,11 +1099,13 @@
):
reasoning_content = chunk.choices[0].delta.reasoning_content
+ self._sequence_number += 1
return ReasoningSummaryTextDeltaEvent(
type=ResponsesAPIStreamEvents.REASONING_SUMMARY_TEXT_DELTA,
item_id=f"rs_{hash(str(reasoning_content))}",
output_index=0,
delta=reasoning_content,
+ sequence_number=self._sequence_number,
)
# Priority 2: Handle text deltas
@@ -1109,8 +1118,8 @@
output_index=0,
content_index=0,
delta=delta_content,
+ sequence_number=self._sequence_number,
)
- text_delta_event.__dict__["sequence_number"] = self._sequence_number
return text_delta_event
# Priority 3: Handle tool call deltas (if any) -> queue events and emit them
@@ -1126,12 +1135,16 @@
return self._pending_tool_events.pop(0)
# Priority 4: If we have pending annotation events, emit the next one
- # This happens when the current chunk has no text/reasoning content
+ # This happens when the current chunk has no text/reasoning content.
+ # Assign the sequence number here (at emit time) so it stays monotonic
+ # relative to other events emitted from intervening chunks.
if (
hasattr(self, "_pending_annotation_events")
and self._pending_annotation_events
):
event = self._pending_annotation_events.pop(0)
+ self._sequence_number += 1
+ event.sequence_number = self._sequence_number
return event
# Priority 5: If we have pending tool events (from earlier chunk), emit the next one
@@ -1191,9 +1204,11 @@
litellm_metadata=self.litellm_metadata,
)
+ self._sequence_number += 1
return ResponseCompletedEvent(
type=ResponsesAPIStreamEvents.RESPONSE_COMPLETED,
response=encoded_response,
+ sequence_number=self._sequence_number,
)
else:
return None
diff --git a/litellm/responses/litellm_completion_transformation/transformation.py b/litellm/responses/litellm_completion_transformation/transformation.py
--- a/litellm/responses/litellm_completion_transformation/transformation.py
+++ b/litellm/responses/litellm_completion_transformation/transformation.py
@@ -1692,7 +1692,10 @@
status=LiteLLMCompletionResponsesConfig._map_chat_completion_finish_reason_to_responses_status(
finish_reason
),
- text={},
+ # OpenAI Responses spec requires `text.format` to be present. Honor the
+ # request's `text` config when supplied; otherwise default to plain text.
+ # Strict deserializers (Grok Build CLI, OpenAI SDK) reject `text: {}`.
+ text=responses_api_request.get("text") or {"format": {"type": "text"}},
truncation=getattr(chat_completion_response, "truncation", None),
usage=LiteLLMCompletionResponsesConfig._transform_chat_completion_usage_to_responses_usage(
chat_completion_response=chat_completion_response
@@ -2079,6 +2082,8 @@
input_tokens=0,
output_tokens=0,
total_tokens=0,
+ input_tokens_details=InputTokensDetails(cached_tokens=0),
+ output_tokens_details=OutputTokensDetails(reasoning_tokens=0),
)
response_usage = ResponseAPIUsage(
@@ -2091,21 +2096,18 @@
if hasattr(usage, "cost") and usage.cost is not None:
setattr(response_usage, "cost", usage.cost)
- # Translate prompt_tokens_details to input_tokens_details
- if (
- hasattr(usage, "prompt_tokens_details")
- and usage.prompt_tokens_details is not None
- ):
- prompt_details = usage.prompt_tokens_details
- input_details_dict: Dict[str, int] = {}
-
+ # Translate prompt_tokens_details -> input_tokens_details.
+ # OpenAI's Responses spec requires this field to always be present on
+ # response.completed.usage, so we emit it with defaults if upstream
+ # omitted prompt_tokens_details entirely.
+ prompt_details = getattr(usage, "prompt_tokens_details", None)
+ input_details_dict: Dict[str, int] = {"cached_tokens": 0}
+ if prompt_details is not None:
if (
hasattr(prompt_details, "cached_tokens")
and prompt_details.cached_tokens is not None
):
input_details_dict["cached_tokens"] = prompt_details.cached_tokens
- else:
- input_details_dict["cached_tokens"] = 0
if (
hasattr(prompt_details, "text_tokens")
@@ -2119,18 +2121,14 @@
):
input_details_dict["audio_tokens"] = prompt_details.audio_tokens
- if input_details_dict:
- response_usage.input_tokens_details = InputTokensDetails(
- **input_details_dict
- )
+ response_usage.input_tokens_details = InputTokensDetails(**input_details_dict)
- # Translate completion_tokens_details to output_tokens_details
- if (
- hasattr(usage, "completion_tokens_details")
- and usage.completion_tokens_details is not None
- ):
- completion_details = usage.completion_tokens_details
- output_details_dict: Dict[str, int] = {}
+ # Translate completion_tokens_details -> output_tokens_details. Same
+ # always-present requirement; strict deserializers (Grok Build CLI, the
+ # OpenAI SDK) reject a usage object without it.
+ completion_details = getattr(usage, "completion_tokens_details", None)
+ output_details_dict: Dict[str, int] = {"reasoning_tokens": 0}
+ if completion_details is not None:
if (
hasattr(completion_details, "reasoning_tokens")
and completion_details.reasoning_tokens is not None
@@ -2138,8 +2136,6 @@
output_details_dict["reasoning_tokens"] = (
completion_details.reasoning_tokens
)
- else:
- output_details_dict["reasoning_tokens"] = 0
if (
hasattr(completion_details, "text_tokens")
@@ -2153,10 +2149,9 @@
):
output_details_dict["image_tokens"] = completion_details.image_tokens
- if output_details_dict:
- response_usage.output_tokens_details = OutputTokensDetails(
- **output_details_dict
- )
+ response_usage.output_tokens_details = OutputTokensDetails(
+ **output_details_dict
+ )
return response_usage
diff --git a/litellm/responses/mcp/mcp_streaming_iterator.py b/litellm/responses/mcp/mcp_streaming_iterator.py
--- a/litellm/responses/mcp/mcp_streaming_iterator.py
+++ b/litellm/responses/mcp/mcp_streaming_iterator.py
@@ -218,6 +218,7 @@
output_item_done_event = OutputItemDoneEvent(
type=ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE,
output_index=0,
+ sequence_number=sequence_start + 4,
item=BaseLiteLLMOpenAIResponseObject(
**{
"id": item_id,
diff --git a/litellm/responses/streaming_iterator.py b/litellm/responses/streaming_iterator.py
--- a/litellm/responses/streaming_iterator.py
+++ b/litellm/responses/streaming_iterator.py
@@ -1212,6 +1212,18 @@
response=transformed,
)
)
+
+ # Assign monotonic sequence_number to every event. The helpers above
+ # build events without consistently passing sequence_number, and several
+ # event types now declare `sequence_number: int = 0` (default), which
+ # would otherwise serialize as 0 for most events and break the strict
+ # monotonic ordering guarantee expected by some Responses API clients.
+ for idx, event in enumerate(events, start=1):
+ try:
+ event.sequence_number = idx
+ except (AttributeError, ValueError):
+ pass
+
return events
diff --git a/litellm/types/llms/openai.py b/litellm/types/llms/openai.py
--- a/litellm/types/llms/openai.py
+++ b/litellm/types/llms/openai.py
@@ -1448,16 +1448,19 @@
class ResponseCreatedEvent(BaseLiteLLMOpenAIResponseObject):
type: Literal[ResponsesAPIStreamEvents.RESPONSE_CREATED]
response: ResponsesAPIResponse
+ sequence_number: int = 0
class ResponseInProgressEvent(BaseLiteLLMOpenAIResponseObject):
type: Literal[ResponsesAPIStreamEvents.RESPONSE_IN_PROGRESS]
response: ResponsesAPIResponse
+ sequence_number: int = 0
class ResponseCompletedEvent(BaseLiteLLMOpenAIResponseObject):
type: Literal[ResponsesAPIStreamEvents.RESPONSE_COMPLETED]
response: ResponsesAPIResponse
+ sequence_number: int = 0
_hidden_params: dict = PrivateAttr(default_factory=dict)
@@ -1484,6 +1487,7 @@
output_index: int
summary_index: int = 0
delta: str
+ sequence_number: int = 0
class ReasoningSummaryTextDoneEvent(BaseLiteLLMOpenAIResponseObject):
@@ -1508,12 +1512,13 @@
type: Literal[ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED]
output_index: int
item: Optional[BaseLiteLLMOpenAIResponseObject]
+ sequence_number: int = 0
class OutputItemDoneEvent(BaseLiteLLMOpenAIResponseObject):
type: Literal[ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE]
output_index: int
- sequence_number: int = 1
+ sequence_number: int = 0
item: BaseLiteLLMOpenAIResponseObject
@@ -1536,6 +1541,7 @@
output_index: int
content_index: int
part: BaseLiteLLMOpenAIResponseObject
+ sequence_number: int = 0
class ContentPartDonePartOutputText(BaseLiteLLMOpenAIResponseObject):
@@ -1568,6 +1574,7 @@
output_index: int
content_index: int
part: PART_UNION_TYPES
+ sequence_number: int = 0
class OutputTextDeltaEvent(BaseLiteLLMOpenAIResponseObject):
@@ -1576,6 +1583,7 @@
output_index: int
content_index: int
delta: str
+ sequence_number: int = 0
class OutputTextAnnotationAddedEvent(BaseLiteLLMOpenAIResponseObject):
@@ -1585,6 +1593,7 @@
content_index: int
annotation_index: int
annotation: dict
+ sequence_number: int = 0
class OutputTextDoneEvent(BaseLiteLLMOpenAIResponseObject):
@@ -1593,6 +1602,7 @@
output_index: int
content_index: int
text: str
+ sequence_number: int = 0
class RefusalDeltaEvent(BaseLiteLLMOpenAIResponseObject):
@@ -1616,6 +1626,7 @@
item_id: str
output_index: int
delta: str
+ sequence_number: int = 0
class FunctionCallArgumentsDoneEvent(BaseLiteLLMOpenAIResponseObject):
@@ -1623,6 +1634,7 @@
item_id: str
output_index: int
arguments: str
+ sequence_number: int = 0
class FileSearchCallInProgressEvent(BaseLiteLLMOpenAIResponseObject):
diff --git a/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py b/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py
--- a/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py
+++ b/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py
@@ -1601,7 +1601,13 @@
assert response_usage.input_tokens_details.text_tokens == 9
def test_transform_usage_without_details(self):
- """Test transformation when prompt_tokens_details and completion_tokens_details are None"""
+ """Test transformation when prompt_tokens_details and completion_tokens_details are None.
+
+ Per the OpenAI Responses spec, `input_tokens_details` and
+ `output_tokens_details` must always be present on the response.completed
+ usage object; strict deserializers (Grok Build CLI, OpenAI SDK) reject
+ the event when either is missing. We emit them with zero defaults.
+ """
# Setup: Usage without details (basic usage only)
usage = Usage(
prompt_tokens=9,
@@ -1629,12 +1635,14 @@
chat_completion_response=chat_completion_response
)
- # Assert: Basic usage should still be transformed, but details should be None
+ # Assert: basic counts transformed, and details always present with zero defaults
assert response_usage.input_tokens == 9
assert response_usage.output_tokens == 27
assert response_usage.total_tokens == 36
- assert response_usage.input_tokens_details is None
- assert response_usage.output_tokens_details is None
+ assert response_usage.input_tokens_details is not None
+ assert response_usage.input_tokens_details.cached_tokens == 0
+ assert response_usage.output_tokens_details is not None
+ assert response_usage.output_tokens_details.reasoning_tokens == 0
def test_transform_usage_with_image_tokens(self):
"""Test that image_tokens from Vertex AI/Gemini are properly transformed to output_tokens_details"""
diff --git a/tests/test_litellm/responses/litellm_completion_transformation/test_tool_call_streaming_transformation.py b/tests/test_litellm/responses/litellm_completion_transformation/test_tool_call_streaming_transformation.py
--- a/tests/test_litellm/responses/litellm_completion_transformation/test_tool_call_streaming_transformation.py
+++ b/tests/test_litellm/responses/litellm_completion_transformation/test_tool_call_streaming_transformation.py
@@ -187,11 +187,15 @@
# Process the chunk once - it queues all events internally
evt = iterator._transform_chat_completion_chunk_to_response_api_chunk(chunk)
- # First event should be OUTPUT_ITEM_ADDED
+ # First event should be OUTPUT_ITEM_ADDED, carrying a serialized sequence_number.
+ # `sequence_number` is passed through the constructor so it lands in
+ # __pydantic_extra__ (BaseLiteLLMOpenAIResponseObject allows extras); a raw
+ # __dict__ assignment would be silently dropped by model_dump(). We assert on
+ # the dump because that is what hits the wire as SSE.
assert evt is not None
assert evt.type == ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED
assert evt.output_index == 1
- assert hasattr(evt, "__dict__") and "sequence_number" in evt.__dict__
+ assert "sequence_number" in evt.model_dump()
# Collect all remaining delta events from the pending queue by creating empty chunks
delta_events = []
@@ -220,19 +224,21 @@
# Verify multiple delta events were created (at least 6 chunks for 67 chars)
assert len(delta_events) >= 6 # 67 chars split into chunks of max 10 chars each
- # Verify each delta is at most 10 characters
+ # Verify each delta is at most 10 characters and carries a serializable
+ # sequence_number (the value lives in __pydantic_extra__, not __dict__).
for evt in delta_events:
assert len(evt.delta) <= 10
assert evt.item_id == "call_test"
assert evt.output_index == 1
- assert hasattr(evt, "__dict__") and "sequence_number" in evt.__dict__
+ assert "sequence_number" in evt.model_dump()
# Verify all deltas concatenated equal the original arguments
concatenated = "".join(evt.delta for evt in delta_events)
assert concatenated == large_arguments
- # Verify sequence numbers are increasing
- sequence_numbers = [evt.__dict__["sequence_number"] for evt in delta_events]
+ # Verify sequence numbers are increasing and unique (read from the dumped
+ # payload, which is what actually hits the wire).
+ sequence_numbers = [evt.model_dump()["sequence_number"] for evt in delta_events]
assert sequence_numbers == sorted(sequence_numbers)
assert len(set(sequence_numbers)) == len(sequence_numbers) # All unique
@@ -397,3 +403,40 @@
assert arguments_by_call_id["call_b"] == '{"b":'
assert arguments_by_call_id["call_a"] != '{"a":1}'
assert arguments_by_call_id["call_b"] != '{"b":1}'
+
+
+def test_streaming_events_serialize_sequence_number_for_strict_clients():
+ """Pin the Grok Build CLI / OpenAI SDK contract: every emitted streaming
+ event must carry `sequence_number` in its on-wire JSON payload.
+
+ Earlier code set `event.__dict__["sequence_number"] = N` after construction,
+ which silently dropped the field during Pydantic's `model_dump()` and broke
+ strict deserializers. The fix routes the value through the constructor so it
+ lands in `__pydantic_extra__` and survives serialization.
+ """
+ iterator = LiteLLMCompletionStreamingIterator(
+ model="test-model",
+ litellm_custom_stream_wrapper=AsyncMock(),
+ request_input="hi",
+ responses_api_request={},
+ )
+
+ created = iterator.create_response_created_event()
+ in_progress = iterator.create_response_in_progress_event()
+ item_added = iterator.create_output_item_added_event()
+ part_added = iterator.create_content_part_added_event()
+
+ for evt in (created, in_progress, item_added, part_added):
+ dumped = evt.model_dump()
+ assert (
+ "sequence_number" in dumped
+ ), f"{type(evt).__name__} dropped sequence_number"
+ assert isinstance(dumped["sequence_number"], int)
+
+ # And the values must be monotonic — strict clients enforce ordering.
+ seqs = [
+ evt.model_dump()["sequence_number"]
+ for evt in (created, in_progress, item_added, part_added)
+ ]
+ assert seqs == sorted(seqs), seqs
+ assert len(set(seqs)) == len(seqs), seqs
diff --git a/tests/test_litellm/test_responses_api_bridge_non_stream.py b/tests/test_litellm/test_responses_api_bridge_non_stream.py
--- a/tests/test_litellm/test_responses_api_bridge_non_stream.py
+++ b/tests/test_litellm/test_responses_api_bridge_non_stream.py
@@ -131,7 +131,11 @@
"""
Test that transformation works when completion response has NO token details.
- This simulates providers that don't return detailed token breakdowns.
+ This simulates providers that don't return detailed token breakdowns. Per the
+ OpenAI Responses spec, `input_tokens_details` and `output_tokens_details` must
+ always be present on `response.completed.usage`; strict deserializers (Grok
+ Build CLI, OpenAI SDK) reject the event when either is missing. Defaults are
+ zeros.
"""
completion_response = create_mock_completion_response(
model="gpt-4",
@@ -150,9 +154,11 @@
assert responses_usage.output_tokens == 20
assert responses_usage.total_tokens == 30
- # Token details should not be present when not provided
- assert responses_usage.input_tokens_details is None
- assert responses_usage.output_tokens_details is None
+ # Token details are always emitted, defaulting to zeros when upstream omits them.
+ assert isinstance(responses_usage.input_tokens_details, InputTokensDetails)
+ assert responses_usage.input_tokens_details.cached_tokens == 0
+ assert isinstance(responses_usage.output_tokens_details, OutputTokensDetails)
+ assert responses_usage.output_tokens_details.reasoning_tokens == 0
print("✓ Transformation works with no token details")
@@ -186,8 +192,10 @@
assert isinstance(responses_usage.input_tokens_details, InputTokensDetails)
assert responses_usage.input_tokens_details.cached_tokens == 80
- # Output details should not be present (no reasoning_tokens provided)
- assert responses_usage.output_tokens_details is None
+ # Output details are always emitted (defaulting reasoning_tokens to 0) to match
+ # the OpenAI Responses spec — strict deserializers require the field.
+ assert isinstance(responses_usage.output_tokens_details, OutputTokensDetails)
+ assert responses_usage.output_tokens_details.reasoning_tokens == 0
print("✓ Transformation works with cached_tokens only")
@@ -216,8 +224,10 @@
assert responses_usage.output_tokens == 100
assert responses_usage.total_tokens == 150
- # Input details should not be present (no cached_tokens provided)
- assert responses_usage.input_tokens_details is None
+ # Input details are always emitted (defaulting cached_tokens to 0) to match
+ # the OpenAI Responses spec.
+ assert isinstance(responses_usage.input_tokens_details, InputTokensDetails)
+ assert responses_usage.input_tokens_details.cached_tokens == 0
# Output details should be present with reasoning_tokens
assert responses_usage.output_tokens_details is not NoneYou can send follow-ups to the cloud agent here.
Reviewed by Cursor Bugbot for commit 3b3da79. Configure here.
Co-authored-by: Yassin Kortam <yassin@berri.ai>
|
@mateo can you add working ss of this? THanks! |
|
hey @mateo-berri, when will this one be merged in? Can we get an ETA? |
|
This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. |
|
Closing as superseded. #44944 is merged and numbers every streamed Responses event, and this branch has gone stale against main |

Summary
Fixes three OpenAI-Responses-spec violations on LiteLLM's
/v1/responsesstreaming surface that cause strict clients (Grok Build CLI 0.2.2, the OpenAI SDK Responses parser) to reject the stream mid-flight. After this PR, Grok Build CLI talks to LiteLLM end-to-end with zero errors.Background
Background and error output
xAI shipped Grok Build CLI (their Claude-Code-style coding agent,
curl -fsSL https://x.ai/cli/install.sh | bash) in early May 2026. It supports a~/.grok/config.toml[model.*]block withbase_url, so it's natural to route it through LiteLLM:The wire endpoint Grok hits is
POST /v1/responses(streaming SSE, OpenAI Responses API shape). Pointing it at LiteLLM revealed that LiteLLM'slitellm_completion_transformationResponses-API surface emits three fields out of spec, all of which Grok's Rust deserializer rejects:This affects every Anthropic-on-Responses-API call (and any other provider routed through the chat-completion → responses-API transformation), not just Grok — it's just that less-strict clients silently tolerate the missing fields.
Root causes
1.
sequence_numberwas being dropped at serialization timeDetails
litellm/responses/litellm_completion_transformation/streaming_iterator.pyset the field with a__dict__mutation after constructing each Pydantic event:With
model_config = ConfigDict(extra="allow"), Pydantic v2 routes extras through__pydantic_extra__, not__dict__. Setting via__dict__after construction updates the instance dict butmodel_dump()only reads declared fields plus__pydantic_extra__, so the field never reaches the wire. Reproducer:There were 13 sites using this buggy pattern, plus 5 more event constructors (
OutputTextDoneEvent,ContentPartDoneEvent,OutputTextAnnotationAddedEvent,ReasoningSummaryTextDeltaEvent,ResponseCompletedEvent) that never setsequence_numberat all. All 18 now route the value through the constructor.2.
response.completed.response.textwas hardcoded to{}Details
litellm/responses/litellm_completion_transformation/transformation.py:1695:OpenAI's Responses spec models this as
text: { format: { type: "text" | "json_schema", ... } }. An empty{}makes strict deserializers fail becauseformatis required. Now defaults to{"format": {"type": "text"}}when the request didn't supply atextconfig, and honors the request's value when it did.3.
usage.input_tokens_details/usage.output_tokens_detailswere dropped on providers that didn't return detailsDetails
In
_transform_chat_completion_usage_to_responses_usage, both fields were only emitted when upstream returned the corresponding details object. Anthropic chat-completion responses omitcompletion_tokens_detailsentirely on some paths (notably tool-only function-calling responses like Grok's session-title subagent). OpenAI's spec requires both fields on everyresponse.completed.usageevent. Both fields now always emit, defaulting tocached_tokens=0/reasoning_tokens=0when upstream provides nothing.What changed
litellm/responses/litellm_completion_transformation/streaming_iterator.pysequence_numberas a kwarg. Removes allevent.__dict__["sequence_number"] = ...mutations.litellm/responses/litellm_completion_transformation/transformation.pytext={}→ request-aware default with{"format": {"type": "text"}}fallback.usage.{input,output}_tokens_detailsalways emitted with zero defaults.tests/test_litellm/test_responses_api_bridge_non_stream.pytests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.pytests/test_litellm/responses/litellm_completion_transformation/test_tool_call_streaming_transformation.py__dict__pattern updated to readsequence_numberfrommodel_dump()(which is what hits the wire). 1 new regression test pins the Grok contract: every streaming event must carrysequence_numberin itsmodel_dump()output, monotonic and unique.Verification
End-to-end against Grok Build CLI
Real Grok Build 0.2.2 binary (
/tmp/grok-bin) talking to a local LiteLLM proxy (localhost:4000, master keysk-1234) backed by Anthropic Claude Haiku 4.5. SandboxedGROK_HOME=/tmp/grok-test-home,GROK_AUTO_UPDATE=0,GROK_SESSION_SUMMARY_MODEL=anthropic-haiku-4-5(to redirect Grok's hardcoded session-title subagent to an actual LiteLLM model name).grok -p 'hi' --model litellm-haikugrok -p 'what is 17 * 23? respond with just the number'"391"grok -p 'name three colors, one per line'"Red\nBlue\nGreen"grok modelslitellm-haiku(default),litellm-haiku-responses,grok-buildBefore this PR, all four failed with
Failed to deserialize ResponseStreamEvent from stream: missing field 'sequence_number'followed bymissing field 'format'andmissing field 'output_tokens_details'.Unit tests
The three ignored files have pre-existing failures on
main, unrelated to this change (MCP-handler test fixtures, a websocket-URL test, and an orjson import in cold-storage). They fail identically on the parent commit.Live
/v1/responsesrequest shapeAfter fix, a curl probe shows all three required fields populated:
sequence_numberis monotonically increasing across every emitted event.For Grok Build CLI users
Scope / risk
litellm_completion_transformationResponses-API code path (litellm/responses/litellm_completion_transformation/), which transforms chat-completions stream chunks into Responses-API SSE events. Providers that natively speak the Responses API (litellm/responses/streaming_iterator.py) are not touched.text.formatandusage.*_tokens_detailsis strictly additive: previously-missing fields are now populated with spec-defaults. Clients that already worked will still work; clients that previously rejected the stream now succeed.sequence_numberchange converts a non-functional__dict__assignment into a working constructor kwarg. The serialized field was missing before, so any client that consumed the value (including caching/logging layers within LiteLLM itself) was readingNone.Checklist
tests/litellm/(1 new positive regression test + 5 contract updates).make test-unitequivalent passes (162/162 in the affected subtree).uv run black .clean.Bugbot summary