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
just improve
mertunsallbc9a3a5fbb97
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.pyindex ad3cd0f26..9dcf60c26 100644--- a/browser_use/agent/message_manager/service.py+++ b/browser_use/agent/message_manager/service.py@@ -19,7 +19,6 @@ from browser_use.llm.messages import (BaseMessage,ContentPartTextParam,SystemMessage,- UserMessage,)from browser_use.observability import observe_debugfrom browser_use.utils import match_url_with_domain_pattern, time_execution_sync@@ -129,7 +128,10 @@ class MessageManager:if len(self.state.history.get_messages()) == 0:self._set_state_message(self.system_prompt, 'system')- # Removed agent_history_description property - now using separate cached history messages+ @property+ def agent_history_description(self) -> str:+ """Build agent history description from list of items, respecting max_history_items limit"""+ return self._get_history_description()def add_new_task(self, new_task: str) -> None:self.task = new_task@@ -230,7 +232,7 @@ class MessageManager:sensitive_data=None,available_file_paths: list[str] | None = None, # Always pass current available_file_paths) -> None:- """Reconstruct all state messages from scratch for optimal caching"""+ """Create single state message with all content"""# Clear contextual messages from previous steps to prevent accumulationself.state.history.context_messages.clear()@@ -245,11 +247,12 @@ class MessageManager:if browser_state_summary.screenshot:screenshots.append(browser_state_summary.screenshot)- # Create the message prompt helper+ # Create the message prompt helper with history descriptionassert browser_state_summarymessage_prompt = AgentMessagePrompt(browser_state_summary=browser_state_summary,file_system=self.file_system,+ agent_history_description=self.agent_history_description,read_state_description=self.state.read_state_description,task=self.task,include_attributes=self.include_attributes,@@ -261,26 +264,11 @@ class MessageManager:vision_detail_level=self.vision_detail_level,)- # Fully reconstruct all messages every time for optimal caching:+ # Create single state message with all content+ state_message = message_prompt.get_user_message(use_vision)- # 1. Rebuild cached history messages from history items- self._rebuild_history_messages()-- # 2. Create fresh agent state message (not cached - changes every step)- agent_state_message = message_prompt.get_agent_state_message()-- # 3. Create fresh browser state message with vision (not cached - changes every step)- browser_state_message = message_prompt.get_browser_state_message(use_vision)-- # 4. Create fresh read state message (cached - only changes when new content extracted)- read_state_message = message_prompt.get_read_state_message()-- # Replace all state messages- self._set_state_message(agent_state_message, 'agent_state')- self._set_state_message(browser_state_message, 'browser_state')- # read state message is optional- if read_state_message:- self._set_state_message(read_state_message, 'read_state')+ # Set the state message with caching enabled+ self._set_state_message(state_message, 'state')def _log_history_lines(self) -> str:"""Generate a formatted log string of message history for debugging / printing to terminal"""@@ -328,13 +316,8 @@ class MessageManager:self.last_input_messages = self.state.history.get_messages()return self.last_input_messages- def _create_history_message_from_item(self, item: HistoryItem) -> UserMessage:- """Convert a HistoryItem into a cached UserMessage"""- content = item.to_string()- return UserMessage(content=content, cache=True)-- def _rebuild_history_messages(self) -> None:- """Rebuild the history messages from agent_history_items, respecting max_history_items limit"""+ def _get_history_description(self) -> str:+ """Build agent history description from list of items, respecting max_history_items limit"""history_items = self.state.agent_history_itemsif self.max_history_items is None:@@ -359,12 +342,10 @@ class MessageManager:omitted_item = HistoryItem(system_message=f'[... {omitted_count} previous steps omitted...]')items_to_include = [history_items[0], omitted_item] + history_items[-recent_items_count:]- # Convert items to cached messages- self.state.history.history_messages = [self._create_history_message_from_item(item) for item in items_to_include]+ # Convert items to strings+ return '\n'.join(item.to_string() for item in items_to_include)- def _set_state_message(- self, message: BaseMessage, message_type: Literal['system', 'agent_state', 'browser_state', 'read_state']- ) -> None:+ def _set_state_message(self, message: BaseMessage, message_type: Literal['system', 'state']) -> None:"""Replace a specific state message slot with a new message"""# filter out sensitive data from the messageif self.sensitive_data:@@ -372,12 +353,8 @@ class MessageManager:if message_type == 'system':self.state.history.system_message = message- elif message_type == 'agent_state':- self.state.history.agent_state_message = message- elif message_type == 'browser_state':- self.state.history.browser_state_message = message- elif message_type == 'read_state':- self.state.history.read_state_message = message+ elif message_type == 'state':+ self.state.history.state_message = messageelse:raise ValueError(f'Invalid state message type: {message_type}')diff --git a/browser_use/agent/message_manager/views.py b/browser_use/agent/message_manager/views.pyindex f5b2d8885..00926abd5 100644--- a/browser_use/agent/message_manager/views.py+++ b/browser_use/agent/message_manager/views.py@@ -71,25 +71,17 @@ class MessageHistory(BaseModel):"""History of messages"""system_message: BaseMessage | None = None- history_messages: list[BaseMessage] = Field(default_factory=list)- agent_state_message: BaseMessage | None = None- browser_state_message: BaseMessage | None = None- read_state_message: BaseMessage | None = None+ state_message: BaseMessage | None = Nonecontext_messages: list[BaseMessage] = Field(default_factory=list)model_config = ConfigDict(arbitrary_types_allowed=True)def get_messages(self) -> list[BaseMessage]:- """Get all messages in the correct order: system -> history -> agent_state -> browser_state -> read_state -> contextual"""+ """Get all messages in the correct order: system -> state -> contextual"""messages = []if self.system_message:messages.append(self.system_message)- messages.extend(self.history_messages)- if self.agent_state_message:- messages.append(self.agent_state_message)- if self.browser_state_message:- messages.append(self.browser_state_message)- if self.read_state_message:- messages.append(self.read_state_message)+ if self.state_message:+ messages.append(self.state_message)messages.extend(self.context_messages)return messagesdiff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.pyindex 7d3d29cd0..064ebd887 100644--- a/browser_use/agent/prompts.py+++ b/browser_use/agent/prompts.py@@ -81,6 +81,7 @@ class AgentMessagePrompt:self,browser_state_summary: 'BrowserStateSummary',file_system: 'FileSystem',+ agent_history_description: str | None = None,read_state_description: str | None = None,task: str | None = None,include_attributes: list[str] | None = None,@@ -94,6 +95,7 @@ class AgentMessagePrompt:):self.browser_state: 'BrowserStateSummary' = browser_state_summaryself.file_system: 'FileSystem | None' = file_system+ self.agent_history_description: str | None = agent_history_descriptionself.read_state_description: str | None = read_state_descriptionself.task: str | None = taskself.include_attributes = include_attributes@@ -214,13 +216,9 @@ Available tabs:agent_state += '<available_file_paths>\n' + '\n'.join(self.available_file_paths) + '\n</available_file_paths>\n'return agent_state- def get_agent_state_message(self) -> UserMessage:- """Get agent state as a separate message (not cached - changes every step)"""- agent_state_content = '<agent_state>\n' + self._get_agent_state_description().strip('\n') + '\n</agent_state>'- return UserMessage(content=agent_state_content, cache=False)-- def get_browser_state_message(self, use_vision: bool = True) -> UserMessage:- """Get browser state as a separate message, optionally with screenshots"""+ @observe_debug(ignore_input=True, ignore_output=True, name='get_user_message')+ def get_user_message(self, use_vision: bool = True) -> UserMessage:+ """Get complete state as a single cached message"""# Don't pass screenshot to model if page is a new tab page, step is 0, and there's only one tabif (is_new_tab_page(self.browser_state.url)@@ -230,16 +228,27 @@ Available tabs:):use_vision = False- browser_state_content = '<browser_state>\n' + self._get_browser_state_description().strip('\n') + '\n</browser_state>'+ # Build complete state description+ state_description = (+ '<agent_history>\n'+ + (self.agent_history_description.strip('\n') if self.agent_history_description else '')+ + '\n</agent_history>\n'+ )+ state_description += '<agent_state>\n' + self._get_agent_state_description().strip('\n') + '\n</agent_state>\n'+ state_description += '<browser_state>\n' + self._get_browser_state_description().strip('\n') + '\n</browser_state>\n'+ # Only add read_state if it has content+ read_state_description = self.read_state_description.strip('\n').strip() if self.read_state_description else ''+ if read_state_description:+ state_description += '<read_state>\n' + read_state_description + '\n</read_state>\n'if self.page_filtered_actions:- browser_state_content += '\n<page_specific_actions>\n'- browser_state_content += self.page_filtered_actions + '\n'- browser_state_content += '</page_specific_actions>\n'+ state_description += '<page_specific_actions>\n'+ state_description += self.page_filtered_actions + '\n'+ state_description += '</page_specific_actions>\n'if use_vision is True and self.screenshots:# Start with text description- content_parts: list[ContentPartTextParam | ContentPartImageParam] = [ContentPartTextParam(text=browser_state_content)]+ content_parts: list[ContentPartTextParam | ContentPartImageParam] = [ContentPartTextParam(text=state_description)]# Add screenshots with labelsfor i, screenshot in enumerate(self.screenshots):@@ -265,42 +274,4 @@ Available tabs:return UserMessage(content=content_parts, cache=True)- return UserMessage(content=browser_state_content, cache=True)-- def get_read_state_message(self) -> UserMessage | None:- """Get read state as a separate message"""- if not self.read_state_description:- return None- if not self.read_state_description.strip('\n').strip():- return None-- read_state_content = '<read_state>\n' + self.read_state_description.strip('\n') + '\n</read_state>'- return UserMessage(content=read_state_content, cache=False)-- @observe_debug(ignore_input=True, ignore_output=True, name='get_user_message')- def get_user_message(self, use_vision: bool = True) -> UserMessage:- """- DEPRECATED: This method is kept for backward compatibility but should not be used.- Use get_agent_state_message(), get_browser_state_message(), and get_read_state_message() instead.- """- # For backward compatibility, return all messages concatenated in a single message- agent_state_message = self.get_agent_state_message()- browser_state_message = self.get_browser_state_message(use_vision)- read_state_message = self.get_read_state_message()-- # Flatten the three message objects into a single list of content parts,- # handling both raw-text (`str`) and already-structured (`list[...]`) cases.- content_parts: list[ContentPartTextParam | ContentPartImageParam] = []-- for msg in (agent_state_message, browser_state_message, read_state_message):- if msg is None:- continue-- if isinstance(msg.content, list):- # Message is already a list of content parts – reuse as-is.- content_parts.extend(msg.content)- else:- # Wrap plain text in a ContentPartTextParam.- content_parts.append(ContentPartTextParam(text=str(msg.content)))-- return UserMessage(content=content_parts, cache=True)+ return UserMessage(content=state_description, cache=True)diff --git a/browser_use/llm/tests/test_single_step.py b/browser_use/llm/tests/test_single_step.pyindex 3613b5e07..7e7513653 100644--- a/browser_use/llm/tests/test_single_step.py+++ b/browser_use/llm/tests/test_single_step.py@@ -70,6 +70,7 @@ def create_mock_state_message(temp_dir: str):agent_prompt = AgentMessagePrompt(browser_state_summary=mock_browser_state,file_system=mock_file_system, # Now using actual FileSystem instance+ agent_history_description='', # Empty historyread_state_description='', # Empty read statetask='Click the button on the page',include_attributes=['id'],@@ -110,7 +111,7 @@ async def test_single_step_parametrized(llm_class, model_name):# Create mock state messagemock_message = create_mock_state_message(temp_dir)- agent.message_manager._set_state_message(mock_message, 'agent_state')+ agent.message_manager._set_state_message(mock_message, 'state')messages = agent.message_manager.get_messages()@@ -151,7 +152,7 @@ async def test_single_step():print(mock_message.content)print('\n' + '=' * 50 + '\n')- agent.message_manager._set_state_message(mock_message, 'agent_state')+ agent.message_manager._set_state_message(mock_message, 'state')messages = agent.message_manager.get_messages()