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
Check for pause more often
magmueller0e107dc5d15b
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 05cec7569..45f264694 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -235,6 +235,12 @@ class Agent:def add_new_task(self, new_task: str) -> None:self.message_manager.add_new_task(new_task)+ def _check_if_stopped_or_paused(self) -> bool:+ if self._stopped or self._paused:+ logger.debug('Agent paused after getting state')+ raise InterruptedError+ return False+@time_execution_async('--step')async def step(self, step_info: Optional[AgentStepInfo] = None) -> None:"""Execute one step of the task"""@@ -246,13 +252,13 @@ class Agent:try:state = await self.browser_context.get_state()- if self._stopped or self._paused:- logger.debug('Agent paused after getting state')- raise InterruptedError+ self._check_if_stopped_or_paused()self.message_manager.add_state_message(state, self._last_result, step_info, self.use_vision)input_messages = self.message_manager.get_messages()+ self._check_if_stopped_or_paused()+try:model_output = await self.get_next_action(input_messages)@@ -262,9 +268,7 @@ class Agent:self._save_conversation(input_messages, model_output)self.message_manager._remove_last_state_message() # we dont want the whole state in the chat history- if self._stopped or self._paused:- logger.debug('Agent paused after getting next action')- raise InterruptedError+ self._check_if_stopped_or_paused()self.message_manager.add_model_output(model_output)except Exception as e:@@ -277,6 +281,7 @@ class Agent:self.browser_context,page_extraction_llm=self.page_extraction_llm,sensitive_data=self.sensitive_data,+ check_break_if_paused=lambda: self._check_if_stopped_or_paused(),)self._last_result = result@@ -287,6 +292,11 @@ class Agent:except InterruptedError:logger.debug('Agent paused')+ self._last_result = [+ ActionResult(+ error='The agent was paused - now continuing actions might need to be repeated', include_in_memory=True+ )+ ]returnexcept Exception as e:result = await self._handle_step_error(e)@@ -488,6 +498,7 @@ class Agent:self.browser_context,check_for_new_elements=False,page_extraction_llm=self.page_extraction_llm,+ check_break_if_paused=lambda: self._check_if_stopped_or_paused(),)self._last_result = resultdiff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex 722693fcf..7dc36271b 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -1,7 +1,7 @@import asyncioimport jsonimport logging-from typing import Dict, Optional, Type+from typing import Callable, Dict, Optional, Typefrom langchain_core.prompts import PromptTemplatefrom pydantic import BaseModel@@ -444,6 +444,7 @@ class Controller:self,actions: list[ActionModel],browser_context: BrowserContext,+ check_break_if_paused: Callable[[], bool],check_for_new_elements: bool = True,page_extraction_llm: Optional[BaseChatModel] = None,sensitive_data: Optional[Dict[str, str]] = None,@@ -454,9 +455,14 @@ class Controller:session = await browser_context.get_session()cached_selector_map = session.cached_state.selector_mapcached_path_hashes = set(e.hash.branch_path_hash for e in cached_selector_map.values())++ check_break_if_paused()+await browser_context.remove_highlights()for i, action in enumerate(actions):+ check_break_if_paused()+if action.get_index() is not None and i != 0:new_state = await browser_context.get_state()new_path_hashes = set(e.hash.branch_path_hash for e in new_state.selector_map.values())@@ -465,6 +471,8 @@ class Controller:logger.info(f'Something new appeared after action {i} / {len(actions)}')break+ check_break_if_paused()+results.append(await self.act(action, browser_context, page_extraction_llm, sensitive_data))logger.debug(f'Executed action {i + 1} / {len(actions)}')diff --git a/examples/features/pause_agent.py b/examples/features/pause_agent.pyindex c13244729..e021224cf 100644--- a/examples/features/pause_agent.py+++ b/examples/features/pause_agent.py@@ -16,7 +16,8 @@ class AgentController:def __init__(self):llm = ChatOpenAI(model='gpt-4o')self.agent = Agent(- task="Go to wikipedia.org and search for 'Python programming language', then read the first paragraph", llm=llm+ task='open in one action https://www.google.com, https://www.wikipedia.org, https://www.youtube.com, https://www.github.com, https://amazon.com',+ llm=llm,)self.running = False