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

Aperta Adatta ai principianti
#4,339 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
78/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python

Direzione di ricerca

Leggi _response.py e _legacy_response.py nei metodi _parse, poi verifica come _utils.is_union() gestisce types.UnionType. Riproduci il malfunzionamento con Python 3.12 usando lo snippet del trasporto mock nell’issue e confronta il comportamento di parsing della risposta grezza per A | None e Union[A, None]. Il lavoro è completato quando entrambi vengono analizzati correttamente nelle versioni precedenti a Python 3.14; esegui i test pertinenti di parsing delle risposte.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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)

Lingua principale
Python
Stelle
32.2k
Fork
5.8k
Merge medio
12h 31m
PR unite (30g)
101

Preparare l'ambiente

Apri in Codespaces

Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di openai/openai-python

Tutte le issue di openai/openai-python

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.