Repository navigation
fix: retry empty OpenAI streams with non-streaming invoke #7736
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Here's my review of the diff:
Potential Issues
1. Recursion risk (most important)
In
_stream, when no chunks arrive, it callsself.invoke(..., stream=False). This is fine as long asinvokedispatches to_generateand not back to_stream. Verify that:Self.invokedoes not route throughChatModel.stream/_streamwhenstream=False._streamdon't end up calling this method again.If any subclass or middleware calls
.stream()whileinvoke()internally re-enters_stream, you'll get unbounded recursion.2.
AIMessageChunk(**message.model_dump(exclude={"type"}))"type"may not be sufficient:AIMessagecan carry fields (id,usage_metadata,response_metadata,tool_calls,additional_kwargs, etc.) that don't map cleanly toAIMessageChunk, or whose shape differs (e.g.,tool_callsshould betool_call_chunks). Safer conversion is suggested in LangChain practice:ChatGenerationChunk(message=AIMessageChunk(...))with explicit mapping.AIMessagecontains atypefield set via Pydantic,model_dump()will include it; the exclude works but coupling the code to that one field name is fragile.3. Duplicate semantics: yielding one "whole" chunk
Yielding a single non-streaming message as a
ChatGenerationChunkviolates the streaming contract for callers that expect incremental content (they will see one big chunk). This may break token-by-token UI consumers. Document this behavior, or consider that an empty stream before completion is more honest.4.
chunk = Nonetyping / lintchunkinferred asChatGenerationChunkafter assignment inside the loop; initializing toNonemakes the typeOptional[ChatGenerationChunk]. Fine at runtime, but annotate explicitly:chunk: ChatGenerationChunk | None = None.last_chunk).5.
usage_metadataside-effect timingself.usage_metadatais only set whenchunk.message.usage_metadataexists. In the fallback path, the code doesn't updateself.usage_metadatafrom the fallback message. Add:6. Sync vs async parity
Both branches mirror each other well. Ensure
ainvoke(*args, **{**kwargs, "stream": False})doesn't accidentally passstream=Falsetwice if caller already includedstream=True/other values — the{**kwargs, "stream": False}handles this correctly, good.7. Exception handling / partial streams
If the parent stream raises mid-way, the fallback block won't execute (good), but any partially accumulated state stays. Consider whether you want to still fire the fallback on unusual early termination. Probably not — document intent in a comment.
8. Import ordering / alphabetical convention
Minor:
AIMessageinserted betweenBaseMessage-adjacent imports; many linters enforce isort ordering — checkruff/isortpasses. Also several existing imports in the block are out of order (get_buffer_stringbeforeBaseMessageChunk); pre-existing, but worth noting.9. Locking / generator finalization
These are generators; if the consumer abandons iteration after the first yielded chunk,
chunk is Nonefallback never matters. No leak concern, just note the fallback only triggers on an empty completed stream.10. Cost/latency
On truly empty streams you make a second API call (non-streaming). That doubles cost in this edge case. Log a warning so this doesn't go unnoticed, e.g.:
Optimization suggestions
_finalize_empty_stream(message)to avoid sync/async duplication._convert_chunk_to_generation_chunkor amessage_to_chunk()util) overmodel_dump.Summary
The gate
if chunk is Noneis a reasonable guard against empty streaming responses, but the fallback has three real risks: (a) recursion ifinvokere-enters_stream, (b) message→chunk conversion viamodel_dump(exclude={"type"})may drop/mis-shapetool_calls, and (c) it silently doubles API calls without updatingusage_metadataor logging. Fix those and it's straightforward.