fix: Always set additionalProperties=false for strict schema compliance #2743
+29
−1
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
Fixes #2740
This PR resolves an issue where Pydantic models using
ConfigDict(extra="allow")fail when used with structured output becauseadditionalPropertiesis not forced tofalse.Problem
The OpenAI API requires
"additionalProperties": falsein JSON schemas for structured output (response_format). When Pydantic models useextra="allow", the generated schema includes"additionalProperties": true, which causes the API to reject the request with:Root Cause
The
_ensure_strict_json_schema()function (line 50) only setadditionalProperties = falsewhen the key was not already present:This conditional approach failed for Pydantic models with
extra="allow"because those models already have"additionalProperties": truein their schema.Solution
Modified the code to always set
additionalProperties = falsefor object types, regardless of whether the key already exists:Changes
src/openai/lib/_pydantic.py: Updated_ensure_strict_json_schema()to unconditionally setadditionalProperties = falsetest_pydantic_extra_allow()intests/lib/test_pydantic.pyto verify the fixTesting
Manual Testing
Reproduced the issue from #2740 and verified the fix resolves it:
Before fix:
After fix:
Test Coverage
Added comprehensive test that verifies:
extra="allow"correctly generateadditionalProperties: falseBackward Compatibility
This change is backward compatible:
extra="allow"already hadadditionalProperties: falseextra="allow"now work correctly (previously failed)References
extra="allow"#2740