Skip to content

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

- Introduce a max_history_items parameter to limit the memory of the model - changed the system messages to have <sys> tag instead of <s> to avoid confusion with HTML - Got rid of MessageMetadata, SupportedMessageTypes and implemented cleaner MessageManagerState - Implemented a HistoryItem class to cleanly reconstruct agent history description

mertunsall2c465a898a2c
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.py
index 32c541d97..504b842d7 100644
--- a/browser_use/agent/message_manager/service.py
+++ b/browser_use/agent/message_manager/service.py
@@ -4,8 +4,7 @@ import json
import logging
from browser_use.agent.message_manager.views import (
- MessageMetadata,
- SupportedMessageTypes,
+ HistoryItem,
)
from browser_use.agent.prompts import AgentMessagePrompt
from browser_use.agent.views import (
@@ -106,6 +105,7 @@ class MessageManager:
include_attributes: list[str] | None = None,
message_context: str | None = None,
sensitive_data: dict[str, str | dict[str, str]] | None = None,
+ max_history_items: int | None = None,
):
self.task = task
self.state = state
@@ -114,6 +114,7 @@ class MessageManager:
self.sensitive_data_description = ''
self.available_file_paths = available_file_paths
self.use_thinking = use_thinking
+ self.max_history_items = max_history_items
# Store settings as direct attributes instead of in a settings object
self.include_attributes = include_attributes or []
@@ -124,16 +125,45 @@ class MessageManager:
if len(self.state.history.messages) == 0:
self._init_messages()
+ @property
+ def agent_history_description(self) -> str:
+ """Build agent history description from list of items, respecting max_history_items limit"""
+ if self.max_history_items is None:
+ # Include all items
+ return '\n'.join(item.to_string() for item in self.state.agent_history_items)
+
+ total_items = len(self.state.agent_history_items)
+
+ # If we have fewer items than the limit, just return all items
+ if total_items <= self.max_history_items:
+ return '\n'.join(item.to_string() for item in self.state.agent_history_items)
+
+ # We have more items than the limit, so we need to omit some
+ omitted_count = total_items - self.max_history_items
+
+ # Show first item + omitted message + most recent (max_history_items - 1) items
+ # The omitted message doesn't count against the limit, only real history items do
+ recent_items_count = self.max_history_items - 1 # -1 for first item
+
+ items_to_include = [
+ self.state.agent_history_items[0].to_string(), # Keep first item (initialization)
+ f'<sys>[... {omitted_count} previous steps omitted...]</sys>',
+ ]
+ # Add most recent items
+ items_to_include.extend([item.to_string() for item in self.state.agent_history_items[-recent_items_count:]])
+
+ 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, message_type='init')
+ self._add_message_with_type(self.system_prompt)
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,
)
# placeholder_message = HumanMessage(content='Example output:')
- self._add_message_with_type(placeholder_message, message_type='init')
+ self._add_message_with_type(placeholder_message)
# Create base example content
example_content = {
@@ -173,18 +203,18 @@ After writing todo.md, I can also initialize a github.md file to accumulate the
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."""
example_tool_call_1 = AssistantMessage(content=json.dumps(example_content), cache=True)
- self._add_message_with_type(example_tool_call_1, message_type='init')
+ 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,
),
- message_type='init',
)
def add_new_task(self, new_task: str) -> None:
self.task = new_task
- self.state.agent_history_description += f'\n<s>User updated <user_request> to: {new_task}</s>\n'
+ task_update_item = HistoryItem(system_message=f'User updated <user_request> to: {new_task}')
+ self.state.agent_history_items.append(task_update_item)
def _update_agent_history_description(
self,
@@ -196,7 +226,7 @@ The file system actions do not change the browser state, so I can also click on
if result is None:
result = []
- step_number = step_info.step_number if step_info else 'unknown'
+ step_number = step_info.step_number if step_info else None
self.state.read_state_description = ''
@@ -220,23 +250,23 @@ The file system actions do not change the browser state, so I can also click on
if action_results:
action_results = f'Action Results:\n{action_results}'
- action_results = action_results.strip('\n')
+ action_results = action_results.strip('\n') if action_results else None
- # Handle case where model_output is None (e.g., parsing failed)
+ # Build the history item
if model_output is None:
- if isinstance(step_number, int) and step_number > 0:
- self.state.agent_history_description += f"""<step_{step_number}>
-Agent failed to output in the right format.
-</step_{step_number}>
-"""
+ # Only add error history item if we have a valid step number
+ if step_number is not None and step_number > 0:
+ history_item = HistoryItem(step_number=step_number, error='Agent failed to output in the right format.')
+ self.state.agent_history_items.append(history_item)
else:
- self.state.agent_history_description += f"""<step_{step_number}>
-Evaluation of Previous Step: {model_output.current_state.evaluation_previous_goal}
-Memory: {model_output.current_state.memory}
-Next Goal: {model_output.current_state.next_goal}
-{action_results}
-</step_{step_number}>
-"""
+ history_item = HistoryItem(
+ step_number=step_number,
+ evaluation_previous_goal=model_output.current_state.evaluation_previous_goal,
+ memory=model_output.current_state.memory,
+ next_goal=model_output.current_state.next_goal,
+ action_results=action_results,
+ )
+ self.state.agent_history_items.append(history_item)
def _get_sensitive_data_description(self, current_page_url) -> str:
sensitive_data = self.sensitive_data
@@ -284,7 +314,7 @@ Next Goal: {model_output.current_state.next_goal}
state_message = AgentMessagePrompt(
browser_state_summary=browser_state_summary,
file_system=self.file_system,
- agent_history_description=self.state.agent_history_description,
+ agent_history_description=self.agent_history_description,
read_state_description=self.state.read_state_description,
task=self.task,
include_attributes=self.include_attributes,
@@ -346,16 +376,15 @@ Next Goal: {model_output.current_state.next_goal}
# Log message history for debugging
logger.debug(self._log_history_lines())
- self.last_input_messages = [m.message for m in self.state.history.messages]
+ self.last_input_messages = list(self.state.history.messages)
return self.last_input_messages
def _add_message_with_type(
self,
message: BaseMessage,
position: int | None = None,
- message_type: SupportedMessageTypes | None = None,
) -> None:
- """Add message with token count metadata
+ """Add message to history
position: None for last, -1 for second last, etc.
"""
@@ -363,8 +392,7 @@ Next Goal: {model_output.current_state.next_goal}
if self.sensitive_data:
message = self._filter_sensitive_data(message)
- metadata = MessageMetadata(message_type=message_type)
- self.state.history.add_message(message, metadata, position)
+ self.state.history.add_message(message, position)
@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 9e605fa34..5e9d91e99 100644
--- a/browser_use/agent/message_manager/views.py
+++ b/browser_use/agent/message_manager/views.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Literal
+from typing import TYPE_CHECKING
from pydantic import BaseModel, ConfigDict, Field
@@ -13,43 +13,81 @@ if TYPE_CHECKING:
pass
-SupportedMessageTypes = Literal['init', 'memory']
-
-
-class MessageMetadata(BaseModel):
- """Metadata for a message"""
-
- message_type: SupportedMessageTypes | None = None
+class HistoryItem:
+ """Represents a single agent history item with its data and string representation"""
+
+ def __init__(
+ self,
+ step_number: int | None = None,
+ evaluation_previous_goal: str | None = None,
+ memory: str | None = None,
+ next_goal: str | None = None,
+ action_results: str | None = None,
+ error: str | None = None,
+ system_message: str | None = None,
+ ):
+ # Validate that error and system_message are not both provided
+ if error is not None and system_message is not None:
+ raise ValueError('Cannot have both error and system_message at the same time')
+
+ self.step_number = step_number
+ self.evaluation_previous_goal = evaluation_previous_goal
+ self.memory = memory
+ self.next_goal = next_goal
+ self.action_results = action_results
+ self.error = error
+ self.system_message = system_message
+
+ def to_string(self) -> str:
+ """Get string representation of the history item"""
+ step_str = f'step_{self.step_number}' if self.step_number is not None else 'step_unknown'
+
+ if self.error:
+ return f"""<{step_str}>
+{self.error}
+</{step_str}>"""
+ elif self.system_message:
+ return f"""<sys>
+{self.system_message}
+</sys>"""
+ else:
+ content_parts = [
+ f'Evaluation of Previous Step: {self.evaluation_previous_goal}',
+ f'Memory: {self.memory}',
+ f'Next Goal: {self.next_goal}',
+ ]
+ if self.action_results:
+ content_parts.append(self.action_results)
-class ManagedMessage(BaseModel):
- """A message with its metadata"""
+ content = '\n'.join(content_parts)
- message: BaseMessage
- metadata: MessageMetadata = Field(default_factory=MessageMetadata)
+ return f"""<{step_str}>
+{content}
+</{step_str}>"""
class MessageHistory(BaseModel):
- """History of messages with metadata"""
+ """History of messages"""
- messages: list[ManagedMessage] = Field(default_factory=list)
+ messages: list[BaseMessage] = Field(default_factory=list)
model_config = ConfigDict(arbitrary_types_allowed=True)
- def add_message(self, message: BaseMessage, metadata: MessageMetadata, position: int | None = None) -> None:
- """Add message with metadata to history"""
+ def add_message(self, message: BaseMessage, position: int | None = None) -> None:
+ """Add message to history"""
if position is None:
- self.messages.append(ManagedMessage(message=message, metadata=metadata))
+ self.messages.append(message)
else:
- self.messages.insert(position, ManagedMessage(message=message, metadata=metadata))
+ self.messages.insert(position, message)
def get_messages(self) -> list[BaseMessage]:
"""Get all messages"""
- return [m.message for m in self.messages]
+ return self.messages
def remove_last_state_message(self) -> None:
"""Remove last state message from history"""
- if len(self.messages) > 2 and isinstance(self.messages[-1].message, UserMessage):
+ if len(self.messages) > 2 and isinstance(self.messages[-1], UserMessage):
self.messages.pop()
@@ -58,7 +96,9 @@ class MessageManagerState(BaseModel):
history: MessageHistory = Field(default_factory=MessageHistory)
tool_id: int = 1
- agent_history_description: str = '<s>Agent initialized</s>\n'
+ agent_history_items: list[HistoryItem] = Field(
+ default_factory=lambda: [HistoryItem(step_number=0, system_message='Agent initialized')]
+ )
read_state_description: str = ''
model_config = ConfigDict(arbitrary_types_allowed=True)
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index d5120923e..e78115fc4 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -169,6 +169,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
],
max_actions_per_step: int = 10,
use_thinking: bool = True,
+ max_history_items: int = 40,
page_extraction_llm: BaseChatModel | None = None,
planner_llm: BaseChatModel | None = None,
planner_interval: int = 1, # Run planner every N steps
@@ -235,12 +236,13 @@ class Agent(Generic[Context, AgentStructuredOutput]):
available_file_paths=available_file_paths,
include_attributes=include_attributes,
max_actions_per_step=max_actions_per_step,
+ use_thinking=use_thinking,
+ max_history_items=max_history_items,
page_extraction_llm=page_extraction_llm,
planner_llm=planner_llm,
planner_interval=planner_interval,
is_planner_reasoning=is_planner_reasoning,
extend_planner_system_message=extend_planner_system_message,
- use_thinking=use_thinking,
calculate_cost=calculate_cost,
)
@@ -318,6 +320,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
include_attributes=self.settings.include_attributes,
message_context=self.settings.message_context,
sensitive_data=sensitive_data,
+ max_history_items=self.settings.max_history_items,
)
if isinstance(browser, BrowserSession):
diff --git a/browser_use/agent/system_prompt.md b/browser_use/agent/system_prompt.md
index 6637facfc..5728328a5 100644
--- a/browser_use/agent/system_prompt.md
+++ b/browser_use/agent/system_prompt.md
@@ -34,7 +34,7 @@ Next Goal: Your goal for this step
Action Results: Your actions and their results
</step_{{step_number}}>
-and system messages wrapped in <s> tag.
+and system messages wrapped in <sys> tag.
</agent_history>
<user_request>
diff --git a/browser_use/agent/system_prompt_no_thinking.md b/browser_use/agent/system_prompt_no_thinking.md
index 36d2c8698..bd16670fe 100644
--- a/browser_use/agent/system_prompt_no_thinking.md
+++ b/browser_use/agent/system_prompt_no_thinking.md
@@ -34,7 +34,7 @@ Next Goal: Your goal for this step
Action Results: Your actions and their results
</step_{{step_number}}>
-and system messages wrapped in <s> tag.
+and system messages wrapped in <sys> tag.
</agent_history>
<user_request>
diff --git a/browser_use/agent/views.py b/browser_use/agent/views.py
index c29482110..6b717d5c1 100644
--- a/browser_use/agent/views.py
+++ b/browser_use/agent/views.py
@@ -54,6 +54,7 @@ class AgentSettings(BaseModel):
]
max_actions_per_step: int = 10
use_thinking: bool = True
+ max_history_items: int = 40
page_extraction_llm: BaseChatModel | None = None
planner_llm: BaseChatModel | None = None