Skip to content

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

Clean up

Magnus Müller90d489832292
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 158a41e66..4a038e81c 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -21,6 +21,7 @@ from browser_use.agent.cloud_events import (
CreateAgentTaskEvent,
UpdateAgentTaskEvent,
)
+from browser_use.agent.message_manager.utils import save_conversation
from browser_use.dom.views import DEFAULT_INCLUDE_ATTRIBUTES
from browser_use.llm.base import BaseChatModel
from browser_use.llm.messages import BaseMessage, UserMessage
@@ -36,9 +37,6 @@ from browser_use.agent.gif import create_history_gif
from browser_use.agent.message_manager.service import (
MessageManager,
)
-from browser_use.agent.message_manager.utils import (
- save_conversation,
-)
from browser_use.agent.prompts import SystemPrompt
from browser_use.agent.views import (
ActionResult,
@@ -640,83 +638,29 @@ class Agent(Generic[Context, AgentStructuredOutput]):
async def step(self, step_info: AgentStepInfo | None = None) -> None:
"""Execute one step of the task"""
browser_state_summary = None
- model_output = None
- result: list[ActionResult] = []
- step_start_time = time.time()
try:
- # Phase 1: Prepare context (browser state, action models, messages)
- browser_state_summary = await self._prepare_step_context(step_info, step_start_time)
+ # Phase 1: Prepare context and timing
+ browser_state_summary = await self._prepare_context(step_info)
- # 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)
+ # Phase 2: Get model output and execute actions
+ await self._get_next_action(browser_state_summary)
+ await self._execute_actions()
- # Phase 3: Post-processing (downloads, reset failures, logging)
- await self._handle_post_action_processing()
+ # Phase 3: Post-processing
+ await self._post_process()
- 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
+ # Handle ALL exceptions in one place
+ await self._handle_step_error(e)
finally:
- await self._finalize_step(browser_state_summary, step_start_time)
-
- 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})...'
- )
-
- try:
- model_output = await self._get_model_output_with_retry(input_messages)
- self.state.last_model_output = model_output
+ await self._finalize(browser_state_summary)
- # Check again for paused/stopped state after getting model output
- await self._raise_if_stopped_or_paused()
-
- self.state.n_steps += 1
-
- # Handle callbacks and conversation saving
- await self._handle_post_llm_processing(browser_state_summary, input_messages)
-
- # check again if Ctrl+C was pressed before we commit the output to history
- await self._raise_if_stopped_or_paused()
-
- return model_output
-
- except Exception as e:
- # model call failed, remove last state message from history
- self.logger.error(f'❌ Step {self.state.n_steps + 1}: LLM call failed: {type(e).__name__}: {e}')
- raise e
-
- 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')
-
- self.state.last_result = result
- return result
-
- async def _prepare_step_context(
- self, step_info: AgentStepInfo | None = None, step_start_time: float | None = None
- ) -> BrowserStateSummary:
+ async def _prepare_context(self, step_info: AgentStepInfo | None = None) -> BrowserStateSummary:
"""Prepare the context for the step: browser state, action models, page actions"""
+ self.step_start_time = time.time()
- 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 + 1}: Getting browser state...')
@@ -753,6 +697,152 @@ class Agent(Generic[Context, AgentStructuredOutput]):
await self._handle_final_step(step_info)
return browser_state_summary
+ async def _get_next_action(self, browser_state_summary: BrowserStateSummary) -> None:
+ """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})...'
+ )
+
+ model_output = await self._get_model_output_with_retry(input_messages)
+ self.state.last_model_output = model_output
+
+ # Check again for paused/stopped state after getting model output
+ await self._raise_if_stopped_or_paused()
+
+ self.state.n_steps += 1
+
+ # Handle callbacks and conversation saving
+ await self._handle_post_llm_processing(browser_state_summary, input_messages)
+
+ # check again if Ctrl+C was pressed before we commit the output to history
+ await self._raise_if_stopped_or_paused()
+
+ async def _execute_actions(self) -> None:
+ """Execute the actions from model output"""
+ if self.state.last_model_output is None:
+ raise ValueError('No model output to execute actions from')
+
+ self.logger.debug(f'⚡ Step {self.state.n_steps}: Executing {len(self.state.last_model_output.action)} actions...')
+ result = await self.multi_act(self.state.last_model_output.action)
+ self.logger.debug(f'✅ Step {self.state.n_steps}: Actions completed')
+
+ self.state.last_result = result
+
+ async def _post_process(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}')
+
+ async def _handle_step_error(self, error: Exception) -> None:
+ """Handle all types of errors that can occur during a step"""
+
+ # Handle InterruptedError specially
+ if isinstance(error, InterruptedError):
+ self.logger.debug(f'InterruptedError: {type(error).__name__}: {error}')
+ self.state.consecutive_failures += 1
+
+ self.state.last_result = [
+ ActionResult(
+ error='The agent was interrupted mid-step' + (f' - {error}' if error else ''),
+ )
+ ]
+ return
+
+ # Handle all other exceptions
+ include_trace = self.logger.isEnabledFor(logging.DEBUG)
+ error_msg = AgentError.format_error(error, include_trace=include_trace)
+ prefix = f'❌ Result failed {self.state.consecutive_failures + 1}/{self.settings.max_failures} times:\n '
+ self.state.consecutive_failures += 1
+
+ if isinstance(error, (ValidationError, ValueError)):
+ self.logger.error(f'{prefix}{error_msg}')
+ if 'Max token limit reached' in error_msg:
+ # TODO: figure out what to do here
+ pass
+ elif 'Could not parse response' in error_msg or 'tool_use_failed' in error_msg:
+ # give model a hint how output should look like
+ logger.debug(f'Model: {self.llm.model} failed')
+ error_msg += '\n\nReturn a valid JSON object with the required fields.'
+ logger.error(f'{prefix}{error_msg}')
+ else:
+ from anthropic import RateLimitError as AnthropicRateLimitError
+ from google.api_core.exceptions import ResourceExhausted
+ from openai import RateLimitError
+
+ # Define a tuple of rate limit error types for easier maintenance
+ RATE_LIMIT_ERRORS = (
+ RateLimitError, # OpenAI
+ ResourceExhausted, # Google
+ AnthropicRateLimitError, # Anthropic
+ )
+
+ 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:
+ self.logger.error(f'{prefix}{error_msg}')
+
+ self.state.last_result = [ActionResult(error=error_msg, include_in_memory=True)]
+ return None
+
+ async def _finalize(self, browser_state_summary: BrowserStateSummary | None) -> None:
+ """Finalize the step with history, logging, and events"""
+ step_end_time = time.time()
+ if not self.state.last_result:
+ return
+
+ if browser_state_summary:
+ metadata = StepMetadata(
+ step_number=self.state.n_steps,
+ step_start_time=self.step_start_time,
+ step_end_time=step_end_time,
+ )
+
+ # 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(self.step_start_time, self.state.last_result)
+
+ # Save file system state after step completion
+ self.save_file_system_state()
+
+ # 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, self.state.last_model_output, self.state.last_result, actions_data, browser_state_summary
+ )
+ self.eventbus.dispatch(step_event)
+
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():
@@ -767,7 +857,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
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
+ model_output = await self.get_model_output(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'
)
@@ -784,7 +874,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
)
retry_messages = input_messages + [clarification_message]
- model_output = await self.get_next_action(retry_messages) # Use get_next_action like main branch
+ model_output = await self.get_model_output(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.')
@@ -823,43 +913,6 @@ class Agent(Generic[Context, AgentStructuredOutput]):
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
-
- if browser_state_summary:
- metadata = StepMetadata(
- step_number=self.state.n_steps,
- step_start_time=step_start_time,
- step_end_time=step_end_time,
- )
-
- # 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, self.state.last_result)
-
- # Save file system state after step completion
- self.save_file_system_state()
-
- # 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, 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,
@@ -891,77 +944,6 @@ class Agent(Generic[Context, AgentStructuredOutput]):
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}')
-
- 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)
- error_msg = AgentError.format_error(error, include_trace=include_trace)
- prefix = f'❌ Result failed {self.state.consecutive_failures + 1}/{self.settings.max_failures} times:\n '
- self.state.consecutive_failures += 1
-
- if isinstance(error, (ValidationError, ValueError)):
- self.logger.error(f'{prefix}{error_msg}')
- if 'Max token limit reached' in error_msg:
- # cut tokens from history
- # self._message_manager.settings.max_input_tokens = self.settings.max_input_tokens - 500
- # self.logger.info(
- # f'Cutting tokens from history - new max input tokens: {self._message_manager.settings.max_input_tokens}'
- # )
- # TODO: figure out what to do here
- pass
-
- # no longer cutting messages, because we revamped the message manager
- # self._message_manager.cut_messages()
- elif 'Could not parse response' in error_msg or 'tool_use_failed' in error_msg:
- # give model a hint how output should look like
- logger.debug(f'Model: {self.llm.model} failed')
- error_msg += '\n\nReturn a valid JSON object with the required fields.'
- logger.error(f'{prefix}{error_msg}')
-
- else:
- from anthropic import RateLimitError as AnthropicRateLimitError
- from google.api_core.exceptions import ResourceExhausted
- from openai import RateLimitError
-
- # Define a tuple of rate limit error types for easier maintenance
- RATE_LIMIT_ERRORS = (
- RateLimitError, # OpenAI
- ResourceExhausted, # Google
- AnthropicRateLimitError, # Anthropic
- )
-
- 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:
- self.logger.error(f'{prefix}{error_msg}')
-
- return [ActionResult(error=error_msg, include_in_memory=True)]
-
def _remove_think_tags(self, text: str) -> str:
THINK_TAGS = re.compile(r'<think>.*?</think>', re.DOTALL)
STRAY_CLOSE_TAG = re.compile(r'.*?</think>', re.DOTALL)
@@ -973,7 +955,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
return text.strip()
@time_execution_async('--get_next_action')
- async def get_next_action(self, input_messages: list[BaseMessage]) -> AgentOutput:
+ async def get_model_output(self, input_messages: list[BaseMessage]) -> AgentOutput:
"""Get next action from LLM based on current state"""
try: