{"record":{"id":"f36ee9ba61c68238","repo":"openai/openai-python","slug":"could-not-convert-data-into-a-valid-instance-of-t","errorCode":null,"errorMessage":"Could not convert data into a valid instance of {type_}","messagePattern":"Could not convert data into a valid instance of (.+?)","errorType":"validation","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"src/openai/_models.py","lineNumber":654,"sourceCode":"        #\n        # without this block, if the data we get is something like `{'kind': 'bar', 'value': 'foo'}` then\n        # we'd end up constructing `FooType` when it should be `BarType`.\n        discriminator = _build_discriminated_union_meta(union=type_, meta_annotations=meta)\n        if discriminator and is_mapping(value):\n            variant_value = value.get(discriminator.field_alias_from or discriminator.field_name)\n            if variant_value and isinstance(variant_value, str):\n                variant_type = discriminator.mapping.get(variant_value)\n                if variant_type:\n                    return construct_type(type_=variant_type, value=value)\n\n        # if the data is not valid, use the first variant that doesn't fail while deserializing\n        for variant in args:\n            try:\n                return construct_type(value=value, type_=variant)\n            except Exception:\n                continue\n\n        raise RuntimeError(f\"Could not convert data into a valid instance of {type_}\")\n\n    if origin == dict:\n        if not is_mapping(value):\n            return value\n\n        _, items_type = get_args(type_)  # Dict[_, items_type]\n        return {key: construct_type(value=item, type_=items_type) for key, item in value.items()}\n\n    if (\n        not is_literal_type(type_)\n        and inspect.isclass(origin)\n        and (issubclass(origin, BaseModel) or issubclass(origin, GenericModel))\n    ):\n        if is_list(value):\n            return [cast(Any, type_).construct(**entry) if is_mapping(entry) else entry for entry in value]\n\n        if is_mapping(value):\n            if issubclass(type_, BaseModel):","sourceCodeStart":636,"sourceCodeEnd":672,"githubUrl":"https://github.com/openai/openai-python/blob/9917c6e28e66e90e1227b3d223c06a8c5441515a/src/openai/_models.py#L636-L672","documentation":"construct_type() failed to coerce the incoming data into the annotated type. For Union types, every variant was attempted and each raised, so the data matches none of the allowed shapes and a RuntimeError summarizing the failure is raised.","triggerScenarios":"A response body or nested field doesn't match any variant of a Union type (e.g. expecting str or ChatCompletion but receiving an error object), or a manually constructed value passed to construct/build with mismatched keys/types.","commonSituations":"API returns an unexpected payload shape (error envelope, new field type) on an older SDK version; hand-building model instances with typo'd field names; partial data passed to construct_type.","solutions":["Log/inspect the raw value being converted and compare it against the model's expected fields","Upgrade the openai package to the latest version so response models match the current API schema","If building manually, pass the exact field names and types the model declares, or use construct()/build for non-validated construction"],"exampleFix":"// before\nconstruct_type(value={\"finshed\": True}, type_=CompletionUsage)\n// after\nconstruct_type(value={\"finished\": True}, type_=CompletionUsage)","handlingStrategy":"try-catch","validationCode":"if not isinstance(data, Mapping):\n    data = coerce_or_reject(data)","typeGuard":"def matches_model_shape(data: object, model: type[BaseModel]) -> bool:\n    return isinstance(data, Mapping) and all(k in model.model_fields for k in data)","tryCatchPattern":"try:\n    obj = construct_type(value=data, type_=MyUnion)\nexcept RuntimeError as e:\n    if 'Could not convert data' in str(e):\n        logger.error('unexpected payload shape: %r', data)\n    raise","preventionTips":["Keep the SDK version in sync with the API (regular upgrades)","Validate/log raw response bodies when debugging conversion failures","Use construct()/build for trusted local data instead of construct_type on untyped payloads"],"tags":["python","serialization","union","schema-mismatch","response-parsing"],"backgroundTag":"response-schema-mismatch","analyzedSha":"9917c6e28e66e90e1227b3d223c06a8c5441515a","analyzedAt":"2026-08-28T11:46:34.183Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}