Fix: Correct streaming order for ReasoningItem and RawResponsesStreamEvent events #1869
+392
−9
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Issues
This PR fixes incorrect streaming order for
ReasoningItem
andRawResponsesStreamEvent
:RawResponsesStreamEvent
should be emitted ASAP.This behavior was accidentally broken in Fix: Emit tool_called events immediately in streaming runs #1300, which changed the original correct ordering.
ReasoningItem
should be emitted right after itsresponse.output_item.done
event, rather than being delayed until afterresponse.completed
. This issue was reported in ReasoningItem of RunStreamEvents are getting emitted out of order #1767 (comment)Solution
Move raw event emission earlier
Restored the correct ordering by moving
RawResponsesStreamEvent
to the top of the handler.Emit
ReasoningItem
earlierApplied the exact same approach as in PR Fix: Emit tool_called events immediately in streaming runs #1300 for early emission of
ToolCallItem
, also applying it to ensure thatReasoningItem
is emitted right after itsResponseOutputItemDoneEvent
.Code intentionally not refactored for DRYness to keep the diff explicit and review-friendly. Refactoring can be done later after test code are merged.
Add comprehensive unit tests
Extended
FakeModel
to fully simulate detailed streaming sequence and added tests verifying the exact event order, ensuring future changes won’t reintroduce regressions.For reference, here is a real example script that calls the OpenAI API, along with the corresponding 27 test events: https://gist.github.com/ihower/b6d9fe9b72b02c5131e210e2202b31b7
Related