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

Aberta Para iniciantes
#4,287 1 comentário 0 reações 0 responsáveis Ver no GitHub

Mantenedores costumam responder em até 1 dia

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
2/5
Tempo estimado
1-3 horas
Facilidade para iniciantes
78/100
Tipo de issue
Bug
Clareza
Claramente especificada
Status de atividade
Ativa
Stack de tecnologia
python

Direção de pesquisa

Comece por src/openai/lib/_parsing/_completions.py, especialmente pela construção de ParsedChoice e ParsedChatCompletion descrita na issue; em seguida, examine os testes de parsing de Chat Completions. Adicione cobertura de regressão mostrando que respostas válidas já parseadas são serializadas sem avisos e que a serialização estrita é bem-sucedida, enquanto incompatibilidades reais continuam gerando avisos ou exceções. A issue relata testes de regressão síncronos e assíncronos existentes e um padrão de correção em PR #3088.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

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

Linguagem predominante
Python
Estrelas
32.2k
Forks
5.8k
Merge médio
12h 29min
PRs com merge (30d)
112

Preparar o ambiente

Abrir no Codespaces

Inicia o contêiner de desenvolvimento do projeto no navegador, com a sua própria conta do GitHub.

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de openai/openai-python

Todas as issues de openai/openai-python

Issues semelhantes

Mais issues de Python

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.