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
Cut errors in output, include attributes in state and rerun only k steps
magmueller75d9239e5f60
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.pyindex 6b68340e0..542a425a5 100644--- a/browser_use/agent/message_manager/service.py+++ b/browser_use/agent/message_manager/service.py@@ -33,6 +33,7 @@ class MessageManager:max_input_tokens: int = 128000,estimated_tokens_per_character: int = 3,image_tokens: int = 800,+ include_attributes: list[str] = [],max_error_length: int = 400,):self.llm = llm@@ -43,8 +44,8 @@ class MessageManager:self.action_descriptions = action_descriptionsself.ESTIMATED_TOKENS_PER_CHARACTER = estimated_tokens_per_characterself.IMG_TOKENS = image_tokens+ self.include_attributes = include_attributesself.max_error_length = max_error_length-system_message = self.system_prompt_class(self.action_descriptions, current_date=datetime.now()).get_system_message()@@ -62,14 +63,17 @@ class MessageManager:msg = HumanMessage(content=str(result.extracted_content))self._add_message_with_tokens(msg)if result.error:- # use only last 400 characters of error- error = result.error[-self.max_error_length :]- msg = HumanMessage(content=str(error))+ msg = HumanMessage(content=str(result.error)[-self.max_error_length :])self._add_message_with_tokens(msg)result = None# otherwise add state message and result to next message (which will not stay in memory)- state_message = AgentMessagePrompt(state, result, self.max_error_length).get_user_message()+ state_message = AgentMessagePrompt(+ state,+ result,+ include_attributes=self.include_attributes,+ max_error_length=self.max_error_length,+ ).get_user_message()self._add_message_with_tokens(state_message)def _remove_last_state_message(self) -> None:diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.pyindex c3bfb7e3a..ab1d3046b 100644--- a/browser_use/agent/prompts.py+++ b/browser_use/agent/prompts.py@@ -107,10 +107,12 @@ class AgentMessagePrompt:state: BrowserState,result: Optional[ActionResult] = None,max_error_length: int = 400,+ include_attributes: list[str] = [],):self.state = stateself.result = resultself.max_error_length = max_error_length+ self.include_attributes = include_attributesdef get_user_message(self) -> HumanMessage:state_description = f"""@@ -118,7 +120,7 @@ Current url: {self.state.url}Available tabs:{self.state.tabs}Interactive elements:-{self.state.element_tree.clickable_elements_to_string()}+{self.state.element_tree.clickable_elements_to_string(include_attributes=self.include_attributes)}"""if self.result:diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex c4e4cd639..1e5908d2e 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -59,6 +59,8 @@ class Agent:system_prompt_class: Type[SystemPrompt] = SystemPrompt,max_input_tokens: int = 128000,validate_output: bool = False,+ include_attributes: list[str] = [],+ max_error_length: int = 400,):self.agent_id = str(uuid.uuid4()) # unique identifier for the agent@@ -82,12 +84,17 @@ class Agent:self.max_input_tokens = max_input_tokens+ self.include_attributes = include_attributes+ self.max_error_length = max_error_length+self.message_manager = MessageManager(llm=self.llm,task=self.task,action_descriptions=self.controller.registry.get_prompt_description(),system_prompt_class=self.system_prompt_class,max_input_tokens=self.max_input_tokens,+ include_attributes=self.include_attributes,+ max_error_length=self.max_error_length,)# Tracking variables@@ -327,7 +334,10 @@ class Agent:if self.controller.browser.session:state = self.controller.browser.session.cached_statecontent = AgentMessagePrompt(- state=state, result=self._last_result, max_error_length=400+ state=state,+ result=self._last_result,+ include_attributes=self.include_attributes,+ max_error_length=self.max_error_length,)msg = [SystemMessage(content=system_msg), content.get_user_message()]else:@@ -444,7 +454,6 @@ class Agent:if not current_element or current_element.highlight_index is None:return None-old_index = action.get_index()if old_index != current_element.highlight_index:action.set_index(current_element.highlight_index)@@ -455,12 +464,14 @@ class Agent:return actionasync def load_and_rerun(- self, history_file: Optional[str | Path] = None, k: int | None = None, **kwargs+ self, history_file: Optional[str | Path] = None, k: Optional[int] = None, **kwargs) -> list[ActionResult]:"""Load history from file and rerun it.Args:+ history_file: Path to the history file+ **kwargs: Additional arguments passed to rerun_historyhistory_file: Path to the history filek: Number of steps to rerun**kwargs: Additional arguments passed to rerun_historydiff --git a/browser_use/dom/views.py b/browser_use/dom/views.pyindex e5e0607bb..60b505819 100644--- a/browser_use/dom/views.py+++ b/browser_use/dom/views.py@@ -88,7 +88,7 @@ class DOMElementNode(DOMBaseNode):collect_text(self)return '\n'.join(text_parts).strip()- def clickable_elements_to_string(self) -> str:+ def clickable_elements_to_string(self, include_attributes: list[str] = []) -> str:"""Convert the processed DOM content to HTML."""formatted_text = []@@ -96,8 +96,15 @@ class DOMElementNode(DOMBaseNode):if isinstance(node, DOMElementNode):# Add element with highlight_indexif node.highlight_index is not None:+ attributes_str = ''+ if include_attributes:+ attributes_str = ' ' + ' '.join(+ f'{key}="{value}"'+ for key, value in node.attributes.items()+ if key in include_attributes+ )formatted_text.append(- f'{node.highlight_index}[:]<{node.tag_name}>{node.get_all_text_till_next_clickable_element()}</{node.tag_name}>'+ f'{node.highlight_index}[:]<{node.tag_name}{attributes_str}>{node.get_all_text_till_next_clickable_element()}</{node.tag_name}>')# Process children regardless