Skip to content

fix: coerce by_alias to bool in model_dump for pydantic v2 compatibility#2937

Open
atian8179 wants to merge 2 commits intoopenai:mainfrom
atian8179:fix/model-dump-by-alias-none
Open

fix: coerce by_alias to bool in model_dump for pydantic v2 compatibility#2937
atian8179 wants to merge 2 commits intoopenai:mainfrom
atian8179:fix/model-dump-by-alias-none

Conversation

@atian8179
Copy link

Problem

Enabling DEBUG logging causes TypeError: argument 'by_alias': 'NoneType' object cannot be converted to 'PyBool' on any API call.

Root Cause

model_dump() in _compat.py declares by_alias: bool | None = None and passes it directly to pydantic v2's model_dump(). Pydantic v2's Rust serializer doesn't accept None for by_alias.

The pydantic v1 fallback path already coerces with bool(by_alias) — the v2 path was missing this.

Fix

by_alias=bool(by_alias) if by_alias is not None else False,

Fixes #2921

When OPENAI_BASE_URL is set to an empty string, os.environ.get()
returns '' instead of None, bypassing the fallback to the default
API endpoint. This causes APIConnectionError.

Add 'or None' to coerce empty strings to None so the default
https://api.openai.com/v1 fallback is reached. Applied to both
sync (OpenAI) and async (AsyncOpenAI) clients.

Fixes openai#2927
Pydantic v2's Rust-based serializer rejects None for by_alias,
raising TypeError. The model_dump() wrapper passes by_alias=None
directly to pydantic v2, which crashes when DEBUG logging is
enabled (triggering the model_dump call in _build_request).

Coerce by_alias to bool before passing to pydantic v2, matching
the existing behavior in the pydantic v1 fallback path.

Fixes openai#2921
@atian8179 atian8179 requested a review from a team as a code owner March 7, 2026 14:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: by_alias: NoneType in openai-python v2.24.0 when logging.DEBUG is enabled

1 participant