{"record":{"id":"ade3eb90d3020fea","repo":"openai/openai-python","slug":"subclasses-of-http-response-classes-cannot-be-pass-ade3eb","errorCode":null,"errorMessage":"Subclasses of HTTP response classes cannot be passed to `cast_to`","messagePattern":"Subclasses of HTTP response classes cannot be passed to `cast_to`","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/openai/_response.py","lineNumber":219,"sourceCode":"        if cast_to == bool:\n            return cast(R, response.text.lower() == \"true\")\n\n        # handle the legacy binary response case\n        if inspect.isclass(cast_to) and cast_to.__name__ == \"HttpxBinaryResponseContent\":\n            return cast(R, cast_to(response))  # type: ignore\n\n        if origin == APIResponse:\n            raise RuntimeError(\"Unexpected state - cast_to is `APIResponse`\")\n\n        response_types = http_response_types()\n        if inspect.isclass(origin) and issubclass(origin, response_types):\n            # Because of the invariance of our ResponseT TypeVar, users can subclass httpx.Response\n            # and pass that class to our request functions. We cannot change the variance to be either\n            # covariant or contravariant as that makes our usage of ResponseT illegal. We could construct\n            # the response class ourselves but that is something that should be supported directly in httpx\n            # as it would be easy to incorrectly construct the Response object due to the multitude of arguments.\n            if cast_to not in response_types:\n                raise ValueError(\"Subclasses of HTTP response classes cannot be passed to `cast_to`\")\n            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        ):","sourceCodeStart":201,"sourceCodeEnd":237,"githubUrl":"https://github.com/openai/openai-python/blob/9917c6e28e66e90e1227b3d223c06a8c5441515a/src/openai/_response.py#L201-L237","documentation":"The SDK's response parsing rejects `cast_to` values that are subclasses of httpx response classes (e.g. a custom subclass of httpx.Response). Because the internal ResponseT TypeVar is invariant, the SDK cannot safely return a user-constructed response subclass, so it raises this ValueError to fail fast instead of returning a mistyped object.","triggerScenarios":"Calling any API method with `cast_to=MyResponse` where MyResponse subclasses httpx.Response (or another HTTP response class) but is not exactly the httpx.Response class itself, e.g. client.get('/foo', cast_to=CustomResponse).","commonSituations":"Developers migrating from raw httpx usage who wrap responses in custom classes, or who try to use `with_raw_response`-style patterns by passing a response subclass to cast_to.","solutions":["Pass cast_to=httpx.Response exactly if you want the raw response object, or omit cast_to to use the SDK default","Use the SDK's built-in `with_raw_response` API wrapper instead of subclassing httpx.Response","If you need extra fields, deserialize into a Pydantic model subclassing openai.BaseModel"],"exampleFix":"// before\nresp = client.get('/v1/models', cast_to=MyHttpResponse)  # subclass of httpx.Response\n\n// after\nresp = client.get('/v1/models', cast_to=httpx.Response)","handlingStrategy":"type-guard","validationCode":null,"typeGuard":"def is_valid_cast_to(cast_to: type) -> bool:\n    import httpx\n    if isinstance(cast_to, type) and issubclass(cast_to, httpx.Response):\n        return cast_to is httpx.Response\n    return True","tryCatchPattern":"try:\n    resp = client.get('/foo', cast_to=MyResponse)\nexcept ValueError as e:\n    if 'cast_to' in str(e):\n        resp = client.get('/foo', cast_to=httpx.Response)","preventionTips":["Always pass the exact httpx.Response class, never a subclass, to cast_to","Use with_raw_response for raw access patterns"],"tags":["cast-to","typing","httpx","response-parsing"],"backgroundTag":"invalid-cast-to-type","analyzedSha":"9917c6e28e66e90e1227b3d223c06a8c5441515a","analyzedAt":"2026-08-28T11:46:34.183Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}