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
Pause function works
magmueller5ec9fea14880
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 8561d72dc..4b6fd9359 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -160,6 +160,9 @@ class Agent:if save_conversation_path:logger.info(f'Saving conversation to {save_conversation_path}')+ self._paused = False+ self._stopped = False+def _set_version_and_source(self) -> None:try:import pkg_resources@@ -414,10 +417,14 @@ class Agent:if self._too_many_failures():break+ # Check control flags before each step+ if not await self._handle_control_flags():+ break+await self.step()if self.history.is_done():- if self.validate_output and step < max_steps - 1: # if last step, we dont need to validate+ if self.validate_output and step < max_steps - 1:if not await self._validate_output():continue@@ -458,6 +465,19 @@ class Agent:return Truereturn False+ async def _handle_control_flags(self) -> bool:+ """Handle pause and stop flags. Returns True if execution should continue."""+ if self._stopped:+ logger.info('Agent stopped')+ return False++ while self._paused:+ await asyncio.sleep(0.2) # Small delay to prevent CPU spinning+ if self._stopped: # Allow stopping while paused+ return False++ return True+async def _validate_output(self) -> bool:"""Validate the output of the last action is what the user wanted"""system_msg = (@@ -1023,3 +1043,18 @@ class Agent:draw.text((number_x, number_y), number_text, font=number_font, fill='white')return frame++ def pause(self) -> None:+ """Pause the agent before the next step"""+ logger.info('🔄 Agent pausing before next step')+ self._paused = True++ def resume(self) -> None:+ """Resume the agent"""+ logger.info('▶️ Agent resuming')+ self._paused = False++ def stop(self) -> None:+ """Stop the agent"""+ logger.info('⏹️ Agent stopping')+ self._stopped = Truediff --git a/examples/pause_agent.py b/examples/pause_agent.pynew file mode 100644index 000000000..c13244729--- /dev/null+++ b/examples/pause_agent.py@@ -0,0 +1,97 @@+import os+import sys++sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++import asyncio+import threading+import time++from langchain_openai import ChatOpenAI++from browser_use import Agent+++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+ )+ self.running = False++ async def run_agent(self):+ """Run the agent"""+ self.running = True+ await self.agent.run()++ def start(self):+ """Start the agent in a separate thread"""+ loop = asyncio.new_event_loop()+ asyncio.set_event_loop(loop)+ loop.run_until_complete(self.run_agent())++ def pause(self):+ """Pause the agent"""+ self.agent.pause()++ def resume(self):+ """Resume the agent"""+ self.agent.resume()++ def stop(self):+ """Stop the agent"""+ self.agent.stop()+ self.running = False+++def print_menu():+ print('\nAgent Control Menu:')+ print('1. Start')+ print('2. Pause')+ print('3. Resume')+ print('4. Stop')+ print('5. Exit')+++def main():+ controller = AgentController()+ agent_thread = None++ while True:+ print_menu()+ choice = input('Enter your choice (1-5): ')++ if choice == '1' and not agent_thread:+ print('Starting agent...')+ agent_thread = threading.Thread(target=controller.start)+ agent_thread.start()++ elif choice == '2':+ print('Pausing agent...')+ controller.pause()++ elif choice == '3':+ print('Resuming agent...')+ controller.resume()++ elif choice == '4':+ print('Stopping agent...')+ controller.stop()+ if agent_thread:+ agent_thread.join()+ agent_thread = None++ elif choice == '5':+ print('Exiting...')+ if controller.running:+ controller.stop()+ if agent_thread:+ agent_thread.join()+ break++ time.sleep(0.1) # Small delay to prevent CPU spinning+++if __name__ == '__main__':+ main()