Why do `pydantic_function_tool` mark all fields as required?
Confirm this is an issue with the Python library and not an underlying OpenAI API
- [x] This is an issue with the Python library
Describe the bug
When using pydantic_function_tool, I noticed that all fields in a Pydantic model are forcibly marked as required in the generated JSON Schema, even if they have default values or are explicitly marked as optional. This behavior seems inconsistent with JSON Schema specifications, which state that only fields explicitly listed in the required array should be mandatory.
I would like to confirm whether this behavior is intentional. If so, could you please clarify the design decision behind it?
Related code: https://github.com/openai/openai-python/blob/7193688e364bd726594fe369032e813ced1bdfe2/src/openai/lib/_pydantic.py#L57
To Reproduce
- run the code snippets
- check "required" in the printed json schema
Code snippets
from pydantic import BaseModel, Field
from typing import Optional
from openai import pydantic_function_tool
import json
class MyModel(BaseModel):
required_field: int = Field(description="This is a required field")
optional_field: Optional[int] = Field(default=None, description="This is an optional field")
# use the model_json_schema method to get the schema
# only "required_field" is listed:
# "required": [
# "required_field"
# ]
print(json.dumps(MyModel.model_json_schema(), indent=2))
# use the pydantic_function_tool to get the schema
# all the fields are listed:
# "required": [
# "required_field",
# "optional_field"
# ]
print(json.dumps(pydantic_function_tool(MyModel), indent=2))
OS
all
Python version
all
Library version
openai>=1.40.0
Yes this behaviour is intentional, all fields will be marked as required but fields that are optional will specify that they can be nullable (e.g. nullable: true). This is because the OpenAI API enforces this shape, see these docs for more information https://platform.openai.com/docs/guides/structured-outputs#supported-schemas.