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
Fix error handling: remove last state in case of error
magmueller86ecf174b16e
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex eb007d61b..ee2414400 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -66,7 +66,7 @@ class Agent:controller: Controller = Controller(),use_vision: bool = True,save_conversation_path: Optional[str] = None,- max_failures: int = 5,+ max_failures: int = 3,retry_delay: int = 10,system_prompt_class: Type[SystemPrompt] = SystemPrompt,max_input_tokens: int = 128000,@@ -171,10 +171,15 @@ class Agent:state = await self.browser_context.get_state(use_vision=self.use_vision)self.message_manager.add_state_message(state, self._last_result, step_info)input_messages = self.message_manager.get_messages()- model_output = await self.get_next_action(input_messages)- self._save_conversation(input_messages, model_output)- self.message_manager._remove_last_state_message() # we dont want the whole state in the chat history- self.message_manager.add_model_output(model_output)+ try:+ model_output = await self.get_next_action(input_messages)+ self._save_conversation(input_messages, model_output)+ self.message_manager._remove_last_state_message() # we dont want the whole state in the chat history+ self.message_manager.add_model_output(model_output)+ except Exception as e:+ # model call failed, remove last state message from history+ self.message_manager._remove_last_state_message()+ raise eresult: list[ActionResult] = await self.controller.multi_act(model_output.action, self.browser_context@@ -219,6 +224,10 @@ class Agent:f'Cutting tokens from history - new max input tokens: {self.message_manager.max_input_tokens}')self.message_manager.cut_messages()+ elif 'Could not parse response' in error_msg:+ # give model a hint how output should look like+ error_msg += '\n\nReturn a valid JSON object with the required fields.'+self.consecutive_failures += 1elif isinstance(error, RateLimitError):logger.warning(f'{prefix}{error_msg}')@@ -267,6 +276,9 @@ class Agent:response: dict[str, Any] = await structured_llm.ainvoke(input_messages) # type: ignoreparsed: AgentOutput = response['parsed']+ if parsed is None:+ raise ValueError(f'Could not parse response.')+# cut the number of actions to max_actions_per_stepparsed.action = parsed.action[: self.max_actions_per_step]self._log_response(parsed)