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
handle mixed order action params
Nick Sweeting4ffd6bedc094
diff --git a/browser_use/controller/registry/service.py b/browser_use/controller/registry/service.pyindex 23561096f..86c9c509b 100644--- a/browser_use/controller/registry/service.py+++ b/browser_use/controller/registry/service.py@@ -163,12 +163,10 @@ class Registry(Generic[Context]):if param_model_provided and parameters and parameters[0].name not in special_param_names:if params is None:raise ValueError(f"{func.__name__}() missing required 'params' argument")- call_args.append(params)- start_idx = 1+ # For Type 1, we'll use the params object as first argument+ passelse:- # Type 2 pattern - unpack params into positional args- start_idx = 0-+ # Type 2 pattern - need to unpack params# If params is None, try to create it from kwargsif params is None and action_params:# Extract action params from kwargs@@ -180,20 +178,15 @@ class Registry(Generic[Context]):# Use the param_model which has the correct types definedparams = param_model(**action_kwargs)- if params is not None:- params_dict = params.model_dump()- # Add action params in correct order- for param in action_params:- if param.name in params_dict:- call_args.append(params_dict[param.name])- elif param.default != Parameter.empty:- call_args.append(param.default)- else:- raise ValueError(f"{func.__name__}() missing required parameter '{param.name}'")+ # Build call_args by iterating through original function parameters in order+ params_dict = params.model_dump() if params is not None else {}- # Add special params in correct order- for param in parameters[start_idx:]:- if param.name in special_param_names:+ for i, param in enumerate(parameters):+ # Skip first param for Type 1 pattern (it's the model itself)+ if param_model_provided and i == 0 and param.name not in special_param_names:+ call_args.append(params)+ elif param.name in special_param_names:+ # This is a special parameterif param.name in kwargs:value = kwargs[param.name]# Check if required special param is None@@ -215,6 +208,14 @@ class Registry(Generic[Context]):raise ValueError(f'Action {func.__name__} requires page_extraction_llm but none provided.')else:raise ValueError(f"{func.__name__}() missing required special parameter '{param.name}'")+ else:+ # This is an action parameter+ if param.name in params_dict:+ call_args.append(params_dict[param.name])+ elif param.default != Parameter.empty:+ call_args.append(param.default)+ else:+ raise ValueError(f"{func.__name__}() missing required parameter '{param.name}'")# Call original function with positional argsif iscoroutinefunction(func):diff --git a/tests/ci/test_controller.py b/tests/ci/test_controller.pyindex 252b024d6..c249ebd79 100644--- a/tests/ci/test_controller.py+++ b/tests/ci/test_controller.py@@ -1159,6 +1159,104 @@ class TestControllerIntegration:selected_value = await page.evaluate("document.getElementById('test-dropdown').value")assert selected_value == 'option2' # Second Option has value "option2"+ @pytest.mark.asyncio+ async def test_extract_content_action(self, controller, browser_session, base_url, http_server):+ """Test the default extract_content action with mixed parameter ordering."""+ # Set up a test page with specific content+ http_server.expect_request('/extract-test').respond_with_data(+ """+ <!DOCTYPE html>+ <html>+ <head>+ <title>Extract Content Test Page</title>+ </head>+ <body>+ <h1>Product Details</h1>+ <div class="product">+ <h2>Awesome Widget</h2>+ <p class="price">$19.99</p>+ <p class="description">This is an amazing widget that does everything!</p>+ <a href="/buy-now">Buy Now</a>+ <a href="/reviews">Read Reviews</a>+ </div>+ <div class="features">+ <h3>Features:</h3>+ <ul>+ <li>Feature 1: Super fast</li>+ <li>Feature 2: Easy to use</li>+ <li>Feature 3: Lifetime warranty</li>+ </ul>+ </div>+ </body>+ </html>+ """,+ content_type='text/html',+ )++ # Navigate to the test page+ goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/extract-test')}++ class GoToUrlActionModel(ActionModel):+ go_to_url: GoToUrlAction | None = None++ await controller.act(GoToUrlActionModel(**goto_action), browser_session)++ # Verify extract_content is registered+ assert 'extract_content' in controller.registry.registry.actions++ # Create a mock LLM for testing+ from langchain_core.language_models.fake_chat_models import FakeListChatModel++ mock_llm = FakeListChatModel(+ responses=['Product: Awesome Widget, Price: $19.99, Description: Amazing widget with 3 key features']+ )++ # Test extract_content with include_links=False (default)+ extract_action = {'extract_content': {'goal': 'Extract product name and price'}}++ class ExtractContentActionModel(ActionModel):+ extract_content: dict | None = None++ # This should fail if page_extraction_llm is not passed correctly+ with pytest.raises(RuntimeError) as exc_info:+ await controller.act(ExtractContentActionModel(**extract_action), browser_session)++ # Should fail because page_extraction_llm is required but not provided+ assert 'page_extraction_llm' in str(exc_info.value)++ # Now test with the LLM provided through controller context+ # Since controller doesn't have a way to pass page_extraction_llm directly,+ # we'll test that the action is properly registered with correct parameters+ action = controller.registry.registry.actions['extract_content']++ # Verify the param model only includes user-facing parameters+ model_fields = action.param_model.model_fields+ assert 'goal' in model_fields+ assert 'include_links' in model_fields+ assert model_fields['include_links'].default is False++ # Special params should NOT be in the model+ assert 'page' not in model_fields+ assert 'page_extraction_llm' not in model_fields++ # Verify the function signature includes the expected parameters+ import inspect++ sig = inspect.signature(action.function)+ # The normalized function should have params and kwargs+ assert 'params' in sig.parameters+ assert 'kwargs' in sig.parameters++ # Test with include_links=True+ extract_action_with_links = {+ 'extract_content': {'goal': 'Extract all product information including links', 'include_links': True}+ }++ # Verify the action model can be created with these parameters+ action_model = ExtractContentActionModel(**extract_action_with_links)+ assert action_model.extract_content['goal'] == 'Extract all product information including links'+ assert action_model.extract_content['include_links'] is True+@pytest.mark.asyncioasync def test_click_element_by_index(self, controller, browser_session, base_url, http_server):"""Test that click_element_by_index correctly clicks an element and handles different outcomes."""