Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

fix: optional enum fields default to None instead of empty string

Saurav Pandaa27cc17f356e
diff --git a/browser_use/tools/extraction/schema_utils.py b/browser_use/tools/extraction/schema_utils.py
index 173561ce1..51f94f836 100644
--- a/browser_use/tools/extraction/schema_utils.py
+++ b/browser_use/tools/extraction/schema_utils.py
@@ -113,11 +113,14 @@ def _build_model(schema: dict, name: str) -> type[BaseModel]:
else:
# Non-required, non-nullable, no explicit default.
# Use a type-appropriate zero value for primitives/arrays;
- # fall back to None (with | None) only for nested objects
- # where constructing a default is not feasible.
+ # fall back to None (with | None) for enums and nested objects
+ # where no in-set or constructible default exists.
json_type = prop_schema.get('type', 'string')
if 'enum' in prop_schema:
- default = ''
+ # Can't pick an arbitrary enum member as default — use None
+ # so absent fields serialize as null, not an out-of-set value.
+ prop_type = prop_type | None
+ default = None
elif json_type in _PRIMITIVE_DEFAULTS:
default = _PRIMITIVE_DEFAULTS[json_type]
elif json_type == 'array':
diff --git a/tests/ci/test_structured_extraction.py b/tests/ci/test_structured_extraction.py
index 8e67a7d91..a075b1fa5 100644
--- a/tests/ci/test_structured_extraction.py
+++ b/tests/ci/test_structured_extraction.py
@@ -106,6 +106,27 @@ class TestSchemaDictToPydanticModel:
instance = Model(status='active')
assert instance.status == 'active' # type: ignore[attr-defined]
+ def test_optional_enum_defaults_to_none(self):
+ """Non-required enum fields default to None, not an out-of-set empty string."""
+ schema = {
+ 'type': 'object',
+ 'properties': {
+ 'name': {'type': 'string'},
+ 'priority': {'type': 'string', 'enum': ['low', 'medium', 'high']},
+ },
+ 'required': ['name'],
+ }
+ Model = schema_dict_to_pydantic_model(schema)
+ instance = Model(name='task1')
+ assert instance.priority is None # type: ignore[attr-defined]
+ # Serialized output must not contain an out-of-set value
+ dumped = instance.model_dump(mode='json')
+ assert dumped['priority'] is None
+
+ # When provided, value still works
+ instance2 = Model(name='task2', priority='high')
+ assert instance2.priority == 'high' # type: ignore[attr-defined]
+
def test_optional_fields_get_type_appropriate_defaults(self):
schema = {
'type': 'object',