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
simplify close messages
Nick Sweeting08726575ac30
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.pyindex 87e92afb8..531583d98 100644--- a/browser_use/agent/message_manager/service.py+++ b/browser_use/agent/message_manager/service.py@@ -70,6 +70,8 @@ def _log_format_agent_output_content(tool_call: dict) -> str:if 'current_state' in args and isinstance(args['current_state'], dict):next_goal = args['current_state'].get('next_goal', '').strip()if next_goal:+ # Clean whitespace from goal text to prevent newlines+ next_goal = _log_clean_whitespace(next_goal)goal_info = f': {next_goal}'# Combine action and goal infodiff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex df31f191f..3f65d084b 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -1170,14 +1170,23 @@ class Agent(Generic[Context]):)current_tokens = getattr(self._message_manager.state.history, 'current_tokens', 0)- # Determine output type- output_type = 'raw text output' if method == 'raw' else 'structured output + tools'- image_status = 'π· images' if has_images else 'no images'+ # Count available tools/actions from the current ActionModel+ # This gives us the actual number of tools exposed to the LLM for this specific call+ tool_count = len(self.ActionModel.model_fields) if hasattr(self, 'ActionModel') else 0++ # Format the log message parts+ image_status = ', π· img' if has_images else ''+ if method == 'raw':+ output_format = '=> raw text'+ tool_info = ''+ else:+ output_format = '=> JSON out'+ tool_info = f' + π¨ {tool_count} tools ({method})'term_width = shutil.get_terminal_size((80, 20)).columnsprint('=' * term_width)logger.info(- f'π§ LLM call: {self.chat_model_library} ({method}) | {message_count} msgs, ~{current_tokens} tokens, {total_chars} chars | {image_status} | {output_type}'+ f'π§ LLM call => {self.chat_model_library} [βοΈ {message_count} msg, ~{current_tokens} tk, {total_chars} char{image_status}] {output_format}{tool_info}')def _log_agent_event(self, max_steps: int, agent_run_error: str | None = None) -> None:diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex c6f128999..2497460e7 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -254,35 +254,22 @@ class BrowserSession(BaseModel):if self.browser_profile.keep_alive:return # nothing to do if keep_alive=True, leave the browser running- if self.browser_context:+ if self.browser_context or self.browser:try:- await self.browser_context.close()+ await (self.browser_context or self.browser).close()logger.info(- 'π Shut down the BrowserSession '- f'(keep_alive=False user_data_dir={_log_pretty_path(self.browser_profile.user_data_dir) or "<None (incognito)>"})'+ f'π Stopped the Browser '+ f'(keep_alive=False user_data_dir={_log_pretty_path(self.browser_profile.user_data_dir) or "<incognito>"})')self.browser_context = Noneexcept Exception as e:logger.debug(f'β Error closing playwright BrowserContext {self.browser_context}: {type(e).__name__}: {e}')- if self.browser:- try:- await self.browser.close()- logger.info(- 'π Shut down the BrowserSession '- f'(keep_alive=False user_data_dir={_log_pretty_path(self.browser_profile.user_data_dir) or "<None (incognito)>"})'- )- self.browser = None- except Exception as e:- logger.debug(f'β Error closing playwright Browser {self.browser}: {type(e).__name__}: {e}')-# kill the chrome subprocess if we were the ones that started itif self.browser_pid:try:psutil.Process(pid=self.browser_pid).terminate()- logger.info(- f'π Shut down the BrowserSession and subprocess with browser_pid={self.browser_pid} (keep_alive=False)'- )+ logger.info(f'βΉ Shut down the browser subprocess with browser_pid={self.browser_pid} (keep_alive=False)')self.browser_pid = Noneexcept Exception as e:if 'NoSuchProcess' not in type(e).__name__:@@ -409,7 +396,7 @@ class BrowserSession(BaseModel):logger.info(f'π Launching local browser 'f'driver={str(type(self.playwright).__module__).split(".")[0]} channel={self.browser_profile.channel.name.lower()} '- f'user_data_dir={_log_pretty_path(self.browser_profile.user_data_dir) if self.browser_profile.user_data_dir else "None (incognito)"}'+ f'user_data_dir={_log_pretty_path(self.browser_profile.user_data_dir) if self.browser_profile.user_data_dir else "<incognito>"}')if not self.browser_profile.user_data_dir:# if no user_data_dir is provided, launch an incognito context with no persistent user_data_dir@@ -655,6 +642,8 @@ class BrowserSession(BaseModel):# TODO: implement applying self.stroage_state to an existing browser_context, currently only works on browser.new_context() I think# await self.browser_context.set_storage_state(self.storage_state)+ page = None+for page in self.browser_context.pages:# apply viewport size settings to any existing pagesif viewport:@@ -664,6 +653,8 @@ class BrowserSession(BaseModel):if page.url == 'about:blank':await self._show_dvd_screensaver_loading_animation(page)+ page = page or (await self.browser_context.new_page())+if (not viewport) and (self.browser_profile.window_size is not None) and not self.browser_profile.headless:# attempt to resize the actual browser windowdiff --git a/browser_use/logging_config.py b/browser_use/logging_config.pyindex dc1f86085..4b62d6141 100644--- a/browser_use/logging_config.py+++ b/browser_use/logging_config.py@@ -1,7 +1,6 @@import loggingimport osimport sys-import warningsfrom dotenv import load_dotenv@@ -60,12 +59,6 @@ def addLoggingLevel(levelName, levelNum, methodName=None):def setup_logging():- # Suppress specific deprecation warnings from FAISS- warnings.filterwarnings('ignore', category=DeprecationWarning, module='faiss.loader')- warnings.filterwarnings('ignore', message='builtin type SwigPyPacked has no __module__ attribute')- warnings.filterwarnings('ignore', message='builtin type SwigPyObject has no __module__ attribute')- warnings.filterwarnings('ignore', message='builtin type swigvarlink has no __module__ attribute')-# Try to add RESULT level, but ignore if it already existstry:addLoggingLevel('RESULT', 35) # This allows ERROR, FATAL and CRITICAL