Parsed Chat Completions emit false serialization warnings and fail with `warnings="error"`
Maintainer thường phản hồi trong vòng 1 ngày
Chưa có ai nhận issue này.
Đánh giá
- Độ khó
- 2/5
- Thời gian dự kiến
- 1-3 giờ
- Mức phù hợp với người mới
- 78/100
- Loại issue
- Lỗi
- Độ rõ ràng
- Đặc tả rõ ràng
- Mức độ hoạt động
- Sôi nổi
- Công nghệ
- python
- Lĩnh vực
- backend-api-design, testing
Hướng nghiên cứu
Bắt đầu với src/openai/lib/_parsing/_completions.py, đặc biệt là phần khởi tạo ParsedChoice và ParsedChatCompletion được mô tả trong issue, sau đó kiểm tra các bài kiểm thử parsing của Chat Completions. Bổ sung kiểm thử hồi quy cho thấy các phản hồi đã parse hợp lệ được serialize mà không có cảnh báo và việc serialize strict thành công, trong khi các sai khác thực sự vẫn phát cảnh báo hoặc gây ra ngoại lệ. Issue đề cập đến các kiểm thử hồi quy đồng bộ và bất đồng bộ hiện có, cùng một mẫu sửa lỗi trong PR #3088.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Mô tả
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
- Ngôn ngữ chính
- Python
- Star
- 32.2k
- Fork
- 5.8k
- Merge trung bình
- 12 giờ 29 phút
- Pull request đã merge (30 ngày)
- 112
Chuẩn bị môi trường
Khởi chạy dev container của dự án ngay trên trình duyệt, bằng tài khoản GitHub của bạn.
- Không có Dockerfile hay tệp Docker Compose
- Có mẫu pull request
- Đọc hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Issue khác của openai/openai-python
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 76/100
openai/openai-python#4338 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
bug
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 65/100
openai/openai-python#4337 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
`BaseClient._prepare_url()` corrupts relative endpoint URLs when `base_url` contains query parametersCó thể đã có người làm @Rewaskc02-lang đã nhận 1 ngày trước. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 78/100
openai/openai-python#4311 · 4 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 78/100
openai/openai-python#4310 · 1 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 82/100
openai/openai-python#4309 · 1 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
Tất cả issue của openai/openai-python
Issue tương tự
-
triage
Độ khó 1/5 1-3 giờ Mức phù hợp với người mới 88/100
kornia/kornia-rs#1416 · 1 bình luận ·
Maintainer thường phản hồi trong vòng 2 ngày
-
ui
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 78/100
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 76/100
PolicyEngine/ai-inequality#64 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
LinearGaussianStateSpace.dist splits states and observations wrongly when the transition varies over timeCó thể đã có người làm @PabloRoque đã nhận hôm nay. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 88/100
pymc-devs/pymc-extras#839 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 76/100
Maintainer thường phản hồi trong vòng 1 ngày