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
Include state manager
magmueller2786152e5831
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.pyindex 96e86cff8..d89975c18 100644--- a/browser_use/agent/message_manager/service.py+++ b/browser_use/agent/message_manager/service.py@@ -16,14 +16,21 @@ from langchain_core.messages import (from langchain_openai import ChatOpenAIfrom 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.agent.prompts import AgentMessagePrompt, SystemPrompt+from browser_use.agent.views import ActionResult, AgentOutputfrom browser_use.browser.views import BrowserStatelogger = logging.getLogger(__name__)class MessageManager:+ # system prompt+ # task message+ # state message+ # model output+ # state message+ # model output+ # state messagedef __init__(self,llm: BaseChatModel,@@ -48,37 +55,34 @@ class MessageManager:task_message = HumanMessage(content=f'Your task is: {task}')self._add_message_with_tokens(task_message)- def add_state_message(self, state: BrowserState) -> None:+ def add_state_message(self, state: BrowserState, result: Optional[ActionResult] = None) -> 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:+ # if keep in memory, add to directly to history and add state without result+ if result and result.include_in_memory:+ if result.extracted_content:+ msg = HumanMessage(content=str(result.extracted_content))+ self._add_message_with_tokens(msg)+ if result.error:+ msg = HumanMessage(content=str(result.error))+ self._add_message_with_tokens(msg)+ result = None+ # otherwise add state message and result to next message (which will not stay in memory)+ else:+ state_message = AgentMessagePrompt(state, result).get_user_message()+ self._add_message_with_tokens(state_message)++ def _remove_last_state_message(self) -> None:+ """Remove last state message from history"""+ if self.history.messages:+ self.history.messages.pop()++ def add_model_output(self, model_output: AgentOutput) -> 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}'+ self._remove_last_state_message()+ content = model_output.model_dump_json(exclude_unset=True)+ msg = AIMessage(content=content)+ self._add_message_with_tokens(msg)def get_messages(self) -> List[BaseMessage]:"""Get current message list, potentially trimmed to max tokens"""@@ -94,6 +98,15 @@ class MessageManager:def _count_tokens(self, message: BaseMessage) -> int:"""Count tokens in a message using the model's tokenizer"""+ tokens = 0if 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 available+ try:+ tokens = self.llm.get_num_tokens(get_buffer_string([message]))+ except Exception as e:+ tokens = len(str(message.content)) // 4 # Rough estimate if no tokenizer available+ logger.warning(+ f'Error counting tokens: {e} - using estimate of characters/4 tokens'+ )+ else:+ tokens = len(str(message.content)) // 4 # Rough estimate if no tokenizer available+ return tokensdiff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.pyindex 6411a5566..60b343226 100644--- a/browser_use/agent/prompts.py+++ b/browser_use/agent/prompts.py@@ -1,7 +1,9 @@from datetime import datetime+from typing import Optionalfrom langchain_core.messages import HumanMessage, SystemMessage+from browser_use.agent.views import ActionResultfrom browser_use.browser.views import BrowserState@@ -99,8 +101,9 @@ IMPORTANT RULES:class AgentMessagePrompt:- def __init__(self, state: BrowserState):+ def __init__(self, state: BrowserState, result: Optional[ActionResult] = None):self.state = state+ self.result = resultdef get_user_message(self) -> HumanMessage:state_description = f"""@@ -111,6 +114,12 @@ Interactive elements:{self.state.dom_items_to_string()}"""+ if self.result:+ if self.result.extracted_content:+ state_description += f'\nResult of last action: {self.result.extracted_content}'+ if self.result.error:+ state_description += f'\nError of last action: {self.result.error}'+if self.state.screenshot:# Format message for vision modelreturn HumanMessage(