openai/openai-python · error · TypeError

Pydantic models must subclass our base model type, e.g. `fro

Error message

Pydantic models must subclass our base model type, e.g. `from openai import BaseModel`

What it means

The SDK requires Pydantic models passed via `cast_to` to subclass its own re-exported BaseModel (from openai import BaseModel), not a directly imported pydantic.BaseModel. The SDK's BaseModel carries extra pydantic config the parser relies on, so foreign pydantic models are rejected with a TypeError.

Source

Thrown at src/openai/_response.py:229

        response_types = http_response_types()
        if inspect.isclass(origin) and issubclass(origin, response_types):
            # Because of the invariance of our ResponseT TypeVar, users can subclass httpx.Response
            # and pass that class to our request functions. We cannot change the variance to be either
            # covariant or contravariant as that makes our usage of ResponseT illegal. We could construct
            # the response class ourselves but that is something that should be supported directly in httpx
            # as it would be easy to incorrectly construct the Response object due to the multitude of arguments.
            if cast_to not in response_types:
                raise ValueError("Subclasses of HTTP response classes cannot be passed to `cast_to`")
            return cast(R, response)

        if (
            inspect.isclass(
                origin  # pyright: ignore[reportUnknownArgumentType]
            )
            and not issubclass(origin, BaseModel)
            and issubclass(origin, pydantic.BaseModel)
        ):
            raise TypeError("Pydantic models must subclass our base model type, e.g. `from openai import BaseModel`")

        if (
            cast_to is not object
            and not origin is list
            and not origin is dict
            and not origin is Union
            and not issubclass(origin, BaseModel)
        ):
            raise RuntimeError(
                f"Unsupported type, expected {cast_to} to be a subclass of {BaseModel}, {dict}, {list}, {Union}, {NoneType}, {str} or {httpx2.Response}."
            )

        # split is required to handle cases where additional information is included
        # in the response, e.g. application/json; charset=utf-8
        content_type, *_ = response.headers.get("content-type", "*").split(";")
        if not content_type.endswith("json"):
            if is_basemodel(cast(type, cast_to)):
                try:

View on GitHub (pinned to 9917c6e28e)

Solutions

  1. Change the model's base class: `from openai import BaseModel` and subclass that
  2. If using generated models, regenerate or ensure they import BaseModel from the openai package
  3. For arbitrary dict-like data, use cast_to=dict or object instead of a pydantic model

Example fix

// before
import pydantic
class MyModel(pydantic.BaseModel):
    id: str

// after
from openai import BaseModel
class MyModel(BaseModel):
    id: str
Defensive patterns

Strategy: validation

Validate before calling

from openai import BaseModel as OpenAIBaseModel
import pydantic

def validate_model(model: type) -> None:
    if issubclass(model, pydantic.BaseModel) and not issubclass(model, OpenAIBaseModel):
        raise TypeError(f"{model.__name__} must subclass openai.BaseModel")

Type guard

def uses_openai_base_model(model: type) -> bool:
    from openai import BaseModel
    return isinstance(model, type) and issubclass(model, BaseModel)

Try / catch

try:
    result = client.post(..., cast_to=MyModel)
except TypeError as e:
    if 'base model' in str(e):
        # switch base class and retry
        ...

Prevention

When it happens

Trigger: Calling client.post(..., cast_to=MyModel) or a typed API method where MyModel subclasses pydantic.BaseModel directly (or a BaseModel from another library version) instead of openai.BaseModel.

Common situations: Copying model definitions from pydantic tutorials, sharing model classes between an app and the SDK, or pydantic v1/v2 import mismatches where the model resolves to plain pydantic.BaseModel.

Related errors


AI-assisted analysis of openai/openai-python@9917c6e28e (2026-08-28). Data as JSON: /api/errors/203f54a0d6b096b6. Report an issue: GitHub.