Implementation:Openai Openai python BaseModel Validation
| 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:
BaseModel(line 101): Extendspydantic.BaseModelwith:extra="allow"configuration to handle unknown API fields gracefullyto_dict()method (line 139): Serializes the model to a dictionary with options formode("json"or"python"),use_api_names(uses field aliases by default),exclude_unset,exclude_defaults, andexclude_noneto_json()method (line 177): Serializes to a JSON string with indentation (defaultindent=2), wrappingmodel_dump_json()construct()class method (line 221): Overrides Pydantic'sconstruct()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_idproperty: Stores thex-request-idheader value on top-level response objects (not nested)- Pydantic v1 compatibility: Provides
model_dump()andmodel_dump_json()shims that delegate to the v1dict()andjson()methods
GenericModel(line 792-796): Subclasses both the compatBaseGenericModeland the SDKBaseModel. Used as the base for generic typed models like paginated responses. UnderTYPE_CHECKING, aliased toBaseModelto simplify type checker behavior.
FinalRequestOptions(line 851): A Pydantic model (not extending the SDKBaseModel) that captures final request configuration:method,url,params,headers,max_retries,timeout,files,json_data,extra_json,content,post_parser, andfollow_redirects. Itsconstruct()override stripsNotGivensentinel values.
- 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,BaseModelsubclasses (via.construct()),datetime/dateparsing, and float coercionvalidate_type(type_, value)(line 758): Strict validation via Pydantic'sTypeAdapter(v2) orRootModel(v1)build(base_model_cls, **kwargs)(line 476): Type-safe construction helperDiscriminatorDetails(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
- Repository: openai-python
- File: src/openai/_models.py
- Lines: 1-913
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)