Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/openai/lib/_pydantic.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ def _ensure_strict_json_schema(
if not is_dict(json_schema):
raise TypeError(f"Expected {json_schema} to be a dictionary; path={path}")

# `examples` is valid JSON Schema metadata but is not accepted by the
# API's strict structured-output schema dialect. It has no validation
# semantics, so removing it preserves the model contract.
json_schema.pop("examples", None)

defs = json_schema.get("$defs")
if is_dict(defs):
for def_name, def_schema in defs.items():
Expand Down
43 changes: 43 additions & 0 deletions tests/lib/test_pydantic_examples.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from __future__ import annotations

from pydantic import Field, BaseModel

from openai.lib._pydantic import to_strict_json_schema


class NestedExample(BaseModel):
value: str = Field(
description="A nested value",
examples=["alpha", "beta"],
)


class ExampleModel(BaseModel):
answer: str = Field(
description="The final answer",
examples=["x = -3", "x = 2"],
)
nested: NestedExample


def test_strict_json_schema_strips_examples_recursively() -> None:
schema = to_strict_json_schema(ExampleModel)

answer = schema["properties"]["answer"]
assert "examples" not in answer
assert answer["description"] == "The final answer"

nested_ref = schema["properties"]["nested"]
assert "examples" not in nested_ref

nested = schema["$defs"]["NestedExample"]["properties"]["value"]
assert "examples" not in nested
assert nested["description"] == "A nested value"


def test_strict_json_schema_keeps_validation_keywords() -> None:
schema = to_strict_json_schema(ExampleModel)

assert schema["type"] == "object"
assert schema["additionalProperties"] is False
assert schema["required"] == ["answer", "nested"]