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
update examples to use new BrowserProfile and BrowserSession
Nick Sweeting63382d8bfc96
diff --git a/examples/browser/stealth.py b/examples/browser/stealth.pyindex a62d380d4..d1c6ae311 100644--- a/examples/browser/stealth.py+++ b/examples/browser/stealth.py@@ -10,18 +10,16 @@ load_dotenv()from langchain_openai import ChatOpenAI-from browser_use import Agent, Browser, BrowserConfig, BrowserContextConfig+from browser_use import Agent+from browser_use.browser import BrowserProfile, BrowserSessionllm = ChatOpenAI(model='gpt-4o')-browser = Browser(- config=BrowserConfig(+browser_session = BrowserSession(+ browser_profile=BrowserProfile(headless=False,disable_security=False,keep_alive=True,- new_context_config=BrowserContextConfig(- keep_alive=True,- disable_security=False,- ),+ user_data_dir='~/.config/browseruse/profiles/default',))@@ -32,7 +30,7 @@ async def main():Go to https://bot-detector.rebrowser.net/ and verify that all the bot checks are passed.""",llm=llm,- browser=browser,+ browser_session=browser_session,)await agent.run()input('Press Enter to continue to the next test...')@@ -42,7 +40,7 @@ async def main():Go to https://www.webflow.com/ and verify that the page is not blocked by a bot check.""",llm=llm,- browser=browser,+ browser_session=browser_session,)await agent.run()input('Press Enter to continue to the next test...')@@ -52,7 +50,7 @@ async def main():Go to https://www.okta.com/ and verify that the page is not blocked by a bot check.""",llm=llm,- browser=browser,+ browser_session=browser_session,)await agent.run()@@ -61,7 +59,7 @@ async def main():Go to https://abrahamjuliot.github.io/creepjs/ and verify that the detection score is >50%.""",llm=llm,- browser=browser,+ browser_session=browser_session,)await agent.run()@@ -72,7 +70,7 @@ async def main():Go to https://nowsecure.nl/ check the "I'm not a robot" checkbox.""",llm=llm,- browser=browser,+ browser_session=browser_session,)await agent.run()diff --git a/examples/custom-functions/action_filters.py b/examples/custom-functions/action_filters.pyindex 177b81f1c..625e9d7de 100644--- a/examples/custom-functions/action_filters.py+++ b/examples/custom-functions/action_filters.py@@ -2,7 +2,7 @@Action filters (domains and page_filter) let you limit actions available to the Agent on a step-by-step/page-by-page basis.@registry.action(..., domains=['*'], page_filter=lambda page: return True)-async def some_action(browser: BrowserContext):+async def some_action(browser_session: BrowserSession):...This helps prevent the LLM from deciding to use an action that is not compatible with the current page.@@ -30,7 +30,8 @@ load_dotenv()from langchain_openai import ChatOpenAIfrom playwright.async_api import Page-from browser_use.agent.service import Agent, Browser, BrowserContext, Controller+from browser_use.agent.service import Agent, Controller+from browser_use.browser import BrowserSession# Initialize controller and registrycontroller = Controller()@@ -39,8 +40,8 @@ registry = controller.registry# Action will only be available to Agent on Google domains because of the domain filter@registry.action(description='Trigger disco mode', domains=['google.com', '*.google.com'])-async def disco_mode(browser: BrowserContext):- page = await browser.get_current_page()+async def disco_mode(browser_session: BrowserSession):+ page = await browser_session.get_current_page()await page.evaluate("""() => {// define the wiggle animationdocument.styleSheets[0].insertRule('@keyframes wiggle { 0% { transform: rotate(0deg); } 50% { transform: rotate(10deg); } 100% { transform: rotate(0deg); } }');@@ -58,9 +59,9 @@ def is_login_page(page: Page) -> bool:# then use it in the action decorator to limit the action to only be available on pages where the filter returns True@registry.action(description='Use the force, luke', page_filter=is_login_page)-async def use_the_force(browser: BrowserContext):+async def use_the_force(browser_session: BrowserSession):# this will only ever run on pages that matched the filter- page = await browser.get_current_page()+ page = await browser_session.get_current_page()assert is_login_page(page)await page.evaluate("""() => { document.querySelector('body').innerHTML = 'These are not the droids you are looking for';}""")@@ -68,7 +69,8 @@ async def use_the_force(browser: BrowserContext):async def main():"""Main function to run the example"""- browser = Browser()+ browser_session = BrowserSession()+ await browser_session.start()llm = ChatOpenAI(model_name='gpt-4o')# Create the agent@@ -79,7 +81,7 @@ async def main():After that, go to the Google login page and Use the force, luke.""",llm=llm,- browser=browser,+ browser_session=browser_session,controller=controller,)@@ -87,7 +89,7 @@ async def main():await agent.run(max_steps=10)# Cleanup- await browser.close()+ await browser_session.stop()if __name__ == '__main__':diff --git a/examples/custom-functions/clipboard.py b/examples/custom-functions/clipboard.pyindex 52be5e274..e5c2e4b44 100644--- a/examples/custom-functions/clipboard.py+++ b/examples/custom-functions/clipboard.py@@ -13,13 +13,10 @@ from langchain_openai import ChatOpenAIfrom browser_use import Agent, Controllerfrom browser_use.agent.views import ActionResult-from browser_use.browser.browser import Browser, BrowserConfig-from browser_use.browser.context import BrowserContext+from browser_use.browser import BrowserProfile, BrowserSession-browser = Browser(- config=BrowserConfig(- headless=False,- )+browser_profile = BrowserProfile(+ headless=False,)controller = Controller()@@ -31,10 +28,10 @@ def copy_to_clipboard(text: str):@controller.registry.action('Paste text from clipboard')-async def paste_from_clipboard(browser: BrowserContext):+async def paste_from_clipboard(browser_session: BrowserSession):text = pyperclip.paste()# send text to browser- page = await browser.get_current_page()+ page = await browser_session.get_current_page()await page.keyboard.type(text)return ActionResult(extracted_content=text)@@ -43,15 +40,17 @@ async def paste_from_clipboard(browser: BrowserContext):async def main():task = 'Copy the text "Hello, world!" to the clipboard, then go to google.com and paste the text'model = ChatOpenAI(model='gpt-4o')+ browser_session = BrowserSession(browser_profile=browser_profile)+ await browser_session.start()agent = Agent(task=task,llm=model,controller=controller,- browser=browser,+ browser_session=browser_session,)await agent.run()- await browser.close()+ await browser_session.stop()input('Press Enter to close...')diff --git a/examples/custom-functions/file_upload.py b/examples/custom-functions/file_upload.pyindex 7252189a2..2fcd90a67 100644--- a/examples/custom-functions/file_upload.py+++ b/examples/custom-functions/file_upload.py@@ -15,17 +15,14 @@ from langchain_openai import ChatOpenAIfrom browser_use import Agent, Controllerfrom browser_use.agent.views import ActionResult-from browser_use.browser.browser import Browser, BrowserConfig-from browser_use.browser.context import BrowserContext+from browser_use.browser import BrowserProfile, BrowserSessionlogger = logging.getLogger(__name__)-# Initialize controller first-browser = Browser(- config=BrowserConfig(- headless=False,- browser_binary_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',- )+# Initialize browser and controller+browser_profile = BrowserProfile(+ headless=False,+ browser_binary_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',)controller = Controller()@@ -33,14 +30,14 @@ controller = Controller()@controller.action('Upload file to interactive element with file path ',)-async def upload_file(index: int, path: str, browser: BrowserContext, available_file_paths: list[str]):+async def upload_file(index: int, path: str, browser_session: BrowserSession, available_file_paths: list[str]):if path not in available_file_paths:return ActionResult(error=f'File path {path} is not available')if not os.path.exists(path):return ActionResult(error=f'File {path} does not exist')- dom_el = await browser.get_dom_element_by_index(index)+ dom_el = await browser_session.get_dom_element_by_index(index)file_upload_dom_el = dom_el.get_file_upload_element()@@ -49,7 +46,7 @@ async def upload_file(index: int, path: str, browser: BrowserContext, available_logger.info(msg)return ActionResult(error=msg)- file_upload_el = await browser.get_locate_element(file_upload_dom_el)+ file_upload_el = await browser_session.get_locate_element(file_upload_dom_el)if file_upload_el is None:msg = f'No file upload element found at index {index}'@@ -93,17 +90,19 @@ async def main():available_file_paths = [create_file('txt'), create_file('pdf'), create_file('csv')]model = ChatOpenAI(model='gpt-4o')+ browser_session = BrowserSession(browser_profile=browser_profile)+ await browser_session.start()agent = Agent(task=task,llm=model,controller=controller,- browser=browser,+ browser_session=browser_session,available_file_paths=available_file_paths,)await agent.run()- await browser.close()+ await browser_session.stop()input('Press Enter to close...')diff --git a/examples/custom-functions/hover_element.py b/examples/custom-functions/hover_element.pyindex f8e064cd4..d1ddcfcb9 100644--- a/examples/custom-functions/hover_element.py+++ b/examples/custom-functions/hover_element.py@@ -13,8 +13,7 @@ from pydantic import BaseModelfrom browser_use import Agent, Controllerfrom browser_use.agent.views import ActionResult-from browser_use.browser.browser import Browser, BrowserConfig-from browser_use.browser.context import BrowserContext+from browser_use.browser import BrowserProfile, BrowserSessionclass HoverAction(BaseModel):@@ -23,10 +22,8 @@ class HoverAction(BaseModel):selector: str | None = None-browser = Browser(- config=BrowserConfig(- headless=False,- )+browser_profile = BrowserProfile(+ headless=False,)controller = Controller()@@ -35,29 +32,27 @@ controller = Controller()'Hover over an element',param_model=HoverAction, # Define this model with at least "index: int" field)-async def hover_element(params: HoverAction, browser: BrowserContext):+async def hover_element(params: HoverAction, browser_session: BrowserSession):"""Hovers over the element specified by its index from the cached selector map or by XPath."""- session = await browser.get_session()- state = session.cached_state-if params.xpath:# Use XPath to locate the element- element_handle = await browser.get_locate_element_by_xpath(params.xpath)+ element_handle = await browser_session.get_locate_element_by_xpath(params.xpath)if element_handle is None:raise Exception(f'Failed to locate element with XPath {params.xpath}')elif params.selector:# Use CSS selector to locate the element- element_handle = await browser.get_locate_element_by_css_selector(params.selector)+ element_handle = await browser_session.get_locate_element_by_css_selector(params.selector)if element_handle is None:raise Exception(f'Failed to locate element with CSS Selector {params.selector}')elif params.index is not None:# Use index to locate the element- if state is None or params.index not in state.selector_map:+ selector_map = await browser_session.get_selector_map()+ if params.index not in selector_map:raise Exception(f'Element index {params.index} does not exist - retry or use alternative actions')- element_node = state.selector_map[params.index]- element_handle = await browser.get_locate_element(element_node)+ element_node = selector_map[params.index]+ element_handle = await browser_session.get_locate_element(element_node)if element_handle is None:raise Exception(f'Failed to locate element with index {params.index}')else:@@ -80,15 +75,17 @@ async def main():task = 'Open https://testpages.eviltester.com/styled/csspseudo/css-hover.html and hover the element with the css selector #hoverdivpara, then click on "Can you click me?"'# task = 'Open https://testpages.eviltester.com/styled/csspseudo/css-hover.html and hover the element with the xpath //*[@id="hoverdivpara"], then click on "Can you click me?"'model = ChatOpenAI(model='gpt-4o')+ browser_session = BrowserSession(browser_profile=browser_profile)+ await browser_session.start()agent = Agent(task=task,llm=model,controller=controller,- browser=browser,+ browser_session=browser_session,)await agent.run()- await browser.close()+ await browser_session.stop()input('Press Enter to close...')diff --git a/examples/features/custom_user_agent.py b/examples/features/custom_user_agent.pyindex bc9c57ca9..c4cb6d525 100644--- a/examples/features/custom_user_agent.py+++ b/examples/features/custom_user_agent.py@@ -13,8 +13,7 @@ from langchain_anthropic import ChatAnthropicfrom langchain_openai import ChatOpenAIfrom browser_use import Agent-from browser_use.browser.browser import Browser, BrowserConfig-from browser_use.browser.context import BrowserContext, BrowserContextConfig+from browser_use.browser import BrowserProfile, BrowserSessionfrom browser_use.controller.service import Controller@@ -49,21 +48,18 @@ args = parser.parse_args()llm = get_llm(args.provider)--browser = Browser(- config=BrowserConfig(- # browser_binary_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+browser_session = BrowserSession(+ browser_profile=BrowserProfile(+ user_agent='foobarfoo',+ user_data_dir='~/.config/browseruse/profiles/default',))-browser_context = BrowserContext(config=BrowserContextConfig(user_agent='foobarfoo'), browser=browser)-agent = Agent(task=args.query,llm=llm,controller=controller,- # browser=browser,- browser_context=browser_context,+ browser_session=browser_session,use_vision=True,max_actions_per_step=1,)@@ -73,7 +69,7 @@ async def main():await agent.run(max_steps=25)input('Press Enter to close the browser...')- await browser_context.close()+ await browser_session.close()asyncio.run(main())diff --git a/examples/features/download_file.py b/examples/features/download_file.pyindex b5170017d..7051c74cd 100644--- a/examples/features/download_file.py+++ b/examples/features/download_file.py@@ -12,16 +12,16 @@ from langchain_google_genai import ChatGoogleGenerativeAIfrom pydantic import SecretStrfrom browser_use import Agent-from browser_use.browser.browser import Browser, BrowserConfig-from browser_use.browser.context import BrowserContextConfig+from browser_use.browser import BrowserProfile, BrowserSessionapi_key = os.getenv('GOOGLE_API_KEY')if not api_key:raise ValueError('GOOGLE_API_KEY is not set')llm = ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp', api_key=SecretStr(api_key))-browser = Browser(- config=BrowserConfig(- new_context_config=BrowserContextConfig(save_downloads_path=os.path.join(os.path.expanduser('~'), 'downloads'))+browser_session = BrowserSession(+ browser_profile=BrowserProfile(+ save_downloads_path=os.path.join(os.path.expanduser('~'), 'downloads'),+ user_data_dir='~/.config/browseruse/profiles/default',))@@ -32,10 +32,10 @@ async def run_download():llm=llm,max_actions_per_step=8,use_vision=True,- browser=browser,+ browser_session=browser_session,)await agent.run(max_steps=25)- await browser.close()+ await browser_session.close()if __name__ == '__main__':diff --git a/examples/features/follow_up_tasks.py b/examples/features/follow_up_tasks.pyindex be127eccf..053227e8c 100644--- a/examples/features/follow_up_tasks.py+++ b/examples/features/follow_up_tasks.py@@ -10,7 +10,8 @@ load_dotenv()from langchain_openai import ChatOpenAI-from browser_use import Agent, Browser, BrowserConfig, BrowserContextConfig, Controller+from browser_use import Agent, Controller+from browser_use.browser import BrowserProfile, BrowserSession# Initialize the modelllm = ChatOpenAI(@@ -18,12 +19,11 @@ llm = ChatOpenAI(temperature=0.0,)# Get your chrome path-browser = Browser(- config=BrowserConfig(- browser_binary_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',- new_context_config=BrowserContextConfig(- keep_alive=True,- ),+browser_session = BrowserSession(+ browser_profile=BrowserProfile(+ executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+ keep_alive=True,+ user_data_dir='~/.config/browseruse/profiles/default',),)@@ -32,7 +32,7 @@ controller = Controller()task = 'Find the founders of browser-use and draft them a short personalized message'-agent = Agent(task=task, llm=llm, controller=controller, browser=browser)+agent = Agent(task=task, llm=llm, controller=controller, browser_session=browser_session)async def main():diff --git a/examples/features/parallel_agents.py b/examples/features/parallel_agents.pyindex fcedcbd41..907bffa94 100644--- a/examples/features/parallel_agents.py+++ b/examples/features/parallel_agents.py@@ -11,14 +11,14 @@ load_dotenv()from langchain_openai import ChatOpenAIfrom browser_use.agent.service import Agent-from browser_use.browser.browser import Browser, BrowserConfig-from browser_use.browser.context import BrowserContextConfig+from browser_use.browser import BrowserProfile, BrowserSession-browser = Browser(- config=BrowserConfig(+browser_session = BrowserSession(+ browser_profile=BrowserProfile(disable_security=True,headless=False,- new_context_config=BrowserContextConfig(save_recording_path='./tmp/recordings'),+ save_recording_path='./tmp/recordings',+ user_data_dir='~/.config/browseruse/profiles/default',))llm = ChatOpenAI(model='gpt-4o')@@ -26,7 +26,7 @@ llm = ChatOpenAI(model='gpt-4o')async def main():agents = [- Agent(task=task, llm=llm, browser=browser)+ Agent(task=task, llm=llm, browser_session=browser_session)for task in ['Search Google for weather in Tokyo','Check Reddit front page title',@@ -43,16 +43,14 @@ async def main():await asyncio.gather(*[agent.run() for agent in agents])- # async with await browser.new_context() as context:agentX = Agent(task='Go to apple.com and return the title of the page',llm=llm,- browser=browser,- # browser_context=context,+ browser_session=browser_session,)await agentX.run()- await browser.close()+ await browser_session.close()if __name__ == '__main__':diff --git a/examples/features/restrict_urls.py b/examples/features/restrict_urls.pyindex a8085b03f..f131456b0 100644--- a/examples/features/restrict_urls.py+++ b/examples/features/restrict_urls.py@@ -11,8 +11,7 @@ load_dotenv()from langchain_openai import ChatOpenAIfrom browser_use import Agent-from browser_use.browser.browser import Browser, BrowserConfig-from browser_use.browser.context import BrowserContextConfig+from browser_use.browser import BrowserProfile, BrowserSessionllm = ChatOpenAI(model='gpt-4o', temperature=0.0)task = (@@ -21,19 +20,18 @@ task = (allowed_domains = ['google.com']-browser = Browser(- config=BrowserConfig(- browser_binary_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',- new_context_config=BrowserContextConfig(- allowed_domains=allowed_domains,- ),+browser_session = BrowserSession(+ browser_profile=BrowserProfile(+ executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+ allowed_domains=allowed_domains,+ user_data_dir='~/.config/browseruse/profiles/default',),)agent = Agent(task=task,llm=llm,- browser=browser,+ browser_session=browser_session,)@@ -41,7 +39,7 @@ async def main():await agent.run(max_steps=25)input('Press Enter to close the browser...')- await browser.close()+ await browser_session.close()asyncio.run(main())diff --git a/examples/features/result_processing.py b/examples/features/result_processing.pyindex 54aa4e06e..6d0980323 100644--- a/examples/features/result_processing.py+++ b/examples/features/result_processing.py@@ -13,30 +13,27 @@ from langchain_openai import ChatOpenAIfrom browser_use import Agentfrom browser_use.agent.views import AgentHistoryList-from browser_use.browser.browser import Browser, BrowserConfig, BrowserContextConfig+from browser_use.browser import BrowserProfile, BrowserSessionllm = ChatOpenAI(model='gpt-4o')-browser = Browser(- config=BrowserConfig(- headless=False,- disable_security=True,- )-)async def main():- async with await browser.new_context(- config=BrowserContextConfig(+ async with BrowserSession(+ browser_profile=BrowserProfile(+ headless=False,+ disable_security=True,trace_path='./tmp/result_processing',no_viewport=False,window_width=1280,window_height=1000,+ user_data_dir='~/.config/browseruse/profiles/default',)- ) as browser_context:+ ) as browser_session:agent = Agent(task="go to google.com and type 'OpenAI' click search and give me the first url",llm=llm,- browser_context=browser_context,+ browser_session=browser_session,)history: AgentHistoryList = await agent.run(max_steps=3)@@ -52,8 +49,6 @@ async def main():print('\nThoughts:')pprint(history.model_thoughts(), indent=4)- # close browser- await browser.close()if __name__ == '__main__':diff --git a/examples/features/save_trace.py b/examples/features/save_trace.pyindex f104fbf25..65e1c0803 100644--- a/examples/features/save_trace.py+++ b/examples/features/save_trace.py@@ -11,24 +11,26 @@ load_dotenv()from langchain_openai import ChatOpenAIfrom browser_use.agent.service import Agent-from browser_use.browser.browser import Browser-from browser_use.browser.context import BrowserContextConfig+from browser_use.browser import BrowserProfile, BrowserSessionllm = ChatOpenAI(model='gpt-4o', temperature=0.0)async def main():- browser = Browser()+ browser_session = BrowserSession(+ browser_profile=BrowserProfile(+ trace_path='./tmp/traces/',+ user_data_dir='~/.config/browseruse/profiles/default',+ )+ )- async with await browser.new_context(config=BrowserContextConfig(trace_path='./tmp/traces/')) as context:+ async with browser_session:agent = Agent(task='Go to hackernews, then go to apple.com and return all titles of open tabs',llm=llm,- browser_context=context,+ browser_session=browser_session,)await agent.run()- await browser.close()-asyncio.run(main())diff --git a/examples/models/gemini.py b/examples/models/gemini.pyindex 4f8dc4bc3..cc6fe77cc 100644--- a/examples/models/gemini.py+++ b/examples/models/gemini.py@@ -11,9 +11,8 @@ load_dotenv()from langchain_google_genai import ChatGoogleGenerativeAIfrom pydantic import SecretStr-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+from browser_use.browser import BrowserProfile, BrowserSessionapi_key = os.getenv('GOOGLE_API_KEY')if not api_key:@@ -21,11 +20,10 @@ if not api_key:llm = ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp', api_key=SecretStr(api_key))-browser = Browser(- config=BrowserConfig(- new_context_config=BrowserContextConfig(- viewport_expansion=0,- )+browser_session = BrowserSession(+ browser_profile=BrowserProfile(+ viewport_expansion=0,+ user_data_dir='~/.config/browseruse/profiles/default',))@@ -35,7 +33,7 @@ async def run_search():task='Go to amazon.com, search for laptop, sort by best rating, and give me the price of the first result',llm=llm,max_actions_per_step=4,- browser=browser,+ browser_session=browser_session,)await agent.run(max_steps=25)diff --git a/examples/use-cases/find_and_apply_to_jobs.py b/examples/use-cases/find_and_apply_to_jobs.pyindex 1f5b7ff69..de2984e6d 100644--- a/examples/use-cases/find_and_apply_to_jobs.py+++ b/examples/use-cases/find_and_apply_to_jobs.py@@ -23,8 +23,7 @@ from pydantic import BaseModel, SecretStrfrom PyPDF2 import PdfReaderfrom browser_use import ActionResult, Agent, Controller-from browser_use.browser.browser import Browser, BrowserConfig-from browser_use.browser.context import BrowserContext+from browser_use.browser import BrowserProfile, BrowserSessionrequired_env_vars = ['AZURE_OPENAI_KEY', 'AZURE_OPENAI_ENDPOINT']for var in required_env_vars:@@ -79,9 +78,9 @@ def read_cv():@controller.action('Upload cv to element - call this function to upload if element is not found, try with different index of the same upload element',)-async def upload_cv(index: int, browser: BrowserContext):+async def upload_cv(index: int, browser_session: BrowserSession):path = str(CV.absolute())- dom_el = await browser.get_dom_element_by_index(index)+ dom_el = await browser_session.get_dom_element_by_index(index)if dom_el is None:return ActionResult(error=f'No element found at index {index}')@@ -92,7 +91,7 @@ async def upload_cv(index: int, browser: BrowserContext):logger.info(f'No file upload element found at index {index}')return ActionResult(error=f'No file upload element found at index {index}')- file_upload_el = await browser.get_locate_element(file_upload_dom_el)+ file_upload_el = await browser_session.get_locate_element(file_upload_dom_el)if file_upload_el is None:logger.info(f'No file upload element found at index {index}')@@ -108,10 +107,11 @@ async def upload_cv(index: int, browser: BrowserContext):return ActionResult(error=f'Failed to upload file to index {index}')-browser = Browser(- config=BrowserConfig(- browser_binary_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+browser_session = BrowserSession(+ browser_profile=BrowserProfile(+ executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',disable_security=True,+ user_data_dir='~/.config/browseruse/profiles/default',))@@ -150,7 +150,7 @@ async def main():agents = []for task in tasks:- agent = Agent(task=task, llm=model, controller=controller, browser=browser)+ agent = Agent(task=task, llm=model, controller=controller, browser_session=browser_session)agents.append(agent)await asyncio.gather(*[agent.run() for agent in agents])diff --git a/examples/use-cases/google_sheets.py b/examples/use-cases/google_sheets.pyindex 5602c8122..f29663a4d 100644--- a/examples/use-cases/google_sheets.py+++ b/examples/use-cases/google_sheets.py@@ -1,8 +1,6 @@import osimport sys-from browser_use.browser.context import BrowserContext-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))import asyncio@@ -11,13 +9,7 @@ from dotenv import load_dotenvfrom langchain_openai import ChatOpenAIfrom browser_use import ActionResult, Agent, Controller-from browser_use.browser.browser import Browser, BrowserConfig--browser = Browser(- config=BrowserConfig(- browser_binary_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',- ),-)+from browser_use.browser import BrowserProfile, BrowserSession# Load environment variablesload_dotenv()@@ -33,8 +25,8 @@ def is_google_sheet(page) -> bool:@controller.registry.action('Google Sheets: Open a specific Google Sheet')-async def open_google_sheet(browser: BrowserContext, google_sheet_url: str):- page = await browser.get_current_page()+async def open_google_sheet(browser_session: BrowserSession, google_sheet_url: str):+ page = await browser_session.get_current_page()if page.url != google_sheet_url:await page.goto(google_sheet_url)await page.wait_for_load_state()@@ -44,8 +36,8 @@ async def open_google_sheet(browser: BrowserContext, google_sheet_url: str):@controller.registry.action('Google Sheets: Get the contents of the entire sheet', page_filter=is_google_sheet)-async def get_sheet_contents(browser: BrowserContext):- page = await browser.get_current_page()+async def get_sheet_contents(browser_session: BrowserSession):+ page = await browser_session.get_current_page()# select all cellsawait page.keyboard.press('Enter')@@ -58,8 +50,8 @@ async def get_sheet_contents(browser: BrowserContext):@controller.registry.action('Google Sheets: Select a specific cell or range of cells', page_filter=is_google_sheet)-async def select_cell_or_range(browser: BrowserContext, cell_or_range: str):- page = await browser.get_current_page()+async def select_cell_or_range(browser_session: BrowserSession, cell_or_range: str):+ page = await browser_session.get_current_page()await page.keyboard.press('Enter') # make sure we dont delete current cell contents if we were last editingawait page.keyboard.press('Escape') # to clear current focus (otherwise select range popup is additive)@@ -78,10 +70,10 @@ async def select_cell_or_range(browser: BrowserContext, cell_or_range: str):@controller.registry.action('Google Sheets: Get the contents of a specific cell or range of cells', page_filter=is_google_sheet)-async def get_range_contents(browser: BrowserContext, cell_or_range: str):- page = await browser.get_current_page()+async def get_range_contents(browser_session: BrowserSession, cell_or_range: str):+ page = await browser_session.get_current_page()- await select_cell_or_range(browser, cell_or_range)+ await select_cell_or_range(browser_session, cell_or_range)await page.keyboard.press('ControlOrMeta+C')await asyncio.sleep(0.1)@@ -90,16 +82,16 @@ async def get_range_contents(browser: BrowserContext, cell_or_range: str):@controller.registry.action('Google Sheets: Clear the currently selected cells', page_filter=is_google_sheet)-async def clear_selected_range(browser: BrowserContext):- page = await browser.get_current_page()+async def clear_selected_range(browser_session: BrowserSession):+ page = await browser_session.get_current_page()await page.keyboard.press('Backspace')return ActionResult(extracted_content='Cleared selected range', include_in_memory=False)@controller.registry.action('Google Sheets: Input text into the currently selected cell', page_filter=is_google_sheet)-async def input_selected_cell_text(browser: BrowserContext, text: str):- page = await browser.get_current_page()+async def input_selected_cell_text(browser_session: BrowserSession, text: str):+ page = await browser_session.get_current_page()await page.keyboard.type(text, delay=0.1)await page.keyboard.press('Enter') # make sure to commit the input so it doesn't get overwritten by the next action@@ -108,17 +100,17 @@ async def input_selected_cell_text(browser: BrowserContext, text: str):@controller.registry.action('Google Sheets: Batch update a range of cells', page_filter=is_google_sheet)-async def update_range_contents(browser: BrowserContext, range: str, new_contents_tsv: str):- page = await browser.get_current_page()+async def update_range_contents(browser_session: BrowserSession, range: str, new_contents_tsv: str):+ page = await browser_session.get_current_page()- await select_cell_or_range(browser, range)+ await select_cell_or_range(browser_session, range)# simulate paste event from clipboard with TSV contentawait page.evaluate(f"""- const clipboardData = new DataTransfer();- clipboardData.setData('text/plain', `{new_contents_tsv}`);- document.activeElement.dispatchEvent(new ClipboardEvent('paste', {{clipboardData}}));- """)+ const clipboardData = new DataTransfer();+ clipboardData.setData('text/plain', `{new_contents_tsv}`);+ document.activeElement.dispatchEvent(new ClipboardEvent('paste', {{clipboardData}}));+ """)return ActionResult(extracted_content=f'Updated cell {range} with {new_contents_tsv}', include_in_memory=False)@@ -133,57 +125,64 @@ async def update_range_contents(browser: BrowserContext, range: str, new_contentasync def main():- async with await browser.new_context() as context:+ browser_session = BrowserSession(+ browser_profile=BrowserProfile(+ executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+ user_data_dir='~/.config/browseruse/profiles/default',+ )+ )++ async with browser_session:model = ChatOpenAI(model='gpt-4o')eraser = Agent(task="""- Clear all the existing values in columns A through F in this Google Sheet:- https://docs.google.com/spreadsheets/d/1INaIcfpYXlMRWO__de61SHFCaqt1lfHlcvtXZPItlpI/edit- """,+ Clear all the existing values in columns A through F in this Google Sheet:+ https://docs.google.com/spreadsheets/d/1INaIcfpYXlMRWO__de61SHFCaqt1lfHlcvtXZPItlpI/edit+ """,llm=model,- browser_context=context,+ browser_session=browser_session,controller=controller,)await eraser.run()researcher = Agent(task="""- Google to find the full name, nationality, and date of birth of the CEO of the top 10 Fortune 100 companies.- For each company, append a row to this existing Google Sheet: https://docs.google.com/spreadsheets/d/1INaIcfpYXlMRWO__de61SHFCaqt1lfHlcvtXZPItlpI/edit- Make sure column headers are present and all existing values in the sheet are formatted correctly.- Columns:- A: Company Name- B: CEO Full Name- C: CEO Country of Birth- D: CEO Date of Birth (YYYY-MM-DD)- E: Source URL where the information was found- """,+ Google to find the full name, nationality, and date of birth of the CEO of the top 10 Fortune 100 companies.+ For each company, append a row to this existing Google Sheet: https://docs.google.com/spreadsheets/d/1INaIcfpYXlMRWO__de61SHFCaqt1lfHlcvtXZPItlpI/edit+ Make sure column headers are present and all existing values in the sheet are formatted correctly.+ Columns:+ A: Company Name+ B: CEO Full Name+ C: CEO Country of Birth+ D: CEO Date of Birth (YYYY-MM-DD)+ E: Source URL where the information was found+ """,llm=model,- browser_context=context,+ browser_session=browser_session,controller=controller,)await researcher.run()improvised_continuer = Agent(task="""- Read the Google Sheet https://docs.google.com/spreadsheets/d/1INaIcfpYXlMRWO__de61SHFCaqt1lfHlcvtXZPItlpI/edit- Add 3 more rows to the bottom continuing the existing pattern, make sure any data you add is sourced correctly.- """,+ Read the Google Sheet https://docs.google.com/spreadsheets/d/1INaIcfpYXlMRWO__de61SHFCaqt1lfHlcvtXZPItlpI/edit+ Add 3 more rows to the bottom continuing the existing pattern, make sure any data you add is sourced correctly.+ """,llm=model,- browser_context=context,+ browser_session=browser_session,controller=controller,)await improvised_continuer.run()final_fact_checker = Agent(task="""- Read the Google Sheet https://docs.google.com/spreadsheets/d/1INaIcfpYXlMRWO__de61SHFCaqt1lfHlcvtXZPItlpI/edit- Fact-check every entry, add a new column F with your findings for each row.- Make sure to check the source URL for each row, and make sure the information is correct.- """,+ Read the Google Sheet https://docs.google.com/spreadsheets/d/1INaIcfpYXlMRWO__de61SHFCaqt1lfHlcvtXZPItlpI/edit+ Fact-check every entry, add a new column F with your findings for each row.+ Make sure to check the source URL for each row, and make sure the information is correct.+ """,llm=model,- browser_context=context,+ browser_session=browser_session,controller=controller,)await final_fact_checker.run()diff --git a/examples/use-cases/twitter_post_using_cookies.py b/examples/use-cases/twitter_post_using_cookies.pyindex 40252ef65..74f29f4b3 100644--- a/examples/use-cases/twitter_post_using_cookies.py+++ b/examples/use-cases/twitter_post_using_cookies.py@@ -14,8 +14,7 @@ from langchain_google_genai import ChatGoogleGenerativeAIfrom pydantic import SecretStrfrom browser_use import Agent-from browser_use.browser.browser import Browser, BrowserConfig-from browser_use.browser.context import BrowserContext, BrowserContextConfig+from browser_use.browser import BrowserProfile, BrowserSessionapi_key = os.getenv('GOOGLE_API_KEY')if not api_key:@@ -24,18 +23,18 @@ if not api_key:llm = ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp', api_key=SecretStr(api_key))-browser = Browser(- config=BrowserConfig(- # browser_binary_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+browser_session = BrowserSession(+ browser_profile=BrowserProfile(+ user_data_dir='~/.config/browseruse/profiles/default',+ # headless=False, # Uncomment to see the browser+ # executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',))-file_path = os.path.join(os.path.dirname(__file__), 'twitter_cookies.txt')-context = BrowserContext(browser=browser, config=BrowserContextConfig(cookies_file=file_path))async def main():agent = Agent(- browser_context=context,+ browser_session=browser_session,task=('go to https://x.com. write a new post with the text "browser-use ftw", and submit it'),llm=llm,max_actions_per_step=4,diff --git a/examples/use-cases/web_voyager_agent.py b/examples/use-cases/web_voyager_agent.pyindex a440fa837..7ea771405 100644--- a/examples/use-cases/web_voyager_agent.py+++ b/examples/use-cases/web_voyager_agent.py@@ -15,7 +15,7 @@ from langchain_openai import AzureChatOpenAI, ChatOpenAIfrom pydantic import SecretStrfrom browser_use.agent.service import Agent-from browser_use.browser.browser import Browser, BrowserConfig, BrowserContextConfig+from browser_use.browser import BrowserProfile, BrowserSession# Set LLM based on defined environment variablesif os.getenv('OPENAI_API_KEY'):@@ -33,21 +33,19 @@ else:raise ValueError('No LLM found. Please set OPENAI_API_KEY or AZURE_OPENAI_KEY and AZURE_OPENAI_ENDPOINT.')-browser = Browser(- config=BrowserConfig(+browser_session = BrowserSession(+ browser_profile=BrowserProfile(headless=False, # This is True in productiondisable_security=True,- new_context_config=BrowserContextConfig(- disable_security=True,- minimum_wait_page_load_time=1, # 3 on prod- maximum_wait_page_load_time=10, # 20 on prod- # Set no_viewport=False to constrain the viewport to the specified dimensions- # This is useful for specific cases where you need a fixed viewport size- no_viewport=False,- window_width=1280,- window_height=1100,- # trace_path='./tmp/web_voyager_agent',- ),+ minimum_wait_page_load_time=1, # 3 on prod+ maximum_wait_page_load_time=10, # 20 on prod+ # Set no_viewport=False to constrain the viewport to the specified dimensions+ # This is useful for specific cases where you need a fixed viewport size+ no_viewport=False,+ window_width=1280,+ window_height=1100,+ user_data_dir='~/.config/browseruse/profiles/default',+ # trace_path='./tmp/web_voyager_agent',))@@ -65,7 +63,7 @@ async def main():agent = Agent(task=TASK,llm=llm,- browser=browser,+ browser_session=browser_session,validate_output=True,enable_memory=False,)diff --git a/examples/use-cases/wikipedia_banana_to_quantum.py b/examples/use-cases/wikipedia_banana_to_quantum.pyindex eb6e78443..f6df63102 100644--- a/examples/use-cases/wikipedia_banana_to_quantum.py+++ b/examples/use-cases/wikipedia_banana_to_quantum.py@@ -11,7 +11,7 @@ load_dotenv()from langchain_openai import ChatOpenAIfrom browser_use import Agent-from browser_use.browser.browser import Browser, BrowserConfig, BrowserContextConfig+from browser_use.browser import BrowserProfile, BrowserSession# video https://preview.screen.studio/share/vuq91Ej8llm = ChatOpenAI(@@ -20,15 +20,14 @@ llm = ChatOpenAI()task = 'go to https://en.wikipedia.org/wiki/Banana and click on buttons on the wikipedia page to go as fast as possible from banna to Quantum mechanics'-browser = Browser(- config=BrowserConfig(- new_context_config=BrowserContextConfig(- viewport_expansion=-1,- highlight_elements=False,- ),+browser_session = BrowserSession(+ browser_profile=BrowserProfile(+ viewport_expansion=-1,+ highlight_elements=False,+ user_data_dir='~/.config/browseruse/profiles/default',),)-agent = Agent(task=task, llm=llm, browser=browser, use_vision=False)+agent = Agent(task=task, llm=llm, browser_session=browser_session, use_vision=False)async def main():diff --git a/pyproject.toml b/pyproject.tomlindex d12f9a3c6..d8100cb4d 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -82,7 +82,7 @@ line-length = 130fix = true[tool.ruff.lint]-select = ["ASYNC", "E", "F", "FAST", "I", "PLE", "E261"]+select = ["ASYNC", "E", "F", "FAST", "I", "PLE"]ignore = ["ASYNC109", "E101", "E402", "E501", "F841", "E731", "W291"] # TODO: determine if adding timeouts to all the unbounded async functions is needed / worth-it so we can un-ignore ASYNC109unfixable = ["E101", "E402", "E501", "F841", "E731"]