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
Mesage manager cut if too long
magmueller29668a6840fe
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.pyindex d89975c18..193d25114 100644--- a/browser_use/agent/message_manager/service.py+++ b/browser_use/agent/message_manager/service.py@@ -74,8 +74,7 @@ class MessageManager:def _remove_last_state_message(self) -> None:"""Remove last state message from history"""- if self.history.messages:- self.history.messages.pop()+ self.history.remove_last_state_message()def add_model_output(self, model_output: AgentOutput) -> None:"""Add model output as AI message"""@@ -86,8 +85,48 @@ class MessageManager:def get_messages(self) -> List[BaseMessage]:"""Get current message list, potentially trimmed to max tokens"""+ self.cut_messages()return [m.message for m in self.history.messages]+ def cut_messages(self):+ """Get current message list, potentially trimmed to max tokens"""+ diff = self.history.total_tokens - self.max_input_tokens+ if diff <= 0:+ return None+ else:+ 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 or 0+ diff -= tokens+ # update total tokens+ self.history.total_tokens -= tokens+ self.history.messages.pop(2)++ if diff > 0:+ # if still over, remove text from state message proportionally to the number of tokens needed with buffer+ msg = self.history.messages[2]+ tokens_to_remove = diff+ msg_tokens = msg.metadata.input_tokens or 0+ # if image do - 800+ if msg_tokens > 0:+ # Calculate the proportion of content to remove+ proportion_to_remove = tokens_to_remove / msg_tokens+ if proportion_to_remove > 1:+ raise ValueError(+ f'To many tokens - history is too long - reduce the system prompt or task. '+ )+ characters_to_remove = int(len(msg.message.content) * proportion_to_remove)+ if isinstance(msg.message.content, str):+ msg.message.content = msg.message.content[:-characters_to_remove]+ elif isinstance(msg.message.content, list):+ for item in msg.message.content:+ if 'text' in item:+ item['text'] = item['text'][:-characters_to_remove]+ self.history.total_tokens -= diff+ # count real tokens+ msg.metadata.input_tokens = self._count_tokens(msg.message)+def _add_message_with_tokens(self, message: BaseMessage) -> None:"""Add message with token count metadata"""token_count = self._count_tokens(message)diff --git a/browser_use/agent/message_manager/views.py b/browser_use/agent/message_manager/views.pyindex 54b0d777e..8ad0fa5d3 100644--- a/browser_use/agent/message_manager/views.py+++ b/browser_use/agent/message_manager/views.py@@ -34,3 +34,8 @@ class MessageHistory(BaseModel):)if metadata and metadata.total_tokens:self.total_tokens += metadata.total_tokens++ def remove_last_state_message(self) -> None:+ """Remove last state message from history"""+ if self.messages:+ self.messages.pop()diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 3c67f2e80..37aae1eb0 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -14,9 +14,6 @@ from langchain_core.language_models.chat_models import BaseChatModelfrom langchain_core.messages import (AIMessage,BaseMessage,- HumanMessage,- SystemMessage,- get_buffer_string,)from langchain_openai import ChatOpenAIfrom openai import RateLimitError@@ -69,6 +66,7 @@ class Agent:self.use_vision = use_visionself.llm = llmself.save_conversation_path = save_conversation_path+ self._last_result = None# Controller setupself.controller_injected = controller is not None@@ -92,8 +90,6 @@ class Agent:max_input_tokens=self.max_input_tokens,)- self.messages = self.message_manager.get_messages()-# Tracking variablesself.history: AgentHistoryList = AgentHistoryList(history=[])self.n_steps = 1@@ -124,18 +120,28 @@ class Agent:"""Execute one step of the task"""logger.info(f'\n📍 Step {self.n_steps}')state = None+try:state = await self.controller.browser.get_state(use_vision=self.use_vision)- model_output = await self.get_next_action(state)+ self.message_manager.add_state_message(state, self._last_result)+ input_messages = self.message_manager.get_messages()+ model_output = await self.get_next_action(input_messages)+ self.message_manager.add_model_output(model_output)+result = await self.controller.act(model_output.action)+ self._last_result = result+if result.extracted_content:logger.info(f'📄 Result: {result.extracted_content}')if result.is_done:- logger.result(f'{result.extracted_content}')+ logger.info(f'{result.extracted_content}')+self.consecutive_failures = 0except Exception as e:result = self._handle_step_error(e)+ self._last_result = result+model_output = Noneif result.error:@@ -177,17 +183,14 @@ class Agent:self.history.history.append(history_item)@time_execution_async('--get_next_action')- async def get_next_action(self, state: BrowserState) -> AgentOutput:+ async def get_next_action(self, input_messages: list[BaseMessage]) -> AgentOutput:"""Get next action from LLM based on current state"""- new_message = AgentMessagePrompt(state).get_user_message()- input_messages = self.messages + [new_message]structured_llm = self.llm.with_structured_output(self.AgentOutput, include_raw=True)response: dict[str, Any] = await structured_llm.ainvoke(input_messages) # type: ignoreparsed: AgentOutput = response['parsed']- self._update_message_history(parsed)self._log_response(parsed)self._save_conversation(input_messages, parsed)self.n_steps += 1@@ -320,10 +323,6 @@ class Agent:f'🔢 Last Tokens: input: {current_tokens.input_tokens} (cached: {current_tokens.input_token_details.cache_read}) + output: {current_tokens.output_tokens} = {current_tokens.total_tokens} ')- def _update_message_history(self, response: AgentOutput) -> None:- """Update message history with new interactions"""- self.messages.append(AIMessage(content=response.model_dump_json(exclude_unset=True)))-def _log_response(self, response: Any) -> None:"""Log the model's response"""if 'Success' in response.current_state.valuation_previous_goal: