Skip to content

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

more improvements to custom actions docs

Nick Sweeting55ce8e8c1404
diff --git a/docs/customize/browser-settings.mdx b/docs/customize/browser-settings.mdx
index ba4c73d8b..ad6cef11e 100644
--- a/docs/customize/browser-settings.mdx
+++ b/docs/customize/browser-settings.mdx
@@ -624,6 +624,19 @@ forced_colors: ForcedColors = 'none'
Forced colors mode: `'active'`, `'none'`, `'null'`
+#### `**playwright.devices[...]`
+
+Playwright provides launch & context arg presets to [emulate common device fingerprints](https://playwright.dev/python/docs/emulation).
+
+```python
+BrowserProfile(
+ ...
+ **playwright.devices['iPhone 13'], # playwright = await async_playwright().start()
+)
+```
+
+Because `BrowserSession` and `BrowserProfile` take all the standard playwright args, we are able to support these device presets as well.
+
### Playwright Security Options
> See `allowed_domains` above too!
@@ -810,18 +823,6 @@ handle_sigterm: bool = False
Whether playwright should swallow SIGTERM signals and kill the browser.
-#### `**playwright.devices['iPhone 13']`
-
-```python
-BrowserProfile(
- ...
- **playwright.devices['iPhone 13'], # playwright = await async_playwright().start()
-)
-```
-
-Playwright provides launch & context args to [emulate common device fingerprints](https://playwright.dev/python/docs/emulation).
-`BrowserSession` and `BrowserProfile` take all the standard playwright args so we are able to support these as well.
-
---
## Full Example
diff --git a/docs/customize/custom-functions.mdx b/docs/customize/custom-functions.mdx
index 60a0c954c..706c89b39 100644
--- a/docs/customize/custom-functions.mdx
+++ b/docs/customize/custom-functions.mdx
@@ -4,7 +4,7 @@ description: "Extend default agent and write custom action functions to do certa
icon: "function"
---
-## Basic Function Registration
+## Action Function Registration
Custom action functions can be either `sync` or `async`. Keep them focused and single-purpose.
@@ -14,15 +14,15 @@ from browser_use import Controller, ActionResult
controller = Controller()
[email protected]('Ask human for help with a question', domains=['https://difficult.example.com']) # pass allowed_domains= or page_filter= to limit actions to certain pages
[email protected]('Ask human for help with a question', domains=['https://hard.example.com']) # pass allowed_domains= or page_filter= to limit actions to certain pages
def ask_human(question: str) -> ActionResult:
answer = input(f'\n{question}\nInput: ')
return ActionResult(extracted_content=answer, include_in_memory=True)
```
<Note>
- Basic `Controller` has all basic functionality you might need to interact with
- the browser already implemented. We provide a default set of common actions, e.g. `new_tab`, `input_text_into_element`, etc.
+ Our default `Controller` has all the basic functionality you might need to interact with
+ the browser already implemented. We provide a default set of common actions, e.g. `new_tab`, `extract_content`, etc.
</Note>
```python
@@ -35,25 +35,70 @@ agent = Agent(
```
<Note>
- Keep the function name and description short and concise. The LLM chooses between actions
- to run solely based on the function name and description. The LLM decides the params to pass
- to the action based on their names and type signatures. The stringified version of the [`ActionResult`](https://github.com/search?q=repo%3Abrowser-use%2Fbrowser-use+%22class+ActionResult%28BaseModel%29%22&type=code) returned
- is passed back to the LLM, and optionally persisted in the long-term memory when `ActionResult(..., include_in_memory=True)`.
+ Keep the function name and description short and concise:
+ - The LLM chooses between actions to run solely based on the function name and description
+ - The LLM decides the params to pass to the action based on the argument names and type signatures
</Note>
-## Browser-Aware Functions
+---
+
+## Action Parameters
+
+Browser Use supports two patterns for defining action parameters: normal function arguments, or a Pydantic model.
+
+### Action Parameters via Function Arguments
+
+For simple actions that don't need default values, you can define the action parameters directly as arguments to the function.
+
+```python
[email protected]('Click element')
+def click_element(css_selector: str, page: Page) -> ActionResult:
+ # css_selector is an action param the LLM must provide when calling
+ # page is a special framework-provided param to access the browser APIs (see below)
+ await page.locator(css_selector).click()
+ return ActionResult(extracted_content=f"Clicked element {css_selector}")
+```
-For actions that need browser access, add special parameters after your action parameters. The framework will automatically inject these if you request them:
+### Action Parameters via Pydantic Model
-### Available Special Parameters
+You can define a pydantic model for the parameters your action expects.
+This allows you to use optional parameters, default values, `Annotated[...]` types with custom validation, and other features offered by pydantic.
+
+When the agent calls calls your agent function, an instance of your model
+with the values filled by the LLM will be passed as the first argument `params` to your action function.
+
+Using a pydantic model is helpful because it allows more flexibility and power to enforce the schema of the values the LLM should provide.
+
+
+```python
+class MyParams(BaseModel):
+ field1: int
+ field2: str = 'default value'
+
[email protected]('My action', param_model=MyParams)
+def my_action(params: MyParams, browser_session: BrowserSession) -> ActionResult:
+ await (await browser_session.get_current_page()).keyboard.type(params.field2)
+ return ActionResult(extracted_content=f"Processed #{params.field1}")
+```
+
+Any special framework-provided arguments (e.g. `page`) will be passed as separate positional arguments after `params`.
+
+
+### Framework-Provided Parameters
+
+These special action parameters are injected by the `Controller` and are passed as extra args to any actions that expect them.
+
+For example, actions that need to run playwright code to interact with the browser should take the argument `page` or `browser_session`.
- `page: Page` - The current Playwright page (shortcut for `browser_session.get_current_page()`)
- `browser_session: BrowserSession` - The current browser session (and playwright context via `browser_session.browser_context`)
-- `context: AgentContext` - Any optional top-level context object passed to the Agent, e.g. Agent(context=user_provided_obj)
+- `context: AgentContext` - Any optional top-level context object passed to the Agent, e.g. `Agent(context=user_provided_obj)`
- `page_extraction_llm: BaseChatModel` - LLM instance used for page content extraction
- `available_file_paths: list[str]` - List of available file paths for upload / processing
- `has_sensitive_data: bool` - Whether the action content contains sensitive data markers (check this to avoid logging sensitive data to terminal by accident)
+#### Example: Custom action that uses the current `page`
+
```python
from playwright.async_api import Page
from browser_use import Controller, ActionResult
@@ -65,6 +110,9 @@ async def input_text_into_page(text: str, page: Page) -> ActionResult:
await page.keyboard.type(text)
return ActionResult(extracted_content='Website opened')
```
+
+#### Example: Custom action that uses the `browser_context`
+
```python
from browser_use import BrowserSession, Controller, ActionResult
@@ -72,81 +120,27 @@ controller = Controller()
@controller.action('Open website')
async def open_website(url: str, browser_session: BrowserSession) -> ActionResult:
+ # find matching existing tab by looking through all pages in playwright browser_context
all_tabs = await browser_session.browser_context.pages
for tab in all_tabs:
if tab.url == url:
await tab.bring_to_foreground()
return ActionResult(extracted_content=f'Switched to tab with url {url}')
- # Create a new tab if URL not found
+ # otherwise, create a new tab
new_tab = await browser_session.browser_context.new_page()
await new_tab.goto(url)
return ActionResult(extracted_content=f'Opened new tab with url {url}')
```
-## Structured Parameters with Pydantic
-
-For complex actions, define parameter schemas using Pydantic models. When using `param_model`, your function should accept the model as its first parameter:
-
-```python
-from pydantic import BaseModel
-from typing import Optional
-from playwright.async_api import Page
-from browser_use import Controller, ActionResult, BrowserSession
-
-controller = Controller()
-
-class JobDetails(BaseModel):
- title: str
- company: str
- job_link: str
- salary: str | None = None # optional parameters are allowed
-
- 'Save job details which you found on page',
- param_model=JobDetails
-)
-async def save_job(params: JobDetails, page: Page) -> ActionResult:
- print(f"Saving job: {params.title} at {params.company}")
-
- 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
-### Important Rules
-
-1. **Return an [`ActionResult`](https://github.com/search?q=repo%3Abrowser-use%2Fbrowser-use+%22class+ActionResult%28BaseModel%29%22&type=code)**: All actions should return an `ActionResult | str | None`.
+1. **Return an [`ActionResult`](https://github.com/search?q=repo%3Abrowser-use%2Fbrowser-use+%22class+ActionResult%28BaseModel%29%22&type=code)**: All actions should return an `ActionResult | str | None`. The stringified version of the result is passed back to the LLM, and optionally persisted in the long-term memory when `ActionResult(..., include_in_memory=True)`.
2. **Type hints on arguments are required**: They are used to verify that action params don't conflict with special arguments injected by the controller (e.g. `page`)
-3. **Actions called directly must be passed kwargs**: When calling actions from other actions, you must **call using kwargs only**, even though the actions are usually defined using positional args (for the same reasons as [pluggy](https://pluggy.readthedocs.io/en/stable/index.html#calling-hooks)).
+3. **Actions functions called directly must be passed kwargs**: When calling actions from other actions or python code, you must **pass all parameters as kwargs only**, even though the actions are usually defined using positional args (for the same reasons as [pluggy](https://pluggy.readthedocs.io/en/stable/index.html#calling-hooks)).
Action arguments are always matched by name and type, **not** positional order, so this helps prevent ambiguity / reordering issues while keeping action signatures short.
```python
@controller.action('Fill in the country form field')
@@ -157,6 +151,14 @@ def click_element(index: int, browser_session: BrowserSession) -> ActionResult:
```
```python3
+# Pattern 1: Use Pydantic model for defaults + special params
+class PinCodeParams(BaseModel):
+ code: int
+ retries: int = 3
+
[email protected]('...', param_model=PinCodeParams)
+async def input_pin_code(params: PinCodeParams, page: Page): ... # ✅ recommended
+
# Pattern 2: Simple actions without defaults
async def input_pin_code(code: int, retries: int, page: Page): ... # ✅ all params required
@@ -165,16 +167,9 @@ async def wait(seconds: int = 3): ... # ✅ no special params needed
# This is a Python SyntaxError - non-default after default
async def input_pin_code(code: int, retries: int=3, page: Page): ... # ❌ Python SyntaxError!
-
-# Pattern 1: Use Pydantic model for defaults + special params
-class PinCodeParams(BaseModel):
- code: int
- retries: int = 3
-
[email protected]('...', param_model=PinCodeParams)
-async def input_pin_code(params: PinCodeParams, page: Page): ... # ✅ best for defaults
```
+
---
diff --git a/tests/test_service.py b/tests/test_service.py
index 11ad26843..ba21a4765 100644
--- a/tests/test_service.py
+++ b/tests/test_service.py
@@ -74,7 +74,6 @@ class TestAgent:
assert 'test_action' in call_args
assert call_args['test_action'] == mock_controller.registry.registry.actions['test_action'].param_model.return_value # type: ignore
- @pytest.mark.asyncio
async def test_step_error_handling(self):
"""
Test the error handling in the step method of the Agent class.
@@ -248,7 +247,7 @@ class TestAgentRetry:
return action_model
@pytest.mark.asyncio
- async def test_step_empty_action_retry(self, mock_llm, mock_controller, mock_browser_context, mock_action_model):
+ async def test_step_empty_action_retry(self, mock_llm, mock_controller, mock_browser_session, mock_action_model):
"""
Test that the step method retries and handles empty actions correctly.
"""
@@ -257,8 +256,7 @@ class TestAgentRetry:
task='Test task',
llm=mock_llm,
controller=mock_controller,
- browser=Mock(),
- browser_context=mock_browser_context,
+ browser_session=mock_browser_session,
)
agent.ActionModel = mock_action_model # Inject the mock ActionModel
@@ -292,7 +290,7 @@ class TestAgentRetry:
assert agent._last_result[0].action == valid_action
@pytest.mark.asyncio
- async def test_step_empty_action_retry_and_fail(self, mock_llm, mock_controller, mock_browser_context, mock_action_model):
+ async def test_step_empty_action_retry_and_fail(self, mock_llm, mock_controller, mock_browser_session, mock_action_model):
"""
Test that the step method handles the case where get_next_action returns
empty actions twice, and inserts a safe noop action.
@@ -302,8 +300,7 @@ class TestAgentRetry:
task='Test task',
llm=mock_llm,
controller=mock_controller,
- browser=Mock(),
- browser_context=mock_browser_context,
+ browser_session=mock_browser_session,
)
agent.ActionModel = mock_action_model # Inject the mock ActionModel