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
Dont take screenshots in multact and move get_browser_state_with_recovery to the browser session
Magnus Müller15dd27f2b5bd
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex f8ce9fbeb..197e49352 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -641,6 +641,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):self.task = new_taskself._message_manager.add_new_task(new_task)+ @observe_debug(ignore_input=True, ignore_output=True, name='_raise_if_stopped_or_paused')async def _raise_if_stopped_or_paused(self) -> None:"""Utility function that raises an InterruptedError if the agent is stopped or paused."""@@ -652,24 +653,6 @@ class Agent(Generic[Context, AgentStructuredOutput]):# self.logger.debug('Agent paused after getting state')raise InterruptedError- @observe_debug(ignore_input=True, ignore_output=True, name='get_browser_state_with_recovery')- async def _get_browser_state_with_recovery(self, cache_clickable_elements_hashes: bool = True) -> BrowserStateSummary:- """Get browser state with multiple fallback strategies for error recovery"""-- assert self.browser_session is not None, 'BrowserSession is not set up'-- # Try 1: Full state summary (current implementation) - like main branch- try:- return await self.browser_session.get_state_summary(cache_clickable_elements_hashes)- except Exception as e:- if self.state.last_result is None:- self.state.last_result = []- self.state.last_result.append(ActionResult(error=str(e)))- self.logger.warning(f'Full state retrieval failed: {type(e).__name__}: {e}')-- self.logger.warning('🔄 Falling back to minimal state summary')- return await self.browser_session.get_minimal_state_summary()-@observe(name='agent.step', ignore_output=True, ignore_input=True)@time_execution_async('--step')async def step(self, step_info: AgentStepInfo | None = None) -> None:@@ -704,7 +687,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):assert self.browser_session is not None, 'BrowserSession is not set up'self.logger.debug(f'🌐 Step {self.state.n_steps + 1}: Getting browser state...')- browser_state_summary = await self._get_browser_state_with_recovery(cache_clickable_elements_hashes=True)+ browser_state_summary = await self.browser_session.get_browser_state_with_recovery(cache_clickable_elements_hashes=True)current_page = await self.browser_session.get_current_page()# Check for new downloads after getting browser state (catches PDF auto-downloads and previous step downloads)@@ -1389,7 +1372,9 @@ class Agent(Generic[Context, AgentStructuredOutput]):breakif action.get_index() is not None and i != 0:- new_browser_state_summary = await self.browser_session.get_state_summary(cache_clickable_elements_hashes=False)+ new_browser_state_summary = await self.browser_session.get_browser_state_with_recovery(+ cache_clickable_elements_hashes=False, include_screenshot=False+ )new_selector_map = new_browser_state_summary.selector_map# Detect index change after previous action@@ -1446,9 +1431,6 @@ class Agent(Generic[Context, AgentStructuredOutput]):if results[-1].is_done or results[-1].error or i == len(actions) - 1:break- await asyncio.sleep(self.browser_profile.wait_between_actions)- # hash all elements. if it is a subset of cached_state its fine - else break (new elements on page)-except Exception as e:# Handle any exceptions during action executionself.logger.error(f'Action {i + 1} failed: {type(e).__name__}: {e}')@@ -1526,7 +1508,9 @@ class Agent(Generic[Context, AgentStructuredOutput]):async def _execute_history_step(self, history_item: AgentHistory, delay: float) -> list[ActionResult]:"""Execute a single step from history with element validation"""assert self.browser_session is not None, 'BrowserSession is not set up'- state = await self.browser_session.get_state_summary(cache_clickable_elements_hashes=False)+ state = await self.browser_session.get_browser_state_with_recovery(+ cache_clickable_elements_hashes=False, include_screenshot=False+ )if not state or not history_item.model_output:raise ValueError('Invalid state or model output')updated_actions = []diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex c8afaf964..e4632721c 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -3053,7 +3053,9 @@ class BrowserSession(BaseModel):@observe_debug(ignore_input=True, ignore_output=True)@time_execution_async('--get_state_summary')@require_healthy_browser(usable_page=True, reopen_page=True)- async def get_state_summary(self, cache_clickable_elements_hashes: bool) -> BrowserStateSummary:+ async def get_state_summary(+ self, cache_clickable_elements_hashes: bool, include_screenshot: bool = True+ ) -> BrowserStateSummary:self.logger.debug('🔄 Starting get_state_summary...')"""Get a summary of the current browser state@@ -3066,9 +3068,12 @@ class BrowserSession(BaseModel):If True, cache the clickable elements hashes for the current state.This is used to calculate which elements are new to the LLM since the last message,which helps reduce token usage.+ include_screenshot: bool+ If True, include screenshot in the state summary. Set to False to improve performance+ when screenshots are not needed (e.g., in multi_act element validation)."""await self._wait_for_page_and_frames_load()- updated_state = await self._get_updated_state()+ updated_state = await self._get_updated_state(include_screenshot=include_screenshot)# Find out which elements are new# Do this only if url has not changed@@ -3143,7 +3148,7 @@ class BrowserSession(BaseModel):)@observe_debug(ignore_input=True, ignore_output=True, name='get_updated_state')- async def _get_updated_state(self, focus_element: int = -1) -> BrowserStateSummary:+ async def _get_updated_state(self, focus_element: int = -1, include_screenshot: bool = True) -> BrowserStateSummary:"""Update and return state."""# Check if current page is still valid, if not switch to another available page@@ -3229,13 +3234,16 @@ class BrowserSession(BaseModel):# )# )- try:- self.logger.debug('📸 Capturing screenshot...')- # Reasonable timeout for screenshot- screenshot_b64 = await self.take_screenshot()- # self.logger.debug('✅ Screenshot completed')- except Exception as e:- self.logger.warning(f'❌ Screenshot failed for {_log_pretty_url(page.url)}: {type(e).__name__} {e}')+ if include_screenshot:+ try:+ self.logger.debug('📸 Capturing screenshot...')+ # Reasonable timeout for screenshot+ screenshot_b64 = await self.take_screenshot()+ # self.logger.debug('✅ Screenshot completed')+ except Exception as e:+ self.logger.warning(f'❌ Screenshot failed for {_log_pretty_url(page.url)}: {type(e).__name__} {e}')+ screenshot_b64 = None+ else:screenshot_b64 = None# Get comprehensive page information@@ -4475,7 +4483,9 @@ class BrowserSession(BaseModel):@observe_debug(ignore_input=True, ignore_output=True, name='get_state_summary_with_fallback')@require_healthy_browser(usable_page=True, reopen_page=True)@time_execution_async('--get_state_summary_with_fallback')- async def get_state_summary_with_fallback(self, cache_clickable_elements_hashes: bool = True) -> BrowserStateSummary:+ async def get_state_summary_with_fallback(+ self, cache_clickable_elements_hashes: bool = True, include_screenshot: bool = True+ ) -> BrowserStateSummary:"""Get browser state with fallback to minimal state on errorsThis method first tries to get a full state summary. If that fails,@@ -4485,6 +4495,8 @@ class BrowserSession(BaseModel):-----------cache_clickable_elements_hashes: boolIf True, cache the clickable elements hashes for the current state.+ include_screenshot: bool+ If True, include screenshot in the state summary.Returns:--------@@ -4492,7 +4504,7 @@ class BrowserSession(BaseModel):"""# Try 1: Full state summary (current implementation)try:- return await self.get_state_summary(cache_clickable_elements_hashes)+ return await self.get_state_summary(cache_clickable_elements_hashes, include_screenshot=include_screenshot)except Exception as e:self.logger.warning(f'Full state retrieval failed: {type(e).__name__}: {e}')self.logger.warning('🔄 Falling back to minimal state summary')@@ -4500,6 +4512,30 @@ class BrowserSession(BaseModel):# Try 2: Minimal state summary as fallbackreturn await self.get_minimal_state_summary()+ @observe_debug(ignore_input=True, ignore_output=True, name='get_browser_state_with_recovery')+ async def get_browser_state_with_recovery(+ self, cache_clickable_elements_hashes: bool = True, include_screenshot: bool = True+ ) -> BrowserStateSummary:+ """Get browser state with multiple fallback strategies for error recovery++ Parameters:+ -----------+ cache_clickable_elements_hashes: bool+ If True, cache the clickable elements hashes for the current state.+ include_screenshot: bool+ If True, include screenshot in the state summary. Set to False to improve performance+ when screenshots are not needed (e.g., in multi_act element validation).+ """++ # Try 1: Full state summary (current implementation) - like main branch+ try:+ return await self.get_state_summary(cache_clickable_elements_hashes, include_screenshot=include_screenshot)+ except Exception as e:+ self.logger.warning(f'Full state retrieval failed: {type(e).__name__}: {e}')++ self.logger.warning('🔄 Falling back to minimal state summary')+ return await self.get_minimal_state_summary()+async def _is_pdf_viewer(self, page: Page) -> bool:"""Check if the current page is displaying a PDF in Chrome's PDF viewer.