Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

Merge branch 'main' into mert/new_everything

Magnus Müller52d4191ba9ed
diff --cc browser_use/agent/message_manager/service.py
index 8f2aba8b3,6d4302780..322630075
--- a/browser_use/agent/message_manager/service.py
+++ b/browser_use/agent/message_manager/service.py
@@@ -17,8 -17,7 +17,8 @@@ from browser_use.agent.message_manager.
from browser_use.agent.prompts import AgentMessagePrompt
from browser_use.agent.views import ActionResult, AgentOutput, AgentStepInfo, MessageManagerState
from browser_use.browser.views import BrowserStateSummary
+from browser_use.filesystem.file_system import FileSystem
- from browser_use.utils import time_execution_sync
+ from browser_use.utils import match_url_with_domain_pattern, time_execution_sync
logger = logging.getLogger(__name__)
@@@ -223,18 -219,15 +223,24 @@@ class MessageManager
context_message = HumanMessage(content='Context for the task' + self.settings.message_context)
self._add_message_with_tokens(context_message, message_type='init')
+ if self.settings.sensitive_data:
+ info = f'Here are placeholders for sensitive data: {list(self.settings.sensitive_data.keys())}'
+ info += '\nTo use them, write <secret>the placeholder name</secret>'
+ info_message = HumanMessage(content=info)
+ self._add_message_with_tokens(info_message, message_type='init')
+
+ placeholder_message = HumanMessage(
+ content='Here is an example thinking and tool call. You can use it as a reference but do not copy it exactly.'
+ )
+ task_message = HumanMessage(
+ content=f'Your ultimate task is: """{self.task}""". If you achieved your ultimate task, stop everything and use the done action in the next step to complete the task. If not, continue as usual.'
+ )
+ self._add_message_with_tokens(task_message, message_type='init')
+
+ placeholder_message = HumanMessage(content='Example output:')
self._add_message_with_tokens(placeholder_message, message_type='init')
- example_tool_call = AIMessage(
+ example_tool_call_1 = AIMessage(
content='',
tool_calls=[
{
@@@ -356,49 -276,28 +362,71 @@@ My next action is to click on the iPhon
self._add_message_with_tokens(msg)
self.task = new_task
+ def _update_agent_history_description(
+ self,
+ model_output: AgentOutput | None = None,
+ result: list[ActionResult] | None = None,
+ step_info: AgentStepInfo | None = None,
+ ) -> None:
+ """Update the agent history description"""
+
+ if None in [model_output, result, step_info]:
+ return
+
+ self.read_state_initialization = (
+ '# Read State (displayed only **one time**, save this information if you need it later)\n'
+ )
+ self.read_state_description = self.read_state_initialization
+
+ step_number = step_info.step_number
+
+ action_results = ''
+ for idx, action_result in enumerate(result):
+ if action_result.update_read_state:
+ self.read_state_description += action_result.extracted_content + '\n'
+ if action_result.memory:
+ action_results += f'Action {idx + 1} Result: {action_result.memory}\n'
+ elif action_result.error:
+ action_results += f'Action {idx + 1} Error: {action_result.error[:200]}\n'
+ elif action_result.extracted_content:
+ action_results += f'Action {idx + 1} Result: {action_result.extracted_content}\n'
+ logger.warning(
+ '⚠️ ActionResult does not have memory but has extracted_content. This is not recommended as extracted_content can be too long.'
+ )
+ else:
+ raise ValueError(f'Action {idx + 1} has no memory or error:\n{action_result}')
+
+ self.agent_history_description += f"""## Step {step_number}
+Evaluation: {model_output.current_state.evaluation_previous_goal}
+Memory: {model_output.current_state.memory}
+Next goal: {model_output.current_state.next_goal}
+{action_results}
+"""
+ if self.read_state_description == self.read_state_initialization:
+ self.read_state_description = ''
+
+ def add_sensitive_data(self, current_page_url) -> None:
+ sensitive_data = self.settings.sensitive_data
+ if not sensitive_data:
+ return
+
+ # Collect placeholders for sensitive data
+ placeholders = set()
+
+ for key, value in sensitive_data.items():
+ if isinstance(value, dict):
+ # New format: {domain: {key: value}}
+ if match_url_with_domain_pattern(current_page_url, key, True):
+ placeholders.update(value.keys())
+ else:
+ # Old format: {key: value}
+ placeholders.add(key)
+ if placeholders:
+ info = f'Here are placeholders for sensitive data: {list(placeholders)}'
+ info += '\nTo use them, write <secret>the placeholder name</secret>'
+ info_message = HumanMessage(content=info)
+ self._add_message_with_tokens(info_message, message_type='init')
+
@time_execution_sync('--add_state_message')
def add_state_message(
self,
diff --cc browser_use/agent/service.py
index da9d98ca6,ee8987853..b31e6905b
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@@ -68,7 -67,7 +69,7 @@@ from browser_use.telemetry.service impo
from browser_use.telemetry.views import (
AgentTelemetryEvent,
)
- from browser_use.utils import handle_llm_error, time_execution_async, time_execution_sync
-from browser_use.utils import get_browser_use_version, time_execution_async, time_execution_sync
++from browser_use.utils import get_browser_use_version, handle_llm_error, time_execution_async, time_execution_sync
logger = logging.getLogger(__name__)
@@@ -958,10 -918,9 +971,10 @@@ class Agent(Generic[Context])
result: list[ActionResult] = await self.multi_act(model_output.action)
self.state.last_result = result
+ self.state.last_model_output = model_output
if len(result) > 0 and result[-1].is_done:
- logger.info(f'📄 Result: {result[-1].extracted_content}')
+ self.logger.info(f'📄 Result: {result[-1].extracted_content}')
self.state.consecutive_failures = 0
@@@ -1038,11 -995,11 +1051,11 @@@
AnthropicRateLimitError, # Anthropic
)
- if isinstance(error, RATE_LIMIT_ERRORS):
- self.logger.warning(f'{prefix}{error_msg}')
+ if isinstance(error, RATE_LIMIT_ERRORS) or 'on tokens per minute (TPM): Limit' in error_msg:
+ logger.warning(f'{prefix}{error_msg}')
await asyncio.sleep(self.settings.retry_delay)
else:
- logger.error(f'{prefix}{error_msg}')
+ self.logger.error(f'{prefix}{error_msg}')
return [ActionResult(error=error_msg, include_in_memory=True)]
@@@ -1625,11 -1555,11 +1623,11 @@@
parsed: ValidationResult = response['parsed']
is_valid = parsed.is_valid
if not is_valid:
- logger.info(f'❌ Validator decision: {parsed.reason}')
+ self.logger.info(f'❌ Validator decision: {parsed.reason}')
msg = f'The output is not yet correct. {parsed.reason}.'
- self.state.last_result = [ActionResult(extracted_content=msg, include_in_memory=True)]
+ self.state.last_result = [ActionResult(extracted_content=msg, include_in_memory=True, memory=msg)]
else:
- logger.info(f'✅ Validator decision: {parsed.reason}')
+ self.logger.info(f'✅ Validator decision: {parsed.reason}')
return is_valid
async def log_completion(self) -> None:
diff --cc browser_use/utils.py
index 3617d4ae9,b02e93e8f..92485484c
--- a/browser_use/utils.py
+++ b/browser_use/utils.py
@@@ -504,59 -494,58 +505,116 @@@ def merge_dicts(a: dict, b: dict, path
return a
+class LLMException(Exception):
+ """Custom exception for LLM-related errors."""
+
+ def __init__(self, code: int, message: str):
+ self.code = code
+ self.message = message
+ super().__init__(message)
+
+
+def handle_llm_error(e: Exception) -> tuple[dict[str, Any], Any | None]:
+ """
+ Handle LLM API errors and extract failed generation data when available.
+
+ Args:
+ e: The exception that occurred during LLM API call
+
+ Returns:
+ Tuple containing:
+ - response: Dict with 'raw' and 'parsed' keys
+ - parsed: Parsed data (None if extraction was needed)
+
+ Raises:
+ LLMException: If the error is not a recognized type with failed generation data
+ """
+ # Handle OpenAI BadRequestError with failed_generation
+ if (
+ OpenAIBadRequestError
+ and isinstance(e, OpenAIBadRequestError)
+ and hasattr(e, 'body')
+ and e.body
+ and 'failed_generation' in e.body
+ ):
+ raw = e.body['failed_generation']
+ response = {'raw': raw, 'parsed': None}
+ parsed = None
+ logger.debug(f'Failed to do tool call, trying to parse raw response: {raw}')
+ return response, parsed
+
+ # Handle Groq BadRequestError with failed_generation
+ if (
+ GroqBadRequestError
+ and isinstance(e, GroqBadRequestError)
+ and hasattr(e, 'body')
+ and e.body
+ and 'error' in e.body
+ and 'failed_generation' in e.body['error']
+ ):
+ raw = e.body['error']['failed_generation'] # type: ignore
+ response = {'raw': raw, 'parsed': None}
+ parsed = None
+ logger.debug(f'Failed to do tool call, trying to parse raw response: {raw}')
+ return response, parsed
+
+ # If it's not a recognized error type, log and raise
+ logger.error(f'Failed to invoke model: {str(e)}')
+ raise LLMException(401, 'LLM API call failed') from e
++
++
+ @cache
+ def get_browser_use_version() -> str:
+ """Get the browser-use package version using the same logic as Agent._set_browser_use_version_and_source"""
+ try:
+ package_root = Path(__file__).parent.parent
+ pyproject_path = package_root / 'pyproject.toml'
+
+ # Try to read version from pyproject.toml
+ if pyproject_path.exists():
+ import re
+
+ with open(pyproject_path, encoding='utf-8') as f:
+ content = f.read()
+ match = re.search(r'version\s*=\s*["\']([^"\']+)["\']', content)
+ if match:
+ return f'{match.group(1)}'
+
+ # If pyproject.toml doesn't exist, try getting version from pip
+ from importlib.metadata import version as get_version
+
+ return str(get_version('browser-use'))
+
+ except Exception as e:
+ logger.debug(f'Error detecting browser-use version: {type(e).__name__}: {e}')
+ return 'unknown'
+
+
+ def _log_pretty_path(path: Path | None) -> str:
+ """Pretty-print a path, shorten home dir to ~ and cwd to ."""
+
+ if not path or not str(path).strip():
+ return '' # always falsy in -> falsy out so it can be used in ternaries
+
+ # dont print anything thats not a path
+ if not isinstance(path, (str, Path)):
+ # no other types are safe to just str(path) and log to terminal unless we know what they are
+ # e.g. what if we get storage_date=dict | Path and the dict version could contain real cookies
+ return f'<{type(path).__name__}>'
+
+ # replace home dir and cwd with ~ and .
+ pretty_path = str(path).replace(str(Path.home()), '~').replace(str(Path.cwd().resolve()), '.')
+
+ # wrap in quotes if it contains spaces
+ if pretty_path.strip() and ' ' in pretty_path:
+ pretty_path = f'"{pretty_path}"'
+
+ return pretty_path
+
+
+ def _log_pretty_url(s: str, max_len: int | None = 22) -> str:
+ """Truncate/pretty-print a URL with a maximum length, removing the protocol and www. prefix"""
+ s = s.replace('https://', '').replace('http://', '').replace('www.', '')
+ if max_len is not None and len(s) > max_len:
+ return s[:max_len] + '…'
+ return s