Fix Union type handling in Pydantic output generation #3736
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.
Fix Union type handling in Pydantic output generation
Summary
Fixed a bug in
generate_model_descriptionwhere all Union types were incorrectly wrapped inOptional[], even whenNonewas not part of the Union. This caused imprecise schema descriptions to be sent to LLMs when generating structured outputs.Before:
Union[str, int]→Optional[Union[str, int]]❌Union[str, int, None]→Optional[Union[str, int]]✓After:
Union[str, int]→Union[str, int]✓Union[str, int, None]→Optional[Union[str, int]]✓Key Changes:
Noneis actually present in the Union before wrapping withOptionalint | str | None)Fixes #3735
Review & Testing Checklist for Human
pytest tests/test_union_types.py -vvto confirm all Union type tests pass (13 tests should pass)converter.pyto ensure the Union/Optional logic is correct and handles edge cases properlytest_converter_with_llama3_1_modelandtest_converter_with_llama3_2_model) will fail with cassette mismatches because the schema format changed. These cassettes should be regenerated or the tests marked as expected to changeoutput_pydanticwith Union types to ensure LLMs correctly understand the new schema formatRecommended test plan:
Notes