`parse(to=A | None)` raises "Unsupported type" below Python 3.14 while `Union[A, None]` works

未關閉 適合新手
#4,339 1 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

維護者通常 1 天內回覆

還沒有人認領這個 Issue。

評估

難度
2/5
預估耗時
1-3 小時
新手友好度
78/100
Issue 類型
缺陷
描述清晰度
描述清楚
活躍度
活躍
技術堆疊
python

研究方向

閱讀 _response.py 和 _legacy_response.py 中的 _parse 方法,接著檢查 _utils.is_union() 如何處理 types.UnionType。使用 issue 中的 mock transport 程式片段在 Python 3.12 上重現故障,並比較 A | None 和 Union[A, None] 的原始回應解析行為。在 Python 3.14 之前的版本中兩者都能成功解析即為完成;執行相關的回應解析測試。

由索引模型根據 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

parse(to=...) on a raw response accepts Union[A, None] and Optional[A], but the same union written as A | None raises RuntimeError: Unsupported type on Python 3.12. On 3.14 both spellings work. I only ran 3.12 and 3.14; from the cause below, 3.10, 3.11 and 3.13 should behave like 3.12.

APIResponse._parse in _response.py and LegacyAPIResponse._parse in _legacy_response.py skip the "unsupported type" check with origin is Union. Below 3.14 the origin of A | None is types.UnionType, not typing.Union, so the check falls through to the error. The is_union() helper in _utils already handles both.

To Reproduce
  1. Run the snippet below on Python 3.12. It answers the request from a mock transport, so it needs no key and no network.
  2. Union[Model, None] and Optional[Model] return Model(id='m1').
  3. Model | None and dict | list raise:
RuntimeError: Unsupported type, expected __main__.Model | None to be a subclass of <class 'openai.BaseModel'>, <class 'dict'>, <class 'list'>, typing.Union, <class 'NoneType'>, <class 'str'> or <class 'httpx2.Response'>.

On Python 3.14.7 all four return a value.

Code snippets
from typing import Optional, Union

import httpx2
from openai import OpenAI
from pydantic import BaseModel

BODY = {"id": "m1", "object": "model", "created": 1, "owned_by": "x"}
client = OpenAI(
    api_key="test",
    base_url="http://localhost/v1",
    http_client=httpx2.Client(transport=httpx2.MockTransport(lambda request: httpx2.Response(200, json=BODY))),
)


class Model(BaseModel):
    id: str


for to in (Union[Model, None], Optional[Model], Model | None, dict | list):
    raw = client.models.with_raw_response.retrieve("m1")
    try:
        print(to, "->", repr(raw.parse(to=to)))
    except Exception as exc:
        print(to, "->", type(exc).__name__, exc)
OS

Windows 11

Python version

Python v3.12.14 (fails), v3.14.7 (works)

Library version

openai v3.60.0 (main at f2b2399)

主要語言
Python
星號
32.2k
分支
5.8k
平均合併
12 小時 31 分鐘
30 天內合併 PR
101

環境準備

在 Codespaces 中開啟

在瀏覽器裡用你自己的 GitHub 帳號啟動這個專案的開發容器。

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

openai/openai-python 的其他 Issue

查看 openai/openai-python 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。