Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
much better structured output + utils for generating pydantic schema
Gregor Žunič48ae2d19cf7a
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 984274169..6e364db2b 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -1196,7 +1196,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):self.logger.info(f'❌ {agent_run_error}')- if self.state.history.structured_output() is not None and self.output_model_schema is not None:+ # set the model output schema and call it on the fly+ if self.state.history._output_model_schema is None and self.output_model_schema is not None:self.state.history._output_model_schema = self.output_model_schemareturn self.state.historydiff --git a/browser_use/agent/utils.py b/browser_use/agent/utils.pynew file mode 100644index 000000000..be70ed5d8--- /dev/null+++ b/browser_use/agent/utils.py@@ -0,0 +1,223 @@+import json+import logging++from datamodel_code_generator import DataModelType, generate+from pydantic import BaseModel++logger = logging.getLogger(__name__)+++def create_pydantic_model_from_schema(schema: dict, model_name: str = 'DynamicModel') -> type[BaseModel]:+ """+ Convert JSON schema to Pydantic model class using datamodel-code-generator.++ Args:+ schema: JSON schema dictionary+ model_name: Name for the generated model class++ Returns:+ Pydantic model class that can be used with Controller(output_model=...)++ Example:+ schema = {+ "type": "object",+ "properties": {+ "name": {"type": "string"},+ "age": {"type": "integer"},+ "email": {"type": "string"}+ },+ "required": ["name", "age"]+ }+ PersonModel = create_pydantic_model_from_schema(schema, "Person")+ controller = Controller(output_model=PersonModel)+ """+ try:+ import importlib.util+ import tempfile+ from pathlib import Path++ # Handle case where schema might be a string (JSON)+ if isinstance(schema, str):+ schema = json.loads(schema)++ logger.debug(f'Creating Pydantic model from schema: {schema}')++ # Initialize paths for cleanup+ schema_path = None+ model_path = None++ try:+ # Create temporary files for input schema and output model+ with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as schema_file:+ json.dump(schema, schema_file, indent=2)+ schema_path = Path(schema_file.name)++ with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as model_file:+ model_path = Path(model_file.name)++ # Generate Pydantic model code using datamodel-code-generator+ generate(+ input_=schema_path,+ output=model_path,+ output_model_type=DataModelType.PydanticV2BaseModel,+ class_name=model_name,+ )++ # Read the generated Python code+ generated_code = model_path.read_text()+ logger.debug(f'Generated Pydantic model code:\n{generated_code}')++ # Create a module and execute the generated code+ spec = importlib.util.spec_from_loader(f'dynamic_model_{model_name}', loader=None)+ if spec is None:+ raise ValueError('Failed to create module spec')++ module = importlib.util.module_from_spec(spec)++ # Add necessary imports to the module namespace before executing+ from typing import Any, Optional, Union++ from pydantic import BaseModel, Field++ module.__dict__.update(+ {+ 'Optional': Optional,+ 'Union': Union,+ 'list': list,+ 'dict': dict,+ 'Any': Any,+ 'BaseModel': BaseModel,+ 'Field': Field,+ 'str': str,+ 'int': int,+ 'float': float,+ 'bool': bool,+ }+ )++ # Execute the generated code in the module's namespace+ exec(generated_code, module.__dict__)++ # Get the generated model class+ if hasattr(module, model_name):+ model_class = getattr(module, model_name)+ # Rebuild the model to resolve forward references and type annotations+ # Pass the module's namespace so it can resolve imports like Optional+ model_class.model_rebuild(_types_namespace=module.__dict__)+ logger.debug(f'Successfully created Pydantic model: {model_class}')+ return model_class+ else:+ # Fallback: look for any BaseModel subclass in the module+ for attr_name in dir(module):+ attr = getattr(module, attr_name)+ if isinstance(attr, type) and issubclass(attr, BaseModel) and attr != BaseModel:+ # Rebuild the model to resolve forward references and type annotations+ # Pass the module's namespace so it can resolve imports like Optional+ attr.model_rebuild(_types_namespace=module.__dict__)+ logger.debug(f'Using fallback model class: {attr}')+ return attr++ raise ValueError('No Pydantic model class found in generated code')++ finally:+ # Clean up temporary files safely+ if schema_path is not None:+ try:+ schema_path.unlink()+ except Exception as cleanup_error:+ logger.warning(f'Failed to cleanup schema file: {cleanup_error}')+ if model_path is not None:+ try:+ model_path.unlink()+ except Exception as cleanup_error:+ logger.warning(f'Failed to cleanup model file: {cleanup_error}')++ except ImportError as e:+ logger.error(f'datamodel-code-generator not available: {e}')+ logger.error('Falling back to basic schema conversion')++ try:+ # Fallback to basic implementation if datamodel-code-generator is not available+ from typing import Any, Optional++ from pydantic import create_model++ def json_type_to_python_type(json_type):+ """Map JSON schema types to Python types"""+ # Handle union types (arrays of types)+ if isinstance(json_type, list):+ # Handle union types like ["string", "null"]+ types = []+ for t in json_type:+ if t == 'null':+ continue # We'll handle null separately+ types.append(json_type_to_python_type(t))++ if len(types) == 0:+ return Any+ elif len(types) == 1:+ return types[0]+ else:+ # len(types) >= 2 - create Union dynamically+ from typing import Union++ # For 2 types, use Union[type1, type2]+ if len(types) == 2:+ return Union[types[0], types[1]]+ # For more types, we need to use a different approach+ # Since Union doesn't support unpacking, we'll just use the first type+ # This is a limitation of the fallback implementation+ return types[0]++ # Handle single types+ if json_type == 'string':+ return str+ elif json_type == 'integer':+ return int+ elif json_type == 'number':+ return float+ elif json_type == 'boolean':+ return bool+ elif json_type == 'array':+ return list[Any]+ elif json_type == 'object':+ return dict[str, Any]+ else:+ return Any++ # Handle case where schema might be a string (JSON)+ if isinstance(schema, str):+ schema = json.loads(schema)++ # Extract properties and required fields from schema+ properties = schema.get('properties', {})+ required_fields = schema.get('required', [])++ # Build field definitions for create_model+ field_definitions = {}++ for field_name, field_schema in properties.items():+ json_type = field_schema.get('type')+ field_type = json_type_to_python_type(json_type)++ # Check if the field allows null (either not required or explicitly allows null)+ allows_null = field_name not in required_fields or (isinstance(json_type, list) and 'null' in json_type)++ # Handle required vs optional fields+ if field_name in required_fields and not allows_null:+ field_definitions[field_name] = (field_type, ...) # Required field+ else:+ optional_type = Optional[field_type] # Use Optional instead of Union[T, None]+ field_definitions[field_name] = (optional_type, None) # Optional field with default None++ # Create the dynamic model using create_model+ return create_model(model_name, **field_definitions)++ except Exception as fallback_error:+ logger.error(f'Fallback schema conversion also failed: {fallback_error}')+ raise ValueError(f'Both primary and fallback schema conversion failed: {fallback_error}') from fallback_error++ except Exception as e:+ logger.error(f'Failed to create Pydantic model from schema: {e}')+ logger.error(f'Schema: {schema}')+ raise ValueError(f'Invalid JSON schema: {e}') from ediff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex 80d5403c3..011e0cbf8 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -462,6 +462,7 @@ class AgentHistoryList(BaseModel, Generic[AgentStructuredOutput]):"""Get the number of steps in the history"""return len(self.history)+ @propertydef structured_output(self) -> AgentStructuredOutput | None:"""Get the structured output from the history@@ -469,8 +470,9 @@ class AgentHistoryList(BaseModel, Generic[AgentStructuredOutput]):The structured output if both final_result and _output_model_schema are available,otherwise None"""- if self.final_result() is not None and self._output_model_schema is not None:- return self._output_model_schema.model_validate_strings(self.final_result())+ final_result = self.final_result()+ if final_result is not None and self._output_model_schema is not None:+ return self._output_model_schema.model_validate_json(final_result)return Nonediff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex dc0c85fa6..f4c389dd2 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -905,7 +905,7 @@ Explain the content of the page and that the requested information is not availa'Complete task - with return text and if the task is finished (success=True) or not yet completely finished (success=False), because last step is reached',param_model=StructuredOutputAction[output_model],)- async def done(params: StructuredOutputAction[output_model]):+ async def done(params: StructuredOutputAction):# Exclude success from the output JSON since it's an internal parameteroutput_dict = params.data.model_dump()diff --git a/browser_use/controller/tests/test_controller_structured_output.py b/browser_use/controller/tests/test_controller_structured_output.pyindex d4661201d..d638175ea 100644--- a/browser_use/controller/tests/test_controller_structured_output.py+++ b/browser_use/controller/tests/test_controller_structured_output.py@@ -3,17 +3,17 @@ import asynciofrom pydantic import BaseModelfrom browser_use.agent.service import Agent+from browser_use.agent.utils import create_pydantic_model_from_schemafrom browser_use.agent.views import AgentOutputfrom browser_use.controller.service import Controllerfrom browser_use.llm.openai.chat import ChatOpenAI-from browser_use.llm.schema import SchemaOptimizerclass OutputModel(BaseModel):"""Test output model"""- name: str- age: int+ city: str+ country: strasync def test_optimized_schema():@@ -26,20 +26,29 @@ async def test_optimized_schema():# Create the agent output model with custom actionsagent_output_model = AgentOutput.type_with_custom_actions(ActionModel)- # Get original schema for comparison- original_schema = agent_output_model.model_json_schema()+ # # Get original schema for comparison+ # original_schema = agent_output_model.model_json_schema()- # Create the optimized schema- optimized_schema = SchemaOptimizer.create_optimized_json_schema(agent_output_model)+ # # Create the optimized schema+ # optimized_schema = SchemaOptimizer.create_optimized_json_schema(agent_output_model)++ scgena = create_pydantic_model_from_schema(OutputModel.model_json_schema(), 'OutputModel')agent = Agent(- task='What is the capital of France?',- llm=ChatOpenAI(model='gpt-4o'),+ task='What is the capital of France? Do not use the internet, just output the done function.',+ llm=ChatOpenAI(model='gpt-4.1-mini'),controller=controller,+ output_model_schema=scgena,)- output = await agent.run()- x = output.structured_output+ history = await agent.run()++ if history.structured_output:+ # print(history.structured_output.city, history.structured_output.country)+ print(OutputModel.model_validate_json(history.final_result() or '{}'))+ else:+ print('No structured output')+ print(history.final_result())if __name__ == '__main__':diff --git a/eval/service.py b/eval/service.pyindex 84b800360..eae586cf3 100644--- a/eval/service.py+++ b/eval/service.py@@ -57,6 +57,7 @@ from lmnr import AsyncLaminarClient, Laminar, observefrom PIL import Imagefrom pydantic import BaseModel+from browser_use.agent.utils import create_pydantic_model_from_schemafrom browser_use.llm.anthropic.chat import ChatAnthropicfrom browser_use.llm.base import BaseChatModelfrom browser_use.llm.google.chat import ChatGoogle@@ -1052,224 +1053,6 @@ async def reformat_agent_history(return results-def create_pydantic_model_from_schema(schema: dict, model_name: str = 'DynamicModel') -> type[BaseModel]:- """- Convert JSON schema to Pydantic model class using datamodel-code-generator.-- Args:- schema: JSON schema dictionary- model_name: Name for the generated model class-- Returns:- Pydantic model class that can be used with Controller(output_model=...)-- Example:- schema = {- "type": "object",- "properties": {- "name": {"type": "string"},- "age": {"type": "integer"},- "email": {"type": "string"}- },- "required": ["name", "age"]- }- PersonModel = create_pydantic_model_from_schema(schema, "Person")- controller = Controller(output_model=PersonModel)- """- try:- import importlib.util- import tempfile- from pathlib import Path-- from datamodel_code_generator import DataModelType, generate-- # Handle case where schema might be a string (JSON)- if isinstance(schema, str):- schema = json.loads(schema)-- logger.debug(f'Creating Pydantic model from schema: {schema}')-- # Initialize paths for cleanup- schema_path = None- model_path = None-- try:- # Create temporary files for input schema and output model- with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as schema_file:- json.dump(schema, schema_file, indent=2)- schema_path = Path(schema_file.name)-- with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as model_file:- model_path = Path(model_file.name)-- # Generate Pydantic model code using datamodel-code-generator- generate(- input_=schema_path,- output=model_path,- output_model_type=DataModelType.PydanticV2BaseModel,- class_name=model_name,- )-- # Read the generated Python code- generated_code = model_path.read_text()- logger.debug(f'Generated Pydantic model code:\n{generated_code}')-- # Create a module and execute the generated code- spec = importlib.util.spec_from_loader(f'dynamic_model_{model_name}', loader=None)- if spec is None:- raise ValueError('Failed to create module spec')-- module = importlib.util.module_from_spec(spec)-- # Add necessary imports to the module namespace before executing- from typing import Any, Optional, Union-- from pydantic import BaseModel, Field-- module.__dict__.update(- {- 'Optional': Optional,- 'Union': Union,- 'list': list,- 'dict': dict,- 'Any': Any,- 'BaseModel': BaseModel,- 'Field': Field,- 'str': str,- 'int': int,- 'float': float,- 'bool': bool,- }- )-- # Execute the generated code in the module's namespace- exec(generated_code, module.__dict__)-- # Get the generated model class- if hasattr(module, model_name):- model_class = getattr(module, model_name)- # Rebuild the model to resolve forward references and type annotations- # Pass the module's namespace so it can resolve imports like Optional- model_class.model_rebuild(_types_namespace=module.__dict__)- logger.debug(f'Successfully created Pydantic model: {model_class}')- return model_class- else:- # Fallback: look for any BaseModel subclass in the module- for attr_name in dir(module):- attr = getattr(module, attr_name)- if isinstance(attr, type) and issubclass(attr, BaseModel) and attr != BaseModel:- # Rebuild the model to resolve forward references and type annotations- # Pass the module's namespace so it can resolve imports like Optional- attr.model_rebuild(_types_namespace=module.__dict__)- logger.debug(f'Using fallback model class: {attr}')- return attr-- raise ValueError('No Pydantic model class found in generated code')-- finally:- # Clean up temporary files safely- if schema_path is not None:- try:- schema_path.unlink()- except Exception as cleanup_error:- logger.warning(f'Failed to cleanup schema file: {cleanup_error}')- if model_path is not None:- try:- model_path.unlink()- except Exception as cleanup_error:- logger.warning(f'Failed to cleanup model file: {cleanup_error}')-- except ImportError as e:- logger.error(f'datamodel-code-generator not available: {e}')- logger.error('Falling back to basic schema conversion')-- try:- # Fallback to basic implementation if datamodel-code-generator is not available- from typing import Any, Optional-- from pydantic import create_model-- def json_type_to_python_type(json_type):- """Map JSON schema types to Python types"""- # Handle union types (arrays of types)- if isinstance(json_type, list):- # Handle union types like ["string", "null"]- types = []- for t in json_type:- if t == 'null':- continue # We'll handle null separately- types.append(json_type_to_python_type(t))-- if len(types) == 0:- return Any- elif len(types) == 1:- return types[0]- else:- # len(types) >= 2 - create Union dynamically- from typing import Union-- # For 2 types, use Union[type1, type2]- if len(types) == 2:- return Union[types[0], types[1]]- # For more types, we need to use a different approach- # Since Union doesn't support unpacking, we'll just use the first type- # This is a limitation of the fallback implementation- return types[0]-- # Handle single types- if json_type == 'string':- return str- elif json_type == 'integer':- return int- elif json_type == 'number':- return float- elif json_type == 'boolean':- return bool- elif json_type == 'array':- return list[Any]- elif json_type == 'object':- return dict[str, Any]- else:- return Any-- # Handle case where schema might be a string (JSON)- if isinstance(schema, str):- schema = json.loads(schema)-- # Extract properties and required fields from schema- properties = schema.get('properties', {})- required_fields = schema.get('required', [])-- # Build field definitions for create_model- field_definitions = {}-- for field_name, field_schema in properties.items():- json_type = field_schema.get('type')- field_type = json_type_to_python_type(json_type)-- # Check if the field allows null (either not required or explicitly allows null)- allows_null = field_name not in required_fields or (isinstance(json_type, list) and 'null' in json_type)-- # Handle required vs optional fields- if field_name in required_fields and not allows_null:- field_definitions[field_name] = (field_type, ...) # Required field- else:- optional_type = Optional[field_type] # Use Optional instead of Union[T, None]- field_definitions[field_name] = (optional_type, None) # Optional field with default None-- # Create the dynamic model using create_model- return create_model(model_name, **field_definitions)-- except Exception as fallback_error:- logger.error(f'Fallback schema conversion also failed: {fallback_error}')- raise ValueError(f'Both primary and fallback schema conversion failed: {fallback_error}') from fallback_error-- except Exception as e:- logger.error(f'Failed to create Pydantic model from schema: {e}')- logger.error(f'Schema: {schema}')- raise ValueError(f'Invalid JSON schema: {e}') from e--class Task:def __init__(self, task_id, confirmed_task, **kwargs):# Validate required fieldsdiff --git a/pyproject.toml b/pyproject.tomlindex 22de26304..7e4c0e9f5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -32,6 +32,7 @@ dependencies = ["typing-extensions>=4.12.2","uuid7>=0.1.0","authlib>=1.6.0",+ "datamodel-code-generator>=0.26.0","google-genai>=1.21.1","openai>=1.81.0","anthropic>=0.54.0",@@ -70,7 +71,6 @@ eval = ["anyio>=4.9.0","Pillow>=11.2.1","psutil>=7.0.0",- "datamodel-code-generator>=0.26.0",]all = ["browser-use[cli,examples,aws]",