Skip to content

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

update pydantic action models exposed to LLM on each page

Nick Sweeting5535a1ec0aa2
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 4731191b6..f355b9626 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -308,6 +308,7 @@ class Agent(Generic[Context]):
def _setup_action_models(self) -> None:
"""Setup dynamic action models from controller's registry"""
+ # Initially only include actions with no filters
self.ActionModel = self.controller.registry.create_action_model()
# Create output model with the dynamic actions
self.AgentOutput = AgentOutput.type_with_custom_actions(self.ActionModel)
@@ -359,25 +360,29 @@ class Agent(Generic[Context]):
try:
state = await self.browser_context.get_state()
+ active_page = await self.browser_context.get_current_page()
await self._raise_if_stopped_or_paused()
-
+
+ # Update action models with page-specific actions
+ await self._update_action_models_for_page(active_page)
+
# Get page-specific filtered actions
- page_filtered_actions = self.controller.registry.get_prompt_description(state.page)
-
+ page_filtered_actions = self.controller.registry.get_prompt_description(active_page)
+
# If there are page-specific actions, add them as a special message for this step only
if page_filtered_actions:
- page_action_message = f"For this page, these additional actions are available:\n{page_filtered_actions}"
+ page_action_message = f'For this page, these additional actions are available:\n{page_filtered_actions}'
self._message_manager._add_message_with_tokens(HumanMessage(content=page_action_message))
-
+
# If using raw tool calling method, we need to update the message context with new actions
if self.tool_calling_method == 'raw':
# For raw tool calling, get all non-filtered actions plus the page-filtered ones
all_unfiltered_actions = self.controller.registry.get_prompt_description()
all_actions = all_unfiltered_actions
if page_filtered_actions:
- all_actions += "\n" + page_filtered_actions
-
+ all_actions += '\n' + page_filtered_actions
+
context_lines = self._message_manager.settings.message_context.split('\n')
non_action_lines = [line for line in context_lines if not line.startswith('Available actions:')]
updated_context = '\n'.join(non_action_lines)
@@ -1143,16 +1148,16 @@ class Agent(Generic[Context]):
# Get current state to filter actions by page
state = await self.browser_context.get_state()
-
+
# Get all standard actions (no filter) and page-specific actions
standard_actions = self.controller.registry.get_prompt_description() # No page = system prompt actions
page_actions = self.controller.registry.get_prompt_description(state.page) # Page-specific actions
-
+
# Combine both for the planner
all_actions = standard_actions
if page_actions:
- all_actions += "\n" + page_actions
-
+ all_actions += '\n' + page_actions
+
# Create planner message history using full message history with all available actions
planner_messages = [
PlannerPrompt(all_actions).get_system_message(),
@@ -1217,4 +1222,15 @@ class Agent(Generic[Context]):
gc.collect()
except Exception as e:
- logger.error(f'Error during cleanup: {e}')
\ No newline at end of file
+ logger.error(f'Error during cleanup: {e}')
+
+ async def _update_action_models_for_page(self, page) -> None:
+ """Update action models with page-specific actions"""
+ # Create new action model with current page's filtered actions
+ self.ActionModel = self.controller.registry.create_action_model(page=page)
+ # Update output model with the new actions
+ self.AgentOutput = AgentOutput.type_with_custom_actions(self.ActionModel)
+
+ # Update done action model too
+ self.DoneActionModel = self.controller.registry.create_action_model(include_actions=['done'], page=page)
+ self.DoneAgentOutput = AgentOutput.type_with_custom_actions(self.DoneActionModel)
diff --git a/browser_use/controller/registry/service.py b/browser_use/controller/registry/service.py
index 802603c2b..511a5ab0e 100644
--- a/browser_use/controller/registry/service.py
+++ b/browser_use/controller/registry/service.py
@@ -175,23 +175,51 @@ class Registry(Generic[Context]):
return params
@time_execution_sync('--create_action_model')
- def create_action_model(self, include_actions: Optional[list[str]] = None) -> Type[ActionModel]:
+ def create_action_model(self, include_actions: Optional[list[str]] = None, page=None) -> Type[ActionModel]:
"""Creates a Pydantic model from registered actions"""
+ # Filter actions based on page if provided
+ available_actions = {}
+ for name, action in self.registry.actions.items():
+ if include_actions is not None and name not in include_actions:
+ continue
+
+ # If no page provided, only include actions with no filters
+ if page is None:
+ if action.page_filter is None and action.domains is None:
+ available_actions[name] = action
+ continue
+
+ # Check page_filter if present
+ page_filter_match = True # Default to True if no filter
+ if action.page_filter is not None:
+ page_filter_match = action.page_filter(page)
+
+ # Check domains if present
+ domains_match = False
+ if action.domains is not None and page.url:
+ # Try to match any of the domain patterns
+ for domain_pattern in action.domains:
+ if self.registry._match_domain(domain_pattern, page.url):
+ domains_match = True
+ break
+
+ # Only include action if either filter matches
+ if page_filter_match or domains_match:
+ available_actions[name] = action
+
fields = {
name: (
Optional[action.param_model],
Field(default=None, description=action.description),
)
- for name, action in self.registry.actions.items()
- if include_actions is None or name in include_actions
+ for name, action in available_actions.items()
}
self.telemetry.capture(
ControllerRegisteredFunctionsTelemetryEvent(
registered_functions=[
RegisteredFunction(name=name, params=action.param_model.model_json_schema())
- for name, action in self.registry.actions.items()
- if include_actions is None or name in include_actions
+ for name, action in available_actions.items()
]
)
)
@@ -200,8 +228,8 @@ class Registry(Generic[Context]):
def get_prompt_description(self, page=None) -> str:
"""Get a description of all actions for the prompt
-
+
If page is provided, only include actions that are available for that page
based on their filter_func
"""
- return self.registry.get_prompt_description(page)
+ return self.registry.get_prompt_description(page=page)
diff --git a/browser_use/controller/registry/views.py b/browser_use/controller/registry/views.py
index afccc8ccb..ecaed9b7e 100644
--- a/browser_use/controller/registry/views.py
+++ b/browser_use/controller/registry/views.py
@@ -73,39 +73,39 @@ class ActionRegistry(BaseModel):
def _match_domain(self, domain_pattern: str, url: str) -> bool:
"""
Match a domain pattern against a URL using glob patterns.
-
+
Args:
domain_pattern: A domain pattern that can include glob patterns (* wildcard)
url: The URL to match against
-
+
Returns:
True if the URL's domain matches the pattern, False otherwise
"""
import fnmatch
from urllib.parse import urlparse
-
+
# Parse the URL to get the domain
try:
parsed_url = urlparse(url)
if not parsed_url.netloc:
return False
-
+
domain = parsed_url.netloc
# Remove port if present
if ':' in domain:
domain = domain.split(':')[0]
-
+
# Perform glob matching
return fnmatch.fnmatch(domain, domain_pattern)
except Exception:
return False
-
+
def get_prompt_description(self, page=None) -> str:
"""Get a description of all actions for the prompt
-
+
Args:
page: If provided, filter actions by page using page_filter and domains.
-
+
Returns:
A string description of available actions.
- If page is None: return only actions with no page_filter and no domains (for system prompt)
@@ -113,15 +113,20 @@ class ActionRegistry(BaseModel):
"""
if page is None:
# For system prompt (no page provided), include only actions with no filters
- return '\n'.join([action.prompt_description() for action in self.actions.values()
- if action.page_filter is None and action.domains is None])
-
+ return '\n'.join(
+ action.prompt_description()
+ for action in self.actions.values()
+ if action.page_filter is None and action.domains is None
+ )
+
# For step-by-step prompts, include filtered actions for the current page
filtered_actions = []
for action in self.actions.values():
# Check page_filter if present
- page_filter_match = action.page_filter is not None and action.page_filter(page)
-
+ page_filter_match = True # Default to True if no filter
+ if action.page_filter is not None:
+ page_filter_match = action.page_filter(page)
+
# Check domains if present
domains_match = False
if action.domains is not None and page.url:
@@ -130,9 +135,9 @@ class ActionRegistry(BaseModel):
if self._match_domain(domain_pattern, page.url):
domains_match = True
break
-
+
# Include action if either filter matches
if page_filter_match or domains_match:
filtered_actions.append(action)
-
- return '\n'.join([action.prompt_description() for action in filtered_actions])
+
+ return '\n'.join(action.prompt_description() for action in filtered_actions)
diff --git a/examples/use-cases/google_sheets.py b/examples/use-cases/google_sheets.py
index 3cb542e0d..5917cbe9c 100644
--- a/examples/use-cases/google_sheets.py
+++ b/examples/use-cases/google_sheets.py
@@ -29,7 +29,7 @@ controller = Controller()
def is_google_sheet(page) -> bool:
- return page.url.startswith('https://docs.google.com/spreadsheets/')
+ return page.url.startswith('https://docas.google.com/spreadsheets/')
# TODO: refactor if not is_google_sheet(page): checks below to something like this:
@@ -49,11 +49,9 @@ async def open_google_sheet(browser: BrowserContext, google_sheet_url: str):
return ActionResult(extracted_content=f'Opened Google Sheet {google_sheet_url}', include_in_memory=False)
[email protected]('Google Sheets: Get the contents of the entire sheet')
[email protected]('Google Sheets: Get the contents of the entire sheet', page_filter=is_google_sheet)
async def get_sheet_contents(browser: BrowserContext):
page = await browser.get_current_page()
- if not is_google_sheet(page):
- return ActionResult(error='Current page is not a Google Sheet')
# select all cells
await page.keyboard.press('Enter')
@@ -65,11 +63,9 @@ async def get_sheet_contents(browser: BrowserContext):
return ActionResult(extracted_content=extracted_tsv, include_in_memory=True)
[email protected]('Google Sheets: Select a specific cell or range of cells')
[email protected]('Google Sheets: Select a specific cell or range of cells', page_filter=is_google_sheet)
async def select_cell_or_range(browser: BrowserContext, cell_or_range: str):
page = await browser.get_current_page()
- if not is_google_sheet(page):
- return ActionResult(error='Current page is not a Google Sheet')
await page.keyboard.press('Enter') # make sure we dont delete current cell contents if we were last editing
await page.keyboard.press('Escape') # to clear current focus (otherwise select range popup is additive)
@@ -87,11 +83,9 @@ async def select_cell_or_range(browser: BrowserContext, cell_or_range: str):
return ActionResult(extracted_content=f'Selected cell {cell_or_range}', include_in_memory=False)
[email protected]('Google Sheets: Get the contents of a specific cell or range of cells')
[email protected]('Google Sheets: Get the contents of a specific cell or range of cells', page_filter=is_google_sheet)
async def get_range_contents(browser: BrowserContext, cell_or_range: str):
page = await browser.get_current_page()
- if not is_google_sheet(page):
- return ActionResult(error='Current page is not a Google Sheet')
await select_cell_or_range(browser, cell_or_range)
@@ -101,21 +95,17 @@ async def get_range_contents(browser: BrowserContext, cell_or_range: str):
return ActionResult(extracted_content=extracted_tsv, include_in_memory=True)
[email protected]('Google Sheets: Clear the currently selected cells')
[email protected]('Google Sheets: Clear the currently selected cells', page_filter=is_google_sheet)
async def clear_selected_range(browser: BrowserContext):
page = await browser.get_current_page()
- if not is_google_sheet(page):
- return ActionResult(error='Current page is not a Google Sheet')
await page.keyboard.press('Backspace')
return ActionResult(extracted_content='Cleared selected range', include_in_memory=False)
[email protected]('Google Sheets: Input text into the currently selected cell')
[email protected]('Google Sheets: Input text into the currently selected cell', page_filter=is_google_sheet)
async def input_selected_cell_text(browser: BrowserContext, text: str):
page = await browser.get_current_page()
- if not is_google_sheet(page):
- return ActionResult(error='Current page is not a Google Sheet')
await page.keyboard.type(text, delay=0.1)
await page.keyboard.press('Enter') # make sure to commit the input so it doesnt get overwritten by the next action
@@ -123,11 +113,9 @@ async def input_selected_cell_text(browser: BrowserContext, text: str):
return ActionResult(extracted_content=f'Inputted text {text}', include_in_memory=False)
[email protected]('Google Sheets: Batch update a range of cells')
[email protected]('Google Sheets: Batch update a range of cells', page_filter=is_google_sheet)
async def update_range_contents(browser: BrowserContext, range: str, new_contents_tsv: str):
page = await browser.get_current_page()
- if not is_google_sheet(page):
- return ActionResult(error='Current page is not a Google Sheet')
await select_cell_or_range(browser, range)
diff --git a/pyproject.toml b/pyproject.toml
index 73d1f91c2..8af71815e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -80,6 +80,7 @@ include = [
[tool.uv]
dev-dependencies = [
+ "ipdb>=0.13.13",
"ruff>=0.11.2",
]
diff --git a/tests/test_action_filters.py b/tests/test_action_filters.py
index 3272a0481..cb2b565b3 100644
--- a/tests/test_action_filters.py
+++ b/tests/test_action_filters.py
@@ -203,7 +203,7 @@ class TestActionFilters:
assert 'domain_only' in description
assert 'page_only' in description
assert 'both_matching' in description
- assert 'both_one_fail' in description # Should match because page_filter matches
+ assert 'both_one_fail' not in description # Should not match because domain filter fails
@pytest.mark.asyncio
async def test_registry_action_decorator(self):
@@ -238,3 +238,45 @@ class TestActionFilters:
page_description = registry.get_prompt_description(mock_page)
assert 'Domain filter action' in page_description
assert 'Page filter action' in page_description
+
+ @pytest.mark.asyncio
+ async def test_action_model_creation(self):
+ """Test that action models are created correctly with filters"""
+ registry = Registry()
+
+ # Define actions with different filters
+ @registry.action(
+ description='No filter action',
+ )
+ def no_filter_action():
+ pass
+
+ @registry.action(description='Domain filter action', domains=['example.com'])
+ def domain_filter_action():
+ pass
+
+ @registry.action(description='Page filter action', page_filter=lambda page: 'admin' in page.url)
+ def page_filter_action():
+ pass
+
+ # Initial action model should only include no_filter_action
+ initial_model = registry.create_action_model()
+ assert 'no_filter_action' in initial_model.model_fields
+ assert 'domain_filter_action' not in initial_model.model_fields
+ assert 'page_filter_action' not in initial_model.model_fields
+
+ # Action model with page should include matching actions
+ mock_page = MagicMock(spec=Page)
+ mock_page.url = 'https://example.com/admin'
+
+ page_model = registry.create_action_model(page=mock_page)
+ assert 'no_filter_action' in page_model.model_fields
+ assert 'domain_filter_action' in page_model.model_fields
+ assert 'page_filter_action' in page_model.model_fields
+
+ # Action model with non-matching page should only include no_filter_action
+ mock_page.url = 'https://other.com/page'
+ non_matching_model = registry.create_action_model(page=mock_page)
+ assert 'no_filter_action' in non_matching_model.model_fields
+ assert 'domain_filter_action' not in non_matching_model.model_fields
+ assert 'page_filter_action' not in non_matching_model.model_fields