Skip to content

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

Extract always first content with llm and keep that extraction in context

magmuellerbef3b03da95c
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 72a72cdab..f7977815c 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -97,9 +97,15 @@ class Agent:
register_new_step_callback: Callable[['BrowserState', 'AgentOutput', int], None] | None = None,
register_done_callback: Callable[['AgentHistoryList'], None] | None = None,
tool_calling_method: Optional[str] = 'auto',
+ page_extraction_llm: Optional[BaseChatModel] = None,
):
self.agent_id = str(uuid.uuid4()) # unique identifier for the agent
+ if not page_extraction_llm:
+ self.page_extraction_llm = llm
+ else:
+ self.page_extraction_llm = page_extraction_llm
+
self.task = task
self.use_vision = use_vision
self.llm = llm
@@ -264,7 +270,9 @@ class Agent:
self.message_manager._remove_last_state_message()
raise e
- result: list[ActionResult] = await self.controller.multi_act(model_output.action, self.browser_context)
+ result: list[ActionResult] = await self.controller.multi_act(
+ model_output.action, self.browser_context, page_extraction_llm=self.page_extraction_llm
+ )
self._last_result = result
if len(result) > 0 and result[-1].is_done:
@@ -470,7 +478,12 @@ class Agent:
# Execute initial actions if provided
if self.initial_actions:
- result = await self.controller.multi_act(self.initial_actions, self.browser_context, check_for_new_elements=False)
+ result = await self.controller.multi_act(
+ self.initial_actions,
+ self.browser_context,
+ check_for_new_elements=False,
+ page_extraction_llm=self.page_extraction_llm,
+ )
self._last_result = result
for step in range(max_steps):
@@ -558,7 +571,7 @@ class Agent:
state=state,
result=self._last_result,
include_attributes=self.include_attributes,
- max_error_length=self.max_error_length
+ max_error_length=self.max_error_length,
)
msg = [SystemMessage(content=system_msg), content.get_user_message(self.use_vision)]
else:
@@ -658,7 +671,9 @@ class Agent:
if updated_action is None:
raise ValueError(f'Could not find matching element {i} in current page')
- result = await self.controller.multi_act(updated_actions, self.browser_context)
+ result = await self.controller.multi_act(
+ updated_actions, self.browser_context, page_extraction_llm=self.page_extraction_llm
+ )
await asyncio.sleep(delay)
return result
diff --git a/browser_use/agent/tests.py b/browser_use/agent/tests.py
index 624a6aeda..fa330c576 100644
--- a/browser_use/agent/tests.py
+++ b/browser_use/agent/tests.py
@@ -37,15 +37,12 @@ def action_registry():
registry = Registry()
# Register the actions we need for testing
- @registry.action(
- description='Click an element', requires_browser=True, param_model=ClickElementAction
- )
+ @registry.action(description='Click an element', param_model=ClickElementAction)
def click_element(params: ClickElementAction, browser=None):
pass
@registry.action(
description='Extract page content',
- requires_browser=True,
param_model=ExtractPageContentAction,
)
def extract_page_content(params: ExtractPageContentAction, browser=None):
@@ -71,9 +68,7 @@ def sample_history(action_registry):
histories = [
AgentHistory(
model_output=AgentOutput(
- current_state=AgentBrain(
- evaluation_previous_goal='None', memory='Started task', next_goal='Click button'
- ),
+ current_state=AgentBrain(evaluation_previous_goal='None', memory='Started task', next_goal='Click button'),
action=[click_action],
),
result=[ActionResult(is_done=False)],
diff --git a/browser_use/controller/registry/service.py b/browser_use/controller/registry/service.py
index ab62513c7..a8200ffd4 100644
--- a/browser_use/controller/registry/service.py
+++ b/browser_use/controller/registry/service.py
@@ -2,6 +2,7 @@ import asyncio
from inspect import iscoroutinefunction, signature
from typing import Any, Callable, Optional, Type
+from langchain_core.language_models.chat_models import BaseChatModel
from pydantic import BaseModel, Field, create_model
from browser_use.browser.context import BrowserContext
@@ -31,7 +32,7 @@ class Registry:
params = {
name: (param.annotation, ... if param.default == param.empty else param.default)
for name, param in sig.parameters.items()
- if name != 'browser'
+ if name != 'browser' and name != 'page_extraction_llm'
}
# TODO: make the types here work
return create_model(
@@ -44,7 +45,6 @@ class Registry:
self,
description: str,
param_model: Optional[Type[BaseModel]] = None,
- requires_browser: bool = False,
):
"""Decorator for registering actions"""
@@ -75,14 +75,19 @@ class Registry:
description=description,
function=wrapped_func,
param_model=actual_param_model,
- requires_browser=requires_browser,
)
self.registry.actions[func.__name__] = action
return func
return decorator
- async def execute_action(self, action_name: str, params: dict, browser: Optional[BrowserContext] = None) -> Any:
+ async def execute_action(
+ self,
+ action_name: str,
+ params: dict,
+ browser: Optional[BrowserContext] = None,
+ page_extraction_llm: Optional[BaseChatModel] = None,
+ ) -> Any:
"""Execute a registered action"""
if action_name not in self.registry.actions:
raise ValueError(f'Action {action_name} not found')
@@ -96,17 +101,33 @@ class Registry:
sig = signature(action.function)
parameters = list(sig.parameters.values())
is_pydantic = parameters and issubclass(parameters[0].annotation, BaseModel)
-
+ parameter_names = [param.name for param in parameters]
# Prepare arguments based on parameter type
- if action.requires_browser:
+ if 'browser' in parameter_names and 'page_extraction_llm' in parameter_names:
if not browser:
- raise ValueError(
- f'Action {action_name} requires browser but none provided. This has to be used in combination of `requires_browser=True` when registering the action.'
- )
+ raise ValueError(f'Action {action_name} requires browser but none provided.')
+ if not page_extraction_llm:
+ raise ValueError(f'Action {action_name} requires page_extraction_llm but none provided.')
+ if is_pydantic:
+ return await action.function(validated_params, browser=browser, page_extraction_llm=page_extraction_llm)
+ return await action.function(
+ **validated_params.model_dump(), browser=browser, page_extraction_llm=page_extraction_llm
+ )
+
+ if 'browser' in parameter_names:
+ if not browser:
+ raise ValueError(f'Action {action_name} requires browser but none provided.')
if is_pydantic:
return await action.function(validated_params, browser=browser)
return await action.function(**validated_params.model_dump(), browser=browser)
+ if 'page_extraction_llm' in parameter_names:
+ if not page_extraction_llm:
+ raise ValueError(f'Action {action_name} requires page_extraction_llm but none provided.')
+ if is_pydantic:
+ return await action.function(validated_params, page_extraction_llm=page_extraction_llm)
+ return await action.function(**validated_params.model_dump(), page_extraction_llm=page_extraction_llm)
+
if is_pydantic:
return await action.function(validated_params)
return await action.function(**validated_params.model_dump())
diff --git a/browser_use/controller/registry/views.py b/browser_use/controller/registry/views.py
index ebb4c998e..211c767a3 100644
--- a/browser_use/controller/registry/views.py
+++ b/browser_use/controller/registry/views.py
@@ -10,7 +10,6 @@ class RegisteredAction(BaseModel):
description: str
function: Callable
param_model: Type[BaseModel]
- requires_browser: bool = False
model_config = ConfigDict(arbitrary_types_allowed=True)
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index 7c04ec995..4285e82ae 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -4,7 +4,6 @@ import logging
from typing import Optional, Type
from langchain_core.prompts import PromptTemplate
-from main_content_extractor import MainContentExtractor
from pydantic import BaseModel
from browser_use.agent.views import ActionModel, ActionResult
@@ -33,13 +32,11 @@ class Controller:
self,
exclude_actions: list[str] = [],
output_model: Optional[Type[BaseModel]] = None,
- llm: Optional[BaseChatModel] = None,
):
self.exclude_actions = exclude_actions
self.output_model = output_model
self.registry = Registry(exclude_actions)
self._register_default_actions()
- self.llm = llm
def _register_default_actions(self):
"""Register all default browser actions"""
@@ -59,7 +56,6 @@ class Controller:
@self.registry.action(
'Search Google in the current tab',
param_model=SearchGoogleAction,
- requires_browser=True,
)
async def search_google(params: SearchGoogleAction, browser: BrowserContext):
page = await browser.get_current_page()
@@ -69,7 +65,7 @@ class Controller:
logger.info(msg)
return ActionResult(extracted_content=msg, include_in_memory=True)
- @self.registry.action('Navigate to URL in the current tab', param_model=GoToUrlAction, requires_browser=True)
+ @self.registry.action('Navigate to URL in the current tab', param_model=GoToUrlAction)
async def go_to_url(params: GoToUrlAction, browser: BrowserContext):
page = await browser.get_current_page()
await page.goto(params.url)
@@ -78,7 +74,7 @@ class Controller:
logger.info(msg)
return ActionResult(extracted_content=msg, include_in_memory=True)
- @self.registry.action('Go back', param_model=NoParamsAction, requires_browser=True)
+ @self.registry.action('Go back', param_model=NoParamsAction)
async def go_back(_: NoParamsAction, browser: BrowserContext):
await browser.go_back()
msg = 'πŸ”™ Navigated back'
@@ -86,7 +82,7 @@ class Controller:
return ActionResult(extracted_content=msg, include_in_memory=True)
# Element Interaction Actions
- @self.registry.action('Click element', param_model=ClickElementAction, requires_browser=True)
+ @self.registry.action('Click element', param_model=ClickElementAction)
async def click_element(params: ClickElementAction, browser: BrowserContext):
session = await browser.get_session()
state = session.cached_state
@@ -127,7 +123,6 @@ class Controller:
@self.registry.action(
'Input text into a input interactive element',
param_model=InputTextAction,
- requires_browser=True,
)
async def input_text(params: InputTextAction, browser: BrowserContext):
session = await browser.get_session()
@@ -144,7 +139,7 @@ class Controller:
return ActionResult(extracted_content=msg, include_in_memory=True)
# Tab Management Actions
- @self.registry.action('Switch tab', param_model=SwitchTabAction, requires_browser=True)
+ @self.registry.action('Switch tab', param_model=SwitchTabAction)
async def switch_tab(params: SwitchTabAction, browser: BrowserContext):
await browser.switch_to_tab(params.page_id)
# Wait for tab to be ready
@@ -154,7 +149,7 @@ class Controller:
logger.info(msg)
return ActionResult(extracted_content=msg, include_in_memory=True)
- @self.registry.action('Open url in new tab', param_model=OpenTabAction, requires_browser=True)
+ @self.registry.action('Open url in new tab', param_model=OpenTabAction)
async def open_tab(params: OpenTabAction, browser: BrowserContext):
await browser.create_new_tab(params.url)
msg = f'πŸ”— Opened new tab with {params.url}'
@@ -164,32 +159,24 @@ class Controller:
# Content Actions
@self.registry.action(
'Extract page content to retrieve specific information from the page, e.g. all company names, a specifc description, all information about, links with companies in structured format or simply links',
- requires_browser=True,
)
- async def extract_content(goal: str, browser: BrowserContext):
+ async def extract_content(goal: str, browser: BrowserContext, page_extraction_llm: BaseChatModel):
page = await browser.get_current_page()
import markdownify
content = markdownify.markdownify(await page.content())
- # logger.debug(f'Page content: {content}')
- if self.llm is not None:
- prompt = 'Your task is to extract the content of the page. You will be given a page and a goal and you should extract all relevant information around this goal from the page. If the goal is vague, summarize the page. Respond in json format. Extraction goal: {goal}, Page: {page}'
- template = PromptTemplate(input_variables=['goal', 'page'], template=prompt)
+ prompt = 'Your task is to extract the content of the page. You will be given a page and a goal and you should extract all relevant information around this goal from the page. If the goal is vague, summarize the page. Respond in json format. Extraction goal: {goal}, Page: {page}'
+ template = PromptTemplate(input_variables=['goal', 'page'], template=prompt)
- output = self.llm.invoke(template.format(goal=goal, page=content))
- msg = f'πŸ“„ Extracted from page\n: {output.content}\n'
- logger.info(msg)
- return ActionResult(extracted_content=msg, include_in_memory=True)
- else:
- msg = f'πŸ“„ Extracted page as markdown\n: {content}\n'
- logger.info(msg)
- return ActionResult(extracted_content=msg)
+ output = page_extraction_llm.invoke(template.format(goal=goal, page=content))
+ msg = f'πŸ“„ Extracted from page\n: {output.content}\n'
+ logger.info(msg)
+ return ActionResult(extracted_content=msg, include_in_memory=True)
@self.registry.action(
'Scroll down the page by pixel amount - if no amount is specified, scroll down one page',
param_model=ScrollAction,
- requires_browser=True,
)
async def scroll_down(params: ScrollAction, browser: BrowserContext):
page = await browser.get_current_page()
@@ -210,7 +197,6 @@ class Controller:
@self.registry.action(
'Scroll up the page by pixel amount - if no amount is specified, scroll up one page',
param_model=ScrollAction,
- requires_browser=True,
)
async def scroll_up(params: ScrollAction, browser: BrowserContext):
page = await browser.get_current_page()
@@ -231,7 +217,6 @@ class Controller:
@self.registry.action(
'Send strings of special keys like Backspace, Insert, PageDown, Delete, Enter, Shortcuts such as `Control+o`, `Control+Shift+T` are supported as well. This gets used in keyboard.press. Be aware of different operating systems and their shortcuts',
param_model=SendKeysAction,
- requires_browser=True,
)
async def send_keys(params: SendKeysAction, browser: BrowserContext):
page = await browser.get_current_page()
@@ -243,7 +228,6 @@ class Controller:
@self.registry.action(
description='If you dont find something which you want to interact with, scroll to it',
- requires_browser=True,
)
async def scroll_to_text(text: str, browser: BrowserContext): # type: ignore
page = await browser.get_current_page()
@@ -279,7 +263,6 @@ class Controller:
@self.registry.action(
description='Get all options from a native dropdown',
- requires_browser=True,
)
async def get_dropdown_options(index: int, browser: BrowserContext) -> ActionResult:
"""Get all options from a native dropdown"""
@@ -350,7 +333,6 @@ class Controller:
@self.registry.action(
description='Select dropdown option for interactive element index by the text of the option you want to select',
- requires_browser=True,
)
async def select_dropdown_option(
index: int,
@@ -454,7 +436,11 @@ class Controller:
@time_execution_async('--multi-act')
async def multi_act(
- self, actions: list[ActionModel], browser_context: BrowserContext, check_for_new_elements: bool = True
+ self,
+ actions: list[ActionModel],
+ browser_context: BrowserContext,
+ check_for_new_elements: bool = True,
+ page_extraction_llm: Optional[BaseChatModel] = None,
) -> list[ActionResult]:
"""Execute multiple actions"""
results = []
@@ -473,7 +459,7 @@ class Controller:
logger.info(f'Something new appeared after action {i} / {len(actions)}')
break
- results.append(await self.act(action, browser_context))
+ results.append(await self.act(action, browser_context, page_extraction_llm))
logger.debug(f'Executed action {i + 1} / {len(actions)}')
if results[-1].is_done or results[-1].error or i == len(actions) - 1:
@@ -485,13 +471,20 @@ class Controller:
return results
@time_execution_sync('--act')
- async def act(self, action: ActionModel, browser_context: BrowserContext) -> ActionResult:
+ async def act(
+ self,
+ action: ActionModel,
+ browser_context: BrowserContext,
+ page_extraction_llm: Optional[BaseChatModel] = None,
+ ) -> ActionResult:
"""Execute an action"""
try:
for action_name, params in action.model_dump(exclude_unset=True).items():
if params is not None:
# remove highlights
- result = await self.registry.execute_action(action_name, params, browser=browser_context)
+ result = await self.registry.execute_action(
+ action_name, params, browser=browser_context, page_extraction_llm=page_extraction_llm
+ )
if isinstance(result, str):
return ActionResult(extracted_content=result)
elif isinstance(result, ActionResult):
diff --git a/docs/customize/custom-functions.mdx b/docs/customize/custom-functions.mdx
index 2fb0dde69..a6fdf1a4f 100644
--- a/docs/customize/custom-functions.mdx
+++ b/docs/customize/custom-functions.mdx
@@ -41,13 +41,13 @@ agent = Agent(
## Browser-Aware Functions
-For actions that need browser access, use the `requires_browser=True` parameter:
+For actions that need browser access, simply add the `browser` parameter inside the function parameters:
```python
from browser_use import Browser, Controller, ActionResult
controller = Controller()
[email protected]('Open website', requires_browser=True)
[email protected]('Open website')
async def open_website(url: str, browser: Browser):
page = browser.get_current_page()
await page.goto(url)
@@ -73,8 +73,7 @@ class JobDetails(BaseModel):
@controller.action(
'Save job details which you found on page',
- param_model=JobDetails,
- requires_browser=True
+ param_model=JobDetails
)
async def save_job(params: JobDetails, browser: Browser):
print(f"Saving job: {params.title} at {params.company}")
diff --git a/examples/custom-functions/clipboard.py b/examples/custom-functions/clipboard.py
index 4980b3b55..e06d3e5de 100644
--- a/examples/custom-functions/clipboard.py
+++ b/examples/custom-functions/clipboard.py
@@ -28,7 +28,7 @@ def copy_to_clipboard(text: str):
return ActionResult(extracted_content=text)
[email protected]('Paste text from clipboard', requires_browser=True)
[email protected]('Paste text from clipboard')
async def paste_from_clipboard(browser: BrowserContext):
text = pyperclip.paste()
# send text to browser
@@ -39,9 +39,7 @@ async def paste_from_clipboard(browser: BrowserContext):
async def main():
- task = (
- f'Copy the text "Hello, world!" to the clipboard, then go to google.com and paste the text'
- )
+ task = f'Copy the text "Hello, world!" to the clipboard, then go to google.com and paste the text'
model = ChatOpenAI(model='gpt-4o')
agent = Agent(
task=task,
diff --git a/examples/custom-functions/file_upload.py b/examples/custom-functions/file_upload.py
index 5af26863b..c85e20177 100644
--- a/examples/custom-functions/file_upload.py
+++ b/examples/custom-functions/file_upload.py
@@ -30,7 +30,6 @@ controller = Controller()
@controller.action(
'Upload file to element ',
- requires_browser=True,
)
async def upload_file(index: int, browser: BrowserContext):
path = str(CV.absolute())
@@ -61,17 +60,14 @@ async def upload_file(index: int, browser: BrowserContext):
return ActionResult(error=f'Failed to upload file to index {index}')
[email protected]('Close file dialog', requires_browser=True)
[email protected]('Close file dialog')
async def close_file_dialog(browser: BrowserContext):
page = await browser.get_current_page()
await page.keyboard.press('Escape')
async def main():
- task = (
- f'go to https://kzmpmkh2zfk1ojnpxfn1.lite.vusercontent.net/'
- f' and upload to each upload field my file'
- )
+ task = f'go to https://kzmpmkh2zfk1ojnpxfn1.lite.vusercontent.net/ and upload to each upload field my file'
model = ChatOpenAI(model='gpt-4o')
agent = Agent(
diff --git a/examples/features/extract_page_with_llm.py b/examples/features/small_model_for_extraction.py
similarity index 71%
rename from examples/features/extract_page_with_llm.py
rename to examples/features/small_model_for_extraction.py
index a72222080..6d1778ebc 100644
--- a/examples/features/extract_page_with_llm.py
+++ b/examples/features/small_model_for_extraction.py
@@ -15,10 +15,11 @@ llm = ChatOpenAI(
)
task = 'Find the founders of browser-use in ycombinator, extract all links and open the links one by one'
-utility_llm = ChatOpenAI(model='gpt-4o-mini', temperature=0.0)
-controller = Controller(llm=utility_llm)
-agent = Agent(task=task, llm=llm, controller=controller, max_actions_per_step=2)
+# smaller model to extract content
+small_llm = ChatOpenAI(model='gpt-4o-mini', temperature=0.0)
+
+agent = Agent(task=task, llm=llm, max_actions_per_step=2, page_extraction_llm=small_llm)
async def main():
diff --git a/examples/use-cases/find_and_apply_to_jobs.py b/examples/use-cases/find_and_apply_to_jobs.py
index fdd2eeabe..81eab5d61 100644
--- a/examples/use-cases/find_and_apply_to_jobs.py
+++ b/examples/use-cases/find_and_apply_to_jobs.py
@@ -77,7 +77,6 @@ def read_cv():
@controller.action(
'Upload cv to element - call this function to upload if element is not found, try with different index of the same upload element',
- requires_browser=True,
)
async def upload_cv(index: int, browser: BrowserContext):
path = str(CV.absolute())
diff --git a/tests/test_service.py b/tests/test_service.py
index 65ddd5873..2d3d426d1 100644
--- a/tests/test_service.py
+++ b/tests/test_service.py
@@ -1,6 +1,10 @@
import os
-import pytest
import sys
+from unittest.mock import AsyncMock, MagicMock, Mock, patch
+
+import pytest
+from langchain_core.language_models.chat_models import BaseChatModel
+from pydantic import BaseModel
from browser_use.agent.message_manager.service import MessageManager
from browser_use.agent.service import Agent
@@ -11,12 +15,10 @@ from browser_use.browser.views import BrowserState
from browser_use.controller.registry.service import Registry
from browser_use.controller.registry.views import ActionModel
from browser_use.controller.service import Controller
-from langchain_core.language_models.chat_models import BaseChatModel
-from pydantic import BaseModel
-from unittest.mock import AsyncMock, MagicMock, Mock, patch
# run with python -m pytest tests/test_service.py
+
# run test with:
# python -m pytest tests/test_service.py
class TestAgent:
@@ -125,93 +127,97 @@ class TestAgent:
assert 'Test error' in agent._last_result[0].error
assert agent._last_result[0].include_in_memory == True
+
class TestRegistry:
- @pytest.fixture
- def registry_with_excludes(self):
- return Registry(exclude_actions=['excluded_action'])
-
- def test_action_decorator_with_excluded_action(self, registry_with_excludes):
- """
- Test that the action decorator does not register an action
- if it's in the exclude_actions list.
- """
- # Define a function to be decorated
- def excluded_action():
- pass
-
- # Apply the action decorator
- decorated_func = registry_with_excludes.action(description="This should be excluded")(excluded_action)
-
- # Assert that the decorated function is the same as the original
- assert decorated_func == excluded_action
-
- # Assert that the action was not added to the registry
- assert 'excluded_action' not in registry_with_excludes.registry.actions
-
- # Define another function that should be included
- def included_action():
- pass
-
- # Apply the action decorator to an included action
- registry_with_excludes.action(description="This should be included")(included_action)
-
- # Assert that the included action was added to the registry
- assert 'included_action' in registry_with_excludes.registry.actions
-
- @pytest.mark.asyncio
- async def test_execute_action_with_and_without_browser_context(self):
- """
- Test that the execute_action method correctly handles actions with and without a browser context.
- This test ensures that:
- 1. An action requiring a browser context is executed correctly.
- 2. An action not requiring a browser context is executed correctly.
- 3. The browser context is passed to the action function when required.
- 4. The action function receives the correct parameters.
- 5. The method raises an error when a browser context is required but not provided.
- """
- registry = Registry()
-
- # Define a mock action model
- class TestActionModel(BaseModel):
- param1: str
-
- # Define mock action functions
- async def test_action_with_browser(param1: str, browser):
- return f"Action executed with {param1} and browser"
-
- async def test_action_without_browser(param1: str):
- return f"Action executed with {param1}"
-
- # Register the actions
- registry.registry.actions['test_action_with_browser'] = MagicMock(
- requires_browser=True,
- function=AsyncMock(side_effect=test_action_with_browser),
- param_model=TestActionModel,
- description="Test action with browser"
- )
-
- registry.registry.actions['test_action_without_browser'] = MagicMock(
- requires_browser=False,
- function=AsyncMock(side_effect=test_action_without_browser),
- param_model=TestActionModel,
- description="Test action without browser"
- )
-
- # Mock BrowserContext
- mock_browser = MagicMock()
-
- # Execute the action with a browser context
- result_with_browser = await registry.execute_action('test_action_with_browser', {'param1': 'test_value'}, browser=mock_browser)
- assert result_with_browser == "Action executed with test_value and browser"
-
- # Execute the action without a browser context
- result_without_browser = await registry.execute_action('test_action_without_browser', {'param1': 'test_value'})
- assert result_without_browser == "Action executed with test_value"
-
- # Test error when browser is required but not provided
- with pytest.raises(RuntimeError, match="Action test_action_with_browser requires browser but none provided"):
- await registry.execute_action('test_action_with_browser', {'param1': 'test_value'})
-
- # Verify that the action functions were called with correct parameters
- registry.registry.actions['test_action_with_browser'].function.assert_called_once_with(param1='test_value', browser=mock_browser)
- registry.registry.actions['test_action_without_browser'].function.assert_called_once_with(param1='test_value')
\ No newline at end of file
+ @pytest.fixture
+ def registry_with_excludes(self):
+ return Registry(exclude_actions=['excluded_action'])
+
+ def test_action_decorator_with_excluded_action(self, registry_with_excludes):
+ """
+ Test that the action decorator does not register an action
+ if it's in the exclude_actions list.
+ """
+
+ # Define a function to be decorated
+ def excluded_action():
+ pass
+
+ # Apply the action decorator
+ decorated_func = registry_with_excludes.action(description='This should be excluded')(excluded_action)
+
+ # Assert that the decorated function is the same as the original
+ assert decorated_func == excluded_action
+
+ # Assert that the action was not added to the registry
+ assert 'excluded_action' not in registry_with_excludes.registry.actions
+
+ # Define another function that should be included
+ def included_action():
+ pass
+
+ # Apply the action decorator to an included action
+ registry_with_excludes.action(description='This should be included')(included_action)
+
+ # Assert that the included action was added to the registry
+ assert 'included_action' in registry_with_excludes.registry.actions
+
+ @pytest.mark.asyncio
+ async def test_execute_action_with_and_without_browser_context(self):
+ """
+ Test that the execute_action method correctly handles actions with and without a browser context.
+ This test ensures that:
+ 1. An action requiring a browser context is executed correctly.
+ 2. An action not requiring a browser context is executed correctly.
+ 3. The browser context is passed to the action function when required.
+ 4. The action function receives the correct parameters.
+ 5. The method raises an error when a browser context is required but not provided.
+ """
+ registry = Registry()
+
+ # Define a mock action model
+ class TestActionModel(BaseModel):
+ param1: str
+
+ # Define mock action functions
+ async def test_action_with_browser(param1: str, browser):
+ return f'Action executed with {param1} and browser'
+
+ async def test_action_without_browser(param1: str):
+ return f'Action executed with {param1}'
+
+ # Register the actions
+ registry.registry.actions['test_action_with_browser'] = MagicMock(
+ function=AsyncMock(side_effect=test_action_with_browser),
+ param_model=TestActionModel,
+ description='Test action with browser',
+ )
+
+ registry.registry.actions['test_action_without_browser'] = MagicMock(
+ function=AsyncMock(side_effect=test_action_without_browser),
+ param_model=TestActionModel,
+ description='Test action without browser',
+ )
+
+ # Mock BrowserContext
+ mock_browser = MagicMock()
+
+ # Execute the action with a browser context
+ result_with_browser = await registry.execute_action(
+ 'test_action_with_browser', {'param1': 'test_value'}, browser=mock_browser
+ )
+ assert result_with_browser == 'Action executed with test_value and browser'
+
+ # Execute the action without a browser context
+ result_without_browser = await registry.execute_action('test_action_without_browser', {'param1': 'test_value'})
+ assert result_without_browser == 'Action executed with test_value'
+
+ # Test error when browser is required but not provided
+ with pytest.raises(RuntimeError, match='Action test_action_with_browser requires browser but none provided'):
+ await registry.execute_action('test_action_with_browser', {'param1': 'test_value'})
+
+ # Verify that the action functions were called with correct parameters
+ registry.registry.actions['test_action_with_browser'].function.assert_called_once_with(
+ param1='test_value', browser=mock_browser
+ )
+ registry.registry.actions['test_action_without_browser'].function.assert_called_once_with(param1='test_value')