Skip to content

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

Let user define initial action to take

magmuellerdf5a63178f2e
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 8561d72dc..363f3e654 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -12,7 +12,7 @@ import time
import uuid
from io import BytesIO
from pathlib import Path
-from typing import Any, Optional, Type, TypeVar
+from typing import Any, Dict, List, Optional, Type, TypeVar
from dotenv import load_dotenv
from langchain_core.language_models.chat_models import BaseChatModel
@@ -90,6 +90,7 @@ class Agent:
max_error_length: int = 400,
max_actions_per_step: int = 10,
tool_calling_method: Optional[str] = 'auto',
+ initial_actions: Optional[List[Dict[str, Dict[str, Any]]]] = None,
):
self.agent_id = str(uuid.uuid4()) # unique identifier for the agent
@@ -156,7 +157,7 @@ class Agent:
self.max_failures = max_failures
self.retry_delay = retry_delay
self.validate_output = validate_output
-
+ self.initial_actions = self._convert_initial_actions(initial_actions) if initial_actions else None
if save_conversation_path:
logger.info(f'Saving conversation to {save_conversation_path}')
@@ -410,6 +411,11 @@ class Agent:
try:
self._log_agent_run()
+ # 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)
+ self._last_result = result
+
for step in range(max_steps):
if self._too_many_failures():
break
@@ -427,7 +433,6 @@ class Agent:
logger.info('❌ Failed to complete task in maximum steps')
return self.history
-
finally:
self.telemetry.capture(
AgentEndTelemetryEvent(
@@ -1023,3 +1028,25 @@ class Agent:
draw.text((number_x, number_y), number_text, font=number_font, fill='white')
return frame
+
+ def _convert_initial_actions(self, actions: List[Dict[str, Dict[str, Any]]]) -> List[ActionModel]:
+ """Convert dictionary-based actions to ActionModel instances"""
+ converted_actions = []
+ action_model = self.ActionModel
+ for action_dict in actions:
+ # Each action_dict should have a single key-value pair
+ action_name = next(iter(action_dict))
+ params = action_dict[action_name]
+
+ # Get the parameter model for this action from registry
+ action_info = self.controller.registry.registry.actions[action_name]
+ param_model = action_info.param_model
+
+ # Create validated parameters using the appropriate param model
+ validated_params = param_model(**params)
+
+ # Create ActionModel instance with the validated parameters
+ action_model = self.ActionModel(**{action_name: validated_params})
+ converted_actions.append(action_model)
+
+ return converted_actions
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index c439eb91b..c8cca2638 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -49,9 +49,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, requires_browser=True)
async def go_to_url(params: GoToUrlAction, browser: BrowserContext):
page = await browser.get_current_page()
await page.goto(params.url)
@@ -70,17 +68,13 @@ 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, requires_browser=True)
async def click_element(params: ClickElementAction, browser: BrowserContext):
session = await browser.get_session()
state = session.cached_state
if params.index not in state.selector_map:
- raise Exception(
- f'Element with index {params.index} does not exist - retry or use alternative actions'
- )
+ raise Exception(f'Element with index {params.index} does not exist - retry or use alternative actions')
element_node = state.selector_map[params.index]
initial_pages = len(session.context.pages)
@@ -106,9 +100,7 @@ class Controller:
await browser.switch_to_tab(-1)
return ActionResult(extracted_content=msg, include_in_memory=True)
except Exception as e:
- logger.warning(
- f'Element no longer available with index {params.index} - most likely the page changed'
- )
+ logger.warning(f'Element no longer available with index {params.index} - most likely the page changed')
return ActionResult(error=str(e))
@self.registry.action(
@@ -121,9 +113,7 @@ class Controller:
state = session.cached_state
if params.index not in state.selector_map:
- raise Exception(
- f'Element index {params.index} does not exist - retry or use alternative actions'
- )
+ raise Exception(f'Element index {params.index} does not exist - retry or use alternative actions')
element_node = state.selector_map[params.index]
await browser._input_text_element_node(element_node, params.text)
@@ -143,9 +133,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, requires_browser=True)
async def open_tab(params: OpenTabAction, browser: BrowserContext):
await browser.create_new_tab(params.url)
msg = f'🔗 Opened new tab with {params.url}'
@@ -351,9 +339,7 @@ class Controller:
# Validate that we're working with a select element
if dom_element.tag_name != 'select':
- logger.error(
- f'Element is not a select! Tag: {dom_element.tag_name}, Attributes: {dom_element.attributes}'
- )
+ logger.error(f'Element is not a select! Tag: {dom_element.tag_name}, Attributes: {dom_element.attributes}')
msg = f'Cannot select option: Element with index {index} is a {dom_element.tag_name}, not a select'
return ActionResult(extracted_content=msg, include_in_memory=True)
@@ -401,9 +387,7 @@ class Controller:
if dropdown_info:
if not dropdown_info.get('found'):
- logger.error(
- f'Frame {frame_index} error: {dropdown_info.get("error")}'
- )
+ logger.error(f'Frame {frame_index} error: {dropdown_info.get("error")}')
continue
logger.debug(f'Found dropdown in frame {frame_index}: {dropdown_info}')
@@ -412,9 +396,7 @@ class Controller:
# nth(0) to disable error thrown by strict mode
# timeout=1000 because we are already waiting for all network events, therefore ideally we don't need to wait a lot here (default 30s)
selected_option_values = (
- await frame.locator('//' + dom_element.xpath)
- .nth(0)
- .select_option(label=text, timeout=1000)
+ await frame.locator('//' + dom_element.xpath).nth(0).select_option(label=text, timeout=1000)
)
msg = f'selected option {text} with value {selected_option_values}'
@@ -447,7 +429,7 @@ class Controller:
@time_execution_async('--multi-act')
async def multi_act(
- self, actions: list[ActionModel], browser_context: BrowserContext
+ self, actions: list[ActionModel], browser_context: BrowserContext, check_for_new_elements: bool = True
) -> list[ActionResult]:
"""Execute multiple actions"""
results = []
@@ -460,10 +442,8 @@ class Controller:
for i, action in enumerate(actions):
if action.get_index() is not None and i != 0:
new_state = await browser_context.get_state()
- new_path_hashes = set(
- e.hash.branch_path_hash for e in new_state.selector_map.values()
- )
- if not new_path_hashes.issubset(cached_path_hashes):
+ new_path_hashes = set(e.hash.branch_path_hash for e in new_state.selector_map.values())
+ if check_for_new_elements and not new_path_hashes.issubset(cached_path_hashes):
# next action requires index but there are new elements on the page
logger.info(f'Something new appeared after action {i} / {len(actions)}')
break
@@ -486,9 +466,7 @@ class Controller:
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)
if isinstance(result, str):
return ActionResult(extracted_content=result)
elif isinstance(result, ActionResult):
diff --git a/examples/initial_actions.py b/examples/initial_actions.py
new file mode 100644
index 000000000..48de5342a
--- /dev/null
+++ b/examples/initial_actions.py
@@ -0,0 +1,29 @@
+from dotenv import load_dotenv
+from langchain_openai import ChatOpenAI
+
+from browser_use import Agent
+
+load_dotenv()
+llm = ChatOpenAI(model='gpt-4o')
+
+initial_actions = [
+ {'open_tab': {'url': 'https://www.amazon.com'}},
+ {'scroll_down': {'amount': 1000}},
+ {'scroll_down': {'amount': 1000}},
+ {'click_element': {'index': 5}},
+ {'click_element': {'index': 1}},
+ {'open_tab': {'url': 'https://www.google.com'}},
+ {'click_element': {'index': 1}},
+]
+
+agent = Agent(task='Your task description', llm=llm, initial_actions=initial_actions)
+
+
+async def main():
+ await agent.run(max_steps=10)
+
+
+if __name__ == '__main__':
+ import asyncio
+
+ asyncio.run(main())