Parsed Chat Completions emit false serialization warnings and fail with `warnings="error"`
維護者通常 1 天內回覆
還沒有人認領這個 Issue。
評估
- 難度
- 2/5
- 預估耗時
- 1-3 小時
- 新手友好度
- 78/100
- Issue 類型
- 缺陷
- 描述清晰度
- 描述清楚
- 活躍度
- 活躍
- 技術堆疊
- python
研究方向
從 src/openai/lib/_parsing/_completions.py 開始,特別檢查 issue 中描述的 ParsedChoice 和 ParsedChatCompletion 建構方式,接著查看 Chat Completions 的解析測試。新增回歸測試,證明有效的已解析回應可以在沒有警告的情況下序列化,且嚴格序列化能夠成功;真正的不相符仍應發出警告或引發例外。issue 提到現有的同步和非同步回歸測試,以及 PR #3088 中的修正模式。
由索引模型根據 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
client.chat.completions.parse(..., response_format=Invoice) successfully returns a completion containing a valid Invoice at completion.choices[0].message.parsed. Serializing the complete SDK response emits a false PydanticSerializationUnexpectedValue warning saying that parsed should be None.
With completion.model_dump_json(warnings="error"), the same valid response raises PydanticSerializationError. A caller saving the complete response as an audit record can therefore fail that persistence step after a successful parse.
Expected: both normal and strict serialization succeed for a valid parsed response; genuine serialization mismatches continue to warn or raise.
Actual: strict serialization raises:
pydantic_core._pydantic_core.PydanticSerializationError: Pydantic serializer warnings:
PydanticSerializationUnexpectedValue(Expected `none` - serialized value may not be as expected [field_name='parsed', ..., input_type=Invoice])
The cause is in parse_chat_completion: the SDK constructs ParsedChoice[ResponseFormatT] and ParsedChatCompletion[ResponseFormatT] at runtime using an unresolved type variable whose default is None. Pydantic then expects None for the already-parsed content.
The following two-line change fixes the reproduction, using the same bare runtime classes with static casts as the Responses parsing fix in #3088:
- type_=ParsedChoice[ResponseFormatT],
+ type_=cast("type[ParsedChoice[ResponseFormatT]]", ParsedChoice),
- type_=ParsedChatCompletion[ResponseFormatT],
+ type_=cast("type[ParsedChatCompletion[ResponseFormatT]]", ParsedChatCompletion),
This preserves existing content validation and public return annotations. It does not suppress serialization warnings. Public sync/async regression tests confirm that valid responses serialize, genuine mismatches still warn or raise, and user-model validators run once. With the change applied, the Chat, Responses, and model suites pass with Pydantic 2.12.5 (1,284 passed, 2 skipped) and Pydantic 1.10.26 (1,268 passed, 18 skipped); repository lint, formatting, and type checks also pass.
To Reproduce
- Use upstream main at
f56a67f1f0c844135261ece304a90d2ec2571d4b(declared SDK version 3.54.0), Python 3.10.16, and Pydantic 2.12.5. - Run the snippet below. It uses synthetic data and a mock HTTP transport, so no real API key or network request is needed.
- The
isinstance(..., Invoice)assertion succeeds, butmodel_dump_json(warnings="error")raises the exception above.
Code snippets
"""Reproduce parsed Chat Completion serialization without network calls or credentials."""
import json
import httpx2
from pydantic import BaseModel
from openai import OpenAI
class Invoice(BaseModel):
invoice_number: str
total_cents: int
def respond(request: httpx2.Request) -> httpx2.Response:
return httpx2.Response(
200,
json={
"id": "synthetic-completion",
"object": "chat.completion",
"created": 0,
"model": "gpt-4o-mini",
"choices": [{
"index": 0,
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": json.dumps({"invoice_number": "INV-001", "total_cents": 2500}),
},
}],
},
)
with OpenAI(
api_key="unused-synthetic-key",
http_client=httpx2.Client(transport=httpx2.MockTransport(respond)),
) as client:
completion = client.chat.completions.parse(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Extract the invoice."}],
response_format=Invoice,
)
assert isinstance(completion.choices[0].message.parsed, Invoice)
# A worker persisting an audit record could perform this serialization.
# Unpatched: PydanticSerializationError despite the valid Invoice above.
print(completion.model_dump_json(warnings="error"))
OS
macOS (Apple Silicon / arm64)
Python version
Python 3.10.16
Library version
openai 3.54.0 from upstream main at f56a67f1f0c844135261ece304a90d2ec2571d4b; Pydantic 2.12.5
- 主要語言
- 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 小時 新手友好度 78/100
openai/openai-python#4310 · 1 則留言 ·
維護者通常 1 天內回覆
-
難度 2/5 1-3 小時 新手友好度 82/100
openai/openai-python#4309 · 1 則留言 ·
維護者通常 1 天內回覆
查看 openai/openai-python 的全部 Issue
相似的 Issue
-
claude-subscription-directsdk: tool calls with raw control characters in string values are dropped未關閉
難度 2/5 1-3 小時 新手友好度 72/100
NousResearch/hermes-official-plugins#538 ·
維護者通常 3 天內回覆
-
bug(qdiffusion): EnergyModel.score_visible_logits computes biased visible/hidden on-ratios when solver returns variable solution counts per candidate可能已有人在做 @houzhongyu 今天認領。 未關閉
難度 2/5 1-3 小時 新手友好度 83/100
qboson/kaiwu-pytorch-plugin#2133 ·
維護者通常 2 天內回覆
-
難度 2/5 1-3 小時 新手友好度 82/100
維護者通常 1 天內回覆
-
needs-triage
難度 2/5 1-3 小時 新手友好度 78/100
MakazhanAlpamys/Soup#3415 ·
維護者通常 1 天內回覆
-
bug
難度 2/5 1-3 小時 新手友好度 78/100
維護者通常 2 天內回覆