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
improve logging and use scheme matching for google urls
Nick Sweetingfbf52be11b43
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.pyindex 24d256606..422c0bf19 100644--- a/browser_use/agent/message_manager/service.py+++ b/browser_use/agent/message_manager/service.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport loggingimport re+import textwrapfrom langchain_core.messages import (AIMessage,@@ -182,6 +183,62 @@ class MessageManager:msg = AIMessage(content=plan)self._add_message_with_tokens(msg, position)+ def _get_message_emoji(self, message_type: str) -> str:+ """Get emoji for a message type"""+ emoji_map = {+ 'HumanMessage': '๐ฌ',+ 'AIMessage': '๐ง ',+ 'ToolMessage': '๐จ',+ }+ return emoji_map.get(message_type, '๐ฎ')++ def _clean_whitespace(self, text: str) -> str:+ """Replace all repeated whitespace with single space and strip"""+ return re.sub(r'\s+', ' ', text).strip()++ def _truncate_text(self, text: str, max_length: int) -> str:+ """Truncate text to max_length and add ellipsis if needed"""+ if len(text) <= max_length:+ return text+ return text[:max_length] + '...'++ def _extract_text_from_list_content(self, content: list) -> str:+ """Extract text from list content structure"""+ text_content = ''+ for item in content:+ if isinstance(item, dict) and 'text' in item:+ text_content += item['text']+ return text_content++ def _format_agent_output_content(self, tool_call: dict) -> str:+ """Format AgentOutput tool call into readable content"""+ args = tool_call.get('args', {})+ action_info = ''++ # Get action name+ if 'action' in args and args['action']:+ first_action = args['action'][0] if isinstance(args['action'], list) and args['action'] else args['action']+ if isinstance(first_action, dict):+ action_name = next(iter(first_action.keys())) if first_action else 'unknown'+ action_info = f'{action_name}()'++ # Get goal+ goal_info = ''+ if 'current_state' in args and isinstance(args['current_state'], dict):+ next_goal = args['current_state'].get('next_goal', '').strip()+ if next_goal:+ goal_info = f': {self._truncate_text(next_goal, 40)}'++ # Combine action and goal info+ if action_info and goal_info:+ return f'{action_info}{goal_info}'+ elif action_info:+ return action_info+ elif goal_info:+ return goal_info[2:] # Remove ': ' prefix for goal-only+ else:+ return 'AgentOutput'+def _generate_history_log(self) -> str:"""Generate a formatted log string of message history for debugging / printing to terminal"""total_input_tokens = 0@@ -193,106 +250,56 @@ class MessageManager:# Get emoji based on message typemessage_type = m.message.__class__.__name__- if message_type == 'HumanMessage':- emoji = '๐ฌ'- elif message_type == 'AIMessage':- emoji = '๐ง '- elif message_type == 'ToolMessage':- emoji = '๐จ'- else:- emoji = '๐ฎ' # fallback for other message types produced by controller+ emoji = self._get_message_emoji(message_type)- # Special handling for last message if it's a HumanMessage with list content+ # Extract content based on message structureif is_last_message and message_type == 'HumanMessage' and isinstance(m.message.content, list):- # Extract text from the list content- text_content = ''- for item in m.message.content:- if isinstance(item, dict) and 'text' in item:- text_content += item['text']-- # Clean up whitespace- text_content = re.sub(r'\s+', ' ', text_content).strip()+ # Special handling for last message with list content+ text_content = self._extract_text_from_list_content(m.message.content)+ text_content = self._clean_whitespace(text_content)# Look for current state sectionif '[Current state starts here]' in text_content:- # Extract just the current state portionstart_idx = text_content.find('[Current state starts here]')- content = text_content[start_idx : start_idx + 150] # Show more of current state- if len(text_content) > start_idx + 150:- content += '...'+ content = self._truncate_text(text_content[start_idx:], 150)else:- # Fallback to showing beginning of content- content = text_content[:150]- if len(text_content) > 150:- content += '...'+ content = self._truncate_text(text_content, 150)else:- # Get simple content preview - replace all repeated whitespace with single space- content = str(m.message.content)[:80]- content = re.sub(r'\s+', ' ', content).strip()+ # Standard content extraction+ content = self._clean_whitespace(str(m.message.content)[:80])- # For AIMessages with empty content but tool calls, show useful tool info- if hasattr(m.message, 'tool_calls') and m.message.tool_calls and not content.strip():+ # Handle AIMessages with tool calls+ if hasattr(m.message, 'tool_calls') and m.message.tool_calls and not content:tool_call = m.message.tool_calls[0]tool_name = tool_call.get('name', 'unknown')if tool_name == 'AgentOutput':- # Extract useful info from AgentOutput- args = tool_call.get('args', {})- action_info = ''- if 'action' in args and args['action']:- # Get the action name- first_action = (- args['action'][0] if isinstance(args['action'], list) and args['action'] else args['action']- )- if isinstance(first_action, dict):- action_name = next(iter(first_action.keys())) if first_action else 'unknown'- action_info = f' โ {action_name}()'-- # Get the goal- goal_info = ''- if 'current_state' in args and isinstance(args['current_state'], dict):- next_goal = args['current_state'].get('next_goal', '').strip()- if next_goal:- goal_info = f': {next_goal[:40]}{"..." if len(next_goal) > 40 else ""}'-- if action_info and goal_info:- content = f'{action_info[3:]}{goal_info}' # Remove ' โ ' prefix- elif action_info:- content = action_info[3:] # Just the action name without ' โ '- elif goal_info:- content = goal_info[2:] # Remove ': ' prefix for goal-only- else:- content = 'AgentOutput'+ content = self._format_agent_output_content(tool_call)else:content = f'[TOOL: {tool_name}]'elif len(str(m.message.content)) > 80:content += '...'- # Left-justify the emoji and token count for alignment+ # Format the message lineleft_part = f' {emoji}[{m.metadata.tokens}]'# For last message, allow multiple lines if neededif is_last_message and '\n' not in content:- # Wrap long last messages nicely- import textwrap-wrapped = textwrap.wrap(content, width=80, subsequent_indent=' ' * 14)if len(wrapped) > 2:wrapped = wrapped[:2]- wrapped[-1] = wrapped[-1][:77] + '...'+ wrapped[-1] = self._truncate_text(wrapped[-1], 77)message_lines.append(f'{left_part.ljust(12)}: {wrapped[0]}')- for line in wrapped[1:]:- message_lines.append(line)+ message_lines.extend(wrapped[1:])else:message_lines.append(f'{left_part.ljust(12)}: {content}')- # Log all messages in a single call- history_log = (+ # Build final log message+ return (f'Messages in history: {len(self.state.history.messages)}:\n'+ '\n'.join(message_lines)+ f'\nTotal input tokens: {total_input_tokens}')- return history_log@time_execution_sync('--get_messages')def get_messages(self) -> list[BaseMessage]:diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex db5cca27e..51ab90f2d 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -792,20 +792,7 @@ class Agent(Generic[Context]):input_messages = self._convert_input_messages(input_messages)if self.tool_calling_method == 'raw':- # Count messages and check for images- message_count = len(input_messages)- total_chars = sum(len(str(msg.content)) for msg in input_messages)- has_images = any(- hasattr(msg, 'content')- and isinstance(msg.content, list)- and any(isinstance(item, dict) and item.get('type') == 'image_url' for item in msg.content)- for msg in input_messages- )- current_tokens = getattr(self._message_manager.state.history, 'current_tokens', 0)-- logger.debug(- f'๐ง LLM call: {self.chat_model_library} ({self.tool_calling_method}) | {message_count} msgs, ~{current_tokens} tokens, {total_chars} chars | {"๐ท images" if has_images else "no images"} | raw text output'- )+ self._log_llm_call_info(input_messages, self.tool_calling_method)try:output = self.llm.invoke(input_messages)response = {'raw': output, 'parsed': None}@@ -833,20 +820,7 @@ class Agent(Generic[Context]):raise LLMException(401, 'LLM API call failed') from eelse:- # Count messages and check for images- message_count = len(input_messages)- total_chars = sum(len(str(msg.content)) for msg in input_messages)- has_images = any(- hasattr(msg, 'content')- and isinstance(msg.content, list)- and any(isinstance(item, dict) and item.get('type') == 'image_url' for item in msg.content)- for msg in input_messages- )- current_tokens = getattr(self._message_manager.state.history, 'current_tokens', 0)-- logger.debug(- f'๐ง LLM call: {self.chat_model_library} ({self.tool_calling_method}) | {message_count} msgs, ~{current_tokens} tokens, {total_chars} chars | {"๐ท images" if has_images else "no images"} | structured output + tools'- )+ self._log_llm_call_info(input_messages, self.tool_calling_method)structured_llm = self.llm.with_structured_output(self.AgentOutput, include_raw=True, method=self.tool_calling_method)response: dict[str, Any] = await structured_llm.ainvoke(input_messages) # type: ignore@@ -972,6 +946,27 @@ class Agent(Generic[Context]):f'๐ Step {self.state.n_steps}: Complete. Ran {action_count} action{"s" if action_count != 1 else ""} in {step_duration:.2f}s: {status_str}')+ def _log_llm_call_info(self, input_messages: list[BaseMessage], method: str) -> None:+ """Log comprehensive information about the LLM call being made"""+ # Count messages and check for images+ message_count = len(input_messages)+ total_chars = sum(len(str(msg.content)) for msg in input_messages)+ has_images = any(+ hasattr(msg, 'content')+ and isinstance(msg.content, list)+ and any(isinstance(item, dict) and item.get('type') == 'image_url' for item in msg.content)+ for msg in input_messages+ )+ 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'++ logger.debug(+ f'๐ง LLM call: {self.chat_model_library} ({method}) | {message_count} msgs, ~{current_tokens} tokens, {total_chars} chars | {image_status} | {output_type}'+ )+def _log_agent_event(self, max_steps: int, agent_run_error: str | None = None) -> None:"""Sent the agent event for this run to telemetry"""diff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex 1e24a4298..a7b4f28d6 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -772,7 +772,7 @@ class Controller(Generic[Context]):logger.error(error_msg)return ActionResult(error=error_msg, include_in_memory=True)- @self.registry.action('Google Sheets: Get the contents of the entire sheet', domains=['docs.google.com'])+ @self.registry.action('Google Sheets: Get the contents of the entire sheet', domains=['https://docs.google.com'])async def get_sheet_contents(browser_session: BrowserSession):page = await browser_session.get_current_page()@@ -785,7 +785,7 @@ class Controller(Generic[Context]):extracted_tsv = await page.evaluate('() => navigator.clipboard.readText()')return ActionResult(extracted_content=extracted_tsv, include_in_memory=True)- @self.registry.action('Google Sheets: Select a specific cell or range of cells', domains=['docs.google.com'])+ @self.registry.action('Google Sheets: Select a specific cell or range of cells', domains=['https://docs.google.com'])async def select_cell_or_range(browser_session: BrowserSession, cell_or_range: str):page = await browser_session.get_current_page()@@ -804,7 +804,9 @@ class Controller(Generic[Context]):await page.keyboard.press('Escape') # to make sure the popup still closes in the case where the jump failedreturn ActionResult(extracted_content=f'Selected cell {cell_or_range}', include_in_memory=False)- @self.registry.action('Google Sheets: Get the contents of a specific cell or range of cells', domains=['docs.google.com'])+ @self.registry.action(+ 'Google Sheets: Get the contents of a specific cell or range of cells', domains=['https://docs.google.com']+ )async def get_range_contents(browser_session: BrowserSession, cell_or_range: str):page = await browser_session.get_current_page()@@ -815,14 +817,14 @@ class Controller(Generic[Context]):extracted_tsv = await page.evaluate('() => navigator.clipboard.readText()')return ActionResult(extracted_content=extracted_tsv, include_in_memory=True)- @self.registry.action('Google Sheets: Clear the currently selected cells', domains=['docs.google.com'])+ @self.registry.action('Google Sheets: Clear the currently selected cells', domains=['https://docs.google.com'])async def clear_selected_range(browser_session: BrowserSession):page = await browser_session.get_current_page()await page.keyboard.press('Backspace')return ActionResult(extracted_content='Cleared selected range', include_in_memory=False)- @self.registry.action('Google Sheets: Input text into the currently selected cell', domains=['docs.google.com'])+ @self.registry.action('Google Sheets: Input text into the currently selected cell', domains=['https://docs.google.com'])async def input_selected_cell_text(browser_session: BrowserSession, text: str):page = await browser_session.get_current_page()@@ -831,7 +833,7 @@ class Controller(Generic[Context]):await page.keyboard.press('ArrowUp')return ActionResult(extracted_content=f'Inputted text {text}', include_in_memory=False)- @self.registry.action('Google Sheets: Batch update a range of cells', domains=['docs.google.com'])+ @self.registry.action('Google Sheets: Batch update a range of cells', domains=['https://docs.google.com'])async def update_range_contents(browser_session: BrowserSession, range: str, new_contents_tsv: str):page = await browser_session.get_current_page()