Skip to content

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

Refactor message management to categorize messages by type. Updated methods to handle system, state, and consistent messages separately, improving message retrieval and organization.

Magnus Müller6f221ec504f2
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.py
index 7fb08e6be..a7b283dc4 100644
--- a/browser_use/agent/message_manager/service.py
+++ b/browser_use/agent/message_manager/service.py
@@ -1,7 +1,7 @@
from __future__ import annotations
-import json
import logging
+from typing import Literal
from browser_use.agent.message_manager.views import (
HistoryItem,
@@ -17,11 +17,9 @@ from browser_use.agent.views import (
from browser_use.browser.views import BrowserStateSummary
from browser_use.filesystem.file_system import FileSystem
from browser_use.llm.messages import (
- AssistantMessage,
BaseMessage,
ContentPartTextParam,
SystemMessage,
- UserMessage,
)
from browser_use.observability import observe_debug
from browser_use.utils import match_url_with_domain_pattern, time_execution_sync
@@ -130,8 +128,8 @@ class MessageManager:
self.sensitive_data = sensitive_data
self.last_input_messages = []
# Only initialize messages if state is empty
- if len(self.state.history.messages) == 0:
- self._init_messages()
+ if len(self.state.history.get_messages()) == 0:
+ self._add_message_with_type(self.system_prompt, 'system')
@property
def agent_history_description(self) -> str:
@@ -162,66 +160,6 @@ class MessageManager:
return '\n'.join(items_to_include)
- def _init_messages(self) -> None:
- """Initialize the message history with system message, context, task, and other initial messages"""
- self._add_message_with_type(self.system_prompt)
-
- # Only add tool call examples if enabled
- if self.include_tool_call_examples:
- placeholder_message = UserMessage(
- content='<example_1>\nHere is an example output of thinking and tool call. You can use it as a reference but do not copy it exactly.',
- cache=True,
- )
- self._add_message_with_type(placeholder_message)
-
- example_content = dict()
-
- # Add thinking field only if use_thinking is True
- if self.use_thinking:
- example_content[
- 'thinking'
- ] = """I have successfully navigated to https://github.com/explore and can see the page has loaded with a list of featured repositories. The page contains interactive elements and I can identify specific repositories like bytedance/UI-TARS-desktop (index [4]) and ray-project/kuberay (index [5]). The user's request is to explore GitHub repositories and collect information about them such as descriptions, stars, or other metadata. So far, I haven't collected any information.
-My navigation to the GitHub explore page was successful. The page loaded correctly and I can see the expected content.
-I need to capture the key repositories I've identified so far into my memory and into a file.
-Since this appears to be a multi-step task involving visiting multiple repositories and collecting their information, I need to create a structured plan in todo.md.
-After writing todo.md, I can also initialize a github.md file to accumulate the information I've collected.
-The file system actions do not change the browser state, so I can also click on the bytedance/UI-TARS-desktop (index [4]) to start collecting information."""
-
- # Create base example content
- example_content['evaluation_previous_goal'] = 'Navigated to GitHub explore page. Verdict: Success'
- example_content['memory'] = 'Found initial repositories such as bytedance/UI-TARS-desktop and ray-project/kuberay.'
- example_content['next_goal'] = (
- 'Create todo.md checklist to track progress, initialize github.md for collecting information, and click on bytedance/UI-TARS-desktop.'
- )
- example_content['action'] = [
- {
- 'write_file': {
- 'path': 'todo.md',
- 'content': '# Interesting Github Repositories in Explore Section\n\n## Tasks\n- [ ] Initialize a tracking file for GitHub repositories called github.md\n- [ ] Visit each Github repository and find their description\n- [ ] Visit bytedance/UI-TARS-desktop\n- [ ] Visit ray-project/kuberay\n- [ ] Check for additional Github repositories by scrolling down\n- [ ] Compile all results in the requested format\n- [ ] Validate that I have not missed anything in the page\n- [ ] Report final results to user',
- }
- },
- {
- 'write_file': {
- 'path': 'github.md',
- 'content': '# Github Repositories:\n',
- }
- },
- {
- 'click_element_by_index': {
- 'index': 4,
- }
- },
- ]
-
- example_tool_call_1 = AssistantMessage(content=json.dumps(example_content), cache=True)
- self._add_message_with_type(example_tool_call_1)
- self._add_message_with_type(
- UserMessage(
- content='Data written to todo.md.\nData written to github.md.\nClicked element with index 4.\n</example_1>',
- cache=True,
- ),
- )
-
def add_new_task(self, new_task: str) -> None:
self.task = new_task
task_update_item = HistoryItem(system_message=f'User updated <user_request> to: {new_task}')
@@ -355,14 +293,7 @@ The file system actions do not change the browser state, so I can also click on
screenshots=screenshots,
).get_user_message(use_vision)
- self._add_message_with_type(state_message)
-
- def add_plan(self, plan: str | None, position: int | None = None) -> None:
- if not plan:
- return
-
- msg = AssistantMessage(content=plan)
- self._add_message_with_type(msg, position)
+ self._add_message_with_type(state_message, 'state')
def _log_history_lines(self) -> str:
"""Generate a formatted log string of message history for debugging / printing to terminal"""
@@ -407,23 +338,24 @@ The file system actions do not change the browser state, so I can also click on
# Log message history for debugging
logger.debug(self._log_history_lines())
- self.last_input_messages = list(self.state.history.messages)
+ self.last_input_messages = self.state.history.get_messages()
return self.last_input_messages
- def _add_message_with_type(
- self,
- message: BaseMessage,
- position: int | None = None,
- ) -> None:
- """Add message to history
- position: None for last, -1 for second last, etc.
- """
+ def _add_message_with_type(self, message: BaseMessage, message_type: Literal['system', 'state', 'consistent']) -> None:
+ """Add message to history"""
# filter out sensitive data from the message
if self.sensitive_data:
message = self._filter_sensitive_data(message)
- self.state.history.add_message(message, position)
+ if message_type == 'system':
+ self.state.history.system_message = message
+ elif message_type == 'state':
+ self.state.history.state_message = message
+ elif message_type == 'consistent':
+ self.state.history.consistent_messages.append(message)
+ else:
+ raise ValueError(f'Invalid message type: {message_type}')
@time_execution_sync('--filter_sensitive_data')
def _filter_sensitive_data(self, message: BaseMessage) -> BaseMessage:
diff --git a/browser_use/agent/message_manager/views.py b/browser_use/agent/message_manager/views.py
index 8eae88045..ebf5f8569 100644
--- a/browser_use/agent/message_manager/views.py
+++ b/browser_use/agent/message_manager/views.py
@@ -62,20 +62,21 @@ class HistoryItem(BaseModel):
class MessageHistory(BaseModel):
"""History of messages"""
- messages: list[BaseMessage] = Field(default_factory=list)
-
+ system_message: BaseMessage | None = None
+ state_message: BaseMessage | None = None
+ consistent_messages: list[BaseMessage] = Field(default_factory=list)
model_config = ConfigDict(arbitrary_types_allowed=True)
- def add_message(self, message: BaseMessage, position: int | None = None) -> None:
- """Add message to history"""
- if position is None:
- self.messages.append(message)
- else:
- self.messages.insert(position, message)
-
def get_messages(self) -> list[BaseMessage]:
"""Get all messages"""
- return self.messages
+ messages = []
+ if self.system_message:
+ messages.append(self.system_message)
+ if self.state_message:
+ messages.append(self.state_message)
+ messages.extend(self.consistent_messages)
+
+ return messages
class MessageManagerState(BaseModel):
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 132725eb8..58af47913 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -666,7 +666,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
# 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))
+ self._message_manager._add_message_with_type(UserMessage(content=page_action_message), 'consistent')
self.logger.debug(f'💬 Step {self.state.n_steps + 1}: Adding state message to context...')
self._message_manager.add_state_message(
@@ -680,13 +680,6 @@ class Agent(Generic[Context, AgentStructuredOutput]):
agent_history_list=self.state.history, # Pass AgentHistoryList for screenshots
)
- # Run planner at specified intervals if planner is configured
- if self.settings.planner_llm and self.state.n_steps % self.settings.planner_interval == 0:
- self.logger.debug(f'🧠 Step {self.state.n_steps + 1}: Running planner...')
- plan = await self._run_planner()
- # add plan before last state message
- self._message_manager.add_plan(plan, position=-1)
-
if step_info and step_info.is_last_step():
# Add last step warning if needed
msg = 'Now comes your last step. Use only the "done" action now. No other actions - so here your action sequence must have length 1.'
@@ -694,7 +687,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
msg += '\nIf the task is fully finished, set success in "done" to true.'
msg += '\nInclude everything you found out for the ultimate task in the done text.'
self.logger.info('Last step finishing up')
- self._message_manager._add_message_with_type(UserMessage(content=msg))
+ self._message_manager._add_message_with_type(UserMessage(content=msg), 'consistent')
self.AgentOutput = self.DoneAgentOutput
input_messages = self._message_manager.get_messages()