From 90f89b8721b41580ec2a8252981532749a031265 Mon Sep 17 00:00:00 2001 From: Sylvester Kaczmarek <16242628+sylvesterkaczmarek@users.noreply.github.com> Date: Tue, 25 Aug 2026 01:43:05 +0100 Subject: [PATCH] fix: strip examples from strict json schemas --- src/openai/lib/_pydantic.py | 5 ++++ tests/lib/test_pydantic_examples.py | 43 +++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 tests/lib/test_pydantic_examples.py diff --git a/src/openai/lib/_pydantic.py b/src/openai/lib/_pydantic.py index 3cfe224cb1..72ca2db43e 100644 --- a/src/openai/lib/_pydantic.py +++ b/src/openai/lib/_pydantic.py @@ -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(): diff --git a/tests/lib/test_pydantic_examples.py b/tests/lib/test_pydantic_examples.py new file mode 100644 index 0000000000..0418f9fac1 --- /dev/null +++ b/tests/lib/test_pydantic_examples.py @@ -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"]