Skip to content

Commit b7f6ec0

Browse files
committed
fix(client): serialise pydantic v1 default fields correctly in params (openai#776)
1 parent a6122ea commit b7f6ec0

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

Diff for: src/openai/_utils/_transform.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ def _transform_recursive(
168168
return data
169169

170170
if isinstance(data, pydantic.BaseModel):
171-
return model_dump(data, exclude_unset=True, exclude_defaults=True)
171+
return model_dump(data, exclude_unset=True)
172172

173173
return _transform_value(data, annotation)
174174

Diff for: tests/test_transform.py

+26
Original file line numberDiff line numberDiff line change
@@ -237,3 +237,29 @@ def test_pydantic_nested_objects() -> None:
237237
model = ModelNestedObjects.construct(nested={"foo": "stainless"})
238238
assert isinstance(model.nested, MyModel)
239239
assert transform(model, Any) == {"nested": {"foo": "stainless"}}
240+
241+
242+
class ModelWithDefaultField(BaseModel):
243+
foo: str
244+
with_none_default: Union[str, None] = None
245+
with_str_default: str = "foo"
246+
247+
248+
def test_pydantic_default_field() -> None:
249+
# should be excluded when defaults are used
250+
model = ModelWithDefaultField.construct()
251+
assert model.with_none_default is None
252+
assert model.with_str_default == "foo"
253+
assert transform(model, Any) == {}
254+
255+
# should be included when the default value is explicitly given
256+
model = ModelWithDefaultField.construct(with_none_default=None, with_str_default="foo")
257+
assert model.with_none_default is None
258+
assert model.with_str_default == "foo"
259+
assert transform(model, Any) == {"with_none_default": None, "with_str_default": "foo"}
260+
261+
# should be included when a non-default value is explicitly given
262+
model = ModelWithDefaultField.construct(with_none_default="bar", with_str_default="baz")
263+
assert model.with_none_default == "bar"
264+
assert model.with_str_default == "baz"
265+
assert transform(model, Any) == {"with_none_default": "bar", "with_str_default": "baz"}

0 commit comments

Comments
 (0)