`parse(to=...)` raises AttributeError on endpoints with a post-parser (embeddings, chat.completions.parse)

Aberta Para iniciantes
#4,338 0 comentários 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
76/100
Tipo de issue
Bug
Clareza
Claramente especificada
Status de atividade
Ativa
Stack de tecnologia
python

Direção de pesquisa

Leia LegacyAPIResponse.parse em _legacy_response.py e APIResponse.parse e AsyncAPIResponse.parse em _response.py; a issue identifica esses pontos como os locais onde o post-parser é executado incondicionalmente. Confira os testes existentes de parsing de respostas raw e streaming e, em seguida, verifique se parse(to=dict) funciona em embeddings e chat completions com um post-parser, enquanto o parsing padrão continua funcionando.

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

parse(to=...) on a raw or streaming response raises AttributeError when the endpoint has a post-parser. The post-parser still runs on the value built for to, and it expects the endpoint's default model.

  • client.embeddings.with_raw_response.create(...).parse(to=dict) raises AttributeError: 'dict' object has no attribute 'data' (same through with_streaming_response).
  • client.chat.completions.with_raw_response.parse(..., response_format=Model).parse(to=dict) raises AttributeError: 'dict' object has no attribute 'choices'.

On endpoints without a post-parser, such as chat.completions.create, parse(to=dict) returns the dict.

The post-parser is applied unconditionally in _legacy_response.py (LegacyAPIResponse.parse) and in _response.py (APIResponse.parse and AsyncAPIResponse.parse). Running it only when to is not given makes all of the calls above return the requested type.

To Reproduce
  1. Run the snippet below. It answers the request from a mock transport, so it needs no key and no network.
  2. The first parse() prints [0.5, -1.0].
  3. parse(to=dict) raises:
  File ".../openai/_legacy_response.py", line 140, in parse
    parsed = self._options.post_parser(parsed)
  File ".../openai/lib/_parsing/_embeddings.py", line 22, in parse_embedding_response
    if not obj.data:
AttributeError: 'dict' object has no attribute 'data'
Code snippets
import array
import base64

import httpx2
from openai import OpenAI

EMBED = {
    "object": "list",
    "model": "text-embedding-3-small",
    "data": [{"object": "embedding", "index": 0, "embedding": base64.b64encode(array.array("f", [0.5, -1.0]).tobytes()).decode()}],
    "usage": {"prompt_tokens": 1, "total_tokens": 1},
}
client = OpenAI(
    api_key="test",
    base_url="http://localhost/v1",
    http_client=httpx2.Client(transport=httpx2.MockTransport(lambda request: httpx2.Response(200, json=EMBED))),
)

raw = client.embeddings.with_raw_response.create(model="text-embedding-3-small", input="hi")
print(raw.parse().data[0].embedding)

raw = client.embeddings.with_raw_response.create(model="text-embedding-3-small", input="hi")
print(raw.parse(to=dict))
OS

Windows 11

Python version

Python v3.14.7

Library version

openai v3.60.0 (main at f2b2399)

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.