Skip to content

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

add support for filtering actions by func or domain globs

Nick Sweetingf941a5cec926
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 0e6f9b4b4..4731191b6 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -197,13 +197,15 @@ class Agent(Generic[Context]):
# Start non-blocking LLM connection verification
self.llm._verified_api_keys = self._verify_llm_connection(self.llm)
- # for models without tool calling, add available actions to context
+ # Initialize available actions for system prompt (only non-filtered actions)
+ # These will be used for the system prompt to maintain caching
self.available_actions = self.controller.registry.get_prompt_description()
self.tool_calling_method = self._set_tool_calling_method()
self.settings.message_context = self._set_message_context()
# Initialize message manager with state
+ # Initial system prompt with all actions - will be updated during each step
self._message_manager = MessageManager(
task=task,
system_message=SystemPrompt(
@@ -359,6 +361,31 @@ class Agent(Generic[Context]):
state = await self.browser_context.get_state()
await self._raise_if_stopped_or_paused()
+
+ # Get page-specific filtered actions
+ page_filtered_actions = self.controller.registry.get_prompt_description(state.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}"
+ 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
+
+ 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)
+ if updated_context:
+ updated_context += f'\n\nAvailable actions: {all_actions}'
+ else:
+ updated_context = f'Available actions: {all_actions}'
+ self._message_manager.settings.message_context = updated_context
self._message_manager.add_state_message(state, self.state.last_result, step_info, self.settings.use_vision)
@@ -1114,9 +1141,21 @@ class Agent(Generic[Context]):
if not self.settings.planner_llm:
return None
- # Create planner message history using full message history
+ # 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
+
+ # Create planner message history using full message history with all available actions
planner_messages = [
- PlannerPrompt(self.controller.registry.get_prompt_description()).get_system_message(),
+ PlannerPrompt(all_actions).get_system_message(),
*self._message_manager.get_messages()[1:], # Use full message history except the first
]
@@ -1178,4 +1217,4 @@ class Agent(Generic[Context]):
gc.collect()
except Exception as e:
- logger.error(f'Error during cleanup: {e}')
+ logger.error(f'Error during cleanup: {e}')
\ No newline at end of file
diff --git a/browser_use/controller/registry/service.py b/browser_use/controller/registry/service.py
index 81f86aa0f..802603c2b 100644
--- a/browser_use/controller/registry/service.py
+++ b/browser_use/controller/registry/service.py
@@ -50,6 +50,7 @@ class Registry(Generic[Context]):
description: str,
param_model: Optional[Type[BaseModel]] = None,
domains: Optional[list[str]] = None,
+ page_filter: Optional[Callable[[Any], bool]] = None,
):
"""Decorator for registering actions"""
@@ -81,6 +82,7 @@ class Registry(Generic[Context]):
function=wrapped_func,
param_model=actual_param_model,
domains=domains,
+ page_filter=page_filter,
)
self.registry.actions[func.__name__] = action
return func
@@ -196,6 +198,10 @@ class Registry(Generic[Context]):
return create_model('ActionModel', __base__=ActionModel, **fields) # type:ignore
- def get_prompt_description(self) -> str:
- """Get a description of all actions for the prompt"""
- return self.registry.get_prompt_description()
+ 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)
diff --git a/browser_use/controller/registry/views.py b/browser_use/controller/registry/views.py
index 75b8959b3..afccc8ccb 100644
--- a/browser_use/controller/registry/views.py
+++ b/browser_use/controller/registry/views.py
@@ -1,5 +1,6 @@
from typing import Callable, Dict, Type
+from playwright.async_api import Page
from pydantic import BaseModel, ConfigDict
@@ -10,7 +11,10 @@ class RegisteredAction(BaseModel):
description: str
function: Callable
param_model: Type[BaseModel]
+
+ # filters: provide specific domains or a function to determine whether the action should be available on the given page or not
domains: list[str] | None = None # e.g. ['*.google.com', 'www.bing.com', 'yahoo.*]
+ page_filter: Callable[[Page], bool] | None = None
model_config = ConfigDict(arbitrary_types_allowed=True)
@@ -66,6 +70,69 @@ class ActionRegistry(BaseModel):
actions: Dict[str, RegisteredAction] = {}
- def get_prompt_description(self) -> str:
- """Get a description of all actions for the prompt"""
- return '\n'.join([action.prompt_description() for action in self.actions.values()])
+ 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)
+ - If page is provided: return filtered actions for the current page
+ """
+ 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])
+
+ # 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)
+
+ # 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._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])