Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
Merge remote-tracking branch 'origin/staging' into multi-step
magmueller13bb5f7141ab
diff --cc browser_use/agent/service.pyindex be15c3fc9,5adef4379..c4b4b9cb0--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@@ -72,11 -72,26 +76,27 @@@ class Agentself.llm = llmself.save_conversation_path = save_conversation_pathself._last_result = None-+ self.include_attributes = include_attributes+ self.max_error_length = max_error_length# Controller setup- self.controller_injected = controller is not None- self.controller = controller or Controller()+ self.controller = controller++ # Browser setup+ self.injected_browser = browser is not None+ self.injected_browser_context = browser_context is not None++ # Initialize browser first if needed+ self.browser = browser if browser is not None else (None if browser_context else Browser())++ # Initialize browser context+ if browser_context:+ self.browser_context = browser_context+ elif self.browser:+ self.browser_context = BrowserContext(browser=self.browser)+ else:+ # If neither is provided, create both new+ self.browser = Browser()+ self.browser_context = BrowserContext(browser=self.browser)self.system_prompt_class = system_prompt_class@@@ -132,14 -150,13 +152,16 @@@self.message_manager._remove_last_state_message() # we dont want the whole state in the chat historyself.message_manager.add_model_output(model_output)- result: list[ActionResult] = await self.controller.multi_act(model_output.action)- result = await self.controller.act(model_output.action, self.browser_context)++ result: list[ActionResult] = await self.controller.multi_act(++ model_output.action, self.browser_context++ )self._last_result = result- if result.extracted_content:- logger.info(f'📄 Result: {result.extracted_content}')- if result.is_done:- logger.result(f'{result.extracted_content}') # type: ignore+ for r in result:+ if r.is_done:+ logger.result(f'{r.extracted_content}')+ elif r.extracted_content:+ logger.info(f'📄 Result: {r.extracted_content}')self.consecutive_failures = 0@@@ -430,27 -439,21 +455,28 @@@return results- async def _execute_history_step(self, history_item: AgentHistory, delay: float) -> ActionResult:+ async def _execute_history_step(+ self, history_item: AgentHistory, delay: float+ ) -> list[ActionResult]:"""Execute a single step from history with element validation"""- state = await self.controller.browser.get_state()+ state = await self.browser_context.get_state()if not state or not history_item.model_output:raise ValueError('Invalid state or model output')+ updated_actions = []+ for i, action in enumerate(history_item.model_output.action):+ updated_action = await self._update_action_indices(+ history_item.state.interacted_element[i],+ action,+ state,+ )+ updated_actions.append(updated_action)- updated_action = await self._update_action_indices(- history_item.state.interacted_element, history_item.model_output.action, state- )+ 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)- if updated_action is None:- raise ValueError('Could not find matching element in current page')++ result = await self.controller.multi_act(updated_actions, self.browser_context)+- result = await self.controller.act(updated_action, self.browser_context)await asyncio.sleep(delay)return resultdiff --cc browser_use/browser/context.pyindex 6cdc8504b,e45751a20..f006d9a3d--- a/browser_use/browser/context.py+++ b/browser_use/browser/context.py@@@ -8,8 -8,9 +8,9 @@@ import jsoimport loggingimport osimport time+ import uuidfrom dataclasses import dataclass, field- from typing import Optional, TypedDict-from typing import TYPE_CHECKING, TypedDict++from typing import TYPE_CHECKING, Optional, TypedDictfrom playwright.async_api import Browser as PlaywrightBrowserfrom playwright.async_api import (@@@ -35,45 -39,51 +39,50 @@@ class BrowserContextWindowSize(TypedDic@dataclass- class BrowserConfig:+ class BrowserContextConfig:"""- Configuration for the Browser.+ Configuration for the BrowserContext.Default values:- headless: False- Whether to run browser in headless mode-- keep_open: False- Keep browser open after script finishes+ cookies_file: None+ Path to cookies file for persistence- disable_security: False- Disable browser security features+ disable_security: False+ Disable browser security features- cookies_file: None- Path to cookies file for persistence-- minimum_wait_page_load_time: 0.5- Minimum time to wait before getting page state for LLM input+ minimum_wait_page_load_time: 0.5+ Minimum time to wait before getting page state for LLM input- wait_for_network_idle_page_load_time: 1.0- Time to wait for network requests to finish before getting page state.- Lower values may result in incomplete page loads.+ wait_for_network_idle_page_load_time: 1.0+ Time to wait for network requests to finish before getting page state.+ Lower values may result in incomplete page loads.- maximum_wait_page_load_time: 5.0- Maximum time to wait for page load before proceeding anyway+ maximum_wait_page_load_time: 5.0+ Maximum time to wait for page load before proceeding anyway++ browser_window_size: {'width': 1280, 'height': 1024}+ Default browser window size++ save_recording_path: None+ Path to save video recordings++ trace_path: None+ Path to save trace files. It will auto name the file with the TRACE_PATH/{context_id}.zip"""- headless: bool = False- keep_open: bool = False- disable_security: bool = Falsecookies_file: str | None = Noneminimum_wait_page_load_time: float = 0.5wait_for_network_idle_page_load_time: float = 1maximum_wait_page_load_time: float = 5+ wait_between_actions: float = 1+ disable_security: bool = False+extra_chromium_args: list[str] = field(default_factory=list)- browser_window_size: Optional[BrowserWindowSize] = None- browser_window_size: BrowserContextWindowSize = field(- default_factory=lambda: {'width': 1280, 'height': 1024}- )++ browser_window_size: Optional[BrowserContextWindowSize] = None++ save_recording_path: str | None = None+ trace_path: str | None = None@dataclassdiff --cc browser_use/controller/service.pyindex a6edd2bcd,5107f7aa9..c3a83b4ac--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@@ -37,19 -33,15 +34,19 @@@ class Controller# Basic Navigation Actions@self.registry.action(- 'Search Google', param_model=SearchGoogleAction, requires_browser=True+ 'Search Google in the current tab',+ param_model=SearchGoogleAction,+ requires_browser=True,)- async def search_google(params: SearchGoogleAction, browser: Browser):+ async def search_google(params: SearchGoogleAction, browser: BrowserContext):page = await browser.get_current_page()await page.goto(f'https://www.google.com/search?q={params.query}')await page.wait_for_load_state()- @self.registry.action('Navigate to URL', 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: Browser):+ async def go_to_url(params: GoToUrlAction, browser: BrowserContext):page = await browser.get_current_page()await page.goto(params.url)await page.wait_for_load_state()@@@ -78,20 -70,23 +75,20 @@@msg = None- for _ in range(params.num_clicks):- try:- await browser._click_element_node(element_node)- msg = f'🖱️ Clicked element {params.index}: {element_node.xpath}'- if params.num_clicks > 1:- msg += f' ({_ + 1}/{params.num_clicks} clicks)'- except Exception as e:- logger.warning(f'Element no longer available after {_ + 1} clicks: {str(e)}')- break-- if len(session.context.pages) > initial_pages:- await browser.switch_to_tab(-1)-- return ActionResult(extracted_content=f'{msg}')+ try:+ await browser._click_element_node(element_node)+ msg = f'🖱️ Clicked element {params.index}: {element_node.xpath}'+ if len(session.context.pages) > initial_pages:+ 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'+ )+ return ActionResult(error=str(e))@self.registry.action('Input text', param_model=InputTextAction, requires_browser=True)- async def input_text(params: InputTextAction, browser: Browser):+ async def input_text(params: InputTextAction, browser: BrowserContext):session = await browser.get_session()state = session.cached_state@@@ -113,10 -108,8 +110,10 @@@page = await browser.get_current_page()await page.wait_for_load_state()- @self.registry.action('Open 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: Browser):+ async def open_tab(params: OpenTabAction, browser: BrowserContext):await browser.create_new_tab(params.url)# Content Actions@@@ -184,52 -177,14 +181,54 @@@"""return self.registry.action(description, **kwargs)+ @time_execution_async('--multi-act')- async def multi_act(self, actions: list[ActionModel]) -> list[ActionResult]:++ async def multi_act(++ self, actions: list[ActionModel], browser_context: BrowserContext++ ) -> list[ActionResult]:+ """Execute multiple actions"""+ results = []+ changed = False- await self.browser.remove_highlights()- session = await self.browser.get_session()++ await browser_context.remove_highlights()++ session = await browser_context.get_session()+ cached_selector_map = session.cached_state.selector_map+ cached_att_hashes = set(e.hash.attributes_hash for e in cached_selector_map.values())+ cached_path_hashes = set(e.hash.branch_path_hash for e in cached_selector_map.values())++ for i, action in enumerate(actions):+ if changed and action.get_index() is not None:+ # next action requires index but there are new elements on the page+ break+- results.append(await self.act(action))++ results.append(await self.act(action, browser_context))+ logger.debug(f'Executed action {i + 1} / {len(actions)}')+ if results[-1].is_done or results[-1].error or i == len(actions) - 1:+ break+- await asyncio.sleep(self.wait_between_actions)++ await asyncio.sleep(browser_context.config.wait_between_actions)+ # hash all elements. if it is a subset of cached_state its fine - else break (new elements on page)+- new_state = await self.browser.get_state()++ new_state = await browser_context.get_state()+ new_att_hashes = set(e.hash.attributes_hash for e in new_state.selector_map.values())++ if not new_att_hashes.issubset(cached_att_hashes):+ logger.debug(f'Attributes changed - stopping after {i + 1} actions')+ changed = True+ 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):+ logger.debug(f'Branch path changed - stopping after {i + 1} actions')+ changed = True++ return results+@time_execution_sync('--act')- async def act(self, action: ActionModel) -> ActionResult:+ async def act(self, action: ActionModel, browser_context: BrowserContext) -> ActionResult:"""Execute an action"""try:for action_name, params in action.model_dump(exclude_unset=True).items():if params is not None:+ # remove highlightsresult = await self.registry.execute_action(- action_name, params, browser=self.browser+ action_name, params, browser=browser_context)if isinstance(result, str):return ActionResult(extracted_content=result)diff --cc examples/find_and_apply_to_jobs.pyindex 8b68e5e8e,585666275..592bc8788--- a/examples/find_and_apply_to_jobs.py+++ b/examples/find_and_apply_to_jobs.py@@@ -13,30 -13,20 +13,23 @@@ from pathlib import Patfrom PyPDF2 import PdfReader- from browser_use.browser.service import Browser, BrowserWindowSize++from browser_use.browser.browser import BrowserConfig+sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))-import asynciofrom typing import List, Optionalfrom dotenv import load_dotenv-from langchain_openai import ChatOpenAI-from pydantic import BaseModel+from langchain_openai import AzureChatOpenAI, ChatOpenAI+from pydantic import BaseModel, SecretStr- from browser_use import ActionResult, Agent, BrowserConfig, Controller+ from browser_use import ActionResult, Agent, Controller+ from browser_use.browser.context import BrowserContextload_dotenv()+# full screen mode- controller = Controller(- browser_config=BrowserConfig(- keep_open=True,- disable_security=True,- browser_window_size=None,- # extra_chromium_args=['--start-maximized'],- )- )+ controller = Controller()CV = Path.cwd() / 'cv_04_24.pdf'diff --cc examples/flight_search.pyindex 07632cfe4,51e8d4171..2846c78bd--- a/examples/flight_search.py+++ b/examples/flight_search.py@@@ -15,18 -12,18 +12,12 @@@ import asyncifrom langchain_openai import ChatOpenAI- from browser_use import ActionModel, Agent, AgentHistoryList, Controller- from browser_use.agent.views import AgentOutput+ from browser_use import Agent, AgentHistoryList, Controllerllm = ChatOpenAI(model='gpt-4o')+ # browser = Browser(config=BrowserConfig(headless=False))controller = Controller()--[email protected](description='Prints the secret text')--async def secret_text(secret_text: str) -> None:-- print(secret_text)----agent = Agent(task='Find flights on kayak.com from Zurich to Beijing on 25.12.2024 to 02.02.2025',llm=llm,diff --cc test_full_screen.pyindex 000000000,000000000..3926761denew file mode 100644--- /dev/null+++ b/test_full_screen.py@@@ -1,0 -1,0 +1,22 @@@++import argparse++import asyncio++++from playwright.async_api import async_playwright++++++async def test_full_screen(start_fullscreen: bool, maximize: bool):++ async with async_playwright() as p:++ browser = await p.chromium.launch(++ headless=False,++ args=['--start-maximized'],++ )++ context = await browser.new_context(no_viewport=True, viewport=None)++ page = await context.new_page()++ await page.goto('https://google.com')++++ await asyncio.sleep(10)++ await browser.close()++++++if __name__ == '__main__':++ asyncio.run(test_full_screen(False, False))diff --cc tests/test_attach_chrome.pyindex 28b7945ae,000000000..c527da4c1mode 100644,000000..100644--- a/tests/test_attach_chrome.py+++ b/tests/test_attach_chrome.py@@@ -1,72 -1,0 +1,70 @@@+import argparse+import asyncio++from playwright.async_api import async_playwright+- from browser_use.browser.service import BrowserWindowSize-++async def test_full_screen(start_fullscreen: bool, maximize: bool):+ async with async_playwright() as p:+ try:+ print('Attempting to connect to Chrome...')+ # run in terminal: /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222 --no-first-run+ browser = await p.chromium.connect_over_cdp(+ 'http://localhost:9222',+ timeout=20000, # 20 second timeout for connection+ )+ print('Connected to Chrome successfully')++ # Get the first context and page, or create new ones if needed+ if len(browser.contexts) == 0:+ context = await browser.new_context(ignore_https_errors=True)+ else:+ context = browser.contexts[0]++ if len(context.pages) == 0:+ page = await context.new_page()+ else:+ page = context.pages[0]++ print('Attempting to navigate to Gmail...')+ try:+ # First try with a shorter timeout+ await page.goto(+ 'https://mail.google.com',+ wait_until='load', # Changed from domcontentloaded+ timeout=10000,+ )+ except Exception as e:+ print(f'First navigation attempt failed: {e}')+ print('Trying again with different settings...')+ # If that fails, try again with different settings+ await page.goto(+ 'https://mail.google.com',+ wait_until='commit', # Less strict wait condition+ timeout=30000,+ )++ # Wait for the page to stabilize+ await asyncio.sleep(2)++ print(f'Current page title: {await page.title()}')++ # Optional: wait for specific Gmail elements+ try:+ await page.wait_for_selector('div[role="main"]', timeout=5000)+ print('Gmail interface detected')+ except Exception as e:+ print(f'Note: Gmail interface not detected: {e}')++ await asyncio.sleep(30)+ except Exception as e:+ print(f'An error occurred: {e}')+ import traceback++ traceback.print_exc()+ finally:+ await browser.close()+++if __name__ == '__main__':+ asyncio.run(test_full_screen(False, False))diff --cc tests/test_full_screen.pyindex 4a682e1ea,000000000..3926761demode 100644,000000..100644--- a/tests/test_full_screen.py+++ b/tests/test_full_screen.py@@@ -1,24 -1,0 +1,22 @@@+import argparse+import asyncio++from playwright.async_api import async_playwright+- from browser_use.browser.service import BrowserWindowSize-++async def test_full_screen(start_fullscreen: bool, maximize: bool):+ async with async_playwright() as p:+ browser = await p.chromium.launch(+ headless=False,+ args=['--start-maximized'],+ )+ context = await browser.new_context(no_viewport=True, viewport=None)+ page = await context.new_page()+ await page.goto('https://google.com')++ await asyncio.sleep(10)+ await browser.close()+++if __name__ == '__main__':+ asyncio.run(test_full_screen(False, False))diff --cc tests/test_vision.pyindex f5ab4361f,000000000..4fa58415fmode 100644,000000..100644--- a/tests/test_vision.py+++ b/tests/test_vision.py@@@ -1,48 -1,0 +1,47 @@@+"""+Simple try of the agent.++@dev You need to add OPENAI_API_KEY to your environment variables.+"""++import json+import os+import sys+from doctest import OutputChecker+from pprint import pprint++sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+import asyncio++from langchain_openai import ChatOpenAI++from browser_use import ActionModel, Agent, AgentHistoryList, Controller+from browser_use.agent.views import AgentOutput++llm = ChatOpenAI(model='gpt-4o')+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++[email protected](description='explain what you see on the screen and ask user for input')+async def explain_screen(text: str) -> str:+ pprint(text)+ answer = input('\nuser input next question: \n')+ return answer+++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',+ llm=llm,+ controller=controller,+)+++async def main():+ history: AgentHistoryList = await agent.run(20)- await controller.browser.close(force=True)+++asyncio.run(main())