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
refactor action registration to consistently require params or args and kwargs
Nick Sweetingd2ac59e211d5
diff --git a/browser_use/controller/registry/service.py b/browser_use/controller/registry/service.pyindex 1e9148390..cee7e81b7 100644--- a/browser_use/controller/registry/service.py+++ b/browser_use/controller/registry/service.py@@ -1,11 +1,14 @@import asyncio+import functools+import inspectimport loggingimport refrom collections.abc import Callable-from inspect import iscoroutinefunction, signature-from typing import Any, Generic, Optional, TypeVar+from inspect import Parameter, iscoroutinefunction, signature+from typing import Any, Generic, Optional, TypeVar, Union, get_args, get_originfrom langchain_core.language_models.chat_models import BaseChatModel+from playwright.async_api import Pagefrom pydantic import BaseModel, Field, create_modelfrom browser_use.browser import BrowserSession@@ -35,6 +38,188 @@ class Registry(Generic[Context]):self.telemetry = ProductTelemetry()self.exclude_actions = exclude_actions if exclude_actions is not None else []+ def _get_special_param_types(self) -> dict[str, type]:+ """Get the expected types for special parameters from SpecialActionParameters"""+ # Manually define the expected types to avoid issues with Optional handling+ return {+ 'context': None, # Context is a TypeVar, so we can't validate type+ 'browser_session': BrowserSession,+ 'browser': BrowserSession, # legacy name+ 'browser_context': BrowserSession, # legacy name+ 'page': Page,+ 'page_extraction_llm': BaseChatModel,+ 'available_file_paths': list,+ 'has_sensitive_data': bool,+ }++ def _normalize_action_function_signature(+ self,+ func: Callable,+ description: str,+ param_model: type[BaseModel] | None = None,+ ) -> tuple[Callable, type[BaseModel]]:+ """+ Normalize action function to accept only kwargs.++ Returns:+ - Normalized function that accepts (*, params: ParamModel, **special_params)+ - The param model to use for registration+ """+ sig = signature(func)+ parameters = list(sig.parameters.values())+ special_param_types = self._get_special_param_types()+ special_param_names = set(special_param_types.keys())++ # Step 1: Validate no **kwargs in original function+ for param in parameters:+ if param.kind == Parameter.VAR_KEYWORD:+ raise ValueError(+ f"Action '{func.__name__}' has **{param.name} which is not allowed. "+ f'Actions must have explicit positional parameters only.'+ )++ # Step 2: Separate special and action parameters+ action_params = []+ special_params = []+ param_model_provided = param_model is not None++ for i, param in enumerate(parameters):+ # Check if this is a Type 1 pattern (first param is BaseModel)+ if i == 0 and param_model_provided and param.name not in special_param_names:+ # This is Type 1 pattern - skip the params argument+ continue++ if param.name in special_param_names:+ # Validate special parameter type+ expected_type = special_param_types.get(param.name)+ if param.annotation != Parameter.empty and expected_type is not None:+ # Handle Optional types - normalize both sides+ param_type = param.annotation+ origin = get_origin(param_type)+ if origin is Union:+ args = get_args(param_type)+ # Find non-None type+ param_type = next((arg for arg in args if arg is not type(None)), param_type)++ # Check if types are compatible (exact match, subclass, or generic list)+ types_compatible = (+ param_type == expected_type+ or (+ inspect.isclass(param_type)+ and inspect.isclass(expected_type)+ and issubclass(param_type, expected_type)+ )+ or+ # Handle list[T] vs list comparison+ (expected_type is list and (param_type is list or get_origin(param_type) is list))+ )++ if not types_compatible:+ expected_type_name = getattr(expected_type, '__name__', str(expected_type))+ param_type_name = getattr(param_type, '__name__', str(param_type))+ raise ValueError(+ f"Action '{func.__name__}' parameter '{param.name}: {param_type_name}' "+ f"conflicts with special argument injected by controller: '{param.name}: {expected_type_name}'"+ )+ special_params.append(param)+ else:+ action_params.append(param)++ # Step 3: Create or validate param model+ if not param_model_provided:+ # Type 2: Generate param model from action params+ if action_params:+ params_dict = {}+ for param in action_params:+ annotation = param.annotation if param.annotation != Parameter.empty else str+ default = ... if param.default == Parameter.empty else param.default+ params_dict[param.name] = (annotation, default)++ param_model = create_model(f'{func.__name__}_Params', __base__=ActionModel, **params_dict)+ else:+ # No action params, create empty model+ param_model = create_model(+ f'{func.__name__}_Params',+ __base__=ActionModel,+ )++ # Step 4: Create normalized wrapper function+ @functools.wraps(func)+ async def normalized_wrapper(*, params: BaseModel | None = None, **kwargs):+ """Normalized action that only accepts kwargs"""+ # Validate no positional args+ if any(k.startswith('_') for k in kwargs.keys()):+ raise TypeError(f'{func.__name__}() does not accept positional arguments')++ # Prepare arguments for original function+ call_args = []+ call_kwargs = {}++ # Handle Type 1 pattern (first arg is the param model)+ 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+ else:+ # Type 2 pattern - unpack params into positional args+ start_idx = 0+ 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}'")++ # Add special params in correct order+ for param in parameters[start_idx:]:+ if param.name in special_param_names:+ if param.name in kwargs:+ value = kwargs[param.name]+ # Check if required special param is None+ if value is None and param.default == Parameter.empty:+ if param.name == 'browser_session':+ raise ValueError(f'Action {func.__name__} requires browser_session but none provided.')+ elif param.name == 'page_extraction_llm':+ 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}'")+ call_args.append(value)+ elif param.default != Parameter.empty:+ call_args.append(param.default)+ else:+ # Special param is required but not provided+ if param.name == 'browser_session':+ raise ValueError(f'Action {func.__name__} requires browser_session but none provided.')+ elif param.name == 'page_extraction_llm':+ 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}'")++ # Call original function with positional args+ if iscoroutinefunction(func):+ return await func(*call_args)+ else:+ return await asyncio.to_thread(func, *call_args)++ # Update wrapper signature to be kwargs-only+ new_params = [Parameter('params', Parameter.KEYWORD_ONLY, default=None, annotation=Optional[param_model])]++ # Add special params as keyword-only+ for sp in special_params:+ new_params.append(Parameter(sp.name, Parameter.KEYWORD_ONLY, default=sp.default, annotation=sp.annotation))++ # Add **kwargs to accept and ignore extra params+ new_params.append(Parameter('kwargs', Parameter.VAR_KEYWORD))++ normalized_wrapper.__signature__ = sig.replace(parameters=new_params)++ return normalized_wrapper, param_model+# @time_execution_sync('--create_param_model')def _create_param_model(self, function: Callable) -> type[BaseModel]:"""Creates a Pydantic model from function signature"""@@ -72,33 +257,21 @@ class Registry(Generic[Context]):if func.__name__ in self.exclude_actions:return func- # Create param model from function if not provided- actual_param_model = param_model or self._create_param_model(func)-- # Wrap sync functions to make them async- if not iscoroutinefunction(func):-- async def async_wrapper(*args, **kwargs):- return await asyncio.to_thread(func, *args, **kwargs)-- # Copy the signature and other metadata from the original function- async_wrapper.__signature__ = signature(func)- async_wrapper.__name__ = func.__name__- async_wrapper.__annotations__ = func.__annotations__- wrapped_func = async_wrapper- else:- wrapped_func = func+ # Normalize the function signature+ normalized_func, actual_param_model = self._normalize_action_function_signature(func, description, param_model)action = RegisteredAction(name=func.__name__,description=description,- function=wrapped_func,+ function=normalized_func,param_model=actual_param_model,domains=final_domains,page_filter=page_filter,)self.registry.actions[func.__name__] = action- return func++ # Return the normalized function so it can be called with kwargs+ return normalized_funcreturn decorator@@ -114,7 +287,7 @@ class Registry(Generic[Context]):#context: Context | None = None,) -> Any:- """Execute a registered action with enhanced parameter handling for backward compatibility"""+ """Execute a registered action with simplified parameter handling"""if action_name not in self.registry.actions:raise ValueError(f'Action {action_name} not found')@@ -126,31 +299,6 @@ class Registry(Generic[Context]):except Exception as e:raise ValueError(f'Invalid parameters {params} for action {action_name}: {type(e)}: {e}') from e- # Analyze function signature for smart parameter injection- sig = signature(action.function)- parameters = list(sig.parameters.values())- parameter_names = [param.name for param in parameters]-- # Check if the first parameter is a Pydantic model (using original safe logic)- # Only consider it pydantic if:- # 1. There are parameters- # 2. First parameter has a BaseModel annotation- # 3. AND the function signature actually takes a BaseModel as first param (not auto-generated)- # 4. AND the first parameter is NOT a special parameter- special_param_names = set(SpecialActionParameters.model_fields.keys())- try:- is_pydantic = (- parameters- and len(parameters) > 0- and hasattr(parameters[0], 'annotation')- and parameters[0].annotation != parameters[0].empty- and issubclass(parameters[0].annotation, BaseModel)- # IMPORTANT: Exclude special parameters from being considered as pydantic models- and parameters[0].name not in special_param_names- )- except (TypeError, AttributeError):- is_pydantic = False-if sensitive_data:# Get current URL if browser_session is providedcurrent_url = None@@ -162,23 +310,8 @@ class Registry(Generic[Context]):current_url = current_page.url if current_page else Nonevalidated_params = self._replace_sensitive_data(validated_params, sensitive_data, current_url)- # Check if the action requires special parameters and validate they're provided- if (- 'browser_session' in parameter_names- or 'browser' in parameter_names- or 'browser_context' in parameter_names- or 'page' in parameter_names- ) and not browser_session:- raise ValueError(f'Action {action_name} requires browser_session but none provided.')- if 'page_extraction_llm' in parameter_names and not page_extraction_llm:- raise ValueError(f'Action {action_name} requires page_extraction_llm but none provided.')- if 'available_file_paths' in parameter_names and not available_file_paths:- raise ValueError(f'Action {action_name} requires available_file_paths but none provided.')- if 'context' in parameter_names and not context:- raise ValueError(f'Action {action_name} requires context but none provided.')-- # Create special parameters model with all available values- special_params_data = {+ # Build special context dict+ special_context = {'context': context,'browser_session': browser_session,'browser': browser_session, # legacy support@@ -189,58 +322,24 @@ class Registry(Generic[Context]):}# Handle async page parameter if needed- if 'page' in parameter_names and browser_session:- special_params_data['page'] = await browser_session.get_current_page()-- # Create special parameters object without validation to preserve BrowserSession state- # We bypass model_validate to avoid copying BrowserSession and losing private attributes- special_params = SpecialActionParameters.model_construct(**special_params_data)-- # Log legacy usage- if 'browser' in parameter_names:- logger.debug(- f'You should update this action {action_name}(browser: BrowserContext) -> to take {action_name}(browser_session: BrowserSession) instead'- )- if 'browser_context' in parameter_names:- logger.debug(- f'You should update this action {action_name}(browser_context: BrowserContext) -> to take {action_name}(browser_session: BrowserSession) instead'- )-- # Enhanced parameter injection logic using Pydantic- if is_pydantic:- # For pydantic functions: function(pydantic_model, **special_params)- # Extract special parameters needed by this function (keep objects, don't serialize)- needed_special_params = set(parameter_names[1:]) & set(SpecialActionParameters.model_fields.keys())- injection_params = {}- for param_name in needed_special_params:- value = getattr(special_params, param_name, None)- if value is not None:- injection_params[param_name] = value-- return await action.function(validated_params, **injection_params)+ if browser_session:+ # Check if function signature includes 'page' parameter+ sig = signature(action.function)+ if 'page' in sig.parameters:+ special_context['page'] = await browser_session.get_current_page()++ # All functions are now normalized to accept kwargs only+ # Call with params and unpacked special context+ return await action.function(params=validated_params, **special_context)++ except ValueError as e:+ # Preserve ValueError messages from validation+ if 'requires browser_session but none provided' in str(e) or 'requires page_extraction_llm but none provided' in str(+ e+ ):+ raise RuntimeError(str(e)) from eelse:- # For individual parameter functions: function(**all_params)- # Merge user params with needed special params, avoiding conflicts- param_dict = validated_params.model_dump()-- # Extract special parameters needed by this function (keep objects, don't serialize)- needed_special_params = set(parameter_names) & set(SpecialActionParameters.model_fields.keys())- injection_params = {}- for param_name in needed_special_params:- value = getattr(special_params, param_name, None)- if value is not None:- injection_params[param_name] = value-- # Remove any special params from user params to avoid conflicts (special params take precedence)- for param_name in injection_params:- if param_name in param_dict:- logger.debug(f'Removing {param_name} from param_dict to avoid conflict')- param_dict.pop(param_name)-- # Combine all parameters- final_params = {**param_dict, **injection_params}- return await action.function(**final_params)-+ raise RuntimeError(f'Error executing action {action_name}: {str(e)}') from eexcept Exception as e:raise RuntimeError(f'Error executing action {action_name}: {str(e)}') from ediff --git a/docs/customize/custom-functions.mdx b/docs/customize/custom-functions.mdxindex 0c729c313..d51965d58 100644--- a/docs/customize/custom-functions.mdx+++ b/docs/customize/custom-functions.mdx@@ -14,7 +14,7 @@ from browser_use import Controller, ActionResultcontroller = Controller()@controller.action('Ask user for information', domains=['https://difficult.example.com']) # pass domains= or page_filter= to limit actions to certain pages-def ask_human(question: str) -> str:+def ask_human(question: str) -> ActionResult:answer = input(f'\n{question}\nInput: ')return ActionResult(extracted_content=answer)```@@ -41,7 +41,15 @@ agent = Agent(## Browser-Aware Functions-For actions that need page or browser access, simply add the `browser_session` or `page` parameter inside the function parameters:+For actions that need browser access, add special parameters after your action parameters. The framework will automatically inject these:++### Available Special Parameters+- `browser_session: BrowserSession` - The current browser session+- `page: Page` - The current Playwright page (shortcut for `browser_session.get_current_page()`)+- `context: AgentContext` - Full agent context including history+- `page_extraction_llm: BaseChatModel` - LLM instance for page content extraction+- `available_file_paths: list[str]` - List of available file paths+- `has_sensitive_data: bool` - Whether the page contains sensitive data```pythonfrom playwright.async_api import Page@@ -50,7 +58,7 @@ from browser_use import Controller, ActionResultcontroller = Controller()@controller.action('Open website')-async def open_website(url: str, page: Page):+async def open_website(url: str, page: Page) -> ActionResult:await page.goto(url)return ActionResult(extracted_content='Website opened')```@@ -60,7 +68,7 @@ from browser_use import BrowserSession, Controller, ActionResultcontroller = Controller()@controller.action('Open website')-async def open_website(url: str, browser_session: BrowserSession):+async def open_website(url: str, browser_session: BrowserSession) -> ActionResult:page = await browser_session.get_current_page()await page.goto(url)return ActionResult(extracted_content='Website opened')@@ -68,12 +76,12 @@ async def open_website(url: str, browser_session: BrowserSession):## Structured Parameters with Pydantic-For complex actions, you can define parameter schemas using Pydantic models:+For complex actions, define parameter schemas using Pydantic models. When using `param_model`, your function should accept the model as its first parameter:```pythonfrom pydantic import BaseModelfrom typing import Optional-from browser_use import Controller, ActionResult, Browser+from browser_use import Controller, ActionResult, BrowserSessioncontroller = Controller()@@ -87,14 +95,52 @@ class JobDetails(BaseModel):'Save job details which you found on page',param_model=JobDetails)-async def save_job(params: JobDetails, browser: Browser):+async def save_job(params: JobDetails, browser_session: BrowserSession) -> ActionResult:print(f"Saving job: {params.title} at {params.company}")# Access browser if needed- page = browser.get_current_page()+ page = await browser_session.get_current_page()await page.goto(params.job_link)++ return ActionResult(extracted_content=f"Saved job: {params.title}")+```++## Action Definition Patterns++Browser Use supports two patterns for defining actions:++### Pattern 1: Pydantic Model First (Recommended for complex parameters)+When using `param_model`, your function receives the model instance as the first parameter:++```python+class MyParams(BaseModel):+ field1: str+ field2: int+[email protected]('My action', param_model=MyParams)+def my_action(params: MyParams, page: Page) -> ActionResult:+ # params contains all action parameters+ return ActionResult(extracted_content=f"Processed {params.field1}")```+### Pattern 2: Loose Parameters (Recommended for simple actions)+Define parameters directly as function arguments:++```python[email protected]('Click element')+def click_element(index: int, browser_session: BrowserSession) -> ActionResult:+ # index is the action parameter+ # browser_session is a special injected parameter+ return ActionResult(extracted_content=f"Clicked element {index}")+```++### Important Rules++1. **No **kwargs allowed**: Actions must use explicit parameters only+2. **Return ActionResult**: All actions should return an `ActionResult` instance+3. **Special parameters come after action parameters**: Always define your action parameters first, then any special parameters you need+4. **Type hints are recommended**: They help with validation and IDE support+## Using Custom Actions with multiple agentsYou can use the same controller for multiple agents.diff --git a/tests/ci/test_action_registry.py b/tests/ci/test_action_registry.pyindex 537db48c5..414436a86 100644--- a/tests/ci/test_action_registry.py+++ b/tests/ci/test_action_registry.py@@ -235,12 +235,14 @@ class TestActionRegistryParameterPatterns:async def test_mixed_special_parameters(self, registry, browser_session, base_url, mock_llm):"""Test action with multiple special injected parameters"""+ from langchain_core.language_models.chat_models import BaseChatModel+@registry.action('Action with multiple special params')async def multi_special_action(text: str,browser_session: BrowserSession,- page_extraction_llm: MockLLM,- available_file_paths: list[str] | None = None,+ page_extraction_llm: BaseChatModel,+ available_file_paths: list,):page = await browser_session.get_current_page()llm_response = await page_extraction_llm.ainvoke('test')@@ -354,20 +356,22 @@ class TestActionToActionCalling:return ActionResult(extracted_content=f'Selected cell {cell_or_range} on {page.url}')@registry.action('Select cell or range')- async def select_cell_or_range(browser_session: BrowserSession, cell_or_range: str):- # This is the PROBLEMATIC pattern that currently fails- # Passing browser_session by name causes "multiple values for argument" error+ async def select_cell_or_range(cell_or_range: str, browser_session: BrowserSession):+ # This pattern now works with kwargsreturn await _select_cell_or_range(browser_session=browser_session, cell_or_range=cell_or_range)@registry.action('Select cell or range (fixed)')- async def select_cell_or_range_fixed(browser_session: BrowserSession, cell_or_range: str):- # This is the WORKING pattern using positional args+ async def select_cell_or_range_fixed(cell_or_range: str, browser_session: BrowserSession):+ # This pattern also worksreturn await _select_cell_or_range(browser_session, cell_or_range)@registry.action('Update range contents')- async def update_range_contents(browser_session: BrowserSession, range_name: str, new_contents: str):+ async def update_range_contents(range_name: str, new_contents: str, browser_session: BrowserSession):# This action calls select_cell_or_range, simulating the real Google Sheets pattern- await select_cell_or_range_fixed(browser_session, range_name) # Should use positional args+ # Get the action's param model to call it properly+ action = registry.registry.actions['select_cell_or_range_fixed']+ params = action.param_model(cell_or_range=range_name)+ await select_cell_or_range_fixed(params=params, browser_session=browser_session)return ActionResult(extracted_content=f'Updated range {range_name} with {new_contents}')# Test the fixed version (should work)@@ -383,18 +387,13 @@ class TestActionToActionCalling:)assert 'Updated range B2:D4 with test data' in result_chain.extracted_content- # Test the problematic version (may fail with current registry, should work with enhanced registry)- try:- result_problematic = await registry.execute_action(- 'select_cell_or_range', {'cell_or_range': 'A1:F100'}, browser_session=test_browser- )- # If this succeeds, great! The enhanced registry is working- assert 'Selected cell A1:F100 on' in result_problematic.extracted_content- assert '/test' in result_problematic.extracted_content- except TypeError as e:- # This is the expected error with the current registry- assert 'multiple values for argument' in str(e) or 'got multiple values' in str(e)- logger.info(f'Expected error with current registry: {e}')+ # Test the problematic version (should work with enhanced registry)+ result_problematic = await registry.execute_action(+ 'select_cell_or_range', {'cell_or_range': 'A1:F100'}, browser_session=test_browser+ )+ # With the enhanced registry, this should succeed+ assert 'Selected cell A1:F100 on' in result_problematic.extracted_content+ assert '/test' in result_problematic.extracted_content@pytest.mark.asyncioasync def test_complex_action_chain(self, registry, test_browser):@@ -453,8 +452,10 @@ class TestRegistryEdgeCases:async def test_missing_required_llm(self, registry, test_browser):"""Test that actions requiring page_extraction_llm fail appropriately when not provided"""+ from langchain_core.language_models.chat_models import BaseChatModel+@registry.action('Requires LLM')- async def requires_llm(text: str, browser_session: BrowserSession, page_extraction_llm: MockLLM):+ async def requires_llm(text: str, browser_session: BrowserSession, page_extraction_llm: BaseChatModel):page = await browser_session.get_current_page()llm_response = await page_extraction_llm.ainvoke('test')return ActionResult(extracted_content=f'Text: {text}, LLM: {llm_response.content}')diff --git a/tests/ci/test_debug_selector_map.py b/tests/ci/test_debug_selector_map.pyindex e491b27c1..bccefe2df 100644--- a/tests/ci/test_debug_selector_map.py+++ b/tests/ci/test_debug_selector_map.py@@ -130,7 +130,7 @@ async def test_assumption_4_click_action_specific_issue(browser_session, control# Create a test action that replicates click_element_by_index logic@controller.registry.action('Test: Debug click logic')- async def test_debug_click_logic(browser_session: BrowserSession, index: int):+ async def test_debug_click_logic(index: int, browser_session: BrowserSession):from browser_use import ActionResult# This is the exact logic from click_element_by_indexdiff --git a/tests/test_action_registry_normalization.py b/tests/test_action_registry_normalization.pyindex 0bfc93faf..ecffb7a2f 100644--- a/tests/test_action_registry_normalization.py+++ b/tests/test_action_registry_normalization.py@@ -13,12 +13,14 @@ from browser_use.browser import BrowserSessionfrom browser_use.controller.registry.service import Registry-class MockBrowserSession(BrowserSession):+class MockBrowserSession:"""Mock BrowserSession for testing"""def __init__(self):- # Don't call super().__init__() to avoid real browser- pass+ self.agent_current_page = None++ async def get_current_page(self):+ return MockPage()class MockPage:@@ -30,6 +32,10 @@ class MockPage:class MockLLM(BaseChatModel):"""Mock LLM for testing"""+ @property+ def _llm_type(self) -> str:+ return 'mock'+def _generate(self, *args, **kwargs):pass@@ -99,8 +105,8 @@ class TestType2Pattern:# Should auto-generate param modelassert action.param_model is not None- assert hasattr(action.param_model, 'index')- assert hasattr(action.param_model, 'text')+ assert 'index' in action.param_model.model_fields+ assert 'text' in action.param_model.model_fieldsdef test_type2_with_defaults(self):"""Type 2 with default values should preserve defaults"""@@ -402,9 +408,7 @@ class TestInterActionCalls:result = await inner_action(params=inner_model(text='Hello'), **special_context)return result- result = await registry.execute_action(- action_name='outer_action', params={}, browser_session=MockBrowserSession(), page=MockPage()- )+ result = await registry.execute_action(action_name='outer_action', params={}, browser_session=MockBrowserSession())assert 'Inner: Hello, has page: True' in result.extracted_content