fix(stream): emit queued events before max-turns exception #2458
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.
Summary
RunResultStreaming.stream_events()currently breaks as soon as_stored_exceptionis set, even if there are still queued run-item events waiting in_event_queue.For max-turn failures this can drop the last
tool_call_output_itemfrom the stream, even though the item has already been produced and queued.This PR changes the loop so we only break on
_stored_exceptionwhen the event queue is empty.Why
Issue: #526
This preserves event ordering and guarantees consumers receive all already-queued semantic events before the final exception is raised.
Changes
RunResultStreaming.stream_events(), changed:_stored_exceptionis set_stored_exceptionis set and_event_queueis emptytest_streaming_max_turns_emits_pending_tool_output_eventstool_call_itemandtool_call_output_itemare emitted beforeMaxTurnsExceededValidation
uv run ruff check src/agents/result.py tests/test_agent_runner_streamed.pyuv run mypy src/agents/result.py tests/test_agent_runner_streamed.pyenv -u all_proxy -u ALL_PROXY -u http_proxy -u HTTP_PROXY -u https_proxy -u HTTPS_PROXY uv run pytest tests/test_agent_runner_streamed.py -k "max_turns" -qenv -u all_proxy -u ALL_PROXY -u http_proxy -u HTTP_PROXY -u https_proxy -u HTTPS_PROXY uv run pytest tests/test_agent_runner_streamed.py -qmake format-checkenv -u all_proxy -u ALL_PROXY -u http_proxy -u HTTP_PROXY -u https_proxy -u HTTPS_PROXY uv run python -m trace --count --coverdir /tmp/openai_agents_526_trace --module pytest tests/test_agent_runner_streamed.py -k "max_turns" -qTrace output confirms the modified branch in
src/agents/result.pyis executed.