Skip to content

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

Update extraction branch (#1296)

Gregor Žunič27b22a39865f
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 68bfa89bc..92cc8ca59 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -23,3 +23,10 @@ repos:
- id: detect-private-key
- id: mixed-line-ending
- id: fix-byte-order-marker
+
+ - repo: https://github.com/codespell-project/codespell
+ rev: v2.4.1
+ hooks:
+ - id: codespell # See pyproject.toml for args
+ additional_dependencies:
+ - tomli
diff --git a/README.md b/README.md
index ec3693706..0860f50f8 100644
--- a/README.md
+++ b/README.md
@@ -137,7 +137,7 @@ Tell your computer what to do, and it gets it done.
### Rerunning tasks
- [ ] LLM as fallback
-- [ ] Make it easy to define workfow templates where LLM fills in the details
+- [ ] Make it easy to define workflow templates where LLM fills in the details
- [ ] Return playwright script from the agent
### Datasets
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.py
index b75ea7d9d..76aab4955 100644
--- a/browser_use/agent/message_manager/service.py
+++ b/browser_use/agent/message_manager/service.py
@@ -62,7 +62,7 @@ class MessageManager:
self._add_message_with_tokens(task_message, message_type='init')
if self.settings.sensitive_data:
- info = f'Here are placeholders for sensitve data: {list(self.settings.sensitive_data.keys())}'
+ info = f'Here are placeholders for sensitive data: {list(self.settings.sensitive_data.keys())}'
info += 'To use them, write <secret>the placeholder name</secret>'
info_message = HumanMessage(content=info)
self._add_message_with_tokens(info_message, message_type='init')
diff --git a/browser_use/agent/message_manager/views.py b/browser_use/agent/message_manager/views.py
index 45addd18e..5e5842497 100644
--- a/browser_use/agent/message_manager/views.py
+++ b/browser_use/agent/message_manager/views.py
@@ -61,6 +61,7 @@ class ManagedMessage(BaseModel):
"""
if isinstance(value, dict) and 'message' in value:
# NOTE: We use langchain's load to convert the JSON string back into a BaseMessage object.
+ filterwarnings('ignore', category=LangChainBetaWarning)
value['message'] = load(value['message'])
return value
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index bbc13941d..69603e081 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -198,7 +198,7 @@ class Agent(Generic[Context]):
# Model setup
self._set_model_names()
logger.info(
- f'Starting an agent with main_model={self.model_name}, planner_model={self.planner_model_name}, '
+ f'🧠 Starting an agent with main_model={self.model_name}, planner_model={self.planner_model_name}, '
f'extraction_model={self.settings.page_extraction_llm.model_name if hasattr(self.settings.page_extraction_llm, "model_name") else None}'
)
@@ -257,12 +257,10 @@ class Agent(Generic[Context]):
# Browser setup
self.injected_browser = browser is not None
self.injected_browser_context = browser_context is not None
- if browser_context:
- self.browser = browser
- self.browser_context = browser_context
- else:
- self.browser = browser or Browser()
- self.browser_context = BrowserContext(browser=self.browser, config=self.browser.config.new_context_config)
+ self.browser = browser or Browser()
+ self.browser_context = browser_context or BrowserContext(
+ browser=self.browser, config=self.browser.config.new_context_config
+ )
# Callbacks
self.register_new_step_callback = register_new_step_callback
@@ -541,6 +539,7 @@ class Agent(Generic[Context]):
include_trace = logger.isEnabledFor(logging.DEBUG)
error_msg = AgentError.format_error(error, include_trace=include_trace)
prefix = f'❌ Result failed {self.state.consecutive_failures + 1}/{self.settings.max_failures} times:\n '
+ self.state.consecutive_failures += 1
if 'Browser closed' in error_msg:
logger.error('❌ Browser is closed or disconnected, unable to proceed')
@@ -559,18 +558,23 @@ class Agent(Generic[Context]):
# give model a hint how output should look like
error_msg += '\n\nReturn a valid JSON object with the required fields.'
- self.state.consecutive_failures += 1
else:
+ from anthropic import RateLimitError as AnthropicRateLimitError
from google.api_core.exceptions import ResourceExhausted
from openai import RateLimitError
- if isinstance(error, RateLimitError) or isinstance(error, ResourceExhausted):
+ # Define a tuple of rate limit error types for easier maintenance
+ RATE_LIMIT_ERRORS = (
+ RateLimitError, # OpenAI
+ ResourceExhausted, # Google
+ AnthropicRateLimitError, # Anthropic
+ )
+
+ if isinstance(error, RATE_LIMIT_ERRORS):
logger.warning(f'{prefix}{error_msg}')
await asyncio.sleep(self.settings.retry_delay)
- self.state.consecutive_failures += 1
else:
logger.error(f'{prefix}{error_msg}')
- self.state.consecutive_failures += 1
return [ActionResult(error=error_msg, include_in_memory=True)]
@@ -627,6 +631,7 @@ class Agent(Generic[Context]):
logger.debug(f'Using {self.tool_calling_method} for {self.chat_model_library}')
try:
output = self.llm.invoke(input_messages)
+ response = {'raw': output, 'parsed': None}
except Exception as e:
logger.error(f'Failed to invoke model: {str(e)}')
raise LLMException(401, 'LLM API call failed') from e
@@ -635,6 +640,7 @@ class Agent(Generic[Context]):
try:
parsed_json = extract_json_from_model_output(output.content)
parsed = self.AgentOutput(**parsed_json)
+ response['parsed'] = parsed
except (ValueError, ValidationError) as e:
logger.warning(f'Failed to parse model output: {output} {str(e)}')
raise ValueError('Could not parse response.')
@@ -761,7 +767,7 @@ class Agent(Generic[Context]):
signal_handler.register()
# Start non-blocking LLM connection verification
- assert await self.llm._verified_api_keys, 'Failed to verify LLM API keys'
+ assert self.llm._verified_api_keys, 'Failed to verify LLM API keys'
try:
self._log_agent_run()
@@ -862,7 +868,20 @@ class Agent(Generic[Context]):
for i, action in enumerate(actions):
if action.get_index() is not None and i != 0:
new_state = await self.browser_context.get_state()
- new_path_hashes = set(e.hash.branch_path_hash for e in new_state.selector_map.values())
+ new_selector_map = new_state.selector_map
+
+ # Detect index change after previous action
+ orig_target = cached_selector_map.get(action.get_index()) # type: ignore
+ orig_target_hash = orig_target.hash.branch_path_hash if orig_target else None
+ new_target = new_selector_map.get(action.get_index()) # type: ignore
+ new_target_hash = new_target.hash.branch_path_hash if new_target else None
+ if orig_target_hash != new_target_hash:
+ msg = f'Element index changed after action {i} / {len(actions)}, because page changed.'
+ logger.info(msg)
+ results.append(ActionResult(extracted_content=msg, include_in_memory=True))
+ break
+
+ new_path_hashes = set(e.hash.branch_path_hash for e in new_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
msg = f'Something new appeared after action {i} / {len(actions)}'
@@ -1156,7 +1175,7 @@ class Agent(Generic[Context]):
if test_answer in response_text:
logger.debug(
- f'🧠 LLM API keys {", ".join(required_keys)} verified, {llm.__class__.__name__} model is connected and responding correctly.'
+ f'🧠 LLM API keys {", ".join(required_keys)} verified, {llm.__class__.__name__} model is connected and responding correctly.'
)
llm._verified_api_keys = True
return True
diff --git a/browser_use/agent/system_prompt.md b/browser_use/agent/system_prompt.md
index 0de6eab90..5f7eff0a1 100644
--- a/browser_use/agent/system_prompt.md
+++ b/browser_use/agent/system_prompt.md
@@ -49,7 +49,7 @@ Common action sequences:
5. TASK COMPLETION:
- Use the done action as the last action as soon as the ultimate task is complete
- Dont use "done" before you are done with everything the user asked you, except you reach the last step of max_steps.
-- If you reach your last step, use the done action even if the task is not fully finished. Provide all the information you have gathered so far. If the ultimate task is completly finished set success to true. If not everything the user asked for is completed set success in done to false!
+- If you reach your last step, use the done action even if the task is not fully finished. Provide all the information you have gathered so far. If the ultimate task is completely finished set success to true. If not everything the user asked for is completed set success in done to false!
- If you have to do something repeatedly for example the task says for "each", or "for all", or "x times", count always inside "memory" how many times you have done it and how many remain. Don't stop until you have completed like the task asked you. Only call done after the last step.
- Don't hallucinate actions
- Make sure you include everything you found out for the ultimate task in the done text parameter. Do not just say you are done, but include the requested information of the task.
diff --git a/browser_use/browser/browser.py b/browser_use/browser/browser.py
index 888f26932..9e7d8140a 100644
--- a/browser_use/browser/browser.py
+++ b/browser_use/browser/browser.py
@@ -56,7 +56,7 @@ class BrowserConfig(BaseModel):
headless: False
Whether to run browser in headless mode (not recommended)
- disable_security: True
+ disable_security: False
Disable browser security features (required for cross-origin iframe support)
extra_browser_args: []
@@ -79,7 +79,14 @@ class BrowserConfig(BaseModel):
Enable deterministic rendering (makes GPU/font rendering consistent across different OS's and docker)
"""
- model_config = ConfigDict(arbitrary_types_allowed=True, extra='ignore')
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ extra='ignore',
+ populate_by_name=True,
+ from_attributes=True,
+ validate_assignment=True,
+ revalidate_instances='subclass-instances',
+ )
wss_url: str | None = None
cdp_url: str | None = None
@@ -89,7 +96,7 @@ class BrowserConfig(BaseModel):
extra_browser_args: list[str] = Field(default_factory=list)
headless: bool = False
- disable_security: bool = True
+ disable_security: bool = False # disable_security=True is dangerous as any malicious URL visited could embed an iframe for the user's bank, and use their cookies to steal money
deterministic_rendering: bool = False
keep_alive: bool = Field(default=False, alias='_force_keep_browser_alive') # used to be called _force_keep_browser_alive
@@ -103,22 +110,22 @@ class Browser:
"""
Playwright browser on steroids.
- This is persistant browser factory that can spawn multiple browser contexts.
+ This is persistent browser factory that can spawn multiple browser contexts.
It is recommended to use only one instance of Browser per your application (RAM usage will grow otherwise).
"""
def __init__(
self,
- config: BrowserConfig = BrowserConfig(),
+ config: BrowserConfig | None = None,
):
logger.debug('🌎 Initializing new browser')
- self.config = config
+ self.config = config or BrowserConfig()
self.playwright: Playwright | None = None
self.playwright_browser: PlaywrightBrowser | None = None
- async def new_context(self, config: BrowserContextConfig = BrowserContextConfig()) -> BrowserContext:
+ async def new_context(self, config: BrowserContextConfig | None = None) -> BrowserContext:
"""Create a browser context"""
- return BrowserContext(config=config, browser=self)
+ return BrowserContext(config=config or self.config, browser=self)
async def get_playwright_browser(self) -> PlaywrightBrowser:
"""Get a browser context"""
@@ -173,7 +180,7 @@ class Browser:
# Check if browser is already running
response = requests.get('http://localhost:9222/json/version', timeout=2)
if response.status_code == 200:
- logger.info('🔌 Re-using existing browser found running on http://localhost:9222')
+ logger.info('🔌 Reusing existing browser found running on http://localhost:9222')
browser_class = getattr(playwright, self.config.browser_class)
browser = await browser_class.connect_over_cdp(
endpoint_url='http://localhost:9222',
@@ -254,7 +261,6 @@ class Browser:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
if s.connect_ex(('localhost', 9222)) == 0:
chrome_args.remove('--remote-debugging-port=9222')
- chrome_args.remove('--remote-debugging-address=0.0.0.0')
browser_class = getattr(playwright, self.config.browser_class)
args = {
diff --git a/browser_use/browser/chrome.py b/browser_use/browser/chrome.py
index 9e8ab34a6..a829fc4ed 100644
--- a/browser_use/browser/chrome.py
+++ b/browser_use/browser/chrome.py
@@ -71,7 +71,7 @@ CHROME_DETERMINISTIC_RENDERING_ARGS = [
# chrome://gpu
'--enable-webgl', # enable web-gl graphics support
'--font-render-hinting=none', # make rendering more deterministic by ignoring OS font hints, may also need css override, try: * {text-rendering: geometricprecision !important; -webkit-font-smoothing: antialiased;}
- '--force-color-profile=srgb', # make rendering more deterministic by using consitent color profile, if browser looks weird, try: generic-rgb
+ '--force-color-profile=srgb', # make rendering more deterministic by using consistent color profile, if browser looks weird, try: generic-rgb
'--disable-partial-raster', # make rendering more deterministic (TODO: verify if still needed)
'--disable-skia-runtime-opts', # make rendering more deterministic by avoiding Skia hot path runtime optimizations
'--disable-2d-canvas-clip-aa', # make rendering more deterministic by disabling antialiasing on 2d canvas clips
@@ -127,7 +127,7 @@ CHROME_ARGS = [
# chrome://inspect
'--log-level=2', # 1=DEBUG 2=WARNING 3=ERROR
'--enable-logging=stderr',
- '--remote-debugging-address=0.0.0.0',
+ # '--remote-debugging-address=127.0.0.1', <- never expose to non-localhost, would allow attacker to drive your browser from any machine
f'--remote-debugging-port={CHROME_DEBUG_PORT}',
'--enable-experimental-extension-apis', # add support for tab groups
'--disable-focus-on-load', # prevent browser from hijacking focus
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.py
index 91da96ff3..4afaa7e59 100644
--- a/browser_use/browser/context.py
+++ b/browser_use/browser/context.py
@@ -56,8 +56,8 @@ class BrowserContextConfig(BaseModel):
cookies_file: None
Path to cookies file for persistence
- disable_security: True
- Disable browser security features
+ disable_security: False
+ Disable browser security features (dangerous, but cross-origin iframe support requires it)
minimum_wait_page_load_time: 0.5
Minimum time to wait before getting page state for LLM input
@@ -106,6 +106,10 @@ class BrowserContextConfig(BaseModel):
include_dynamic_attributes: bool = True
Include dynamic attributes in the CSS selector. If you want to reuse the css_selectors, it might be better to set this to False.
+ http_credentials: None
+ Dictionary with HTTP basic authentication credentials for corporate intranets (only supports one set of credentials for all URLs at the moment), e.g.
+ {"username": "bill", "password": "pa55w0rd"}
+
is_mobile: None
Whether the meta viewport tag is taken into account and touch events are enabled.
@@ -122,7 +126,14 @@ class BrowserContextConfig(BaseModel):
Changes the timezone of the browser. Example: 'Europe/Berlin'
"""
- model_config = ConfigDict(arbitrary_types_allowed=True, extra='ignore')
+ model_config = ConfigDict(
+ arbitrary_types_allowed=True,
+ extra='ignore',
+ populate_by_name=True,
+ from_attributes=True,
+ validate_assignment=True,
+ revalidate_instances='subclass-instances',
+ )
cookies_file: str | None = None
minimum_wait_page_load_time: float = 0.25
@@ -130,7 +141,7 @@ class BrowserContextConfig(BaseModel):
maximum_wait_page_load_time: float = 5
wait_between_actions: float = 0.5
- disable_security: bool = True
+ disable_security: bool = False # disable_security=True is dangerous as any malicious URL visited could embed an iframe for the user's bank, and use their cookies to steal money
browser_window_size: BrowserContextWindowSize = Field(default_factory=lambda: {'width': 1280, 'height': 1100})
no_viewport: Optional[bool] = None
@@ -148,6 +159,7 @@ class BrowserContextConfig(BaseModel):
viewport_expansion: int = 0
allowed_domains: list[str] | None = None
include_dynamic_attributes: bool = True
+ http_credentials: dict[str, str] | None = None
keep_alive: bool = Field(default=False, alias='_force_keep_context_alive') # used to be called _force_keep_context_alive
is_mobile: bool | None = None
@@ -203,6 +215,7 @@ class BrowserSession:
}
})()
"""
+ self.active_tab = None
self.context = context
self.cached_state = cached_state
self.context.on('page', lambda page: page.add_init_script(init_script))
@@ -233,6 +246,7 @@ class BrowserContext:
# Initialize these as None - they'll be set up when needed
self.session: BrowserSession | None = None
+ self.active_tab: Page | None = None
async def __aenter__(self):
"""Async context manager entry"""
@@ -278,6 +292,7 @@ class BrowserContext:
finally:
# Dereference everything
+ self.active_tab = None
self.session = None
self._page_event_handler = None
@@ -354,6 +369,8 @@ class BrowserContext:
await active_page.bring_to_front()
await active_page.wait_for_load_state('load')
+ self.active_tab = active_page
+
return self.session
def _add_new_page_listener(self, context: PlaywrightBrowserContext):
@@ -362,6 +379,10 @@ class BrowserContext:
await page.reload() # Reload the page to avoid timeout errors
await page.wait_for_load_state()
logger.debug(f'📑 New page opened: {page.url}')
+
+ if not page.url.startswith('chrome-extension://') and not page.url.startswith('chrome://'):
+ self.active_tab = page
+
if self.session is not None:
self.state.target_id = None
@@ -402,6 +423,7 @@ class BrowserContext:
record_video_size=self.config.browser_window_size,
record_har_path=self.config.save_har_path,
locale=self.config.locale,
+ http_credentials=self.config.http_credentials,
is_mobile=self.config.is_mobile,
has_touch=self.config.has_touch,
geolocation=self.config.geolocation,
@@ -415,9 +437,22 @@ class BrowserContext:
# Load cookies if they exist
if self.config.cookies_file and os.path.exists(self.config.cookies_file):
with open(self.config.cookies_file, 'r') as f:
- cookies = json.load(f)
- logger.info(f'🍪 Loaded {len(cookies)} cookies from {self.config.cookies_file}')
- await context.add_cookies(cookies)
+ try:
+ cookies = json.load(f)
+
+ valid_same_site_values = ['Strict', 'Lax', 'None']
+ for cookie in cookies:
+ if 'sameSite' in cookie:
+ if cookie['sameSite'] not in valid_same_site_values:
+ logger.warning(
+ f"Fixed invalid sameSite value '{cookie['sameSite']}' to 'None' for cookie {cookie.get('name')}"
+ )
+ cookie['sameSite'] = 'None'
+ logger.info(f'🍪 Loaded {len(cookies)} cookies from {self.config.cookies_file}')
+ await context.add_cookies(cookies)
+
+ except json.JSONDecodeError as e:
+ logger.error(f'Failed to parse cookies file: {str(e)}')
# Expose anti-detection scripts
await context.add_init_script(
@@ -737,10 +772,11 @@ class BrowserContext:
session = await self.get_session()
page = await self._get_current_page(session)
await page.close()
-
+ self.active_tab = None
# Switch to the first available tab if any exist
if session.context.pages:
await self.switch_to_tab(0)
+ self.active_tab = session.context.pages[0]
# otherwise the browser will be closed
@@ -872,7 +908,7 @@ class BrowserContext:
# Get all cross-origin iframes within the page and open them in new tabs
# mark the titles of the new tabs so the LLM knows to check them for additional content
# unfortunately too buggy for now, too many sites use invisible cross-origin iframes for ads, tracking, youtube videos, social media, etc.
- # and it distracts the bot by openeing a lot of new tabs
+ # and it distracts the bot by opening a lot of new tabs
# iframe_urls = await dom_service.get_cross_origin_iframes()
# for url in iframe_urls:
# if url in [tab.url for tab in tabs_info]:
@@ -1362,7 +1398,7 @@ class BrowserContext:
try:
tab_info = TabInfo(page_id=page_id, url=page.url, title=await asyncio.wait_for(page.title(), timeout=1))
except asyncio.TimeoutError:
- # page.title() can hang forever on tabs that are crashed/dissapeared/about:blank
+ # page.title() can hang forever on tabs that are crashed/disappeared/about:blank
# we dont want to try automating those tabs because they will hang the whole script
logger.debug('⚠ Failed to get tab info for tab #%s: %s (ignoring)', page_id, page.url)
tab_info = TabInfo(page_id=page_id, url='about:blank', title='ignore this tab and do not use it')
@@ -1393,6 +1429,7 @@ class BrowserContext:
self.state.target_id = target['targetId']
break
+ self.active_tab = page
await page.bring_to_front()
await page.wait_for_load_state()
@@ -1404,6 +1441,9 @@ class BrowserContext:
session = await self.get_session()
new_page = await session.context.new_page()
+
+ self.active_tab = new_page
+
await new_page.wait_for_load_state()
if url:
@@ -1433,6 +1473,9 @@ class BrowserContext:
if page.url == target['url']:
return page
+ if self.active_tab and self.active_tab in session.context.pages and not self.active_tab.is_closed():
+ return self.active_tab
+
# fall back to most recently opened non-extension page (extensions are almost always invisible background targets)
non_extension_pages = [
page for page in pages if not page.url.startswith('chrome-extension://') and not page.url.startswith('chrome://')
@@ -1448,7 +1491,9 @@ class BrowserContext:
# reopen a new window in the browser and try again
logger.warning('⚠️ No browser window available, opening a new window')
await self._initialize_session()
- return await session.context.new_page()
+ page = await session.context.new_page()
+ self.active_tab = page
+ return page
async def get_selector_map(self) -> SelectorMap:
session = await self.get_session()
@@ -1529,6 +1574,7 @@ class BrowserContext:
for page in pages:
await page.close()
+ self.active_tab = None
session.cached_state = None
self.state.target_id = None
diff --git a/browser_use/controller/registry/views.py b/browser_use/controller/registry/views.py
index a2a88797a..47956a048 100644
--- a/browser_use/controller/registry/views.py
+++ b/browser_use/controller/registry/views.py
@@ -26,7 +26,7 @@ class RegisteredAction(BaseModel):
s += str(
{
k: {sub_k: sub_v for sub_k, sub_v in v.items() if sub_k not in skip_keys}
- for k, v in self.param_model.schema()['properties'].items()
+ for k, v in self.param_model.model_json_schema()['properties'].items()
}
)
s += '}'
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index dc526bc36..2ccabe496 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -4,10 +4,11 @@ import enum
import json
import logging
import re
-from typing import Dict, Generic, Optional, Type, TypeVar
+from typing import Dict, Generic, Optional, Tuple, Type, TypeVar, cast
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.prompts import PromptTemplate
+from playwright.async_api import ElementHandle, Page
# from lmnr.sdk.laminar import Laminar
from pydantic import BaseModel
@@ -22,10 +23,12 @@ from browser_use.controller.views import (
ClickElementByXpathAction,
CloseTabAction,
DoneAction,
+ DragDropAction,
GoToUrlAction,
InputTextAction,
NoParamsAction,
OpenTabAction,
+ Position,
ScrollAction,
SearchGoogleAction,
SendKeysAction,
@@ -57,7 +60,7 @@ class Controller(Generic[Context]):
data: output_model
@self.registry.action(
- 'Complete task - with return text and if the task is finished (success=True) or not yet completly finished (success=False), because last step is reached',
+ 'Complete task - with return text and if the task is finished (success=True) or not yet completely finished (success=False), because last step is reached',
param_model=ExtendedOutputModel,
)
async def done(params: ExtendedOutputModel):
@@ -73,7 +76,7 @@ class Controller(Generic[Context]):
else:
@self.registry.action(
- 'Complete task - with return text and if the task is finished (success=True) or not yet completly finished (success=False), because last step is reached',
+ 'Complete task - with return text and if the task is finished (success=True) or not yet completely finished (success=False), because last step is reached',
param_model=DoneAction,
)
async def done(params: DoneAction):
@@ -299,7 +302,7 @@ class Controller(Generic[Context]):
# 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',
+ 'Extract page content to retrieve specific information from the page, e.g. all company names, a specific description, all information about, links with companies in structured format or simply links',
)
async def extract_content(
goal: str, should_strip_link_urls: bool, browser: BrowserContext, page_extraction_llm: BaseChatModel
@@ -627,6 +630,220 @@ class Controller(Generic[Context]):
logger.error(msg)
return ActionResult(error=msg, include_in_memory=True)
+ @self.registry.action(
+ 'Drag and drop elements or between coordinates on the page - useful for canvas drawing, sortable lists, sliders, file uploads, and UI rearrangement',
+ param_model=DragDropAction,
+ )
+ async def drag_drop(params: DragDropAction, browser: BrowserContext) -> ActionResult:
+ """
+ Performs a precise drag and drop operation between elements or coordinates.
+ """
+
+ async def get_drag_elements(
+ page: Page,
+ source_selector: str,
+ target_selector: str,
+ ) -> Tuple[Optional[ElementHandle], Optional[ElementHandle]]:
+ """Get source and target elements with appropriate error handling."""
+ source_element = None
+ target_element = None
+
+ try:
+ # page.locator() auto-detects CSS and XPath
+ source_locator = page.locator(source_selector)
+ target_locator = page.locator(target_selector)
+
+ # Check if elements exist
+ source_count = await source_locator.count()
+ target_count = await target_locator.count()
+
+ if source_count > 0:
+ source_element = await source_locator.first.element_handle()
+ logger.debug(f'Found source element with selector: {source_selector}')
+ else:
+ logger.warning(f'Source element not found: {source_selector}')
+
+ if target_count > 0:
+ target_element = await target_locator.first.element_handle()
+ logger.debug(f'Found target element with selector: {target_selector}')
+ else:
+ logger.warning(f'Target element not found: {target_selector}')
+
+ except Exception as e:
+ logger.error(f'Error finding elements: {str(e)}')
+
+ return source_element, target_element
+
+ async def get_element_coordinates(
+ source_element: ElementHandle,
+ target_element: ElementHandle,
+ source_position: Optional[Position],
+ target_position: Optional[Position],
+ ) -> Tuple[Optional[Tuple[int, int]], Optional[Tuple[int, int]]]:
+ """Get coordinates from elements with appropriate error handling."""
+ source_coords = None
+ target_coords = None
+
+ try:
+ # Get source coordinates
+ if source_position:
+ source_coords = (source_position.x, source_position.y)
+ else:
+ source_box = await source_element.bounding_box()
+ if source_box:
+ source_coords = (
+ int(source_box['x'] + source_box['width'] / 2),
+ int(source_box['y'] + source_box['height'] / 2),
+ )
+
+ # Get target coordinates
+ if target_position:
+ target_coords = (target_position.x, target_position.y)
+ else:
+ target_box = await target_element.bounding_box()
+ if target_box:
+ target_coords = (
+ int(target_box['x'] + target_box['width'] / 2),
+ int(target_box['y'] + target_box['height'] / 2),
+ )
+ except Exception as e:
+ logger.error(f'Error getting element coordinates: {str(e)}')
+
+ return source_coords, target_coords
+
+ async def execute_drag_operation(
+ page: Page,
+ source_x: int,
+ source_y: int,
+ target_x: int,
+ target_y: int,
+ steps: int,
+ delay_ms: int,
+ ) -> Tuple[bool, str]:
+ """Execute the drag operation with comprehensive error handling."""
+ try:
+ # Try to move to source position
+ try:
+ await page.mouse.move(source_x, source_y)
+ logger.debug(f'Moved to source position ({source_x}, {source_y})')
+ except Exception as e:
+ logger.error(f'Failed to move to source position: {str(e)}')
+ return False, f'Failed to move to source position: {str(e)}'
+
+ # Press mouse button down
+ await page.mouse.down()
+
+ # Move to target position with intermediate steps
+ for i in range(1, steps + 1):
+ ratio = i / steps
+ intermediate_x = int(source_x + (target_x - source_x) * ratio)
+ intermediate_y = int(source_y + (target_y - source_y) * ratio)
+
+ await page.mouse.move(intermediate_x, intermediate_y)
+
+ if delay_ms > 0:
+ await asyncio.sleep(delay_ms / 1000)
+
+ # Move to final target position
+ await page.mouse.move(target_x, target_y)
+
+ # Move again to ensure dragover events are properly triggered
+ await page.mouse.move(target_x, target_y)
+
+ # Release mouse button
+ await page.mouse.up()
+
+ return True, 'Drag operation completed successfully'
+
+ except Exception as e:
+ return False, f'Error during drag operation: {str(e)}'
+
+ page = await browser.get_current_page()
+
+ try:
+ # Initialize variables
+ source_x: Optional[int] = None
+ source_y: Optional[int] = None
+ target_x: Optional[int] = None
+ target_y: Optional[int] = None
+
+ # Normalize parameters
+ steps = max(1, params.steps or 10)
+ delay_ms = max(0, params.delay_ms or 5)
+
+ # Case 1: Element selectors provided
+ if params.element_source and params.element_target:
+ logger.debug('Using element-based approach with selectors')
+
+ source_element, target_element = await get_drag_elements(
+ page,
+ params.element_source,
+ params.element_target,
+ )
+
+ if not source_element or not target_element:
+ error_msg = f'Failed to find {"source" if not source_element else "target"} element'
+ return ActionResult(error=error_msg, include_in_memory=True)
+
+ source_coords, target_coords = await get_element_coordinates(
+ source_element, target_element, params.element_source_offset, params.element_target_offset
+ )
+
+ if not source_coords or not target_coords:
+ error_msg = f'Failed to determine {"source" if not source_coords else "target"} coordinates'
+ return ActionResult(error=error_msg, include_in_memory=True)
+
+ source_x, source_y = source_coords
+ target_x, target_y = target_coords
+
+ # Case 2: Coordinates provided directly
+ elif all(
+ coord is not None
+ for coord in [params.coord_source_x, params.coord_source_y, params.coord_target_x, params.coord_target_y]
+ ):
+ logger.debug('Using coordinate-based approach')
+ source_x = params.coord_source_x
+ source_y = params.coord_source_y
+ target_x = params.coord_target_x
+ target_y = params.coord_target_y
+ else:
+ error_msg = 'Must provide either source/target selectors or source/target coordinates'
+ return ActionResult(error=error_msg, include_in_memory=True)
+
+ # Validate coordinates
+ if any(coord is None for coord in [source_x, source_y, target_x, target_y]):
+ error_msg = 'Failed to determine source or target coordinates'
+ return ActionResult(error=error_msg, include_in_memory=True)
+
+ # Perform the drag operation
+ success, message = await execute_drag_operation(
+ page,
+ cast(int, source_x),
+ cast(int, source_y),
+ cast(int, target_x),
+ cast(int, target_y),
+ steps,
+ delay_ms,
+ )
+
+ if not success:
+ logger.error(f'Drag operation failed: {message}')
+ return ActionResult(error=message, include_in_memory=True)
+
+ # Create descriptive message
+ if params.element_source and params.element_target:
+ msg = f"🖱️ Dragged element '{params.element_source}' to '{params.element_target}'"
+ else:
+ msg = f'🖱️ Dragged from ({source_x}, {source_y}) to ({target_x}, {target_y})'
+
+ logger.info(msg)
+ return ActionResult(extracted_content=msg, include_in_memory=True)
+
+ except Exception as e:
+ error_msg = f'Failed to perform drag and drop: {str(e)}'
+ logger.error(error_msg)
+ return ActionResult(error=error_msg, include_in_memory=True)
+
# Register ---------------------------------------------------------------
def action(self, description: str, **kwargs):
diff --git a/browser_use/controller/views.py b/browser_use/controller/views.py
index 579b64ec5..e1a4fa49c 100644
--- a/browser_use/controller/views.py
+++ b/browser_use/controller/views.py
@@ -1,6 +1,6 @@
from typing import Optional
-from pydantic import BaseModel, Field, model_validator
+from pydantic import BaseModel, ConfigDict, Field, model_validator
# Action Input Models
@@ -90,12 +90,36 @@ class NoParamsAction(BaseModel):
and discards it, so the final parsed model is empty.
"""
+ model_config = ConfigDict(extra='allow')
+
@model_validator(mode='before')
def ignore_all_inputs(cls, values):
# No matter what the user sends, discard it and return empty.
return {}
- class Config:
- # If you want to silently allow unknown fields at top-level,
- # set extra = 'allow' as well:
- extra = 'allow'
+
+class Position(BaseModel):
+ x: int
+ y: int
+
+
+class DragDropAction(BaseModel):
+ # Element-based approach
+ element_source: Optional[str] = Field(None, description='CSS selector or XPath of the element to drag from')
+ element_target: Optional[str] = Field(None, description='CSS selector or XPath of the element to drop onto')
+ element_source_offset: Optional[Position] = Field(
+ None, description='Precise position within the source element to start drag (in pixels from top-left corner)'
+ )
+ element_target_offset: Optional[Position] = Field(
+ None, description='Precise position within the target element to drop (in pixels from top-left corner)'
+ )
+
+ # Coordinate-based approach (used if selectors not provided)
+ coord_source_x: Optional[int] = Field(None, description='Absolute X coordinate on page to start drag from (in pixels)')
+ coord_source_y: Optional[int] = Field(None, description='Absolute Y coordinate on page to start drag from (in pixels)')
+ coord_target_x: Optional[int] = Field(None, description='Absolute X coordinate on page to drop at (in pixels)')
+ coord_target_y: Optional[int] = Field(None, description='Absolute Y coordinate on page to drop at (in pixels)')
+
+ # Common options
+ steps: Optional[int] = Field(10, description='Number of intermediate points for smoother movement (5-20 recommended)')
+ delay_ms: Optional[int] = Field(5, description='Delay in milliseconds between steps (0 for fastest, 10-20 for more natural)')
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index 2405da168..0510d9d98 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -32,7 +32,7 @@ class DomService:
self.page = page
self.xpath_cache = {}
- self.js_code = resources.read_text('browser_use.dom', 'buildDomTree.js')
+ self.js_code = resources.files('browser_use.dom').joinpath('buildDomTree.js').read_text()
# region - Clickable elements
@time_execution_async('--get_clickable_elements')
diff --git a/browser_use/utils.py b/browser_use/utils.py
index 38485bf16..bd3bad1fb 100644
--- a/browser_use/utils.py
+++ b/browser_use/utils.py
@@ -74,20 +74,28 @@ class SignalHandler:
def register(self) -> None:
"""Register signal handlers for SIGINT and SIGTERM."""
- if self.is_windows:
- # On Windows, use simple signal handling with immediate exit on Ctrl+C
- def windows_handler(sig, frame):
- print('\n\n🛑 Got Ctrl+C. Exiting immediately on Windows...\n', file=stderr)
- # Run the custom exit callback if provided
- if self.custom_exit_callback:
- self.custom_exit_callback()
- os._exit(0)
+ try:
+ if self.is_windows:
+ # On Windows, use simple signal handling with immediate exit on Ctrl+C
+ def windows_handler(sig, frame):
+ print('\n\n🛑 Got Ctrl+C. Exiting immediately on Windows...\n', file=stderr)
+ # Run the custom exit callback if provided
+ if self.custom_exit_callback:
+ self.custom_exit_callback()
+ os._exit(0)
+
+ self.original_sigint_handler = signal.signal(signal.SIGINT, windows_handler)
+ else:
+ # On Unix-like systems, use asyncio's signal handling for smoother experience
+ self.original_sigint_handler = self.loop.add_signal_handler(signal.SIGINT, lambda: self.sigint_handler())
+ self.original_sigterm_handler = self.loop.add_signal_handler(signal.SIGTERM, lambda: self.sigterm_handler())
- self.original_sigint_handler = signal.signal(signal.SIGINT, windows_handler)
- else:
- # On Unix-like systems, use asyncio's signal handling for smoother experience
- self.original_sigint_handler = self.loop.add_signal_handler(signal.SIGINT, lambda: self.sigint_handler())
- self.original_sigterm_handler = self.loop.add_signal_handler(signal.SIGTERM, lambda: self.sigterm_handler())
+ except Exception:
+ # there are situations where signal handlers are not supported, e.g.
+ # - when running in a thread other than the main thread
+ # - some operating systems
+ # - inside jupyter notebooks
+ pass
def unregister(self) -> None:
"""Unregister signal handlers and restore original handlers if possible."""
@@ -219,7 +227,12 @@ class SignalHandler:
# Temporarily restore default signal handling for SIGINT
# This ensures KeyboardInterrupt will be raised during input()
original_handler = signal.getsignal(signal.SIGINT)
- signal.signal(signal.SIGINT, signal.default_int_handler)
+ try:
+ signal.signal(signal.SIGINT, signal.default_int_handler)
+ except ValueError:
+ # we are running in a thread other than the main thread
+ # or signal handlers are not supported for some other reason
+ pass
green = '\x1b[32;1m'
red = '\x1b[31m'
diff --git a/docs/customize/agent-settings.mdx b/docs/customize/agent-settings.mdx
index 00bde30e2..501415c22 100644
--- a/docs/customize/agent-settings.mdx
+++ b/docs/customize/agent-settings.mdx
@@ -47,7 +47,8 @@ agent = Agent(
- Disable to reduce costs or use models without vision support
- For GPT-4o, image processing costs approximately 800-1000 tokens (~$0.002 USD) per image (but this depends on the defined screen size)
- `save_conversation_path`: Path to save the complete conversation history. Useful for debugging.
-- `system_prompt_class`: Custom system prompt class. See <a href="/customize/system-prompt">System Prompt</a> for customization options.
+- `override_system_message`: Completely replace the default system prompt with a custom one.
+- `extend_system_message`: Add additional instructions to the default system prompt.
<Note>
Vision capabilities are recommended for better web interaction understanding,
@@ -183,7 +184,7 @@ agent = Agent(
You can configure the agent and provide a separate message to help the LLM understand the task better.
-```python
+```python
from langchain_openai import ChatOpenAI
agent = Agent(
diff --git a/docs/customize/browser-settings.mdx b/docs/customize/browser-settings.mdx
index c5dfb6754..13bdefeb3 100644
--- a/docs/customize/browser-settings.mdx
+++ b/docs/customize/browser-settings.mdx
@@ -22,7 +22,7 @@ from browser_use import BrowserConfig
# Basic configuration
config = BrowserConfig(
headless=False,
- disable_security=True
+ disable_security=False
)
browser = Browser(config=config)
@@ -38,7 +38,7 @@ agent = Agent(
- **headless** (default: `False`)
Runs the browser without a visible UI. Note that some websites may detect headless mode.
-- **disable_security** (default: `True`)
+- **disable_security** (default: `False`)
Disables browser security features. While this can fix certain functionality issues (like cross-site iFrames), it should be used cautiously, especially when visiting untrusted websites.
### Additional Settings
@@ -161,8 +161,8 @@ async def run_search():
Highlight interactive elements on the screen with colorful bounding boxes.
- **viewport_expansion** (default: `500`)
- Viewport expansion in pixels. With this you can controll how much of the page is included in the context of the LLM. If set to -1, all elements from the entire page will be included (this leads to high token usage). If set to 0, only the elements which are visible in the viewport will be included.
- Default is 500 pixels, that means that we inlcude a little bit more than the visible viewport inside the context.
+ Viewport expansion in pixels. With this you can control how much of the page is included in the context of the LLM. If set to -1, all elements from the entire page will be included (this leads to high token usage). If set to 0, only the elements which are visible in the viewport will be included.
+ Default is 500 pixels, that means that we include a little bit more than the visible viewport inside the context.
### Restrict URLs
diff --git a/docs/customize/custom-functions.mdx b/docs/customize/custom-functions.mdx
index 082cb2774..282020449 100644
--- a/docs/customize/custom-functions.mdx
+++ b/docs/customize/custom-functions.mdx
@@ -55,7 +55,7 @@ from browser_use import Browser, Controller, ActionResult
controller = Controller()
@controller.action('Open website')
async def open_website(url: str, browser: Browser):
- page = browser.get_current_page()
+ page = await browser.get_current_page()
await page.goto(url)
return ActionResult(extracted_content='Website opened')
```
diff --git a/docs/customize/sensitive-data.mdx b/docs/customize/sensitive-data.mdx
index 5b012d0dd..3bb5f6c66 100644
--- a/docs/customize/sensitive-data.mdx
+++ b/docs/customize/sensitive-data.mdx
@@ -43,7 +43,7 @@ if __name__ == '__main__':
In this example:
1. The model only sees `x_name` and `x_password` as placeholders.
2. When the model wants to use your password it outputs x_password - and we replace it with the actual value.
-3. When your password is visable on the current page, we replace it in the LLM input - so that the model never has it in its state.
+3. When your password is visible on the current page, we replace it in the LLM input - so that the model never has it in its state.
Warning: Vision models still see the image of the page - where the sensitive data might be visible.
diff --git a/eval/claude.py b/eval/claude.py
index b34c668c4..8e9c7b135 100644
--- a/eval/claude.py
+++ b/eval/claude.py
@@ -1,18 +1,19 @@
from dotenv import load_dotenv
from langchain_anthropic import ChatAnthropic
-from browser_use import Agent
+from browser_use import Agent, Browser
load_dotenv()
-async def run_agent(task: str, max_steps: int = 38):
+async def run_agent(task: str, browser: Browser | None = None, max_steps: int = 38):
+ browser = browser or Browser()
llm = ChatAnthropic(
model_name='claude-3-5-sonnet-20240620',
temperature=0.0,
timeout=100,
stop=None,
)
- agent = Agent(task=task, llm=llm)
+ agent = Agent(task=task, llm=llm, browser=browser)
result = await agent.run(max_steps=max_steps)
return result
diff --git a/eval/deepseek-r1.py b/eval/deepseek-r1.py
index 03da9edfc..a13397ba9 100644
--- a/eval/deepseek-r1.py
+++ b/eval/deepseek-r1.py
@@ -4,7 +4,7 @@ from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from pydantic import SecretStr
-from browser_use import Agent
+from browser_use import Agent, Browser
load_dotenv()
@@ -13,12 +13,13 @@ if not api_key_deepseek:
raise ValueError('DEEPSEEK_API_KEY is not set')
-async def run_agent(task: str, max_steps: int = 38):
+async def run_agent(task: str, browser: Browser | None = None, max_steps: int = 38):
+ browser = browser or Browser()
llm = ChatOpenAI(
base_url='https://api.deepseek.com/v1',
model='deepseek-reasoner',
api_key=SecretStr(api_key_deepseek),
)
- agent = Agent(task=task, llm=llm, use_vision=False)
+ agent = Agent(task=task, llm=llm, use_vision=False, browser=browser)
result = await agent.run(max_steps=max_steps)
return result
diff --git a/eval/deepseek.py b/eval/deepseek.py
index 1ec8289bc..c1a0b18bd 100644
--- a/eval/deepseek.py
+++ b/eval/deepseek.py
@@ -4,7 +4,7 @@ from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from pydantic import SecretStr
-from browser_use import Agent
+from browser_use import Agent, Browser
load_dotenv()
@@ -13,12 +13,13 @@ if not api_key_deepseek:
raise ValueError('DEEPSEEK_API_KEY is not set')
-async def run_agent(task: str, max_steps: int = 38):
+async def run_agent(task: str, browser: Browser | None = None, max_steps: int = 38):
+ browser = browser or Browser()
llm = ChatOpenAI(
base_url='https://api.deepseek.com/v1',
model='deepseek-chat',
api_key=SecretStr(api_key_deepseek),
)
- agent = Agent(task=task, llm=llm, use_vision=False)
+ agent = Agent(task=task, llm=llm, use_vision=False, browser=browser)
result = await agent.run(max_steps=max_steps)
return result
diff --git a/eval/gemini-1.5-flash.py b/eval/gemini-1.5-flash.py
index 051f85d3c..4a23414e4 100644
--- a/eval/gemini-1.5-flash.py
+++ b/eval/gemini-1.5-flash.py
@@ -4,7 +4,7 @@ from dotenv import load_dotenv
from langchain_google_genai import ChatGoogleGenerativeAI
from pydantic import SecretStr
-from browser_use import Agent
+from browser_use import Agent, Browser
load_dotenv()
@@ -13,8 +13,9 @@ if not api_key:
raise ValueError('GEMINI_API_KEY is not set')
-async def run_agent(task: str, max_steps: int = 38):
+async def run_agent(task: str, browser: Browser | None = None, max_steps: int = 38):
+ browser = browser or Browser()
llm = ChatGoogleGenerativeAI(model='gemini-1.5-flash-latest', api_key=SecretStr(api_key))
- agent = Agent(task=task, llm=llm)
+ agent = Agent(task=task, llm=llm, browser=browser)
result = await agent.run(max_steps=max_steps)
return result
diff --git a/eval/gemini-2.0-flash.py b/eval/gemini-2.0-flash.py
index 803895c77..5e4fe9949 100644
--- a/eval/gemini-2.0-flash.py
+++ b/eval/gemini-2.0-flash.py
@@ -4,7 +4,7 @@ from dotenv import load_dotenv
from langchain_google_genai import ChatGoogleGenerativeAI
from pydantic import SecretStr
-from browser_use import Agent
+from browser_use import Agent, Browser
load_dotenv()
@@ -13,8 +13,9 @@ if not api_key:
raise ValueError('GEMINI_API_KEY is not set')
-async def run_agent(task: str, max_steps: int = 38):
+async def run_agent(task: str, browser: Browser | None = None, max_steps: int = 38):
+ browser = browser or Browser()
llm = ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp', api_key=SecretStr(api_key))
- agent = Agent(task=task, llm=llm)
+ agent = Agent(task=task, llm=llm, browser=browser)
result = await agent.run(max_steps=max_steps)
return result
diff --git a/eval/gpt-4o-no-boundingbox.py b/eval/gpt-4o-no-boundingbox.py
index 634382414..03b571ac8 100644
--- a/eval/gpt-4o-no-boundingbox.py
+++ b/eval/gpt-4o-no-boundingbox.py
@@ -3,21 +3,14 @@ import asyncio
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
-from browser_use import Agent, BrowserConfig
-from browser_use.browser.browser import Browser
-from browser_use.browser.context import BrowserContextConfig
+from browser_use import Agent, Browser
load_dotenv()
-async def run_agent(task: str, max_steps: int = 38):
- browser = Browser(
- config=BrowserConfig(
- new_context_config=BrowserContextConfig(
- highlight_elements=False,
- ),
- ),
- )
+async def run_agent(task: str, browser: Browser | None = None, max_steps: int = 38):
+ browser = browser or Browser()
+ browser.config.new_context_config.highlight_elements = False
llm = ChatOpenAI(
model='gpt-4o',
temperature=0.0,
diff --git a/eval/gpt-4o-no-vision.py b/eval/gpt-4o-no-vision.py
index 47a5c21fe..87be9f8f9 100644
--- a/eval/gpt-4o-no-vision.py
+++ b/eval/gpt-4o-no-vision.py
@@ -1,16 +1,17 @@
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
-from browser_use import Agent
+from browser_use import Agent, Browser
load_dotenv()
-async def run_agent(task: str, max_steps: int = 38):
+async def run_agent(task: str, browser: Browser | None = None, max_steps: int = 38):
+ browser = browser or Browser()
llm = ChatOpenAI(
model='gpt-4o',
temperature=0.0,
)
- agent = Agent(task=task, llm=llm, use_vision=False)
+ agent = Agent(task=task, llm=llm, use_vision=False, browser=browser)
result = await agent.run(max_steps=max_steps)
return result
diff --git a/eval/gpt-4o-viewport-0.py b/eval/gpt-4o-viewport-0.py
index eb3ada91b..3ebd01b7b 100644
--- a/eval/gpt-4o-viewport-0.py
+++ b/eval/gpt-4o-viewport-0.py
@@ -3,25 +3,18 @@ import asyncio
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
-from browser_use import Agent, BrowserConfig
-from browser_use.browser.browser import Browser
-from browser_use.browser.context import BrowserContextConfig
+from browser_use import Agent, Browser
load_dotenv()
-async def run_agent(task: str, max_steps: int = 38):
+async def run_agent(task: str, browser: Browser | None = None, max_steps: int = 38):
+ browser = browser or Browser()
llm = ChatOpenAI(
model='gpt-4o',
temperature=0.0,
)
- browser = Browser(
- config=BrowserConfig(
- new_context_config=BrowserContextConfig(
- viewport_expansion=0,
- ),
- ),
- )
+ browser.config.new_context_config.viewport_expansion = 0
agent = Agent(task=task, llm=llm, browser=browser)
result = await agent.run(max_steps=max_steps)
return result
diff --git a/eval/gpt-4o.py b/eval/gpt-4o.py
index 3cdcbd64d..71d5b90f8 100644
--- a/eval/gpt-4o.py
+++ b/eval/gpt-4o.py
@@ -1,24 +1,17 @@
-import asyncio
-
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
-from browser_use import Agent
+from browser_use import Agent, Browser
load_dotenv()
-async def run_agent(task: str, max_steps: int = 38):
+async def run_agent(task: str, browser: Browser | None = None, max_steps: int = 38):
+ browser = browser or Browser()
llm = ChatOpenAI(
model='gpt-4o',
temperature=0.0,
)
- agent = Agent(task=task, llm=llm)
+ agent = Agent(task=task, llm=llm, browser=browser)
result = await agent.run(max_steps=max_steps)
return result
-
-
-if __name__ == '__main__':
- task = 'Go to https://www.google.com and search for "python" and click on the first result'
- result = asyncio.run(run_agent(task))
- print(result)
diff --git a/eval/grok.py b/eval/grok.py
index 4df613b6b..905a77642 100644
--- a/eval/grok.py
+++ b/eval/grok.py
@@ -1,11 +1,10 @@
-import asyncio
import os
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from pydantic import SecretStr
-from browser_use import Agent
+from browser_use import Agent, Browser
load_dotenv()
@@ -14,14 +13,13 @@ if not api_key:
raise ValueError('GROK_API_KEY is not set')
-async def main():
+async def run_agent(task: str, browser: Browser | None = None, max_steps: int = 38):
+ browser = browser or Browser()
agent = Agent(
- task='Go to https://www.google.com and search for "python" and click on the first result',
+ task=task,
use_vision=False,
llm=ChatOpenAI(model='grok-2-1212', base_url='https://api.x.ai/v1', api_key=SecretStr(api_key)),
+ browser=browser,
)
await agent.run()
-
-
-asyncio.run(main())
diff --git a/examples/browser/stealth.py b/examples/browser/stealth.py
index b69601636..aed94c53e 100644
--- a/examples/browser/stealth.py
+++ b/examples/browser/stealth.py
@@ -23,6 +23,16 @@ browser = Browser(
async def main():
+ agent = Agent(
+ task="""
+ Go to https://bot-detector.rebrowser.net/ and verify that all the bot checks are passed.
+ """,
+ llm=llm,
+ browser=browser,
+ )
+ await agent.run()
+ input('Press Enter to continue to the next test...')
+
agent = Agent(
task="""
Go to https://www.webflow.com/ and verify that the page is not blocked by a bot check.
@@ -42,6 +52,17 @@ async def main():
)
await agent.run()
+ agent = Agent(
+ task="""
+ Go to https://abrahamjuliot.github.io/creepjs/ and verify that the detection score is >50%.
+ """,
+ llm=llm,
+ browser=browser,
+ )
+ await agent.run()
+
+ input('Press Enter to close the browser...')
+
agent = Agent(
task="""
Go to https://nowsecure.nl/ check the "I'm not a robot" checkbox.
diff --git a/examples/custom-functions/action_filters.py b/examples/custom-functions/action_filters.py
index 7976ab9d3..ef7c60280 100644
--- a/examples/custom-functions/action_filters.py
+++ b/examples/custom-functions/action_filters.py
@@ -64,7 +64,7 @@ async def main():
llm = ChatOpenAI(model_name='gpt-4o')
# Create the agent
- agent = Agent( # disco mode will not be triggered on apple.com because the LLM wont be able to see that action available, it should work on Google.com though.
+ agent = Agent( # disco mode will not be triggered on apple.com because the LLM won't be able to see that action available, it should work on Google.com though.
task="""
Go to apple.com and trigger disco mode (if dont know how to do that, then just move on).
Then go to google.com and trigger disco mode.
diff --git a/examples/custom-functions/notification.py b/examples/custom-functions/notification.py
index 3f73b9640..971697cc2 100644
--- a/examples/custom-functions/notification.py
+++ b/examples/custom-functions/notification.py
@@ -21,7 +21,7 @@ async def done(text: str):
# To send emails use
# STEP 1: go to https://support.google.com/accounts/answer/185833
- # STEP 2: Create an app password (you cant use here your normal gmail password)
+ # STEP 2: Create an app password (you can't use here your normal gmail password)
# STEP 3: Use the app password in the code below for the password
yag = yagmail.SMTP('[email protected]', 'your_app_password')
yag.send(
diff --git a/examples/custom-functions/onepassword_2fa.py b/examples/custom-functions/onepassword_2fa.py
new file mode 100644
index 000000000..b4a32ac3f
--- /dev/null
+++ b/examples/custom-functions/onepassword_2fa.py
@@ -0,0 +1,56 @@
+import asyncio
+import logging
+import os
+import sys
+
+from dotenv import load_dotenv
+from langchain_openai import ChatOpenAI
+from onepassword.client import Client # pip install onepassword-sdk
+
+sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from browser_use import ActionResult, Agent, Controller
+
+# Set up logging
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
+
+load_dotenv()
+
+OP_SERVICE_ACCOUNT_TOKEN = os.getenv('OP_SERVICE_ACCOUNT_TOKEN')
+OP_ITEM_ID = os.getenv('OP_ITEM_ID') # Go to 1Password, right click on the item, click "Copy Secret Reference"
+
+
+controller = Controller()
+
+
[email protected]('Get 2FA code from 1Password for Google Account', domains=['*.google.com', 'google.com'])
+async def get_1password_2fa() -> ActionResult:
+ """
+ Custom action to retrieve 2FA/MFA code from 1Password using onepassword.client SDK.
+ """
+ client = await Client.authenticate(
+ # setup instructions: https://github.com/1Password/onepassword-sdk-python/#-get-started
+ auth=OP_SERVICE_ACCOUNT_TOKEN,
+ integration_name='Browser-Use',
+ integration_version='v1.0.0',
+ )
+
+ mfa_code = await client.secrets.resolve(f'op://Private/{OP_ITEM_ID}/One-time passcode')
+
+ return ActionResult(extracted_content=mfa_code)
+
+
+async def main():
+ # Example task using the 1Password 2FA action
+ task = 'Go to account.google.com, enter username and password, then if prompted for 2FA code, get 2FA code from 1Password for and enter it'
+
+ model = ChatOpenAI(model='gpt-4o')
+ agent = Agent(task=task, llm=model, controller=controller)
+
+ result = await agent.run()
+ print(f'Task completed with result: {result}')
+
+
+if __name__ == '__main__':
+ asyncio.run(main())
diff --git a/examples/features/drag_drop.py b/examples/features/drag_drop.py
new file mode 100644
index 000000000..797664943
--- /dev/null
+++ b/examples/features/drag_drop.py
@@ -0,0 +1,46 @@
+import asyncio
+import os
+
+from dotenv import load_dotenv
+from langchain_google_genai import ChatGoogleGenerativeAI
+from pydantic import SecretStr
+
+from browser_use import Agent
+
+load_dotenv()
+api_key = os.getenv('GEMINI_API_KEY')
+if not api_key:
+ raise ValueError('GEMINI_API_KEY is not set')
+
+llm = ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp', api_key=SecretStr(api_key))
+
+
+task_1 = """
+Navigate to: https://sortablejs.github.io/Sortable/.
+Then scroll down to the first examplw with title "Simple list example".
+Drag the element with name "item 1" to below the element with name "item 3".
+"""
+
+
+task_2 = """
+Navigate to: https://excalidraw.com/.
+Click on the pencil icon (with index 40).
+Then draw a triangle in the canvas.
+Draw the triangle starting from coordinate (400,400).
+You can use the drag and drop action to draw the triangle.
+"""
+
+
+async def run_search():
+ agent = Agent(
+ task=task_1,
+ llm=llm,
+ max_actions_per_step=1,
+ use_vision=True,
+ )
+
+ await agent.run(max_steps=25)
+
+
+if __name__ == '__main__':
+ asyncio.run(run_search())
diff --git a/examples/features/restrict_urls.py b/examples/features/restrict_urls.py
index 2f4ce0952..f481277e0 100644
--- a/examples/features/restrict_urls.py
+++ b/examples/features/restrict_urls.py
@@ -13,7 +13,7 @@ from browser_use.browser.browser import Browser, BrowserConfig
llm = ChatOpenAI(model='gpt-4o', temperature=0.0)
task = (
- 'go to google.com and search for openai.com and click on the first link then extract content and scroll down - whats there?'
+ "go to google.com and search for openai.com and click on the first link then extract content and scroll down - what's there?"
)
allowed_domains = ['google.com']
diff --git a/examples/features/validate_output.py b/examples/features/validate_output.py
index afe96083e..332c4fdda 100644
--- a/examples/features/validate_output.py
+++ b/examples/features/validate_output.py
@@ -1,5 +1,5 @@
"""
-Demostrate output validator.
+Demonstrate output validator.
@dev You need to add OPENAI_API_KEY to your environment variables.
"""
diff --git a/examples/integrations/discord/discord_example.py b/examples/integrations/discord/discord_example.py
index 259e68cc6..c7435d854 100644
--- a/examples/integrations/discord/discord_example.py
+++ b/examples/integrations/discord/discord_example.py
@@ -29,7 +29,7 @@ Five Steps to create and invite a Discord bot:
* Click “Authorize”.
--> Note: The person adding the bot needs "Manage Server" permissions.
6. Run the code below to start the bot with your bot token.
-7. Write e.g. "/bu whats the weather in Tokyo?" to start a browser-use task and get a response inside the Discord channel.
+7. Write e.g. "/bu what's the weather in Tokyo?" to start a browser-use task and get a response inside the Discord channel.
"""
import os
diff --git a/examples/integrations/slack/README.md b/examples/integrations/slack/README.md
index deea9dba4..3184dbc14 100644
--- a/examples/integrations/slack/README.md
+++ b/examples/integrations/slack/README.md
@@ -38,14 +38,14 @@ Steps to create and configure a Slack bot:
6. Invite the bot to a channel:
* Use the `/invite @your-bot-name` command in the Slack channel where you want the bot to be active.
7. Run the code in `examples/slack_example.py` to start the bot with your bot token and signing secret.
-8. Write e.g. "$bu whats the weather in Tokyo?" to start a browser-use task and get a response inside the Slack channel.
+8. Write e.g. "$bu what's the weather in Tokyo?" to start a browser-use task and get a response inside the Slack channel.
## Installing and Starting ngrok
To expose your local server to the internet, you can use ngrok. Follow these steps to install and start ngrok:
1. Download ngrok from the official website: https://ngrok.com/download
-2. Create a free account and follow the offical steps to install ngrok.
+2. Create a free account and follow the official steps to install ngrok.
3. Start ngrok by running the following command in your terminal:
```sh
ngrok http 3000
diff --git a/examples/models/azure_openai.py b/examples/models/azure_openai.py
index dd2efc0bf..d7ed35e24 100644
--- a/examples/models/azure_openai.py
+++ b/examples/models/azure_openai.py
@@ -38,6 +38,7 @@ llm = AzureChatOpenAI(
agent = Agent(
task='Go to amazon.com, search for laptop, sort by best rating, and give me the price of the first result',
llm=llm,
+ enable_memory=False,
)
diff --git a/examples/models/bedrock_claude.py b/examples/models/bedrock_claude.py
index 5d834994c..091f6cf72 100644
--- a/examples/models/bedrock_claude.py
+++ b/examples/models/bedrock_claude.py
@@ -4,14 +4,16 @@ Automated news analysis and sentiment scoring using Bedrock.
@dev Ensure AWS environment variables are set correctly for Bedrock access.
"""
+import argparse
+import asyncio
import os
import sys
+import boto3
+from botocore.config import Config
from langchain_aws import ChatBedrockConverse
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-import argparse
-import asyncio
from browser_use import Agent
from browser_use.browser.browser import Browser, BrowserConfig
@@ -19,10 +21,14 @@ from browser_use.controller.service import Controller
def get_llm():
+ config = Config(retries={'max_attempts': 10, 'mode': 'adaptive'})
+ bedrock_client = boto3.client('bedrock-runtime', region_name='us-east-1', config=config)
+
return ChatBedrockConverse(
model_id='us.anthropic.claude-3-5-sonnet-20241022-v2:0',
temperature=0.0,
max_tokens=None,
+ client=bedrock_client,
)
diff --git a/examples/use-cases/google_sheets.py b/examples/use-cases/google_sheets.py
index 73a2a2d87..5602c8122 100644
--- a/examples/use-cases/google_sheets.py
+++ b/examples/use-cases/google_sheets.py
@@ -102,7 +102,7 @@ async def input_selected_cell_text(browser: BrowserContext, text: str):
page = await browser.get_current_page()
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
+ await page.keyboard.press('Enter') # make sure to commit the input so it doesn't get overwritten by the next action
await page.keyboard.press('ArrowUp')
return ActionResult(extracted_content=f'Inputted text {text}', include_in_memory=False)
@@ -128,7 +128,7 @@ async def update_range_contents(browser: BrowserContext, range: str, new_content
# - https://github.com/philc/sheetkeys/blob/master/content_scripts/commands.js
# - https://support.google.com/docs/answer/181110?hl=en&co=GENIE.Platform%3DDesktop#zippy=%2Cmac-shortcuts
-# Tip: LLM is bad at spacial reasoning, don't make it navigate with arrow keys relative to current cell
+# Tip: LLM is bad at spatial reasoning, don't make it navigate with arrow keys relative to current cell
# if given arrow keys, it will try to jump from G1 to A2 by pressing Down, without realizing needs to go Down+LeftLeftLeftLeft
diff --git a/examples/use-cases/shopping.py b/examples/use-cases/shopping.py
index 4ba67ac99..cf6e80bef 100644
--- a/examples/use-cases/shopping.py
+++ b/examples/use-cases/shopping.py
@@ -77,7 +77,7 @@ At this stage, check the basket on the top right (indicates the price) and check
- If the total order **is below CHF 99**, add **a liquid soap refill** to reach the minimum. If it;s still you can buy some bread, dark chockolate.
- At this step, check if you have bought MORE items than needed. If the price is more then CHF200, you MUST remove items.
- If an item is not available, choose an alternative.
-- if an age verification is needed, remove alchoholic products, we haven't verified yet.
+- if an age verification is needed, remove alcoholic products, we haven't verified yet.
---
diff --git a/pyproject.toml b/pyproject.toml
index a3dca676d..bc22ea4bd 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -2,7 +2,7 @@
name = "browser-use"
description = "Make websites accessible for AI agents"
authors = [{ name = "Gregor Zunic" }]
-version = "0.1.40"
+version = "0.1.41rc2"
readme = "README.md"
requires-python = ">=3.11,<4.0"
classifiers = [
@@ -12,7 +12,7 @@ classifiers = [
]
dependencies = [
"httpx>=0.27.2",
- "pydantic>=2.10.4",
+ "pydantic>=2.10.4,<2.11.0",
"python-dotenv>=1.0.1",
"requests>=2.32.3",
"posthog>=3.7.0",
@@ -25,6 +25,7 @@ dependencies = [
"langchain-google-genai==2.1.2",
"langchain>=0.3.21",
"langchain-aws>=0.2.11",
+ "botocore>=1.37.23",
"google-api-core>=2.24.0",
"pyperclip>=1.9.0",
"pyobjc>=11.0; platform_system == 'darwin'",
@@ -34,6 +35,9 @@ dependencies = [
"faiss-cpu>=1.10.0",
"mem0ai==0.1.81",
]
+
+# botocore: only needed for Bedrock Claude boto3 examples/models/bedrock_claude.py
+# pydantic: >2.11 introduces many pydantic deprecation warnings until langchain-core upgrades their pydantic support lets keep it on 2.10
# google-api-core: only used for Google LLM APIs
# pyperclip: only used for examples that use copy/paste
# pyobjc: only used to get screen resolution on macOS
@@ -43,6 +47,10 @@ dependencies = [
urls = { "Repository" = "https://github.com/browser-use/browser-use" }
+[tool.codespell]
+ignore-words-list = "bu"
+skip = "*.json"
+
[tool.ruff]
line-length = 130
fix = true
@@ -83,4 +91,5 @@ dev-dependencies = [
"langchain-fireworks>=0.2.6",
"ipdb>=0.13.13",
"pre-commit>=4.2.0",
+ "codespell>=2.4.1",
]
diff --git a/tests/test_vision.py b/tests/test_vision.py
index 91c01b667..9851b1a6f 100644
--- a/tests/test_vision.py
+++ b/tests/test_vision.py
@@ -23,7 +23,7 @@ controller = Controller()
# use this test to ask the model questions about the page like
# which color do you see for bbox labels, list all with their label
-# whats the smallest bboxes with labels and
+# what's the smallest bboxes with labels and
@controller.registry.action(description='explain what you see on the screen and ask user for input')
@@ -40,7 +40,7 @@ async def done(text: str) -> str:
agent = Agent(
- task='call explain_screen all the time the user asks you questions e.g. about the page like bbox which you see are labels - your task is to expalin it and get the next question',
+ task='call explain_screen all the time the user asks you questions e.g. about the page like bbox which you see are labels - your task is to explain it and get the next question',
llm=llm,
controller=controller,
browser=Browser(config=BrowserConfig(disable_security=True, headless=False)),