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
force-llm-output-after-failure
Magnus Müllerf474e24b28a5
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 22d8873e4..d1dc1e5f5 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -179,6 +179,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):directly_open_url: bool = True,include_recent_events: bool = False,sample_images: list[ContentPartTextParam | ContentPartImageParam] | None = None,+ final_response_after_failure: bool = True,**kwargs,):if llm is None:@@ -262,6 +263,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):include_tool_call_examples=include_tool_call_examples,llm_timeout=llm_timeout,step_timeout=step_timeout,+ final_response_after_failure=final_response_after_failure,)# Token cost service@@ -687,7 +689,8 @@ class Agent(Generic[Context, AgentStructuredOutput]):available_file_paths=self.available_file_paths, # Always pass current available_file_paths)- await self._handle_final_step(step_info)+ await self._force_done_after_last_step(step_info)+ await self._force_done_after_failure()return browser_state_summary@observe_debug(ignore_input=True, name='get_next_action')@@ -838,7 +841,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):# Increment step counter after step is fully completedself.state.n_steps += 1- async def _handle_final_step(self, step_info: AgentStepInfo | None = None) -> None:+ async def _force_done_after_last_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@@ -850,6 +853,19 @@ class Agent(Generic[Context, AgentStructuredOutput]):self._message_manager._add_context_message(UserMessage(content=msg))self.AgentOutput = self.DoneAgentOutput+ async def _force_done_after_failure(self) -> None:+ """Force done after failure"""+ # Create recovery message+ if self.state.consecutive_failures >= self.settings.max_failures and self.settings.final_response_after_failure:+ msg = f'You have failed {self.settings.max_failures} consecutive times. This is your final step to complete the task or provide what you found. '+ msg += 'Use only the "done" action now. No other actions - so here your action sequence must have length 1.'+ msg += '\nIf the task could not be completed due to the failures, set success in "done" to false!'+ msg += '\nInclude everything you found out for the task in the done text.'++ self.logger.debug('Final recovery step setup')+ self._message_manager._add_context_message(UserMessage(content=msg))+ 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_model_output(input_messages)@@ -1277,7 +1293,9 @@ class Agent(Generic[Context, AgentStructuredOutput]):signal_handler.reset()# Check if we should stop due to too many failures- if self.state.consecutive_failures >= self.settings.max_failures:+ if (+ self.state.consecutive_failures + int(self.settings.final_response_after_failure)+ ) >= self.settings.max_failures:self.logger.error(f'❌ Stopping due to {self.settings.max_failures} consecutive failures')agent_run_error = f'Stopped due to {self.settings.max_failures} consecutive failures'breakdiff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex 395c95414..fb85e8973 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -49,6 +49,7 @@ class AgentSettings(BaseModel):include_tool_call_examples: bool = Falsellm_timeout: int = 60 # Timeout in seconds for LLM callsstep_timeout: int = 180 # Timeout in seconds for each step+ final_response_after_failure: bool = True # If True, attempt one final recovery call after max_failuresclass AgentState(BaseModel):@@ -64,6 +65,7 @@ class AgentState(BaseModel):stopped: bool = Falsesession_initialized: bool = False # Track if session events have been dispatchedfollow_up_task: bool = False # Track if the agent is a follow-up task+ recovery_attempted: bool = False # Track if final recovery has been attemptedmessage_manager_state: MessageManagerState = Field(default_factory=MessageManagerState)file_system_state: FileSystemState | None = Nonediff --git a/docs/customize/agent/all-parameters.mdx b/docs/customize/agent/all-parameters.mdxindex 5f4469f67..05f6e217e 100644--- a/docs/customize/agent/all-parameters.mdx+++ b/docs/customize/agent/all-parameters.mdx@@ -21,6 +21,7 @@ mode: "wide"- `initial_actions`: List of actions to run before the main task without LLM. [Example](https://github.com/browser-use/browser-use/blob/main/examples/features/initial_actions.py)- `max_actions_per_step` (default: `10`): Maximum actions per step, e.g. for form filling the agent can output 10 fields at once. We execute the actions until the page changes.- `max_failures` (default: `3`): Maximum retries for steps with errors+- `final_response_after_failure` (default: `True`): If True, attempt to force one final model call with intermediate output after max_failures is reached- `use_thinking` (default: `True`): Controls whether the agent uses its internal "thinking" field for explicit reasoning steps.- `flash_mode` (default: `False`): Fast mode that skips evaluation, next goal and thinking and only uses memory. If `flash_mode` is enabled, it overrides `use_thinking` and disables the thinking process entirely. [Example](https://github.com/browser-use/browser-use/blob/main/examples/getting_started/05_fast_agent.py)