Skip to content

Commit bcf94fb

Browse files
fix: preserve structured additionalProperties schemas for Dict types
Addresses review feedback: - Only set additionalProperties=False when it's True (from extra="allow") or missing, preserving structured schemas for Dict[str, T] types - Convert test to use inline snapshots as requested This fix ensures that Dict[str, T] typed fields maintain their structured additionalProperties schemas (e.g., {"type": "number"}) instead of being forced to False, which would break validation for dynamic keys.
1 parent cdebce9 commit bcf94fb

File tree

2 files changed

+14
-10
lines changed

2 files changed

+14
-10
lines changed

src/openai/lib/_pydantic.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,13 @@ def _ensure_strict_json_schema(
4848

4949
typ = json_schema.get("type")
5050
if typ == "object":
51-
# Always set additionalProperties to False for strict schema compliance.
51+
# Set additionalProperties to False for strict schema compliance, but preserve
52+
# structured schemas (e.g., for Dict[str, T] which needs {"additionalProperties": {schema}}).
5253
# The OpenAI API requires additionalProperties=false for structured output,
5354
# even if Pydantic models use extra="allow" which sets it to True.
54-
json_schema["additionalProperties"] = False
55+
additional_props = json_schema.get("additionalProperties")
56+
if additional_props is True or "additionalProperties" not in json_schema:
57+
json_schema["additionalProperties"] = False
5558

5659
# object types
5760
# { 'type': 'object', 'properties': { 'a': {...} } }

tests/lib/test_pydantic.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -426,11 +426,12 @@ class MyClassWithExtraAllow(BaseModel):
426426

427427
schema = to_strict_json_schema(MyClassWithExtraAllow)
428428

429-
# The schema must have additionalProperties set to False
430-
assert schema.get("additionalProperties") == False, \
431-
"additionalProperties must be False for API compliance, even with extra='allow'"
432-
433-
# Verify the rest of the schema is correct
434-
assert schema["type"] == "object"
435-
assert "field" in schema["properties"]
436-
assert schema["required"] == ["field"]
429+
assert schema == snapshot(
430+
{
431+
"properties": {"field": {"description": "A test field", "title": "Field", "type": "string"}},
432+
"required": ["field"],
433+
"title": "MyClassWithExtraAllow",
434+
"type": "object",
435+
"additionalProperties": False,
436+
}
437+
)

0 commit comments

Comments
 (0)