Skip to content

Commit 4bd22da

Browse files
author
giulio-leone
committed
fix: coerce by_alias to bool in model_dump to prevent TypeError
`model_dump()` in `_compat.py` declares `by_alias: bool | None = None` but passes the value directly to Pydantic v2's `model_dump()`, which expects a `bool`. When `by_alias` is `None` (the default), pydantic-core's Rust serializer raises `TypeError: argument 'by_alias': 'NoneType' object cannot be converted to 'PyBool'`. This only manifests when DEBUG logging is enabled, because the affected call path is inside `_build_request()`'s `log.isEnabledFor(logging.DEBUG)` block. Apply `bool(by_alias)` (matching the existing Pydantic v1 path on line 157) to coerce `None` → `False` safely. Fixes #2921 Signed-off-by: Giulio Leone <6887247+giulio-leone@users.noreply.github.com>
1 parent 15afa21 commit 4bd22da

2 files changed

Lines changed: 10 additions & 2 deletions

File tree

src/openai/_compat.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ def model_dump(
149149
exclude_defaults=exclude_defaults,
150150
# warnings are not supported in Pydantic v1
151151
warnings=True if PYDANTIC_V1 else warnings,
152-
by_alias=by_alias,
152+
by_alias=bool(by_alias),
153153
)
154154
return cast(
155155
"dict[str, Any]",

tests/test_models.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,15 @@ def test_unknown_fields() -> None:
157157
assert model_dump(m2) == {"foo": "foo", "unknown": {"foo_bar": True}}
158158

159159

160-
def test_strict_validation_unknown_fields() -> None:
160+
def test_model_dump_by_alias_none() -> None:
161+
"""Ensure model_dump does not crash when by_alias defaults to None (GH-2921)."""
162+
m = BasicModel.construct(foo="hello")
163+
# by_alias=None is the default — must not raise TypeError
164+
result = model_dump(m)
165+
assert result == {"foo": "hello"}
166+
# Explicit by_alias=None must also work
167+
result = model_dump(m, by_alias=None)
168+
assert result == {"foo": "hello"}
161169
class Model(BaseModel):
162170
foo: str
163171

0 commit comments

Comments
 (0)