Hacktoberfest 2026: los issues que los mantenedores marcaron para octubre, abiertos y aptos para principiantes. Explorar issues de Hacktoberfest

Improper handling of pydantic `extra="allow"`

Abierto
#2,740 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

@yashwantbezawada ya está trabajando en esto.

Desde el 9/11/2025.

  • #2741 de @yashwantbezawada — cerrado sin fusionar
  • #2743 de @yashwantbezawada — abierto
  • #3805 de @Bhumika-1432006 — cerrado sin fusionar

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
55/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Estancado
Stack tecnológico
python
Área
api

Línea de trabajo

Empieza por src/openai/lib/_pydantic.py y el método to_strict_json_schema en la línea enlazada. Ejecuta el ejemplo MyClass reportado o llama a to_strict_json_schema(MyClass) para inspeccionar el esquema generado. Está hecho cuando un modelo Pydantic de nivel superior que usa extra="allow" produce additionalProperties: false y deja de provocar el error reportado de response_format.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

bug
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

The response_format option requires "additionalProperties": false to be present in the json schema that is submitted. When using Pydantic models, setting the extra="allow" option causes the json schema return addtionalProperties=True. The to_strict_json_schema method attempts to fix this, but doesn't correctly handle top-level models with extra="allow". In particular, the bug is here, where it only sets additionalProperties=False when the key is not already present, rather than always as required by the API.

Per the support forum, the library should be handling this, but is not.

To Reproduce

I set up a venv with the latest versions of pydantic and openai:

python3.10 -m venv /tmp/openaivenv
/tmp/openaivenv/bin/pip install openai pydantic ipython
/tmp/openaivenv/bin/ipython

Then run a simple chat completion with a response format:

from openai import AsyncOpenAI
from pydantic import BaseModel, ConfigDict
client = AsyncOpenAI()  # set OPENAI_API_KEY env variable

class MyClass(BaseModel):
    model_config = ConfigDict(extra="allow")
    field: str

response = await client.beta.chat.completions.parse(
    model='gpt-4.1',
    messages=[
        {
            "role": "user",
            "content": "Yo i need some fake data for a test plz halp."
        },
    ],
    response_format=MyClass,
)

This outputs a 400 bad request:

BadRequestError: Error code: 400 - {'error': {'message': "Invalid schema for response_format 'MyClass': In context=(), 'additionalProperties' is required to be supplied and to be false.", 'type': 'invalid_request_error', 'param': 'response_format', 'code': None}}

The cause is that the schema is not correctly updated:

In [2]: from openai.lib._pydantic import to_strict_json_schema
   ...:

In [3]: to_strict_json_schema(MyClass)
   ...:
Out[3]:
{'additionalProperties': True,
 'properties': {'field': {'title': 'Field', 'type': 'string'}},
 'required': ['field'],
 'title': 'MyClass',
 'type': 'object'}

The examples above are using the following versions:

# /tmp/openaivenv/bin/python --version
Python 3.10.12
# /tmp/openaivenv/bin/pip freeze | grep -P 'openai|pydantic'
openai==2.7.1
pydantic==2.12.4
pydantic_core==2.41.5
Code snippets

OS

ubuntu

Python version

python v3.1

Library version

2.7.1

Lenguaje dominante
Python
Estrellas
31.8k
Forks
7.3k
Merge medio
1 d 3 h
PR fusionados (30 d)
131

Preparar el entorno

Abrir en Codespaces

Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de openai/openai-python

Todos los issues de openai/openai-python

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.