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
New tab opening & switching works
magmuellera256a1965273
diff --git a/src/browser/service.py b/src/browser/service.pyindex d775fd244..ace85f674 100644--- a/src/browser/service.py+++ b/src/browser/service.py@@ -403,3 +403,9 @@ class BrowserService:}self._tab_cache[handle] = tab_inforeturn tab_info++ def open_tab(self, url: str):+ driver = self._get_driver()+ driver.execute_script(f'window.open("{url}", "_blank");')+ self.wait_for_page_load()+ return self.handle_new_tab()diff --git a/src/controller/service.py b/src/controller/service.pyindex c13860034..ef47e7c15 100644--- a/src/controller/service.py+++ b/src/controller/service.py@@ -57,6 +57,8 @@ class ControllerService:self.browser.search_google(action.search_google.query)elif action.switch_tab:self.browser.switch_tab(action.switch_tab.handle)+ elif action.open_tab:+ self.browser.open_tab(action.open_tab.url)elif action.go_to_url:self.browser.go_to_url(action.go_to_url.url)elif action.nothing:diff --git a/src/controller/views.py b/src/controller/views.pyindex b4f467eaa..c4d5f3489 100644--- a/src/controller/views.py+++ b/src/controller/views.py@@ -30,6 +30,10 @@ class SwitchTabControllerAction(BaseModel):handle: str # The window handle to switch to+class OpenTabControllerAction(BaseModel):+ url: str++class ControllerActions(BaseModel):"""Controller actions you can use to interact.@@ -43,7 +47,8 @@ class ControllerActions(BaseModel):click_element: Optional[ClickElementControllerAction] = Noneinput_text: Optional[InputTextControllerAction] = Noneextract_page_content: Optional[Literal[True]] = None- switch_tab: Optional[SwitchTabControllerAction] = None # New action+ switch_tab: Optional[SwitchTabControllerAction] = None+ open_tab: Optional[OpenTabControllerAction] = None@staticmethoddef description() -> str:@@ -69,6 +74,8 @@ class ControllerActions(BaseModel):Example: {"extract_page_content": true}- Switch to a different browser tabExample: {"switch_tab": {"handle": "CDwindow-1234..."}}+- Open a new tab+ Example: {"open_tab": {"url": "https://abc.com"}}"""diff --git a/src/tests/test_kayak_search.py b/src/tests/test_search.pysimilarity index 57%rename from src/tests/test_kayak_search.pyrename to src/tests/test_search.pyindex 9a1fa926d..e05cebcc2 100644--- a/src/tests/test_kayak_search.py+++ b/src/tests/test_search.py@@ -32,8 +32,8 @@ def setup_run_folder(timestamp_prefix: str) -> str:return run_folder-# run with pytest src/tests/test_kayak_search.py -v -s-# @pytest.mark.skip+# clear && pytest src/tests/test_search.py -v -s+# clear && pytest src/tests/test_search.py::test_wikipedia_tabs -v -s@pytest.mark.asyncio@observe()async def test_kayak_flight_search():@@ -43,9 +43,9 @@ async def test_kayak_flight_search():controller = ControllerService()model = ChatAnthropic(- model_name='claude-3-5-sonnet-20240620', timeout=25, stop=None, temperature=0.0+ model_name='claude-3-5-sonnet-20240620', timeout=25, stop=None, temperature=0.3)- model = ChatOpenAI(model='gpt-4o', temperature=0.0)+ model = ChatOpenAI(model='gpt-4o', temperature=0.3)agent = AgentService(task,@@ -64,50 +64,61 @@ async def test_kayak_flight_search():for i in range(max_steps):print(f'\n📍 Step {i+1}')action, result = await agent.step()+ if result.done:+ print('\n✅ Task completed successfully')+ print('Extracted content:', result.extracted_content)+ break- # print('action:\n', action)print('result:\n', result.model_dump_json(indent=4))- # input('Press Enter to continue...')-- # current_state = agent.get_current_state()- # save_formatted_html(- # current_state.interactable_elements, f'{run_folder}/current_state_{i}.html'- # )- # # save normal html- # save_formatted_html(driver.page_source, f'{run_folder}/html_{i}.html')-- # url_history.append(driver.current_url)-- # state_text = f'Current interactive elements: {current_state.interactable_elements}'- # if output.extracted_content:- # state_text += f', Extracted content: {output.extracted_content}'- # if output.user_input:- # agent.update_system_prompt(output.user_input)- # state_text += f', User input: {output.user_input}'- # if output.error:- # state_text += f', Previous action error: {output.error}'-- # input('Press Enter to continue...')-- # action = await agent.chat(- # state_text,- # images=current_state.screenshot,- # store_conversation=f'{run_folder}/conversation_{i}.txt',- # )- # output: ActionResult = actions.execute_action(action, current_state.selector_map)-- # # check if output is exactly True (boolean)++ except KeyboardInterrupt:+ print('\n\nReceived interrupt, closing browser...')+ controller.browser.close()+ raise+ except:+ print('\n' + '=' * 50)+ print('❌ Failed to complete task in maximum steps')+ print('=' * 50)+ assert False, 'Failed to complete task in maximum steps'+ finally:+ controller.browser.close()+++# clear && pytest src/tests/test_search.py::test_wikipedia_tabs -v -s+@observe()+async def test_wikipedia_tabs():+ # task = 'open 3 wikipedia pages in different tabs and then go back to the first one and summarize me the content of the page.'+ task = 'open 3 wikipedia pages in different tabs and summarize me the content of all pages.'+ run_folder = setup_run_folder('wikipedia_tabs')++ controller = ControllerService()++ model = ChatAnthropic(+ model_name='claude-3-5-sonnet-20240620', timeout=25, stop=None, temperature=0.3+ )+ model = ChatOpenAI(model='gpt-4o', temperature=0.3)++ agent = AgentService(+ task, model, controller, use_vision=True, save_file=f'{run_folder}/conversation'+ )++ try:+ max_steps = 50+ for i in range(max_steps):+ print(f'\n📍 Step {i+1}')+ action, result = await agent.step()if result.done:print('\n✅ Task completed successfully')print('Extracted content:', result.extracted_content)break+ print('result:\n', result.model_dump_json(indent=4))- # time.sleep(0.5)except KeyboardInterrupt:- print('\n\nReceived interrupt, closing browser...')+ print('\nReceived interrupt, closing browser...')controller.browser.close()raise- else:+ except:print('\n' + '=' * 50)print('❌ Failed to complete task in maximum steps')print('=' * 50)