Skip to content

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

fix: non-required fields no longer unconditionally nullable

Saurav Panda69635e77459d
diff --git a/browser_use/tools/extraction/schema_utils.py b/browser_use/tools/extraction/schema_utils.py
index da92a81f7..173561ce1 100644
--- a/browser_use/tools/extraction/schema_utils.py
+++ b/browser_use/tools/extraction/schema_utils.py
@@ -84,6 +84,14 @@ def _resolve_type(schema: dict, name: str) -> Any:
return base
+_PRIMITIVE_DEFAULTS: dict[str, Any] = {
+ 'string': '',
+ 'number': 0.0,
+ 'integer': 0,
+ 'boolean': False,
+}
+
+
def _build_model(schema: dict, name: str) -> type[BaseModel]:
"""Build a pydantic model from an object-type JSON Schema node."""
_check_unsupported(schema)
@@ -97,15 +105,36 @@ def _build_model(schema: dict, name: str) -> type[BaseModel]:
if prop_name in required_fields:
default = ...
+ elif 'default' in prop_schema:
+ default = prop_schema['default']
+ elif prop_schema.get('nullable', False):
+ # _resolve_type already made the type include None
+ default = None
else:
- prop_type = prop_type | None
- default = prop_schema.get('default', None)
+ # 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.
+ json_type = prop_schema.get('type', 'string')
+ if 'enum' in prop_schema:
+ default = ''
+ elif json_type in _PRIMITIVE_DEFAULTS:
+ default = _PRIMITIVE_DEFAULTS[json_type]
+ elif json_type == 'array':
+ default = []
+ else:
+ # Nested object or unknown — must allow None as sentinel
+ prop_type = prop_type | None
+ default = None
field_kwargs: dict[str, Any] = {}
if 'description' in prop_schema:
field_kwargs['description'] = prop_schema['description']
- fields[prop_name] = (prop_type, Field(default, **field_kwargs))
+ if isinstance(default, list) and not default:
+ fields[prop_name] = (prop_type, Field(default_factory=list, **field_kwargs))
+ else:
+ fields[prop_name] = (prop_type, Field(default, **field_kwargs))
return create_model(name, __base__=_StrictBase, **fields)
diff --git a/tests/ci/test_structured_extraction.py b/tests/ci/test_structured_extraction.py
index e92b23ea1..8e67a7d91 100644
--- a/tests/ci/test_structured_extraction.py
+++ b/tests/ci/test_structured_extraction.py
@@ -106,19 +106,72 @@ class TestSchemaDictToPydanticModel:
instance = Model(status='active')
assert instance.status == 'active' # type: ignore[attr-defined]
- def test_optional_fields(self):
+ def test_optional_fields_get_type_appropriate_defaults(self):
schema = {
'type': 'object',
'properties': {
'name': {'type': 'string'},
'nickname': {'type': 'string'},
+ 'score': {'type': 'number'},
+ 'rank': {'type': 'integer'},
+ 'active': {'type': 'boolean'},
+ 'tags': {'type': 'array', 'items': {'type': 'string'}},
},
'required': ['name'],
}
Model = schema_dict_to_pydantic_model(schema)
instance = Model(name='Alice')
assert instance.name == 'Alice' # type: ignore[attr-defined]
- assert instance.nickname is None # type: ignore[attr-defined]
+ assert instance.nickname == '' # type: ignore[attr-defined]
+ assert instance.score == 0.0 # type: ignore[attr-defined]
+ assert instance.rank == 0 # type: ignore[attr-defined]
+ assert instance.active is False # type: ignore[attr-defined]
+ assert instance.tags == [] # type: ignore[attr-defined]
+
+ def test_optional_non_nullable_rejects_null(self):
+ """Non-required fields that aren't nullable must reject explicit null."""
+ schema = {
+ 'type': 'object',
+ 'properties': {
+ 'name': {'type': 'string'},
+ 'nickname': {'type': 'string'},
+ },
+ 'required': ['name'],
+ }
+ Model = schema_dict_to_pydantic_model(schema)
+ with pytest.raises(ValidationError):
+ Model(name='Alice', nickname=None)
+
+ def test_optional_with_explicit_default(self):
+ schema = {
+ 'type': 'object',
+ 'properties': {
+ 'name': {'type': 'string'},
+ 'color': {'type': 'string', 'default': 'blue'},
+ },
+ 'required': ['name'],
+ }
+ Model = schema_dict_to_pydantic_model(schema)
+ instance = Model(name='Alice')
+ assert instance.color == 'blue' # type: ignore[attr-defined]
+
+ def test_optional_nested_object_defaults_to_none(self):
+ """Non-required nested objects fall back to None since constructing a default is not feasible."""
+ schema = {
+ 'type': 'object',
+ 'properties': {
+ 'name': {'type': 'string'},
+ 'address': {
+ 'type': 'object',
+ 'properties': {'city': {'type': 'string'}},
+ 'required': ['city'],
+ },
+ },
+ 'required': ['name'],
+ }
+ Model = schema_dict_to_pydantic_model(schema)
+ instance = Model(name='Alice')
+ assert instance.address is None # type: ignore[attr-defined]
def test_model_name_from_title(self):
schema = {