feat: Add finish_reason
field to StreamingChunk
#9536
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.
Why:
Introduces a strategic migration path for standardizing
finish_reason
handling across all chat generators in Haystack. This PR adds a dedicatedfinish_reason
field inStreamingChunk
class to replace the current dictionary-based approach of readingfinish_reason
from meta, enabling better type safety, self-documented and easier to understand finish_reason logic while providing a smooth migration timeline from Haystack 2.15 to 2.17.finish_reason
field toStreamingChunk
#9471What:
finish_reason: Optional[Union[FinishReason, str]]
field toStreamingChunk
classFinishReason
Literal type with OpenAI standard values ("stop", "length", "tool_calls", "content_filter")OpenAIChatGenerator
to populate both new field and legacy meta field during transitionmeta["finish_reason"]
How can it be used:
The migration plan enables immediate adoption while maintaining compatibility:
How did you test it:
meta["finish_reason"]
continues working with deprecation warningsNotes for the reviewer:
Migration Strategy: This PR implements Phase 1 of a planned 3-phase migration:
meta["finish_reason"]
support and complete migrationCritical Migration Logic: The fallback in
_convert_streaming_chunks_to_chat_message
is essential - it handles chunks from both updated generators (usingchunk.finish_reason
) and non-updated generators (usingmeta["finish_reason"]
) during the 2-version migration window. This ensures zero breaking changes while we systematically update all chat generators.