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
Merge remote-tracking branch 'origin/main' into refactor-agent-stable
Magnus Müller542bcdacfdc5
diff --cc browser_use/agent/service.pyindex 8e94d184f,2830de1d9..158a41e66--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@@ -645,284 -646,190 +645,277 @@@ class Agent(Generic[Context, AgentStrucstep_start_time = time.time()try:- assert self.browser_session is not None, 'BrowserSession is not set up'+ # Phase 1: Prepare context (browser state, action models, messages)+ browser_state_summary = await self._prepare_step_context(step_info, step_start_time)- 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)- current_page = await self.browser_session.get_current_page()+ # Phase 2: Execute LLM interaction AND action execution in SAME try block (critical for performance!)+ model_output = await self._execute_llm_interaction(browser_state_summary)+ result = await self._execute_actions(model_output)- self._log_step_context(current_page, browser_state_summary)+ # Phase 3: Post-processing (downloads, reset failures, logging)+ await self._handle_post_action_processing()- await self._raise_if_stopped_or_paused()+ except InterruptedError as e:+ self.logger.debug(f'InterruptedError: {type(e).__name__}: {e}')+ self.state.consecutive_failures += 1+ self.state.last_result = [+ ActionResult(+ error='The agent was interrupted mid-step' + (f' - {e}' if e else ''),+ )+ ]+ return+ except Exception as e:+ # Handle ALL exceptions (LLM AND action execution) - like main branch!+ result = await self._handle_step_error(e)+ self.state.last_result = result- # Update action models with page-specific actions- self.logger.debug(f'📝 Step {self.state.n_steps + 1}: Updating action models...')- await self._update_action_models_for_page(current_page)+ finally:+ await self._finalize_step(browser_state_summary, step_start_time)- # Get page-specific filtered actions- page_filtered_actions = self.controller.registry.get_prompt_description(current_page)+ async def _execute_llm_interaction(self, browser_state_summary: BrowserStateSummary) -> AgentOutput:+ """Execute LLM interaction with retry logic and handle callbacks"""+ input_messages = self._message_manager.get_messages()+ self.logger.debug(+ f'🤖 Step {self.state.n_steps + 1}: Calling LLM with {len(input_messages)} messages (model: {self.llm.model})...'+ )- # If there are page-specific actions, add them as a special message for this step only- if page_filtered_actions:- page_action_message = f'For this page, these additional actions are available:\n{page_filtered_actions}'- self._message_manager._add_message_with_type(UserMessage(content=page_action_message), 'consistent')+ try:+ model_output = await self._get_model_output_with_retry(input_messages)+ self.state.last_model_output = model_output- self.logger.debug(f'💬 Step {self.state.n_steps + 1}: Adding state message to context...')- self._message_manager.add_state_message(- browser_state_summary=browser_state_summary,- model_output=self.state.last_model_output,- result=self.state.last_result,- step_info=step_info,- use_vision=self.settings.use_vision,- page_filtered_actions=page_filtered_actions if page_filtered_actions else None,- sensitive_data=self.sensitive_data,- agent_history_list=self.state.history, # Pass AgentHistoryList for screenshots- )+ # Check again for paused/stopped state after getting model output+ await self._raise_if_stopped_or_paused()- if step_info and step_info.is_last_step():- # Add last step warning if needed- msg = 'Now comes your last step. Use only the "done" action now. No other actions - so here your action sequence must have length 1.'- msg += '\nIf the task is not yet fully finished as requested by the user, set success in "done" to false! E.g. if not all steps are fully completed.'- msg += '\nIf the task is fully finished, set success in "done" to true.'- msg += '\nInclude everything you found out for the ultimate task in the done text.'- self.logger.info('Last step finishing up')- self._message_manager._add_message_with_type(UserMessage(content=msg), 'consistent')- self.AgentOutput = self.DoneAgentOutput-- input_messages = self._message_manager.get_messages()- self.logger.debug(- f'🤖 Step {self.state.n_steps + 1}: Calling LLM with {len(input_messages)} messages (model: {self.llm.model})...'- )+ self.state.n_steps += 1- try:- model_output = await self.get_next_action(input_messages)- self.logger.debug(- f'✅ Step {self.state.n_steps + 1}: Got LLM response with {len(model_output.action) if model_output.action else 0} actions'- )+ # Handle callbacks and conversation saving+ await self._handle_post_llm_processing(browser_state_summary, input_messages)- self._message_manager._remove_last_state_message() # we dont want the whole state in the chat history-- if (- not model_output.action- or not isinstance(model_output.action, list)- or all(action.model_dump() == {} for action in model_output.action)- ):- self.logger.warning('Model returned empty action. Retrying...')+ # check again if Ctrl+C was pressed before we commit the output to history+ await self._raise_if_stopped_or_paused()- clarification_message = UserMessage(- content='You forgot to return an action. Please respond only with a valid JSON action according to the expected format.'- )+ return model_output- except InterruptedError:- # Agent was paused during get_next_action - handle like main branch- self._message_manager._remove_last_state_message()- raise # Re-raise to be caught by the outer try/except- retry_messages = input_messages + [clarification_message]- model_output = await self.get_next_action(retry_messages)-- if not model_output.action or all(action.model_dump() == {} for action in model_output.action):- self.logger.warning('Model still returned empty after retry. Inserting safe noop action.')- action_instance = self.ActionModel()- setattr(- action_instance,- 'done',- {- 'success': False,- 'text': 'No next action returned by LLM!',- },- )- model_output.action = [action_instance]- self.state.last_model_output = model_output- # Check again for paused/stopped state after getting model output- await self._raise_if_stopped_or_paused()+ except Exception as e:+ # model call failed, remove last state message from history- self._message_manager._remove_last_state_message()+ self.logger.error(f'❌ Step {self.state.n_steps + 1}: LLM call failed: {type(e).__name__}: {e}')+ raise e- self.state.n_steps += 1+ async def _execute_actions(self, model_output: AgentOutput) -> list[ActionResult]:+ """Execute the actions from model output"""+ self.logger.debug(f'⚡ Step {self.state.n_steps}: Executing {len(model_output.action)} actions...')+ result = await self.multi_act(model_output.action)+ self.logger.debug(f'✅ Step {self.state.n_steps}: Actions completed')- if self.register_new_step_callback:- if inspect.iscoroutinefunction(self.register_new_step_callback):- await self.register_new_step_callback(browser_state_summary, model_output, self.state.n_steps)- else:- self.register_new_step_callback(browser_state_summary, model_output, self.state.n_steps)- if self.settings.save_conversation_path:- # Treat save_conversation_path as a directory (consistent with other recording paths)- conversation_dir = Path(self.settings.save_conversation_path)- conversation_filename = f'conversation_{self.id}_{self.state.n_steps}.txt'- target = conversation_dir / conversation_filename- await save_conversation(- input_messages,- model_output,- target,- self.settings.save_conversation_path_encoding,- )+ self.state.last_result = result+ return result- await self._raise_if_stopped_or_paused()+ async def _prepare_step_context(+ self, step_info: AgentStepInfo | None = None, step_start_time: float | None = None+ ) -> BrowserStateSummary:+ """Prepare the context for the step: browser state, action models, page actions"""- except Exception as e:- # model call failed- self.logger.error(f'❌ Step {self.state.n_steps + 1}: LLM call failed: {type(e).__name__}: {e}')- raise e+ if step_start_time is None:+ step_start_time = time.time()+ assert self.browser_session is not None, 'BrowserSession is not set up'- self.logger.debug(f'⚡ Step {self.state.n_steps}: Executing {len(model_output.action)} actions...')- result: list[ActionResult] = await self.multi_act(model_output.action)- self.logger.debug(f'✅ Step {self.state.n_steps}: Actions completed')+ 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)+ current_page = await self.browser_session.get_current_page()++ self._log_step_context(current_page, browser_state_summary)+ await self._raise_if_stopped_or_paused()++ # Update action models with page-specific actions+ self.logger.debug(f'📝 Step {self.state.n_steps + 1}: Updating action models...')+ await self._update_action_models_for_page(current_page)++ # Get page-specific filtered actions+ page_filtered_actions = self.controller.registry.get_prompt_description(current_page)++ # If there are page-specific actions, add them as a special message for this step only+ if page_filtered_actions:+ page_action_message = f'For this page, these additional actions are available:\n{page_filtered_actions}'- self._message_manager._add_message_with_type(UserMessage(content=page_action_message))++ self._message_manager._add_message_with_type(UserMessage(content=page_action_message), 'consistent')++ self.logger.debug(f'💬 Step {self.state.n_steps + 1}: Adding state message to context...')+ self._message_manager.add_state_message(+ browser_state_summary=browser_state_summary,+ model_output=self.state.last_model_output,+ result=self.state.last_result,+ step_info=step_info,+ use_vision=self.settings.use_vision,+ page_filtered_actions=page_filtered_actions if page_filtered_actions else None,+ sensitive_data=self.sensitive_data,+ agent_history_list=self.state.history, # Pass AgentHistoryList for screenshots+ )- self.state.last_result = result+ await self._handle_final_step(step_info)+ return browser_state_summary++ async def _handle_final_step(self, step_info: AgentStepInfo | None = None) -> None:+ """Handle special processing for the last step"""+ if step_info and step_info.is_last_step():+ # Add last step warning if needed+ msg = 'Now comes your last step. Use only the "done" action now. No other actions - so here your action sequence must have length 1.'+ msg += '\nIf the task is not yet fully finished as requested by the user, set success in "done" to false! E.g. if not all steps are fully completed.'+ msg += '\nIf the task is fully finished, set success in "done" to true.'+ msg += '\nInclude everything you found out for the ultimate task in the done text.'+ self.logger.info('Last step finishing up')- self._message_manager._add_message_with_type(UserMessage(content=msg))++ self._message_manager._add_message_with_type(UserMessage(content=msg), 'consistent')+ self.AgentOutput = self.DoneAgentOutput++ async def _get_model_output_with_retry(self, input_messages: list[BaseMessage]) -> AgentOutput:+ """Get model output with retry logic for empty actions"""+ model_output = await self.get_next_action(input_messages) # Use get_next_action like main branch+ self.logger.debug(+ f'✅ Step {self.state.n_steps + 1}: Got LLM response with {len(model_output.action) if model_output.action else 0} actions'+ )- # Check for new downloads after executing actions- if self.has_downloads_path:- try:- current_downloads = self.browser_session.downloaded_files- if current_downloads != self._last_known_downloads:- self._update_available_file_paths(current_downloads)- self._last_known_downloads = current_downloads- except Exception as e:- self.logger.debug(f'📁 Failed to check for new downloads: {type(e).__name__}: {e}')+ if (+ not model_output.action+ or not isinstance(model_output.action, list)+ or all(action.model_dump() == {} for action in model_output.action)+ ):+ self.logger.warning('Model returned empty action. Retrying...')- self.state.consecutive_failures = 0- self.logger.debug(f'🔄 Step {self.state.n_steps}: Consecutive failures reset to: {self.state.consecutive_failures}')+ clarification_message = UserMessage(+ content='You forgot to return an action. Please respond only with a valid JSON action according to the expected format.'+ )- if len(result) > 0 and result[-1].is_done:- self.logger.info(f'📄 Result: {result[-1].extracted_content}')- if result[-1].attachments:- self.logger.info('📎 Click links below to access the attachments:')- for file_path in result[-1].attachments:- self.logger.info(f'👉 {file_path}')+ retry_messages = input_messages + [clarification_message]+ model_output = await self.get_next_action(retry_messages) # Use get_next_action like main branch++ if not model_output.action or all(action.model_dump() == {} for action in model_output.action):+ self.logger.warning('Model still returned empty after retry. Inserting safe noop action.')+ action_instance = self.ActionModel()+ setattr(+ action_instance,+ 'done',+ {+ 'success': False,+ 'text': 'No next action returned by LLM!',+ },+ )+ model_output.action = [action_instance]- except InterruptedError as e:- self.logger.debug(f'InterruptedError: {type(e).__name__}: {e}')+ return model_output- self.state.last_result = [- ActionResult(- error='The agent was interrupted mid-step' + (f' - {e}' if e else ''),- )- ]- self.state.consecutive_failures += 1+ async def _handle_post_llm_processing(+ self, browser_state_summary: BrowserStateSummary, input_messages: list[BaseMessage]+ ) -> None:+ """Handle callbacks and conversation saving after LLM interaction"""+ if self.register_new_step_callback and self.state.last_model_output:+ if inspect.iscoroutinefunction(self.register_new_step_callback):+ await self.register_new_step_callback(browser_state_summary, self.state.last_model_output, self.state.n_steps)+ else:+ self.register_new_step_callback(browser_state_summary, self.state.last_model_output, self.state.n_steps)++ if self.settings.save_conversation_path and self.state.last_model_output:+ # Treat save_conversation_path as a directory (consistent with other recording paths)+ conversation_dir = Path(self.settings.save_conversation_path)+ conversation_filename = f'conversation_{self.id}_{self.state.n_steps}.txt'+ target = conversation_dir / conversation_filename+ await save_conversation(+ input_messages,+ self.state.last_model_output,+ target,+ self.settings.save_conversation_path_encoding,+ )++ async def _finalize_step(self, browser_state_summary: BrowserStateSummary | None, step_start_time: float) -> None:+ """Finalize the step with history, logging, and events"""+ step_end_time = time.time()+ if not self.state.last_result:return- except Exception as e:- result = await self._handle_step_error(e)- self.state.last_result = result- finally:- step_end_time = time.time()- if not result:- return+ if browser_state_summary:+ metadata = StepMetadata(+ step_number=self.state.n_steps,+ step_start_time=step_start_time,+ step_end_time=step_end_time,+ )- if browser_state_summary:- metadata = StepMetadata(- step_number=self.state.n_steps,- step_start_time=step_start_time,- step_end_time=step_end_time,- )- self._make_history_item(model_output, browser_state_summary, result, metadata)+ # Use _make_history_item like main branch+ self._make_history_item(self.state.last_model_output, browser_state_summary, self.state.last_result, metadata)- # Log step completion summary- self._log_step_completion_summary(step_start_time, result)+ # Log step completion summary+ self._log_step_completion_summary(step_start_time, self.state.last_result)- # Save file system state after step completion- self.save_file_system_state()+ # Save file system state after step completion+ self.save_file_system_state()- # Emit both step created and executed events- if browser_state_summary and model_output:- # Extract key step data for the event- actions_data = []- if model_output.action:- for action in model_output.action:- action_dict = action.model_dump() if hasattr(action, 'model_dump') else {}- actions_data.append(action_dict)+ # Emit both step created and executed events+ if browser_state_summary and self.state.last_model_output:+ # Extract key step data for the event+ actions_data = []+ if self.state.last_model_output.action:+ for action in self.state.last_model_output.action:+ action_dict = action.model_dump() if hasattr(action, 'model_dump') else {}+ actions_data.append(action_dict)- # Emit CreateAgentStepEvent- step_event = CreateAgentStepEvent.from_agent_step(self, model_output, result, actions_data, browser_state_summary)- self.eventbus.dispatch(step_event)+ # Emit CreateAgentStepEvent+ step_event = CreateAgentStepEvent.from_agent_step(+ self, self.state.last_model_output, self.state.last_result, actions_data, browser_state_summary+ )+ self.eventbus.dispatch(step_event)++ def _make_history_item(+ self,+ model_output: AgentOutput | None,+ browser_state_summary: BrowserStateSummary,+ result: list[ActionResult],+ metadata: StepMetadata | None = None,+ ) -> None:+ """Create and store history item"""++ if model_output:+ interacted_elements = AgentHistory.get_interacted_element(model_output, browser_state_summary.selector_map)+ else:+ interacted_elements = [None]++ state_history = BrowserStateHistory(+ url=browser_state_summary.url,+ title=browser_state_summary.title,+ tabs=browser_state_summary.tabs,+ interacted_element=interacted_elements,+ screenshot=browser_state_summary.screenshot,+ )++ history_item = AgentHistory(+ model_output=model_output,+ result=result,+ state=state_history,+ metadata=metadata,+ )++ self.state.history.history.append(history_item)++ async def _handle_post_action_processing(self) -> None:+ """Handle post-action processing like download tracking and result logging"""+ assert self.browser_session is not None, 'BrowserSession is not set up'++ # Check for new downloads after executing actions+ if self.has_downloads_path:+ try:+ current_downloads = self.browser_session.downloaded_files+ if current_downloads != self._last_known_downloads:+ self._update_available_file_paths(current_downloads)+ self._last_known_downloads = current_downloads+ except Exception as e:+ self.logger.debug(f'📁 Failed to check for new downloads: {type(e).__name__}: {e}')++ self.state.consecutive_failures = 0+ self.logger.debug(f'🔄 Step {self.state.n_steps}: Consecutive failures reset to: {self.state.consecutive_failures}')++ # Log completion results+ if self.state.last_result and len(self.state.last_result) > 0 and self.state.last_result[-1].is_done:+ self.logger.info(f'📄 Result: {self.state.last_result[-1].extracted_content}')+ if self.state.last_result[-1].attachments:+ self.logger.info('📎 Click links below to access the attachments:')+ for file_path in self.state.last_result[-1].attachments:+ self.logger.info(f'👉 {file_path}')- @time_execution_async('--handle_step_error (agent)')async def _handle_step_error(self, error: Exception) -> list[ActionResult]:"""Handle all types of errors that can occur during a step"""include_trace = self.logger.isEnabledFor(logging.DEBUG)diff --cc browser_use/browser/session.pyindex 0f1072349,f0e341d3f..c0421439b--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@@ -4021,30 -4102,137 +4102,165 @@@ class BrowserSession(BaseModel)str(self.id)[-4:],)+ @observe_debug(name='get_state_summary_with_fallback')+ @require_initialization+ @time_execution_async('--get_state_summary_with_fallback')+ async def get_state_summary_with_fallback(self, cache_clickable_elements_hashes: bool = True) -> BrowserStateSummary:+ """Get browser state with fallback to minimal state on errors++ This method first tries to get a full state summary. If that fails,+ it falls back to a minimal state summary to allow basic navigation.++ Parameters:+ -----------+ cache_clickable_elements_hashes: bool+ If True, cache the clickable elements hashes for the current state.++ Returns:+ --------+ BrowserStateSummary: Either full state or minimal fallback state+ """+ # Try 1: Full state summary (current implementation)+ try:+ return await self.get_state_summary(cache_clickable_elements_hashes)+ 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')++ # Try 2: Minimal state summary as fallback+ 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.+ Returns True if PDF is detected, False otherwise.+ """+ try:+ is_pdf_viewer = await page.evaluate("""+ () => {+ // Check for Chrome's built-in PDF viewer (updated selector)+ const pdfEmbed = document.querySelector('embed[type="application/x-google-chrome-pdf"]') ||+ document.querySelector('embed[type="application/pdf"]');+ const isPdfViewer = !!pdfEmbed;++ // Also check if the URL ends with .pdf or has PDF content-type+ const url = window.location.href;+ const isPdfUrl = url.toLowerCase().includes('.pdf') ||+ document.contentType === 'application/pdf';++ return isPdfViewer || isPdfUrl;+ }+ """)+ return is_pdf_viewer+ except Exception as e:+ self.logger.debug(f'Error checking PDF viewer: {type(e).__name__}: {e}')+ return False++ async def _auto_download_pdf_if_needed(self, page: Page) -> str | None:+ """+ Check if the current page is a PDF viewer and automatically download the PDF if so.+ Returns the download path if a PDF was downloaded, None otherwise.+ """+ if not self.browser_profile.downloads_path or not self._auto_download_pdfs:+ return None++ try:+ # Check if we're in a PDF viewer+ is_pdf_viewer = await self._is_pdf_viewer(page)+ self.logger.debug(f'is_pdf_viewer: {is_pdf_viewer}')++ if not is_pdf_viewer:+ return None++ # Get the PDF URL+ pdf_url = page.url++ # Check if we've already downloaded this PDF+ pdf_filename = os.path.basename(pdf_url.split('?')[0]) # Remove query params+ if not pdf_filename or not pdf_filename.endswith('.pdf'):+ # Generate filename from URL+ from urllib.parse import urlparse++ parsed = urlparse(pdf_url)+ pdf_filename = os.path.basename(parsed.path) or 'document.pdf'+ if not pdf_filename.endswith('.pdf'):+ pdf_filename += '.pdf'++ # Check if already downloaded+ expected_path = os.path.join(self.browser_profile.downloads_path, pdf_filename)+ if any(os.path.basename(downloaded) == pdf_filename for downloaded in self._downloaded_files):+ self.logger.debug(f'📄 PDF already downloaded: {pdf_filename}')+ return None++ self.logger.info(f'📄 Auto-downloading PDF from: {pdf_url}')++ # Download the actual PDF file using JavaScript fetch+ # Note: This should hit the browser cache since Chrome already downloaded the PDF to display it+ try:+ self.logger.debug(f'Downloading PDF from URL: {pdf_url}')++ # Properly escape the URL to prevent JavaScript injection+ escaped_pdf_url = json.dumps(pdf_url)++ download_result = await page.evaluate(f"""+ async () => {{+ try {{+ // Use fetch with cache: 'force-cache' to prioritize cached version+ const response = await fetch({escaped_pdf_url}, {{+ cache: 'force-cache'+ }});+ if (!response.ok) {{+ throw new Error(`HTTP error! status: ${{response.status}}`);+ }}+ const blob = await response.blob();+ const arrayBuffer = await blob.arrayBuffer();+ const uint8Array = new Uint8Array(arrayBuffer);++ // Log whether this was served from cache+ const fromCache = response.headers.has('age') ||+ !response.headers.has('date') ||+ performance.getEntriesByName({escaped_pdf_url}).some(entry =>+ entry.transferSize === 0 || entry.transferSize < entry.encodedBodySize+ );++ return {{+ data: Array.from(uint8Array),+ fromCache: fromCache,+ responseSize: uint8Array.length,+ transferSize: response.headers.get('content-length') || 'unknown'+ }};+ }} catch (error) {{+ throw new Error(`Fetch failed: ${{error.message}}`);+ }}+ }}+ """)++ if download_result and download_result.get('data') and len(download_result['data']) > 0:+ # Ensure unique filename+ unique_filename = await self._get_unique_filename(self.browser_profile.downloads_path, pdf_filename)+ download_path = os.path.join(self.browser_profile.downloads_path, unique_filename)++ # Save the PDF asynchronously+ async with await anyio.open_file(download_path, 'wb') as f:+ await f.write(bytes(download_result['data']))++ # Track the downloaded file+ self._downloaded_files.append(download_path)++ # Log cache information+ cache_status = 'from cache' if download_result.get('fromCache') else 'from network'+ response_size = download_result.get('responseSize', 0)+ self.logger.info(f'📄 Auto-downloaded PDF ({cache_status}, {response_size:,} bytes): {download_path}')++ return download_path+ else:+ self.logger.warning(f'⚠️ No data received when downloading PDF from {pdf_url}')+ return None++ except Exception as e:+ self.logger.warning(f'⚠️ Failed to auto-download PDF from {pdf_url}: {type(e).__name__}: {e}')+ return None++ except Exception as e:+ self.logger.warning(f'⚠️ Error in PDF auto-download check: {type(e).__name__}: {e}')+ return None