From 6a7f82cf08fef42c55746e86a1b8d5ee6a53360f Mon Sep 17 00:00:00 2001 From: Matt Van Horn Date: Tue, 10 Mar 2026 01:01:33 -0700 Subject: [PATCH] fix(compat): handle None by_alias in model_dump for Pydantic v2 Pydantic v2's Rust serializer requires by_alias to be a bool, not None. The v1 fallback path already did bool(by_alias), but the v2 path passed None directly, causing TypeError when DEBUG logging was enabled. Fixes #2921 Co-Authored-By: Claude Opus 4.6 --- src/openai/_compat.py | 2 +- tests/compat/test_model_dump.py | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 tests/compat/test_model_dump.py diff --git a/src/openai/_compat.py b/src/openai/_compat.py index 020ffeb2ca..b4b05b171b 100644 --- a/src/openai/_compat.py +++ b/src/openai/_compat.py @@ -149,7 +149,7 @@ def model_dump( exclude_defaults=exclude_defaults, # warnings are not supported in Pydantic v1 warnings=True if PYDANTIC_V1 else warnings, - by_alias=by_alias, + by_alias=bool(by_alias) if by_alias is not None else False, ) return cast( "dict[str, Any]", diff --git a/tests/compat/test_model_dump.py b/tests/compat/test_model_dump.py new file mode 100644 index 0000000000..5d4a7f6806 --- /dev/null +++ b/tests/compat/test_model_dump.py @@ -0,0 +1,23 @@ +import pydantic + +from openai._compat import model_dump + + +class SimpleModel(pydantic.BaseModel): + foo: str = "bar" + + +def test_model_dump_by_alias_none() -> None: + """Regression test for #2921: by_alias=None should not raise TypeError.""" + result = model_dump(SimpleModel(), by_alias=None) + assert result == {"foo": "bar"} + + +def test_model_dump_by_alias_true() -> None: + result = model_dump(SimpleModel(), by_alias=True) + assert result == {"foo": "bar"} + + +def test_model_dump_by_alias_false() -> None: + result = model_dump(SimpleModel(), by_alias=False) + assert result == {"foo": "bar"}