Skip to content

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

fix type hint errors

Nick Sweetingb67be374905e
diff --git a/browser_use/agent/cloud_events.py b/browser_use/agent/cloud_events.py
index 5bcf93116..5b1092fa9 100644
--- a/browser_use/agent/cloud_events.py
+++ b/browser_use/agent/cloud_events.py
@@ -195,6 +195,9 @@ class CreateAgentTaskEvent(BaseEvent):
done_output=None,
started_at=datetime.fromtimestamp(agent._task_start_time, tz=timezone.utc),
finished_at=None,
+ user_feedback_type=None,
+ user_comment=None,
+ gif_url=None,
)
diff --git a/browser_use/agent/memory/views.py b/browser_use/agent/memory/views.py
index 670c60fce..2a52adc0c 100644
--- a/browser_use/agent/memory/views.py
+++ b/browser_use/agent/memory/views.py
@@ -80,7 +80,7 @@ class MemoryConfig(BaseModel):
Returns the vector store configuration dictionary for Mem0,
tailored to the selected provider.
"""
- provider_specific_config = {'embedding_model_dims': self.embedder_dims}
+ provider_specific_config: dict[str, Any] = {'embedding_model_dims': self.embedder_dims}
# --- Default collection_name handling ---
if self.vector_store_collection_name:
@@ -167,7 +167,7 @@ class MemoryConfig(BaseModel):
}
@property
- def full_config_dict(self) -> dict[str, dict[str, Any]]:
+ def full_config_dict(self) -> dict[str, Any]:
"""Returns the complete configuration dictionary for Mem0."""
return {
'embedder': self.embedder_config_dict,
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.py
index 55e95f009..17020e72f 100644
--- a/browser_use/agent/message_manager/service.py
+++ b/browser_use/agent/message_manager/service.py
@@ -13,7 +13,7 @@ from langchain_core.messages import (
)
from pydantic import BaseModel
-from browser_use.agent.message_manager.views import MessageMetadata
+from browser_use.agent.message_manager.views import ManagedMessage, MessageMetadata
from browser_use.agent.prompts import AgentMessagePrompt
from browser_use.agent.views import ActionResult, AgentOutput, AgentStepInfo, MessageManagerState
from browser_use.browser.views import BrowserStateSummary
@@ -109,7 +109,7 @@ def _log_extract_message_content(message: BaseMessage, is_last_message: bool, me
cleaned_content = _log_clean_whitespace(str(message.content))
# Handle AIMessages with tool calls
- if hasattr(message, 'tool_calls') and message.tool_calls and not cleaned_content:
+ if isinstance(message, AIMessage) and hasattr(message, 'tool_calls') and message.tool_calls and not cleaned_content:
tool_call = message.tool_calls[0]
tool_name = tool_call.get('name', 'unknown')
@@ -117,7 +117,7 @@ def _log_extract_message_content(message: BaseMessage, is_last_message: bool, me
# Skip formatting for init example messages
if metadata and metadata.message_type == 'init':
return '[Example AgentOutput]'
- content = _log_format_agent_output_content(tool_call)
+ content = _log_format_agent_output_content(dict(tool_call)) # Convert ToolCall to dict
else:
content = f'[TOOL: {tool_name}]'
else:
@@ -141,9 +141,12 @@ def _log_format_message_line(
lines = []
# Get emoji and token info
- message_type = message_with_metadata.message.__class__.__name__
- emoji = _log_get_message_emoji(message_type)
- token_str = str(message_with_metadata.metadata.tokens).rjust(4)
+ if isinstance(message_with_metadata, ManagedMessage):
+ message_type = message_with_metadata.message.__class__.__name__
+ emoji = _log_get_message_emoji(message_type)
+ token_str = str(message_with_metadata.metadata.tokens).rjust(4)
+ else:
+ return ['❓[ ?]: [Invalid message format]']
prefix = f'{emoji}[{token_str}]: '
# Calculate available width (emoji=2 visual cols + [token]: =8 chars)
diff --git a/browser_use/agent/message_manager/tests.py b/browser_use/agent/message_manager/tests.py
index d8293788e..77f84c5d5 100644
--- a/browser_use/agent/message_manager/tests.py
+++ b/browser_use/agent/message_manager/tests.py
@@ -157,7 +157,7 @@ def test_token_overflow_handling_with_real_flow(message_manager: MessageManager,
parent=None,
xpath='//div',
),
- selector_map={j: f'//div[{j}]' for j in range(5)},
+ selector_map={},
tabs=[TabInfo(page_id=1, url=f'https://test{i}.com', title=f'Test Page {i}')],
)
@@ -192,21 +192,21 @@ def test_token_overflow_handling_with_real_flow(message_manager: MessageManager,
assert isinstance(message_manager.state.history.messages[-2].message, HumanMessage)
if i % 2 == 0 and not i % 4 == 0:
if isinstance(last_msg.content, list):
- assert 'Current url: https://test' in last_msg.content[0]['text']
+ assert any(
+ 'Current url: https://test' in item.get('text', '') for item in last_msg.content if isinstance(item, dict)
+ )
else:
assert 'Current url: https://test' in last_msg.content
# Add model output every time
- from browser_use.agent.views import AgentBrain, AgentOutput
- from browser_use.controller.registry.views import ActionModel
+ from browser_use.agent.views import AgentOutput
output = AgentOutput(
- current_state=AgentBrain(
- evaluation_previous_goal=f'Success in step {i}',
- memory=f'Memory from step {i}',
- next_goal=f'Goal for step {i + 1}',
- ),
- action=[ActionModel()],
+ thinking=f'Thinking for step {i}',
+ evaluation_previous_goal=f'Success in step {i}',
+ memory=f'Memory from step {i}',
+ next_goal=f'Goal for step {i + 1}',
+ action=[], # Empty action list - ActionModel requires specific action parameters
)
message_manager._remove_last_state_message()
message_manager.add_model_output(output)
diff --git a/browser_use/agent/message_manager/utils.py b/browser_use/agent/message_manager/utils.py
index 55eae8fd5..15d81fe12 100644
--- a/browser_use/agent/message_manager/utils.py
+++ b/browser_use/agent/message_manager/utils.py
@@ -34,6 +34,9 @@ def extract_json_from_model_output(content: str | BaseMessage) -> dict:
if isinstance(content, BaseMessage):
# for langchain_core.messages.BaseMessage
content = content.content
+ # Ensure content is a string
+ if isinstance(content, list):
+ content = str(content[0]) if content else ''
# If content is wrapped in code blocks, extract just the JSON part
if '```' in content:
# Find the JSON content between code blocks
diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.py
index a7106f587..868e3eb1f 100644
--- a/browser_use/agent/prompts.py
+++ b/browser_use/agent/prompts.py
@@ -75,7 +75,7 @@ class AgentMessagePrompt:
sensitive_data: str | None = None,
):
self.browser_state: 'BrowserStateSummary' = browser_state_summary
- self.file_system: 'FileSystem' | None = file_system
+ self.file_system: 'FileSystem | None' = file_system
self.agent_history_description: str | None = agent_history_description
self.read_state_description: str | None = read_state_description
self.task: str | None = task
@@ -143,7 +143,7 @@ Interactive elements from top layer of the current page inside the viewport{trun
time_str = datetime.now().strftime('%Y-%m-%d %H:%M')
step_info_description += f'Current date and time: {time_str}'
- todo_contents = self.file_system.get_todo_contents()
+ todo_contents = self.file_system.get_todo_contents() if self.file_system else ''
if not len(todo_contents):
todo_contents = '[Current todo.md is empty, fill it with your plan when applicable]'
@@ -152,7 +152,7 @@ Interactive elements from top layer of the current page inside the viewport{trun
{self.task}
</user_request>
<file_system>
-{self.file_system.describe()}
+{self.file_system.describe() if self.file_system else 'No file system available'}
</file_system>
<todo_contents>
{todo_contents}
@@ -165,10 +165,18 @@ Interactive elements from top layer of the current page inside the viewport{trun
return agent_state
def get_user_message(self, use_vision: bool = True) -> HumanMessage:
- state_description = '<agent_history>\n' + self.agent_history_description.strip('\n') + '\n</agent_history>\n'
+ state_description = (
+ '<agent_history>\n'
+ + (self.agent_history_description.strip('\n') if self.agent_history_description else '')
+ + '\n</agent_history>\n'
+ )
state_description += '<agent_state>\n' + self._get_agent_state_description().strip('\n') + '\n</agent_state>\n'
state_description += '<browser_state>\n' + self._get_browser_state_description().strip('\n') + '\n</browser_state>\n'
- state_description += '<read_state>\n' + self.read_state_description.strip('\n') + '\n</read_state>\n'
+ state_description += (
+ '<read_state>\n'
+ + (self.read_state_description.strip('\n') if self.read_state_description else '')
+ + '\n</read_state>\n'
+ )
if self.page_filtered_actions:
state_description += 'For this page, these additional actions are available:\n'
state_description += self.page_filtered_actions + '\n'
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 06c76bdd7..dd09393e2 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -1703,7 +1703,7 @@ class Agent(Generic[Context]):
assert browser_state_summary
content = AgentMessagePrompt(
browser_state_summary=browser_state_summary,
- result=self.state.last_result,
+ file_system=self.file_system,
include_attributes=self.settings.include_attributes,
)
msg = [SystemMessage(content=system_msg), content.get_user_message(self.settings.use_vision)]
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 4b2b43d17..ef5eecb75 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -1076,7 +1076,7 @@ class BrowserSession(BaseModel):
if pages:
foreground_page = pages[0]
self.logger.debug(
- f'👁️‍🗨️ Found {len(pages)} existing tabs in browser, agent session {self.id[-4:]}.{str(id(self.agent_current_page))[-2:]} will start focused on Tab [{pages.index(foreground_page)}]: {foreground_page.url}'
+ f'👁️‍🗨️ Found {len(pages)} existing tabs in browser, agent session {self.id[-4:]}.{str(id(self.agent_current_page))[-2:]} will start focused on Tab [{pages.index(foreground_page)}]: {foreground_page.url}' # type: ignore
)
else:
foreground_page = await self.browser_context.new_page()
@@ -1095,15 +1095,15 @@ class BrowserSession(BaseModel):
old_foreground = self.human_current_page
assert self.browser_context is not None, 'BrowserContext object is not set'
assert old_foreground is not None, 'Old foreground page is not set'
- old_tab_idx = self.browser_context.pages.index(old_foreground)
+ old_tab_idx = self.browser_context.pages.index(old_foreground) # type: ignore
self.human_current_page = new_page
- new_tab_idx = self.browser_context.pages.index(new_page)
+ new_tab_idx = self.browser_context.pages.index(new_page) # type: ignore
# Log before and after for debugging
old_url = old_foreground and old_foreground.url or 'about:blank'
new_url = new_page and new_page.url or 'about:blank'
agent_url = self.agent_current_page and self.agent_current_page.url or 'about:blank'
- agent_tab_idx = self.browser_context.pages.index(self.agent_current_page)
+ agent_tab_idx = self.browser_context.pages.index(self.agent_current_page) # type: ignore
if old_url != new_url:
self.logger.info(
f'👁️ Foregound tab changed by human from [{old_tab_idx}]{_log_pretty_url(old_url)} '
@@ -1172,7 +1172,7 @@ class BrowserSession(BaseModel):
await page.evaluate(update_tab_focus_script)
# self.logger.debug(f'👁️ Added visibility listener to existing tab: {page.url}')
except Exception as e:
- page_idx = self.browser_context.pages.index(page)
+ page_idx = self.browser_context.pages.index(page) # type: ignore
self.logger.debug(
f'⚠️ Failed to add visibility listener to existing tab, is it crashed or ignoring CDP commands?: [{page_idx}]{page.url}: {type(e).__name__}: {e}'
)
@@ -1263,7 +1263,7 @@ class BrowserSession(BaseModel):
# cdp api: https://chromedevtools.github.io/devtools-protocol/tot/Browser/#method-setWindowBounds
try:
- cdp_session = await page.context.new_cdp_session(page)
+ cdp_session = await page.context.new_cdp_session(page) # type: ignore
window_id_result = await cdp_session.send('Browser.getWindowForTarget')
await cdp_session.send(
'Browser.setWindowBounds',
diff --git a/browser_use/controller/registry/views.py b/browser_use/controller/registry/views.py
index 84353a640..fc371ff63 100644
--- a/browser_use/controller/registry/views.py
+++ b/browser_use/controller/registry/views.py
@@ -1,5 +1,5 @@
from collections.abc import Callable
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
from langchain_core.language_models.chat_models import BaseChatModel
from pydantic import BaseModel, ConfigDict
@@ -9,7 +9,7 @@ from browser_use.browser.types import Page
from browser_use.filesystem.file_system import FileSystem
if TYPE_CHECKING:
- from browser_use.agent.service import Context
+ pass
class RegisteredAction(BaseModel):
@@ -153,7 +153,7 @@ class SpecialActionParameters(BaseModel):
# e.g. can contain anything, external db connections, file handles, queues, runtime config objects, etc.
# that you might want to be able to access quickly from within many of your actions
# browser-use code doesn't use this at all, we just pass it down to your actions for convenience
- context: 'Context | None' = None
+ context: Any | None = None
# browser-use session object, can be used to create new tabs, navigate, access playwright objects, etc.
browser_session: BrowserSession | None = None
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index 2a725bece..c3ebeb2d4 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -502,7 +502,7 @@ Explain the content of the page and that the requested information is not availa
dy = dy_result
try:
- await browser_session._scroll_container(dy)
+ await browser_session._scroll_container(cast(int, dy))
except Exception as e:
# Hard fallback: always works on root scroller
await page.evaluate('(y) => window.scrollBy(0, y)', dy)
@@ -530,7 +530,7 @@ Explain the content of the page and that the requested information is not availa
)
if action_result:
return action_result
- dy = -(dy_result)
+ dy = -(dy_result or 0)
try:
await browser_session._scroll_container(dy)
diff --git a/tests/test_agent_actions.py b/tests/test_agent_actions.py
index bdd276b16..721be1e41 100644
--- a/tests/test_agent_actions.py
+++ b/tests/test_agent_actions.py
@@ -25,10 +25,10 @@ def llm():
@pytest.fixture
async def browser_session():
- browser_session = BrowserSession(
- headless=True,
- user_data_dir=None,
- )
+ from browser_use.browser.profile import BrowserProfile
+
+ profile = BrowserProfile(headless=True, user_data_dir=None)
+ browser_session = BrowserSession(browser_profile=profile)
await browser_session.start()
yield browser_session
await browser_session.stop()
diff --git a/tests/test_core_functionality.py b/tests/test_core_functionality.py
index 438e39f6f..47ede5266 100644
--- a/tests/test_core_functionality.py
+++ b/tests/test_core_functionality.py
@@ -68,7 +68,10 @@ class TestCoreFunctionality:
@pytest.fixture(scope='module')
async def browser_session(self):
"""Create and provide a BrowserSession instance with security disabled."""
- browser_session = BrowserSession(headless=True, user_data_dir=None)
+ from browser_use.browser.profile import BrowserProfile
+
+ profile = BrowserProfile(headless=True, user_data_dir=None)
+ browser_session = BrowserSession(browser_profile=profile)
yield browser_session
await browser_session.kill()
diff --git a/tests/test_excluded_actions.py b/tests/test_excluded_actions.py
index 193a05a28..ad43265ea 100644
--- a/tests/test_excluded_actions.py
+++ b/tests/test_excluded_actions.py
@@ -21,10 +21,10 @@ class MockLLM:
@pytest.fixture(scope='module')
async def browser_session():
- browser_session = BrowserSession(
- headless=True,
- user_data_dir=None,
- )
+ from browser_use.browser.profile import BrowserProfile
+
+ profile = BrowserProfile(headless=True, user_data_dir=None)
+ browser_session = BrowserSession(browser_profile=profile)
await browser_session.start()
yield browser_session
await browser_session.stop()
diff --git a/tests/test_service.py b/tests/test_service.py
deleted file mode 100644
index dd7a3cbe3..000000000
--- a/tests/test_service.py
+++ /dev/null
@@ -1,333 +0,0 @@
-from unittest.mock import AsyncMock, MagicMock, Mock, patch
-
-import pytest
-from langchain_core.language_models.chat_models import BaseChatModel
-from langchain_core.messages import HumanMessage
-from pydantic import BaseModel
-
-from browser_use.agent.service import Agent
-from browser_use.agent.views import ActionResult
-from browser_use.browser import BrowserSession
-from browser_use.browser.views import BrowserStateSummary
-from browser_use.controller.registry.service import Registry
-from browser_use.controller.registry.views import ActionModel
-from browser_use.controller.service import Controller
-
-# run with python -m pytest tests/test_service.py
-
-
-# run test with:
-# python -m pytest tests/test_service.py
-class TestAgent:
- @pytest.fixture
- def mock_controller(self):
- controller = Mock(spec=Controller)
- registry = Mock(spec=Registry)
- registry.registry = MagicMock()
- registry.registry.actions = {'test_action': MagicMock(param_model=MagicMock())} # type: ignore
- controller.registry = registry
- return controller
-
- @pytest.fixture
- def mock_llm(self):
- return Mock(spec=BaseChatModel)
-
- @pytest.fixture
- def mock_browser_session(self):
- return Mock(spec=BrowserSession)
-
- def test_convert_initial_actions(self, mock_controller, mock_llm, mock_browser_session): # type: ignore
- """
- Test that the _convert_initial_actions method correctly converts
- dictionary-based actions to ActionModel instances.
-
- This test ensures that:
- 1. The method processes the initial actions correctly.
- 2. The correct param_model is called with the right parameters.
- 3. The ActionModel is created with the validated parameters.
- 4. The method returns a list of ActionModel instances.
- """
- # Arrange
- agent = Agent(task='Test task', llm=mock_llm, controller=mock_controller, browser_session=mock_browser_session)
- initial_actions = [{'test_action': {'param1': 'value1', 'param2': 'value2'}}]
-
- # Mock the ActionModel
- mock_action_model = MagicMock(spec=ActionModel)
- mock_action_model_instance = MagicMock()
- mock_action_model.return_value = mock_action_model_instance
- agent.ActionModel = mock_action_model # type: ignore
-
- # Act
- result = agent._convert_initial_actions(initial_actions)
-
- # Assert
- assert len(result) == 1
- mock_controller.registry.registry.actions['test_action'].param_model.assert_called_once_with( # type: ignore
- param1='value1', param2='value2'
- )
- mock_action_model.assert_called_once()
- assert isinstance(result[0], MagicMock)
- assert result[0] == mock_action_model_instance
-
- # Check that the ActionModel was called with the correct parameters
- call_args = mock_action_model.call_args[1]
- assert 'test_action' in call_args
- assert call_args['test_action'] == mock_controller.registry.registry.actions['test_action'].param_model.return_value # type: ignore
-
- async def test_step_error_handling(self):
- """
- Test the error handling in the step method of the Agent class.
- This test simulates a failure in the get_next_action method and
- checks if the error is properly handled and recorded.
- """
- # Mock the LLM
- mock_llm = MagicMock(spec=BaseChatModel)
-
- # Mock the MessageManager
- with patch('browser_use.agent.service.MessageManager') as mock_message_manager:
- # Create an Agent instance with mocked dependencies
- agent = Agent(task='Test task', llm=mock_llm)
-
- # Mock the get_next_action method to raise an exception
- agent.get_next_action = AsyncMock(side_effect=ValueError('Test error'))
-
- # Mock the browser_session
- agent.browser_session = AsyncMock()
- agent.browser_session.get_state_summary = AsyncMock(
- return_value=BrowserStateSummary(
- url='https://example.com',
- title='Example',
- element_tree=MagicMock(), # Mocked element tree
- tabs=[],
- selector_map={},
- screenshot='',
- )
- )
-
- # Mock the controller
- agent.controller = AsyncMock()
-
- # Call the step method
- await agent.step()
-
- # Assert that the error was handled and recorded
- assert agent.consecutive_failures == 1
- assert len(agent._last_result) == 1
- assert isinstance(agent._last_result[0], ActionResult)
- assert 'Test error' in agent._last_result[0].error
- assert agent._last_result[0].include_in_memory is True
-
-
-class TestRegistry:
- @pytest.fixture
- def registry_with_excludes(self):
- return Registry(exclude_actions=['excluded_action'])
-
- def test_action_decorator_with_excluded_action(self, registry_with_excludes):
- """
- Test that the action decorator does not register an action
- if it's in the exclude_actions list.
- """
-
- # Define a function to be decorated
- def excluded_action():
- pass
-
- # Apply the action decorator
- decorated_func = registry_with_excludes.action(description='This should be excluded')(excluded_action)
-
- # Assert that the decorated function is the same as the original
- assert decorated_func == excluded_action
-
- # Assert that the action was not added to the registry
- assert 'excluded_action' not in registry_with_excludes.registry.actions
-
- # Define another function that should be included
- def included_action():
- pass
-
- # Apply the action decorator to an included action
- registry_with_excludes.action(description='This should be included')(included_action)
-
- # Assert that the included action was added to the registry
- assert 'included_action' in registry_with_excludes.registry.actions
-
- async def test_execute_action_with_and_without_browser_context(self):
- """
- Test that the execute_action method correctly handles actions with and without a browser context.
- This test ensures that:
- 1. An action requiring a browser context is executed correctly.
- 2. An action not requiring a browser context is executed correctly.
- 3. The browser context is passed to the action function when required.
- 4. The action function receives the correct parameters.
- 5. The method raises an error when a browser context is required but not provided.
- """
- registry = Registry()
-
- # Define a mock action model
- class TestActionModel(BaseModel):
- param1: str
-
- # Define mock action functions
- async def test_action_with_browser(param1: str, browser):
- return f'Action executed with {param1} and browser'
-
- async def test_action_without_browser(param1: str):
- return f'Action executed with {param1}'
-
- # Register the actions
- registry.registry.actions['test_action_with_browser'] = MagicMock(
- function=AsyncMock(side_effect=test_action_with_browser),
- param_model=TestActionModel,
- description='Test action with browser',
- )
-
- registry.registry.actions['test_action_without_browser'] = MagicMock(
- function=AsyncMock(side_effect=test_action_without_browser),
- param_model=TestActionModel,
- description='Test action without browser',
- )
-
- # Mock BrowserContext
- mock_browser = MagicMock()
-
- # Execute the action with a browser context
- result_with_browser = await registry.execute_action(
- 'test_action_with_browser', {'param1': 'test_value'}, browser=mock_browser
- )
- assert result_with_browser == 'Action executed with test_value and browser'
-
- # Execute the action without a browser context
- result_without_browser = await registry.execute_action('test_action_without_browser', {'param1': 'test_value'})
- assert result_without_browser == 'Action executed with test_value'
-
- # Test error when browser is required but not provided
- with pytest.raises(RuntimeError, match='Action test_action_with_browser requires browser but none provided'):
- await registry.execute_action('test_action_with_browser', {'param1': 'test_value'})
-
- # Verify that the action functions were called with correct parameters
- registry.registry.actions['test_action_with_browser'].function.assert_called_once_with(
- param1='test_value', browser=mock_browser
- )
- registry.registry.actions['test_action_without_browser'].function.assert_called_once_with(param1='test_value')
-
-
-class TestAgentRetry:
- @pytest.fixture
- def mock_llm(self):
- return AsyncMock()
-
- @pytest.fixture
- def mock_controller(self):
- controller = Mock()
- controller.registry = Mock()
- controller.registry.registry = Mock()
- controller.registry.registry.actions = {}
- return controller
-
- @pytest.fixture
- def mock_browser_session(self):
- browser_session = Mock()
- browser_session.get_state_summary = AsyncMock(
- return_value=BrowserStateSummary(
- url='https://parabank.parasoft.com/parabank/index.htm',
- title='ParaBank',
- element_tree=MagicMock(),
- tabs=[],
- selector_map={},
- screenshot='',
- )
- )
- return browser_session
-
- @pytest.fixture
- def mock_action_model(self):
- action_model = Mock(spec=ActionModel)
- return action_model
-
- @pytest.mark.asyncio
- async def test_step_empty_action_retry(self, mock_llm, mock_controller, mock_browser_session, mock_action_model):
- """
- Test that the step method retries and handles empty actions correctly.
- """
- # Arrange
- agent = Agent(
- task='Test task',
- llm=mock_llm,
- controller=mock_controller,
- browser_session=mock_browser_session,
- )
- agent.ActionModel = mock_action_model # Inject the mock ActionModel
-
- # Mock get_next_action to return empty action the first time, then a valid action
- empty_model_output = MagicMock()
- empty_model_output.action = [] # Empty action
- valid_model_output = MagicMock()
- valid_action = MagicMock()
- valid_model_output.action = [valid_action]
-
- mock_llm.return_value.invoke.side_effect = [empty_model_output, valid_model_output]
- agent.get_next_action = mock_llm.return_value.invoke
-
- # Act
- await agent.step()
-
- # Assert
- # Check that get_next_action was called twice (initial call + retry)
- assert agent.get_next_action.call_count == 2
- # Check that the LLM was called twice
- assert mock_llm.return_value.invoke.call_count == 2
-
- # Check that the second call to get_next_action included the clarification message
- _, retry_messages = mock_llm.return_value.invoke.call_args_list[1]
- assert len(retry_messages[0]) == 2 # input_messages + clarification message
- assert isinstance(retry_messages[0][1], HumanMessage)
- assert 'You forgot to return an action' in retry_messages[0][1].content
-
- # Check that _last_result contains the valid action
- assert len(agent._last_result) == 1
- assert agent._last_result[0].action == valid_action
-
- @pytest.mark.asyncio
- async def test_step_empty_action_retry_and_fail(self, mock_llm, mock_controller, mock_browser_session, mock_action_model):
- """
- Test that the step method handles the case where get_next_action returns
- empty actions twice, and inserts a safe noop action.
- """
- # Arrange
- agent = Agent(
- task='Test task',
- llm=mock_llm,
- controller=mock_controller,
- browser_session=mock_browser_session,
- )
- agent.ActionModel = mock_action_model # Inject the mock ActionModel
-
- # Mock get_next_action to return empty action both times
- empty_model_output = MagicMock()
- empty_model_output.action = [] # Empty action
- mock_llm.return_value.invoke.return_value = empty_model_output
- agent.get_next_action = mock_llm.return_value.invoke
-
- # Mock the ActionModel instance creation
- mock_action_instance = MagicMock()
- mock_action_model.return_value = mock_action_instance
-
- # Act
- await agent.step()
-
- # Assert
- # Check that get_next_action was called twice
- assert agent.get_next_action.call_count == 2
- # Check that the LLM was called twice
- assert mock_llm.return_value.invoke.call_count == 2
-
- # Check that ActionModel was instantiated with the noop action
- mock_action_model.assert_called_once()
- call_args = mock_action_model.call_args[1]
- assert 'done' in call_args
- assert call_args['done'] == {'success': False, 'text': 'No action returned, safe exit.'}
-
- # Check that _last_result contains the noop action
- assert len(agent._last_result) == 1
- assert agent._last_result[0].action == mock_action_instance
diff --git a/tests/test_vision.py b/tests/test_vision.py
index 7886377bc..f8affde31 100644
--- a/tests/test_vision.py
+++ b/tests/test_vision.py
@@ -40,7 +40,10 @@ async def done(text: str) -> str:
@pytest.mark.skip(reason='this is for local testing only')
async def test_vision():
- browser_session = BrowserSession(headless=True, user_data_dir=None)
+ from browser_use.browser.profile import BrowserProfile
+
+ profile = BrowserProfile(headless=True, user_data_dir=None)
+ browser_session = BrowserSession(browser_profile=profile)
await browser_session.start()
try:
agent = Agent(