Parsed Chat Completions emit false serialization warnings and fail with `warnings="error"`

未关闭 适合新手
#4,287 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 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

  1. Use upstream main at f56a67f1f0c844135261ece304a90d2ec2571d4b (declared SDK version 3.54.0), Python 3.10.16, and Pydantic 2.12.5.
  2. Run the snippet below. It uses synthetic data and a mock HTTP transport, so no real API key or network request is needed.
  3. The isinstance(..., Invoice) assertion succeeds, but model_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

环境准备

在 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 摘要。