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
Work in progress - message manager
magmueller8a90a8855a3f
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.pynew file mode 100644index 000000000..96e86cff8--- /dev/null+++ b/browser_use/agent/message_manager/service.py@@ -0,0 +1,99 @@+from __future__ import annotations++import logging+from datetime import datetime+from typing import List, Optional, Type++from langchain_anthropic import ChatAnthropic+from langchain_core.language_models import BaseChatModel+from langchain_core.messages import (+ AIMessage,+ BaseMessage,+ HumanMessage,+ SystemMessage,+ get_buffer_string,+)+from langchain_openai import ChatOpenAI++from browser_use.agent.message_manager.views import MessageHistory, MessageMetadata+from browser_use.agent.prompts import SystemPrompt+from browser_use.agent.views import ActionResult+from browser_use.browser.views import BrowserState++logger = logging.getLogger(__name__)+++class MessageManager:+ def __init__(+ self,+ llm: BaseChatModel,+ task: str,+ action_descriptions: str,+ system_prompt_class: Type[SystemPrompt],+ max_input_tokens: int = 128000,+ ):+ self.llm = llm+ self.system_prompt_class = system_prompt_class+ self.max_input_tokens = max_input_tokens+ self.history = MessageHistory()+ self.task = task+ self.action_descriptions = action_descriptions++ system_message = self.system_prompt_class(+ self.action_descriptions, current_date=datetime.now()+ ).get_system_message()+ self._add_message_with_tokens(system_message)++ # Add task message+ task_message = HumanMessage(content=f'Your task is: {task}')+ self._add_message_with_tokens(task_message)++ def add_state_message(self, state: BrowserState) -> None:+ """Add browser state as human message"""+ from browser_use.agent.prompts import AgentMessagePrompt++ state_message = AgentMessagePrompt(state).get_user_message()+ self._add_message_with_tokens(state_message)++ def add_model_output(self, model_output: AIMessage) -> None:+ """Add model output as AI message"""+ self._add_message_with_tokens(model_output)++ def update_with_action_result(+ self, result: ActionResult, include_in_state: bool = True+ ) -> None:+ """Update history with action result"""+ if not result.extracted_content and not result.error:+ return++ content = result.extracted_content or result.error+ if content is None:+ return++ if result.include_in_memory:+ message = HumanMessage(content=str(content))+ self._add_message_with_tokens(message)+ elif include_in_state:+ # Update the content of the last state message+ if self.history.messages:+ last_message = self.history.messages[-1].message+ if isinstance(last_message, HumanMessage):+ last_message.content = str(last_message.content) + f'\n{content}'++ def get_messages(self) -> List[BaseMessage]:+ """Get current message list, potentially trimmed to max tokens"""+ return [m.message for m in self.history.messages]++ def _add_message_with_tokens(self, message: BaseMessage) -> None:+ """Add message with token count metadata"""+ token_count = self._count_tokens(message)+ metadata = MessageMetadata(+ input_tokens=token_count, output_tokens=0, total_tokens=token_count+ )+ self.history.add_message(message, metadata)++ def _count_tokens(self, message: BaseMessage) -> int:+ """Count tokens in a message using the model's tokenizer"""+ if isinstance(self.llm, (ChatOpenAI, ChatAnthropic)):+ return self.llm.get_num_tokens(get_buffer_string([message]))+ return len(str(message.content)) // 4 # Rough estimate if no tokenizer availablediff --git a/browser_use/agent/message_manager/views.py b/browser_use/agent/message_manager/views.pynew file mode 100644index 000000000..54b0d777e--- /dev/null+++ b/browser_use/agent/message_manager/views.py@@ -0,0 +1,36 @@+from __future__ import annotations++from typing import List, Optional++from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessage+from pydantic import BaseModel, Field+++class MessageMetadata(BaseModel):+ """Metadata for a message including token counts"""++ input_tokens: Optional[int] = None+ output_tokens: Optional[int] = None+ total_tokens: Optional[int] = None+++class ManagedMessage(BaseModel):+ """A message with its metadata"""++ message: BaseMessage+ metadata: MessageMetadata = Field(default_factory=MessageMetadata)+++class MessageHistory(BaseModel):+ """Container for message history with metadata"""++ messages: List[ManagedMessage] = Field(default_factory=list)+ total_tokens: int = 0++ def add_message(self, message: BaseMessage, metadata: Optional[MessageMetadata] = None) -> None:+ """Add a message with optional metadata"""+ self.messages.append(+ ManagedMessage(message=message, metadata=metadata or MessageMetadata())+ )+ if metadata and metadata.total_tokens:+ self.total_tokens += metadata.total_tokensdiff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 24ebecf97..5f92f2aa0 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -22,6 +22,7 @@ from langchain_openai import ChatOpenAIfrom openai import RateLimitErrorfrom pydantic import BaseModel, ValidationError+from browser_use.agent.message_manager.service import MessageManagerfrom browser_use.agent.prompts import AgentMessagePrompt, SystemPromptfrom browser_use.agent.views import (ActionResult,@@ -80,8 +81,17 @@ class Agent:# Action and output models setupself._setup_action_models()- self.messages = []- self._initialize_messages()+ self.max_input_tokens = max_input_tokens++ self.message_manager = MessageManager(+ llm=self.llm,+ task=self.task,+ action_descriptions=self.controller.registry.get_prompt_description(),+ system_prompt_class=self.system_prompt_class,+ max_input_tokens=self.max_input_tokens,+ )++ self.messages = self.message_manager.get_messages()# Tracking variablesself.history: list[AgentHistory] = []@@ -89,7 +99,6 @@ class Agent:self.consecutive_failures = 0self.max_failures = max_failuresself.retry_delay = retry_delay- self.max_input_tokens = max_input_tokensif save_conversation_path:logger.info(f'Saving conversation to {save_conversation_path}')@@ -109,23 +118,15 @@ class Agent:# Create output model with the dynamic actionsself.AgentOutput = AgentOutput.type_with_custom_actions(self.ActionModel)- def _initialize_messages(self) -> None:- """Initialize message history with system and first message"""- # Get action descriptions from controller's registry- action_descriptions = self.controller.registry.get_prompt_description()- self.system_prompt = self.system_prompt_class(action_descriptions, datetime.now())- self.messages.append(self.system_prompt.get_system_message())- self.set_task(self.task)-- def set_task(self, task: str) -> None:- self.messages.append(HumanMessage(content=f'Your task is: {task}'))-@time_execution_async('--step')async def step(self) -> None:"""Execute one step of the task"""logger.info(f'\n📍 Step {self.n_steps}')state = self.controller.browser.get_state(use_vision=self.use_vision)+ # Add state to messages+ self.message_manager.add_state_message(state)+try:model_output = await self.get_next_action(state)result = self.controller.act(model_output.action)@@ -145,7 +146,8 @@ class Agent:))- self._update_messages_with_result(result)+ # Update messages with result+ self.message_manager.update_with_action_result(result)self._make_history_item(model_output, state, result)def _handle_step_error(self, error: Exception, state: BrowserState) -> ActionResult:@@ -166,19 +168,6 @@ class Agent:return ActionResult(error=error_msg, include_in_memory=True)- def _update_messages_with_result(self, result: ActionResult) -> None:- """Update message history with action results"""- l = len(self.messages)- if result.include_in_memory:- if result.extracted_content:- self.messages.append(HumanMessage(content=result.extracted_content))- if result.error:- self.messages.append(HumanMessage(content=result.error))-- # if no update make empty message- if len(self.messages) == l:- self.messages.append(HumanMessage(content=''))-def _make_history_item(self,model_output: AgentOutput | None,diff --git a/tests/test_stress.py b/tests/test_stress.pyindex 2cbcdee34..5b5234775 100644--- a/tests/test_stress.py+++ b/tests/test_stress.py@@ -57,20 +57,17 @@ async def test_token_limit_with_large_extraction(llm, controller):# Generate large text that will exceed token limitagent = Agent(- task='Concatenate strings times',+ task='Concatenate strings a and b with function',llm=llm,controller=controller,max_input_tokens=5000,- save_conversation_path='tmp/test_token_limit_with_large_extraction.json',+ save_conversation_path='tmp/stress_test/test_token_limit_with_large_extraction.json',)history = await agent.run(max_steps=3)- if history[-1].model_output:- last_action = history[-1].model_output.action- # Verify that messages were properly truncated- assert last_action == 'done'- # Verify the agent didn't crash and completed some steps- assert len(history) > 0+ actions = [h.model_output.action for h in history if h.model_output]+ assert 'concatenate_strings' in actions+ assert 'done' in actions@pytest.mark.asyncio@@ -82,6 +79,7 @@ async def test_token_limit_with_multiple_extractions(llm, controller):llm=llm,controller=controller,max_input_tokens=4000,+ save_conversation_path='tmp/stress_test/test_token_limit_with_multiple_extractions.json',)history = await agent.run(max_steps=10)@@ -106,6 +104,7 @@ async def test_open_10_tabs_and_extract_content(llm, controller):task='Open new tabs with example.com, example.net, example.org, and seven more example sites. Then, extract the content from each.',llm=llm,controller=controller,+ save_conversation_path='tmp/stress_test/test_open_10_tabs_and_extract_content.json',)start_time = time.time()history = await agent.run(max_steps=50)