Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Openai Openai python BaseModel Validation

From Leeroopedia
Knowledge Sources
Domains SDK_Infrastructure, Python
Last Updated 2026-02-15 00:00 GMT

Overview

Concrete tool for Pydantic model base classes and type construction provided by the openai-python SDK.

Description

The _models.py module (913 lines) extends Pydantic's BaseModel to provide the foundation for all API response and request models in the SDK. It supports both Pydantic v1 and v2 through compatibility shims. Key components:

  1. BaseModel (line 101): Extends pydantic.BaseModel with:
    • extra="allow" configuration to handle unknown API fields gracefully
    • to_dict() method (line 139): Serializes the model to a dictionary with options for mode ("json" or "python"), use_api_names (uses field aliases by default), exclude_unset, exclude_defaults, and exclude_none
    • to_json() method (line 177): Serializes to a JSON string with indentation (default indent=2), wrapping model_dump_json()
    • construct() class method (line 221): Overrides Pydantic's construct() to support recursive construction without validation. Iterates model fields, resolves aliases, constructs nested types via _construct_field(), and handles extra fields. Sets pydantic-internal attributes (__pydantic_private__, __pydantic_extra__, __pydantic_fields_set__) for v2 or __fields_set__ for v1
    • _request_id property: Stores the x-request-id header value on top-level response objects (not nested)
    • Pydantic v1 compatibility: Provides model_dump() and model_dump_json() shims that delegate to the v1 dict() and json() methods
  1. GenericModel (line 792-796): Subclasses both the compat BaseGenericModel and the SDK BaseModel. Used as the base for generic typed models like paginated responses. Under TYPE_CHECKING, aliased to BaseModel to simplify type checker behavior.
  1. FinalRequestOptions (line 851): A Pydantic model (not extending the SDK BaseModel) that captures final request configuration: method, url, params, headers, max_retries, timeout, files, json_data, extra_json, content, post_parser, and follow_redirects. Its construct() override strips NotGiven sentinel values.
  1. Type construction utilities:
    • construct_type(value, type_, metadata) (line 508): Loosely coerces a value to the expected type. Handles unions (with discriminated union support), dicts, lists, BaseModel subclasses (via .construct()), datetime/date parsing, and float coercion
    • validate_type(type_, value) (line 758): Strict validation via Pydantic's TypeAdapter (v2) or RootModel (v1)
    • build(base_model_cls, **kwargs) (line 476): Type-safe construction helper
    • DiscriminatorDetails (line 636): Caches discriminated union metadata for efficient variant selection

Usage

All API response types in the SDK inherit from this BaseModel. Use to_dict() and to_json() for serialization. The construct() method is used internally for fast, validation-free model instantiation from API response JSON.

Code Reference

Source Location

Signature

class BaseModel(pydantic.BaseModel):
    def to_dict(
        self,
        *,
        mode: Literal["json", "python"] = "python",
        use_api_names: bool = True,
        exclude_unset: bool = True,
        exclude_defaults: bool = False,
        exclude_none: bool = False,
        warnings: bool = True,
    ) -> dict[str, object]: ...

    def to_json(
        self,
        *,
        indent: int | None = 2,
        use_api_names: bool = True,
        exclude_unset: bool = True,
        exclude_defaults: bool = False,
        exclude_none: bool = False,
        warnings: bool = True,
    ) -> str: ...

    @classmethod
    def construct(
        __cls: Type[ModelT],
        _fields_set: set[str] | None = None,
        **values: object,
    ) -> ModelT: ...

class GenericModel(BaseGenericModel, BaseModel): ...

class FinalRequestOptions(pydantic.BaseModel):
    method: str
    url: str
    params: Query = {}
    headers: Union[Headers, NotGiven] = NotGiven()
    max_retries: Union[int, NotGiven] = NotGiven()
    timeout: Union[float, Timeout, None, NotGiven] = NotGiven()
    files: Union[HttpxRequestFiles, None] = None
    json_data: Union[Body, None] = None
    extra_json: Union[AnyMapping, None] = None

def construct_type(*, value: object, type_: object, metadata: Optional[List[Any]] = None) -> object: ...
def validate_type(*, type_: type[_T], value: object) -> _T: ...

Import

from openai import BaseModel
from openai._models import BaseModel, GenericModel, FinalRequestOptions
from openai._models import construct_type, validate_type

I/O Contract

Inputs (BaseModel.to_dict)

Name Type Required Description
mode Literal["json", "python"] No "json" for JSON-safe types, "python" for native Python objects. Default: "python"
use_api_names bool No Use API field aliases as keys. Default: True
exclude_unset bool No Exclude fields not explicitly set. Default: True
exclude_defaults bool No Exclude fields with default values. Default: False
exclude_none bool No Exclude fields with None values. Default: False
warnings bool No Log serialization warnings (Pydantic v2 only). Default: True

Outputs

Name Type Description
to_dict() return dict[str, object] Dictionary representation of the model
to_json() return str JSON string representation of the model
construct() return ModelT Instance created without validation

Usage Examples

Serialization

from openai import OpenAI

client = OpenAI()
completion = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Hello"}]
)

# Convert to dictionary using API field names
data = completion.to_dict()

# Convert to formatted JSON string
json_str = completion.to_json(indent=2)

# Access the request ID
print(completion._request_id)

Construction Without Validation

from openai._models import BaseModel

class MyModel(BaseModel):
    name: str
    value: int

# Fast construction without validation
obj = MyModel.construct(name="test", value=42)

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment