{"record":{"id":"da0dbd1bfeadf56d","repo":"openai/openai-python","slug":"unsupported-type-expected-cast-to-to-be-a-subcl","errorCode":null,"errorMessage":"Unsupported type, expected {cast_to} to be a subclass of {BaseModel}, {dict}, {list}, {Union}, {NoneType}, {str} or {httpx2.Response}.","messagePattern":"Unsupported type, expected (.+?) to be a subclass of (.+?), (.+?), (.+?), (.+?), (.+?), (.+?) or (.+?)\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"src/openai/_legacy_response.py","lineNumber":305,"sourceCode":"            return cast(R, response)\n\n        if (\n            inspect.isclass(\n                origin  # pyright: ignore[reportUnknownArgumentType]\n            )\n            and not issubclass(origin, BaseModel)\n            and issubclass(origin, pydantic.BaseModel)\n        ):\n            raise TypeError(\"Pydantic models must subclass our base model type, e.g. `from openai import BaseModel`\")\n\n        if (\n            cast_to is not object\n            and not origin is list\n            and not origin is dict\n            and not origin is Union\n            and not issubclass(origin, BaseModel)\n        ):\n            raise RuntimeError(\n                f\"Unsupported type, expected {cast_to} to be a subclass of {BaseModel}, {dict}, {list}, {Union}, {NoneType}, {str} or {httpx2.Response}.\"\n            )\n\n        # split is required to handle cases where additional information is included\n        # in the response, e.g. application/json; charset=utf-8\n        content_type, *_ = response.headers.get(\"content-type\", \"*\").split(\";\")\n        if not content_type.endswith(\"json\"):\n            if is_basemodel(cast_to):\n                try:\n                    data = response.json()\n                except Exception as exc:\n                    log.debug(\"Could not read JSON from response data due to %s\", type(exc).__name__)\n                else:\n                    return self._client._process_response_data(\n                        data=data,\n                        cast_to=cast_to,  # type: ignore\n                        response=response,\n                    )","sourceCodeStart":287,"sourceCodeEnd":323,"githubUrl":"https://github.com/openai/openai-python/blob/9917c6e28e66e90e1227b3d223c06a8c5441515a/src/openai/_legacy_response.py#L287-L323","documentation":"The runtime cast_to validation allows only: the SDK BaseModel, dict, list, Union, None, str, or httpx.Response (and object). Any other class — or a non-class value such as a string or instance — reaches this branch and raises a RuntimeError listing the supported types.","triggerScenarios":"Passing cast_to=str-typo values like cast_to='MyModel' (a string instead of a class), cast_to=int/float/tuple/typing.Any-like objects, or a class not deriving from the allowed roots; also passing a generic alias the parser does not recognize.","commonSituations":"Dynamically computing cast_to from a mapping or config string and forgetting to resolve it to the actual class; passing typing constructs unsupported by this parser; refactors that change a model's base class.","solutions":["Ensure cast_to is an actual class deriving from openai.BaseModel (or dict/list/Union/None/str/httpx.Response)","If cast_to comes from a string, resolve it via a registry: {'my_model': MyModel}.get(name)","Add a unit test asserting the configured cast_to value passes issubclass(x, BaseModel) or is in the allowed set"],"exampleFix":"# before\nresp = client.get('/models', cast_to='Model', ...)\n# after\nresp = client.get('/models', cast_to=Model, ...)\n","handlingStrategy":"type-guard","validationCode":"from openai import BaseModel\nimport httpx, typing\nALLOWED_EXACT = {dict, list, str, httpx.Response, object, None}\ndef check_cast(t):\n    ok = t in ALLOWED_EXACT or (isinstance(t, type) and issubclass(t, BaseModel)) or typing.get_origin(t) is typing.Union\n    assert ok, f'unsupported cast_to: {t!r}'\ncheck_cast(cast_to)","typeGuard":"def is_supported_cast_to(t: object) -> bool:\n    import typing, httpx\n    from openai import BaseModel\n    return t in {dict, list, str, httpx.Response, object} or (isinstance(t, type) and issubclass(t, BaseModel)) or typing.get_origin(t) is typing.Union","tryCatchPattern":"try:\n    parsed = response.parse()\nexcept RuntimeError as e:\n    if 'Unsupported type' in str(e):\n        parsed = response.parse() if False else response.text","preventionTips":["Resolve cast_to strings through an explicit class registry","Unit-test that configured cast_to values pass the allowed-set check"],"tags":["cast-to","typing","runtime-validation"],"backgroundTag":"invalid-type-argument","analyzedSha":"9917c6e28e66e90e1227b3d223c06a8c5441515a","analyzedAt":"2026-08-28T11:46:34.183Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}