openai-python icon indicating copy to clipboard operation
openai-python copied to clipboard

Why do `pydantic_function_tool` mark all fields as required?

Open Epsirom opened this issue 1 year ago • 1 comments

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

  1. run the code snippets
  2. 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

Epsirom avatar Feb 08 '25 10:02 Epsirom

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.

RobertCraigie avatar Feb 10 '25 08:02 RobertCraigie