`BaseModel.construct()` leaks consumed field aliases into `model_extra`, emitting duplicate JSON keys and shadowing field mutations

Open Beginner friendly
#4,310 1 comment 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
78/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
python
Domain
backend

Research direction

Start in src/openai/_models.py at BaseModel.construct(), where declared fields are resolved via field.alias and extras are then collected with if key not in model_fields. Record the alias keys consumed by the first loop and exclude them when building _extra, watching both the Pydantic v1 and v2 branches in that method. Done means construct_type() on ResponseFunctionToolCall with async leaves model_extra empty, to_json() emits a single async key, and a mutated async_ shows up in to_dict().

Written by the indexing model from the issue text.

Description

Confirm this is an issue with the Python library and not an underlying OpenAI API
  • This is an issue with the Python library
Describe the bug

In src/openai/_models.py, BaseModel.construct() populates declared fields by resolving each field's alias (field.alias), but then collects extra fields by checking only if key not in model_fields: (lines 269–293):

model_fields = get_model_fields(__cls)
for name, field in model_fields.items():
    key = field.alias
    if key is None or (key not in values and populate_by_name):
        key = name

    if key in values:
        fields_values[name] = _construct_field(value=values[key], field=field, key=key)
        _fields_set.add(name)
    else:
        fields_values[name] = field_get_default(field)

extra_field_type = _get_extra_fields_type(__cls)

_extra = {}
for key, value in values.items():
    if key not in model_fields:
        ...
        _extra[key] = parsed

Because model_fields is keyed by Python attribute names (e.g., "async_", "schema_") rather than wire aliases (e.g., "async", "schema"), every consumed alias key is also copied into __pydantic_extra__ (model_extra) (and into __dict__ / __fields_set__ on Pydantic v1).

Since default API response deserialization (construct_type) uses BaseModel.construct(), this affects every aliased field in src/openai/types/ (e.g., ResponseFunctionToolCall.async_, ResponseFormatTextJSONSchemaConfig.schema_, etc.):

  1. model.model_extra is polluted with already-parsed declared fields.
  2. model.to_json() emits duplicate JSON keys out of the box (e.g., "async":true,"async":true or "schema":{...},"schema":{...}).
  3. model.model_dump() and model.to_dict(use_api_names=False) emit both the attribute name and the wire alias.
  4. Mutating an aliased attribute (e.g., fc.async_ = False) is silently overwritten by the stale entry in model_extra on to_dict() and emits conflicting duplicate keys on to_json().
To Reproduce
  1. Construct any SDK model with an aliased field via construct_type() or Model.construct(), such as ResponseFunctionToolCall (async_ / "async") or ResponseFormatTextJSONSchemaConfig (schema_ / "schema").
  2. Inspect model.model_extra, model.to_json(indent=None), and model.to_dict(use_api_names=False).
  3. Mutate the aliased field (fc.async_ = False) and inspect fc.to_dict()["async"] and fc.to_json(indent=None).
Code snippets
from openai._models import construct_type
from openai.types.responses import (
    ResponseFormatTextJSONSchemaConfig,
    ResponseFunctionToolCall,
)

fc = construct_type(
    type_=ResponseFunctionToolCall,
    value={
        "type": "function_call",
        "call_id": "call_1",
        "name": "do_work",
        "arguments": "{}",
        "async": True,
    },
)
print("model_extra:", fc.model_extra)
# {'async': True}

print("to_json:", fc.to_json(indent=None))
# {"arguments":"{}","call_id":"call_1","name":"do_work","type":"function_call","async":true,"async":true}

print("to_dict(use_api_names=False):", fc.to_dict(use_api_names=False))
# {'arguments': '{}', 'call_id': 'call_1', 'name': 'do_work', 'type': 'function_call', 'async_': True, 'async': True}

fc.async_ = False
print("after mutation to_dict['async']:", fc.to_dict()["async"])
# True  (stale extra overwrites mutated field!)
print("after mutation to_json:", fc.to_json(indent=None))
# {"arguments":"{}","call_id":"call_1","name":"do_work","type":"function_call","async":false,"async":true}

cfg = construct_type(
    type_=ResponseFormatTextJSONSchemaConfig,
    value={
        "type": "json_schema",
        "name": "answer",
        "schema": {"type": "object", "properties": {}},
    },
)
print("cfg to_json:", cfg.to_json(indent=None))
# {"name":"answer","schema":{"type":"object","properties":{}},"type":"json_schema","schema":{"type":"object","properties":{}}}
Suggested fix

Track consumed input keys during the field-construction loop and exclude them when populating extras:

--- a/src/openai/_models.py
+++ b/src/openai/_models.py
@@ -267,6 +267,7 @@ class BaseModel(pydantic.BaseModel):
             _fields_set = set()
 
         model_fields = get_model_fields(__cls)
+        consumed_keys: set[str] = set()
         for name, field in model_fields.items():
             key = field.alias
             if key is None or (key not in values and populate_by_name):
@@ -275,6 +276,7 @@ class BaseModel(pydantic.BaseModel):
             if key in values:
                 fields_values[name] = _construct_field(value=values[key], field=field, key=key)
                 _fields_set.add(name)
+                consumed_keys.add(key)
             else:
                 fields_values[name] = field_get_default(field)
 
@@ -282,7 +284,7 @@ class BaseModel(pydantic.BaseModel):
 
         _extra = {}
         for key, value in values.items():
-            if key not in model_fields:
+            if key not in consumed_keys and key not in model_fields:
                 parsed = construct_type(value=value, type_=extra_field_type) if extra_field_type is not None else value
 
                 if PYDANTIC_V1:
OS

macOS

Python version

Python 3.14

Library version

openai v3.57.0 (main@f63f14b)

Dominant language
Python
Stars
32.2k
Forks
5.8k
Avg merge
12h 29m
Merged PRs (30d)
112

Getting set up

Open in Codespaces

Starts the project's dev container in your browser, under your own GitHub account.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from openai/openai-python

All issues in openai/openai-python

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.