Skip to content

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

Fix tests - now most of them are running through again

magmueller21198f59041e
diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.py
index 60b343226..9a2b0a681 100644
--- a/browser_use/agent/prompts.py
+++ b/browser_use/agent/prompts.py
@@ -56,6 +56,7 @@ class SystemPrompt:
7. If the page is empty use actions like "go_to_url", "search_google" or "open_tab"
8. Remember: Choose EXACTLY ONE action per response. Invalid combinations or multiple actions will be rejected.
9. If popups like cookies appear, accept or close them
+10. Call 'done' when you are done with the task - dont hallucinate or make up actions
"""
def input_format(self) -> str:
diff --git a/browser_use/browser/tests/test_clicks.py b/browser_use/browser/tests/test_clicks.py
index 248491827..76ded4482 100644
--- a/browser_use/browser/tests/test_clicks.py
+++ b/browser_use/browser/tests/test_clicks.py
@@ -8,62 +8,58 @@ from browser_use.utils import time_execution_sync
@pytest.mark.asyncio
async def test_highlight_elements():
- browser = Browser(headless=False, keep_open=False)
+ browser = Browser(headless=False, keep_open=False)
- session = await browser.get_session()
+ session = await browser.get_session()
- print(session)
+ print(session)
- page = await browser.get_current_page()
- # await page.goto('https://immobilienscout24.de')
- await page.goto("https://kayak.com")
+ page = await browser.get_current_page()
+ # await page.goto('https://immobilienscout24.de')
+ await page.goto('https://kayak.com')
- time.sleep(3)
- # browser._click_element_by_xpath(
- # '/html/body/div[5]/div/div[2]/div/div/div[3]/div/div[1]/button[1]'
- # )
- # browser._click_element_by_xpath("//button[div/div[text()='Alle akzeptieren']]")
+ time.sleep(3)
+ # browser._click_element_by_xpath(
+ # '/html/body/div[5]/div/div[2]/div/div/div[3]/div/div[1]/button[1]'
+ # )
+ # browser._click_element_by_xpath("//button[div/div[text()='Alle akzeptieren']]")
- while True:
- state = await browser.get_state()
+ while True:
+ state = await browser.get_state()
- await time_execution_sync("highlight_selector_map_elements")(
- browser.highlight_selector_map_elements
- )(state.selector_map)
+ await time_execution_sync('highlight_selector_map_elements')(
+ browser.highlight_selector_map_elements
+ )(state.selector_map)
- print(state.dom_items_to_string(use_tabs=False))
- # print(state.selector_map)
+ print(state.dom_items_to_string(use_tabs=False))
+ # print(state.selector_map)
- # Find and print duplicate XPaths
- xpath_counts = {}
- for selector in state.selector_map.values():
- if selector in xpath_counts:
- xpath_counts[selector] += 1
- else:
- xpath_counts[selector] = 1
+ # Find and print duplicate XPaths
+ xpath_counts = {}
+ for selector in state.selector_map.values():
+ if selector in xpath_counts:
+ xpath_counts[selector] += 1
+ else:
+ xpath_counts[selector] = 1
- print("\nDuplicate XPaths found:")
- for xpath, count in xpath_counts.items():
- if count > 1:
- print(f"XPath: {xpath}")
- print(f"Count: {count}\n")
+ print('\nDuplicate XPaths found:')
+ for xpath, count in xpath_counts.items():
+ if count > 1:
+ print(f'XPath: {xpath}')
+ print(f'Count: {count}\n')
- print(state.selector_map.keys(), "Selector map keys")
- action = input("Select next action: ")
+ print(state.selector_map.keys(), 'Selector map keys')
+ action = input('Select next action: ')
- await time_execution_sync("remove_highlight_elements")(
- browser.remove_highlights
- )()
+ await time_execution_sync('remove_highlight_elements')(browser.remove_highlights)()
- xpath = state.selector_map[int(action)]
+ xpath = state.selector_map[int(action)]
- # check if index of selector map are the same as index of items in dom_items
+ # check if index of selector map are the same as index of items in dom_items
- indcies = list(state.selector_map.keys())
- dom_items = state.items
- dom_indices = [item.index for item in dom_items if not item.is_text_only]
- assert (
- indcies == dom_indices
- ), "Indices of selector map and dom items do not match"
+ indcies = list(state.selector_map.keys())
+ dom_items = state.items
+ dom_indices = [item.index for item in dom_items if not item.is_text_only]
+ assert indcies == dom_indices, 'Indices of selector map and dom items do not match'
- await browser._click_element_by_xpath(xpath)
+ await browser._click_element_by_xpath(xpath)
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index a03e5eff3..fa472cd41 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -152,7 +152,7 @@ class Controller:
# scroll up
@self.registry.action(
- 'Scroll up the page by pixel amount',
+ 'Scroll up the page by pixel amount - if no amount is specified, scroll up one page',
param_model=ScrollAction,
requires_browser=True,
)
diff --git a/tests/test_agent_actions.py b/tests/test_agent_actions.py
index 79721ffff..bc2ccfbc2 100644
--- a/tests/test_agent_actions.py
+++ b/tests/test_agent_actions.py
@@ -1,8 +1,11 @@
+import os
+
import pytest
-from langchain_openai import ChatOpenAI
-from pydantic import BaseModel
+from langchain_openai import AzureChatOpenAI, ChatOpenAI
+from pydantic import BaseModel, SecretStr
from browser_use.agent.service import Agent
+from browser_use.agent.views import AgentHistoryList
from browser_use.controller.service import Controller
@@ -11,7 +14,12 @@ def llm():
"""Initialize language model for testing"""
# return ChatAnthropic(model_name='claude-3-5-sonnet-20240620', timeout=25, stop=None)
- return ChatOpenAI(model='gpt-4o')
+ return AzureChatOpenAI(
+ model='gpt-4o',
+ api_version='2024-10-21',
+ azure_endpoint=os.getenv('AZURE_OPENAI_ENDPOINT', ''),
+ api_key=SecretStr(os.getenv('AZURE_OPENAI_KEY', '')),
+ )
# return ChatOpenAI(model='gpt-4o-mini')
@@ -27,6 +35,7 @@ async def agent_with_controller():
await controller.browser.close(force=True)
+# pytest tests/test_agent_actions.py -v -k "test_ecommerce_interaction" --capture=no
# @pytest.mark.asyncio
async def test_ecommerce_interaction(llm, agent_with_controller):
"""Test complex ecommerce interaction sequence"""
@@ -37,32 +46,27 @@ async def test_ecommerce_interaction(llm, agent_with_controller):
save_conversation_path='tmp/test_ecommerce_interaction/conversation',
)
- history = await agent.run(max_steps=20)
+ history: AgentHistoryList = await agent.run(max_steps=20)
# Verify sequence of actions
action_sequence = []
- for h in history:
- action = getattr(h.model_output, 'action', None)
- if action and (getattr(action, 'go_to_url', None) or getattr(action, 'open_tab', None)):
+ for action in history.model_actions():
+ action_name = list(action.keys())[0]
+ if action_name in ['go_to_url', 'open_tab']:
action_sequence.append('navigate')
- elif action and getattr(action, 'input_text', None):
+ elif action_name == 'input_text':
action_sequence.append('input')
# Check that the input is 'laptop'
- inp = action.input_text.text.lower()
+ inp = action['input_text']['text'].lower() # type: ignore
if inp == 'laptop':
action_sequence.append('input_exact_correct')
elif 'laptop' in inp:
action_sequence.append('correct_in_input')
else:
action_sequence.append('incorrect_input')
-
- elif action and getattr(action, 'click_element', None):
+ elif action_name == 'click_element':
action_sequence.append('click')
- if action is None:
- print(h.result)
- print(h.model_output)
-
# Verify essential steps were performed
assert 'navigate' in action_sequence # Navigated to Amazon
assert 'input' in action_sequence # Entered search term
@@ -74,25 +78,25 @@ async def test_ecommerce_interaction(llm, agent_with_controller):
async def test_error_recovery(llm, agent_with_controller):
"""Test agent's ability to recover from errors"""
agent = Agent(
- task='Navigate to nonexistent-site.com and then recover by going to google.com',
+ task='Navigate to nonexistent-site.com and then recover by going to google.com ',
llm=llm,
controller=agent_with_controller,
)
- history = await agent.run(max_steps=10)
-
- recovery_action = next(
- (
- h
- for h in history
- if h.model_output
- and getattr(h.model_output, 'action', None)
- and getattr(h.model_output.action, 'go_to_url', None)
- and getattr(h.model_output.action.go_to_url, 'url', '').endswith('google.com') # type: ignore -> pretty weird way to do this
- ),
- None,
- )
- assert recovery_action is not None
+ history: AgentHistoryList = await agent.run(max_steps=10)
+
+ actions_names = history.action_names()
+ actions = history.model_actions()
+ assert (
+ 'go_to_url' in actions_names or 'open_tab' in actions_names
+ ), f'{actions_names} does not contain go_to_url or open_tab'
+ for action in actions:
+ if 'go_to_url' in action:
+ assert 'url' in action['go_to_url'], 'url is not in go_to_url'
+ assert action['go_to_url']['url'].endswith(
+ 'google.com'
+ ), f'url does not end with google.com'
+ break
# @pytest.mark.asyncio
@@ -104,18 +108,16 @@ async def test_find_contact_email(llm, agent_with_controller):
controller=agent_with_controller,
)
- history = await agent.run(max_steps=10)
+ history: AgentHistoryList = await agent.run(max_steps=10)
# Verify the agent found the contact email
- email_action = next(
- (
- h
- for h in history
- if h.result.extracted_content and '[email protected]' in h.result.extracted_content
- ),
- None,
- )
- assert email_action is not None
+ extracted_content = history.extracted_content()
+ email = '[email protected]'
+ for content in extracted_content:
+ if email in content:
+ break
+ else:
+ pytest.fail(f'{extracted_content} does not contain {email}')
# @pytest.mark.asyncio
@@ -127,19 +129,16 @@ async def test_agent_finds_installation_command(llm, agent_with_controller):
controller=agent_with_controller,
)
- history = await agent.run(max_steps=10)
+ history: AgentHistoryList = await agent.run(max_steps=10)
# Verify the agent found the correct installation command
- install_command_action = next(
- (
- h
- for h in history
- if h.result.extracted_content
- and 'pip install browser-use' in h.result.extracted_content
- ),
- None,
- )
- assert install_command_action is not None
+ extracted_content = history.extracted_content()
+ install_command = 'pip install browser-use'
+ for content in extracted_content:
+ if install_command in content:
+ break
+ else:
+ pytest.fail(f'{extracted_content} does not contain {install_command}')
class CaptchaTest(BaseModel):
@@ -188,11 +187,11 @@ async def test_captcha_solver(llm, agent_with_controller, captcha: CaptchaTest):
)
from browser_use.agent.views import AgentHistoryList
- history = await agent.run(max_steps=10)
+ history: AgentHistoryList = await agent.run(max_steps=7)
# Verify the agent solved the captcha
solved = False
- for h in history:
+ for h in history.history:
last = h.state.items
if any(captcha.success_text in item.text for item in last):
solved = True
diff --git a/tests/test_core_functionality.py b/tests/test_core_functionality.py
index d693a7cc9..b7dc76114 100644
--- a/tests/test_core_functionality.py
+++ b/tests/test_core_functionality.py
@@ -1,5 +1,8 @@
+import os
+
import pytest
-from langchain_openai import ChatOpenAI
+from langchain_openai import AzureChatOpenAI, ChatOpenAI
+from pydantic import SecretStr
from browser_use.agent.service import Agent
from browser_use.agent.views import AgentHistoryList
@@ -9,14 +12,21 @@ from browser_use.controller.service import Controller
@pytest.fixture
def llm():
"""Initialize language model for testing"""
- return ChatOpenAI(model='gpt-4o') # Use appropriate model
+
+ # return ChatAnthropic(model_name='claude-3-5-sonnet-20240620', timeout=25, stop=None)
+ return AzureChatOpenAI(
+ model='gpt-4o',
+ api_version='2024-10-21',
+ azure_endpoint=os.getenv('AZURE_OPENAI_ENDPOINT', ''),
+ api_key=SecretStr(os.getenv('AZURE_OPENAI_KEY', '')),
+ )
# pytest -s -k test_search_google
@pytest.fixture
async def controller():
"""Initialize the controller with persistent browser"""
- controller = Controller(keep_open=True, headless=False)
+ controller = Controller(keep_open=False, headless=False)
try:
yield controller
@@ -75,7 +85,7 @@ async def test_click_element(llm, controller):
)
history = await agent.run(max_steps=4)
action_names = history.action_names()
- assert 'go_to_url' in action_names
+ assert 'go_to_url' in action_names or 'open_tab' in action_names
assert 'click_element' in action_names
@@ -177,9 +187,5 @@ async def test_scroll_down(llm, controller: Controller):
# Validate that the 'scroll_down' action was executed
history = agent.history
- model_output = history.model_actions()
- if model_output:
- keys = [key for key in model_output[0].keys()]
- assert 'scroll_down' in keys
- else:
- pytest.fail('No model outputs found')
+ action_names = history.action_names()
+ assert 'scroll_down' in action_names
diff --git a/tests/test_mind2web.py b/tests/test_mind2web.py
index 01b38eec1..c07db9c15 100644
--- a/tests/test_mind2web.py
+++ b/tests/test_mind2web.py
@@ -7,7 +7,8 @@ import os
from typing import Any, Dict, List
import pytest
-from langchain_openai import ChatOpenAI
+from langchain_openai import AzureChatOpenAI, ChatOpenAI
+from pydantic import SecretStr
from browser_use.agent.service import Agent
from browser_use.controller.service import Controller
@@ -32,10 +33,17 @@ def test_cases() -> List[Dict[str, Any]]:
return subset
[email protected](scope='session')
def llm():
- """Initialize the language model"""
- return ChatOpenAI(model='gpt-4o')
+ """Initialize language model for testing"""
+
+ # return ChatAnthropic(model_name='claude-3-5-sonnet-20240620', timeout=25, stop=None)
+ return AzureChatOpenAI(
+ model='gpt-4o',
+ api_version='2024-10-21',
+ azure_endpoint=os.getenv('AZURE_OPENAI_ENDPOINT', ''),
+ api_key=SecretStr(os.getenv('AZURE_OPENAI_KEY', '')),
+ )
@pytest.fixture(scope='function')
diff --git a/tests/test_self_registered_actions.py b/tests/test_self_registered_actions.py
index 4ab7b1be7..d7bb9b0f5 100644
--- a/tests/test_self_registered_actions.py
+++ b/tests/test_self_registered_actions.py
@@ -1,17 +1,14 @@
+import os
+
import pytest
-from langchain_openai import ChatOpenAI
-from pydantic import BaseModel
+from langchain_openai import AzureChatOpenAI, ChatOpenAI
+from pydantic import BaseModel, SecretStr
from browser_use.agent.service import Agent
+from browser_use.agent.views import AgentHistoryList
from browser_use.controller.service import Controller
-def llm():
- """Initialize the language model"""
- return ChatOpenAI(model='gpt-4o') # Use appropriate model
-
-
@pytest.fixture
async def controller():
"""Initialize the controller with self-registered actions"""
@@ -68,6 +65,19 @@ async def controller():
await controller.browser.close(force=True)
+def llm():
+ """Initialize language model for testing"""
+
+ # return ChatAnthropic(model_name='claude-3-5-sonnet-20240620', timeout=25, stop=None)
+ return AzureChatOpenAI(
+ model='gpt-4o',
+ api_version='2024-10-21',
+ azure_endpoint=os.getenv('AZURE_OPENAI_ENDPOINT', ''),
+ api_key=SecretStr(os.getenv('AZURE_OPENAI_KEY', '')),
+ )
+
+
# @pytest.mark.skip(reason="Skipping test for now")
@pytest.mark.asyncio
async def test_self_registered_actions_no_pydantic(llm, controller):
@@ -77,10 +87,9 @@ async def test_self_registered_actions_no_pydantic(llm, controller):
llm=llm,
controller=controller,
)
- history = await agent.run(max_steps=10)
+ history: AgentHistoryList = await agent.run(max_steps=10)
# Check that custom actions were executed
- actions = [h.model_output.action for h in history if h.model_output and h.model_output.action]
- action_names = [list(action.model_dump(exclude_unset=True).keys())[0] for action in actions]
+ action_names = history.action_names()
assert 'print_message' in action_names
assert 'add_numbers' in action_names
@@ -107,13 +116,16 @@ async def test_mixed_arguments_actions(llm, controller):
history = await agent.run(max_steps=5)
# Check that the action was executed
- actions = [h.model_output.action for h in history if h.model_output and h.model_output.action]
- action_names = [list(action.model_dump(exclude_unset=True).keys())[0] for action in actions]
+ action_names = history.action_names()
assert 'calculate_area' in action_names
# check result
correct = 'The area is 17.6'
- assert correct in [h.result.extracted_content for h in history if h.model_output]
+ for content in history.extracted_content():
+ if correct in content:
+ break
+ else:
+ pytest.fail(f'{correct} not found in extracted content')
@pytest.mark.asyncio
@@ -127,12 +139,15 @@ async def test_pydantic_simple_model(llm, controller):
history = await agent.run(max_steps=5)
# Check that the action was executed
- actions = [h.model_output.action for h in history if h.model_output and h.model_output.action]
- action_names = [list(action.model_dump(exclude_unset=True).keys())[0] for action in actions]
+ action_names = history.action_names()
assert 'process_simple_model' in action_names
correct = 'Processed Alice, age 30'
- assert correct in [h.result.extracted_content for h in history if h.model_output]
+ for content in history.extracted_content():
+ if correct in content:
+ break
+ else:
+ pytest.fail(f'{correct} not found in extracted content')
@pytest.mark.asyncio
@@ -146,31 +161,15 @@ async def test_pydantic_nested_model(llm, controller):
history = await agent.run(max_steps=5)
# Check that the action was executed
- actions = [h.model_output.action for h in history if h.model_output and h.model_output.action]
- action_names = [list(action.model_dump(exclude_unset=True).keys())[0] for action in actions]
+ action_names = history.action_names()
assert 'process_nested_model' in action_names
correct = 'Processed user Bob, age 25 at address 123 Maple St, Springfield'
- assert correct in [h.result.extracted_content for h in history if h.model_output]
-
-
-async def test_pydantic_multiple_models(llm, controller):
- """Test action with multiple Pydantic model arguments"""
- agent = Agent(
- task="Process models with user name 'Carol', age 28, living at '456 Oak Ave', 'Shelbyville'.",
- llm=llm,
- controller=controller,
- )
- history = await agent.run(max_steps=5)
-
- # Check that the action was executed
- actions = [h.model_output.action for h in history if h.model_output and h.model_output.action]
- action_names = [list(action.model_dump(exclude_unset=True).keys())[0] for action in actions]
-
- assert 'process_multiple_models' in action_names
- correct = 'Processed Carol living at 456 Oak Ave, Shelbyville'
- assert correct in [h.result.extracted_content for h in history if h.model_output]
+ for content in history.extracted_content():
+ if correct in content:
+ break
+ else:
+ pytest.fail(f'{correct} not found in extracted content')
# run this file with: