Skip to content

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

First remove state - dont remove old messages

magmuellere326844fa976
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.py
index 73203d005..e687d3038 100644
--- a/browser_use/agent/message_manager/service.py
+++ b/browser_use/agent/message_manager/service.py
@@ -93,21 +93,7 @@ class MessageManager:
if diff <= 0:
return None
- while diff > 0 and len(self.history.messages) > 3:
- # remove message from index 2 (which is the oldest message after system and task) until current message until within max tokens
- msg = self.history.messages[2]
- tokens = msg.metadata.input_tokens
- diff -= tokens
- # update total tokens
- self.history.remove_message(index=2)
- logger.debug(
- f'Removed message with {tokens} tokens - total tokens now: {self.history.total_tokens}/{self.max_input_tokens}'
- )
-
- if diff <= 0:
- return None
-
- msg = self.history.messages[2]
+ msg = self.history.messages[-1]
# if list with image remove image
if isinstance(msg.message.content, list):
@@ -124,7 +110,7 @@ class MessageManager:
elif 'text' in item and isinstance(item, dict):
text += item['text']
msg.message.content = text
- self.history.messages[2] = msg
+ self.history.messages[-1] = msg
if diff <= 0:
return None
@@ -132,13 +118,13 @@ class MessageManager:
# if still over, remove text from state message proportionally to the number of tokens needed with buffer
# Calculate the proportion of content to remove
proportion_to_remove = diff / msg.metadata.input_tokens
- if proportion_to_remove > 1:
+ if proportion_to_remove > 0.99:
raise ValueError(
- f'Max token limit reached - history is too long - reduce the system prompt or task. '
+ f'Max token limit reached - history is too long - reduce the system prompt or task less tasks or remove old messages. '
f'proportion_to_remove: {proportion_to_remove}'
)
logger.debug(
- f'Removing {proportion_to_remove * 100:.2f}% of the last message with {msg.metadata.input_tokens} tokens (removing approx {proportion_to_remove * msg.metadata.input_tokens} tokens)'
+ f'Removing {proportion_to_remove * 100:.2f}% of the last message {proportion_to_remove * msg.metadata.input_tokens:.2f} / {msg.metadata.input_tokens:.2f} tokens)'
)
content = msg.message.content
@@ -146,7 +132,7 @@ class MessageManager:
content = content[:-characters_to_remove]
# remove tokens and old long message
- self.history.remove_message(index=2)
+ self.history.remove_message(index=-1)
# new message with updated content
msg = HumanMessage(content=content)
@@ -155,7 +141,7 @@ class MessageManager:
last_msg = self.history.messages[-1]
logger.debug(
- f'Added message with {last_msg.metadata.input_tokens} tokens - total tokens now: {self.history.total_tokens}/{self.max_input_tokens}'
+ f'Added message with {last_msg.metadata.input_tokens} tokens - total tokens now: {self.history.total_tokens}/{self.max_input_tokens} - total messages: {len(self.history.messages)}'
)
def _add_message_with_tokens(self, message: BaseMessage) -> None:
diff --git a/browser_use/agent/message_manager/tests.py b/browser_use/agent/message_manager/tests.py
index d176c7064..65a913f9d 100644
--- a/browser_use/agent/message_manager/tests.py
+++ b/browser_use/agent/message_manager/tests.py
@@ -143,15 +143,26 @@ def test_token_overflow_handling_with_real_flow(message_manager: MessageManager,
# Add state message
message_manager.add_state_message(state, result)
- last_msg = message_manager.history.messages[-1].message
+ try:
+ messages = message_manager.get_messages()
+ except ValueError as e:
+ if 'Max token limit reached - history is too long' in str(e):
+ return # If error occurs, end the test
+ else:
+ raise e
+
+ assert message_manager.history.total_tokens <= message_manager.max_input_tokens + 100
+
+ last_msg = messages[-1]
assert isinstance(last_msg, HumanMessage)
+
if i % 4 == 0:
assert isinstance(message_manager.history.messages[-2].message, HumanMessage)
if i % 2 == 0 and not i % 4 == 0:
if isinstance(last_msg.content, list):
- assert 'Important content from step' in last_msg.content[0]['text']
+ assert 'Current url: https://test' in last_msg.content[0]['text']
else:
- assert 'Important content from step' in last_msg.content
+ assert 'Current url: https://test' in last_msg.content
# Add model output every time
from browser_use.agent.views import AgentBrain, AgentOutput
@@ -169,10 +180,9 @@ def test_token_overflow_handling_with_real_flow(message_manager: MessageManager,
message_manager.add_model_output(output)
# Get messages and verify after each addition
- messages = message_manager.get_messages()
+ messages = [m.message for m in message_manager.history.messages]
# Verify token limit is respected
- assert message_manager.history.total_tokens <= message_manager.max_input_tokens
# Verify essential messages are preserved
assert isinstance(messages[0], SystemMessage) # System prompt always first
@@ -186,7 +196,7 @@ def test_token_overflow_handling_with_real_flow(message_manager: MessageManager,
# Log token usage for debugging
token_usage = message_manager.history.total_tokens
token_limit = message_manager.max_input_tokens
- print(f'Step {i}: Using {token_usage}/{token_limit} tokens')
+ # print(f'Step {i}: Using {token_usage}/{token_limit} tokens')
# go through all messages and verify that the token count and total tokens is correct
total_tokens = 0
@@ -199,3 +209,6 @@ def test_token_overflow_handling_with_real_flow(message_manager: MessageManager,
assert total_tokens == sum(real_tokens)
assert stored_tokens == real_tokens
assert message_manager.history.total_tokens == total_tokens
+
+
+# pytest -s browser_use/agent/message_manager/tests.py
diff --git a/examples/file_upload.py b/examples/file_upload.py
index 6a64a8a0b..1d6d0c735 100644
--- a/examples/file_upload.py
+++ b/examples/file_upload.py
@@ -38,8 +38,8 @@ async def main():
sites = [
'https://practice.expandtesting.com/upload',
]
- task = f'go to {", ".join(sites)} and Upload my file then subbmit and stop '
- # task = f'go to {" ".join(sites)} each in new tabs and Upload my file then subbmit extract the page content and go to google and find elon musk '
+ # task = f'go to {", ".join(sites)} and Upload my file then subbmit and stop '
+ task = f'go to {" ".join(sites)} each in new tabs and Upload my file then subbmit extract the page content and go to google and find elon musk '
model = ChatOpenAI(model='gpt-4o-mini')
agent = Agent(