Skip to content

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

Merge branch 'main' into mert/improve_messages_for_kv_cache

Mert Unsal714b5f7d0b46
diff --cc browser_use/agent/message_manager/service.py
index 0d37c2f56,8126b1c4f..3aceba15c
--- a/browser_use/agent/message_manager/service.py
+++ b/browser_use/agent/message_manager/service.py
@@@ -229,15 -255,10 +228,14 @@@ class MessageManager
use_vision=True,
page_filtered_actions: str | None = None,
sensitive_data=None,
- agent_history_list: AgentHistoryList | None = None, # Pass AgentHistoryList from agent
available_file_paths: list[str] | None = None, # Always pass current available_file_paths
) -> None:
- """Add browser state as human message"""
+ """Reconstruct all state messages from scratch for optimal caching"""
+ # Clear contextual messages from previous steps to prevent accumulation
+ self.state.history.context_messages.clear()
+
+ # First, update the agent history items with the latest step results
self._update_agent_history_description(model_output, result, step_info)
if sensitive_data:
self.sensitive_data_description = self._get_sensitive_data_description(browser_state_summary.url)
@@@ -266,28 -282,10 +258,29 @@@
sensitive_data=self.sensitive_data_description,
available_file_paths=available_file_paths,
screenshots=screenshots,
- vision_detail_level=self.vision_detail_level,
- ).get_user_message(use_vision)
++ vision_detail_level=self.vision_detail_level,
+ )
+
+ # Fully reconstruct all messages every time for optimal caching:
+
+ # 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()
- self._add_message_with_type(state_message, 'state')
+ # 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')
def _log_history_lines(self) -> str:
"""Generate a formatted log string of message history for debugging / printing to terminal"""
diff --cc browser_use/agent/prompts.py
index b53d9b344,36802cea6..7d3d29cd0
--- a/browser_use/agent/prompts.py
+++ b/browser_use/agent/prompts.py
@@@ -263,14 -245,11 +239,11 @@@ Available tabs
if use_vision is True and self.screenshots:
# Start with text description
- content_parts: list[ContentPartTextParam | ContentPartImageParam] = [ContentPartTextParam(text=state_description)]
+ content_parts: list[ContentPartTextParam | ContentPartImageParam] = [ContentPartTextParam(text=browser_state_content)]
- # Deduplicate screenshots, keeping only the most recent of each unique image
- unique_screenshots = self._deduplicate_screenshots(self.screenshots)
-
# Add screenshots with labels
- for i, screenshot in enumerate(unique_screenshots):
- if i == len(unique_screenshots) - 1:
+ for i, screenshot in enumerate(self.screenshots):
+ if i == len(self.screenshots) - 1:
label = 'Current screenshot:'
else:
# Use simple, accurate labeling since we don't have actual step timing info
@@@ -289,44 -269,6 +263,44 @@@
)
)
- return UserMessage(content=content_parts, cache=False)
+ return UserMessage(content=content_parts, cache=True)
- return UserMessage(content=browser_state_content, cache=False)
- return UserMessage(content=state_description, 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)
diff --cc browser_use/agent/service.py
index 5ae2ef16c,6778e5f9f..d687a8620
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@@ -712,9 -728,13 +728,9 @@@ class Agent(Generic[Context, AgentStruc
# Get page-specific filtered actions
page_filtered_actions = self.controller.registry.get_prompt_description(current_page)
- # If there are page-specific actions, add them as a special message for this step only
- if page_filtered_actions:
- page_action_message = f'For this page, these additional actions are available:\n{page_filtered_actions}'
- self._message_manager._add_message_with_type(UserMessage(content=page_action_message), 'consistent')
-
- self.logger.debug(f'💬 Step {self.state.n_steps}: Adding state message to context...')
- self._message_manager.add_state_message(
+ # Page-specific actions will be included directly in the browser_state message
- self.logger.debug(f'💬 Step {self.state.n_steps + 1}: Creating state messages for context...')
++ self.logger.debug(f'💬 Step {self.state.n_steps}: Creating state messages for context...')
+ self._message_manager.create_state_messages(
browser_state_summary=browser_state_summary,
model_output=self.state.last_model_output,
result=self.state.last_result,