`BaseModel.construct()` leaks consumed field aliases into `model_extra`, emitting duplicate JSON keys and shadowing field mutations
維護者通常 1 天內回覆
還沒有人認領這個 Issue。
評估
研究方向
從 src/openai/_models.py 的 BaseModel.construct() 開始,其中宣告的欄位透過 field.alias 解析,隨後用 if key not in model_fields 收集 extras。記錄第一個迴圈消耗的 alias 鍵,並在建構 _extra 時排除它們,同時注意該方法中 Pydantic v1 和 v2 兩個分支。完成意味著 construct_type() 對 ResponseFunctionToolCall 在 async 下執行時使 model_extra 為空,to_json() 輸出單一 async 鍵,並且被修改的 async_ 會出現在 to_dict() 中。
由索引模型根據 Issue 內容生成。
描述
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.):
model.model_extrais polluted with already-parsed declared fields.model.to_json()emits duplicate JSON keys out of the box (e.g.,"async":true,"async":trueor"schema":{...},"schema":{...}).model.model_dump()andmodel.to_dict(use_api_names=False)emit both the attribute name and the wire alias.- Mutating an aliased attribute (e.g.,
fc.async_ = False) is silently overwritten by the stale entry inmodel_extraonto_dict()and emits conflicting duplicate keys onto_json().
To Reproduce
- Construct any SDK model with an aliased field via
construct_type()orModel.construct(), such asResponseFunctionToolCall(async_/"async") orResponseFormatTextJSONSchemaConfig(schema_/"schema"). - Inspect
model.model_extra,model.to_json(indent=None), andmodel.to_dict(use_api_names=False). - Mutate the aliased field (
fc.async_ = False) and inspectfc.to_dict()["async"]andfc.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)
- 主要語言
- Python
- 星號
- 32.2k
- 分支
- 5.8k
- 平均合併
- 12 小時 29 分鐘
- 30 天內合併 PR
- 112
環境準備
在瀏覽器裡用你自己的 GitHub 帳號啟動這個專案的開發容器。
- 沒有 Dockerfile 或 Docker Compose 檔案
- 有 Pull Request 範本
- 閱讀貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
openai/openai-python 的其他 Issue
-
難度 2/5 1-3 小時 新手友好度 76/100
openai/openai-python#4338 ·
維護者通常 1 天內回覆
-
bug
難度 2/5 1-3 小時 新手友好度 65/100
openai/openai-python#4337 ·
維護者通常 1 天內回覆
-
`BaseClient._prepare_url()` corrupts relative endpoint URLs when `base_url` contains query parameters可能已有人在做 @Rewaskc02-lang 於 1 天前認領。 未關閉
難度 2/5 1-3 小時 新手友好度 78/100
openai/openai-python#4311 · 4 則留言 ·
維護者通常 1 天內回覆
-
難度 2/5 1-3 小時 新手友好度 82/100
openai/openai-python#4309 · 1 則留言 ·
維護者通常 1 天內回覆
-
難度 1/5 1 小時以內 新手友好度 82/100
openai/openai-python#4308 · 1 則留言 ·
維護者通常 1 天內回覆
查看 openai/openai-python 的全部 Issue
相似的 Issue
-
triage
難度 1/5 1-3 小時 新手友好度 88/100
kornia/kornia-rs#1416 · 1 則留言 ·
維護者通常 2 天內回覆
-
ui
難度 2/5 1-3 小時 新手友好度 78/100
維護者通常 1 天內回覆
-
難度 2/5 1-3 小時 新手友好度 76/100
PolicyEngine/ai-inequality#64 ·
維護者通常 1 天內回覆
-
LinearGaussianStateSpace.dist splits states and observations wrongly when the transition varies over time可能已有人在做 @PabloRoque 今天認領。 未關閉
難度 2/5 1-3 小時 新手友好度 88/100
pymc-devs/pymc-extras#839 ·
維護者通常 1 天內回覆
-
難度 2/5 1-3 小時 新手友好度 76/100
維護者通常 1 天內回覆