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
Functionality to stop the agent externally
mertunsall4709ab9afd0b
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 054158a89..8ebeb85c2 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -151,6 +151,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):| None) = None,register_external_agent_status_raise_error_callback: Callable[[], Awaitable[bool]] | None = None,+ register_should_stop_callback: Callable[[], Awaitable[bool]] | None = None,# Agent settingsoutput_model_schema: type[AgentStructuredOutput] | None = None,use_vision: bool = True,@@ -426,6 +427,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):# Callbacksself.register_new_step_callback = register_new_step_callbackself.register_done_callback = register_done_callback+ self.register_should_stop_callback = register_should_stop_callbackself.register_external_agent_status_raise_error_callback = register_external_agent_status_raise_error_callback# Telemetry@@ -633,8 +635,15 @@ class Agent(Generic[Context, AgentStructuredOutput]):if hasattr(self, 'cloud_sync') and self.cloud_sync and self.enable_cloud_sync:self.eventbus.on('*', self.cloud_sync.handle_event)- async def _raise_if_stopped_or_paused(self) -> None:- """Utility function that raises an InterruptedError if the agent is stopped or paused."""+ async def _check_stop_or_pause(self) -> None:+ """Check if the agent should stop or pause, and handle accordingly."""++ # Check new should_stop_callback - sets stopped state cleanly without raising+ if self.register_should_stop_callback:+ if await self.register_should_stop_callback():+ self.logger.info('External callback requested stop')+ self.state.stopped = True+ raise InterruptedErrorif self.register_external_agent_status_raise_error_callback:if await self.register_external_agent_status_raise_error_callback():@@ -696,7 +705,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):await self._check_and_update_downloads(f'Step {self.state.n_steps}: after getting browser state')self._log_step_context(browser_state_summary)- await self._raise_if_stopped_or_paused()+ await self._check_stop_or_pause()# Update action models with page-specific actionsself.logger.debug(f'π Step {self.state.n_steps}: Updating action models...')@@ -751,13 +760,13 @@ class Agent(Generic[Context, AgentStructuredOutput]):self.state.last_model_output = model_output# Check again for paused/stopped state after getting model output- await self._raise_if_stopped_or_paused()+ await self._check_stop_or_pause()# Handle callbacks and conversation savingawait self._handle_post_llm_processing(browser_state_summary, input_messages)# check again if Ctrl+C was pressed before we commit the output to history- await self._raise_if_stopped_or_paused()+ await self._check_stop_or_pause()async def _execute_actions(self) -> None:"""Execute the actions from model output"""@@ -803,24 +812,22 @@ class Agent(Generic[Context, AgentStructuredOutput]):async def _handle_step_error(self, error: Exception) -> None:"""Handle all types of errors that can occur during a step"""+ # Handle InterruptedError specially+ if isinstance(error, InterruptedError):+ error_msg = 'The agent was interrupted mid-step' + (f' - {str(error)}' if str(error) else '')+ self.logger.error(f'{error_msg}')+ return+# Handle all other exceptionsinclude_trace = self.logger.isEnabledFor(logging.DEBUG)error_msg = AgentError.format_error(error, include_trace=include_trace)prefix = f'β Result failed {self.state.consecutive_failures + 1}/{self.settings.max_failures + int(self.settings.final_response_after_failure)} times:\n 'self.state.consecutive_failures += 1- # Handle InterruptedError specially- if isinstance(error, InterruptedError):- error_msg = 'The agent was interrupted mid-step' + (f' - {error}' if error else '')- self.logger.error(f'{prefix}{error_msg}')- elif 'Could not parse response' in error_msg or 'tool_use_failed' in error_msg:+ if 'Could not parse response' in error_msg or 'tool_use_failed' in error_msg:# give model a hint how output should look like- logger.debug(f'Model: {self.llm.model} failed')- error_msg += '\n\nReturn a valid JSON object with the required fields.'+ logger.error(f'Model: {self.llm.model} failed')logger.error(f'{prefix}{error_msg}')- # Add context message to help model fix parsing errors- parse_hint = 'Your response could not be parsed. Return a valid JSON object with the required fields.'- # self._message_manager._add_context_message(UserMessage(content=parse_hint))else:self.logger.error(f'{prefix}{error_msg}')@@ -1213,7 +1220,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):def _log_first_step_startup(self) -> None:"""Log startup message only on the first step"""if len(self.history.history) == 0:- self.logger.info(f'π§ Starting a browser-use version {self.version} with model={self.llm.model}')+ self.logger.info(f'π§ Starting a browser-use agent with version {self.version} and model={self.llm.model}')def _log_step_context(self, browser_state_summary: BrowserStateSummary) -> None:"""Log step context information"""@@ -1346,7 +1353,13 @@ class Agent(Generic[Context, AgentStructuredOutput]):if step_info is not None and step_info.step_number == 0:# First stepself._log_first_step_startup()- await self._execute_initial_actions()+ # Normally there was no try catch here but the callback can raise an InterruptedError which we skip+ try:+ await self._execute_initial_actions()+ except InterruptedError:+ pass+ except Exception as e:+ raise eawait self.step(step_info)@@ -1461,12 +1474,18 @@ class Agent(Generic[Context, AgentStructuredOutput]):# Emit CreateAgentTaskEvent at the START of run()self.eventbus.dispatch(CreateAgentTaskEvent.from_agent(self))+ # Log startup message on first step (only if we haven't already done steps)+ self._log_first_step_startup()# Start browser session and attach watchdogsawait self.browser_session.start()- await self._execute_initial_actions()- # Log startup message on first step (only if we haven't already done steps)- self._log_first_step_startup()+ # Normally there was no try catch here but the callback can raise an InterruptedError+ try:+ await self._execute_initial_actions()+ except InterruptedError:+ pass+ except Exception as e:+ raise eself.logger.debug(f'π Starting main execution loop with max {max_steps} steps...')for step in range(max_steps):@@ -1727,7 +1746,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):reset = '\033[0m'try:- await self._raise_if_stopped_or_paused()+ await self._check_stop_or_pause()# Get action name from the action modelaction_data = action.model_dump(exclude_unset=True)action_name = next(iter(action_data.keys())) if action_data else 'unknown'@@ -1762,9 +1781,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):except Exception as e:# Handle any exceptions during action execution- self.logger.error(- f'β Executing action {i + 1} failed in {time_elapsed:.2f}s {red}({action_params}) -> {type(e).__name__}: {e}{reset}'- )+ self.logger.error(f'β Executing action {i + 1} failed -> {type(e).__name__}: {e}')raise ereturn resultsdiff --git a/examples/features/stop_externally.py b/examples/features/stop_externally.pynew file mode 100644index 000000000..ee12e83d9--- /dev/null+++ b/examples/features/stop_externally.py@@ -0,0 +1,43 @@+import asyncio+import os+import random+import sys++from browser_use.llm.google.chat import ChatGoogle++sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from dotenv import load_dotenv++load_dotenv()++from browser_use import Agent++llm = ChatGoogle(model='gemini-flash-latest', temperature=1.0)+++def check_is_task_stopped():+ async def _internal_check_is_task_stopped() -> bool:+ if random.random() < 0.1:+ print('[TASK STOPPER] Task is stopped')+ return True+ else:+ print('[TASK STOPPER] Task is not stopped')+ return False++ return _internal_check_is_task_stopped+++task = """+Go to https://browser-use.github.io/stress-tests/challenges/wufoo-style-form.html and complete the Wufoo-style form by filling in all required fields and submitting.+"""++agent = Agent(task=task, llm=llm, flash_mode=True, register_should_stop_callback=check_is_task_stopped(), max_actions_per_step=1)+++async def main():+ await agent.run(max_steps=30)+++if __name__ == '__main__':+ asyncio.run(main())