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
Count tool_call tokens and reorder messages
magmuellerd86c47c96b27
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.pyindex 5cd95320a..1513bbe95 100644--- a/browser_use/agent/message_manager/service.py+++ b/browser_use/agent/message_manager/service.py@@ -55,6 +55,8 @@ class MessageManager:self._add_message_with_tokens(system_message)self.system_prompt = system_message+ task_message = self.task_instructions(task)+ self._add_message_with_tokens(task_message)self.tool_id = 1tool_calls = [{@@ -83,8 +85,6 @@ class MessageManager:)self._add_message_with_tokens(tool_message)self.tool_id += 1- task_message = self.task_instructions(task)- self._add_message_with_tokens(task_message)@staticmethoddef task_instructions(task: str) -> HumanMessage:@@ -157,8 +157,54 @@ 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]++ msg = [m.message for m in self.history.messages]+ # debug which messages are in history with token count # log+ total_input_tokens = 0+ logger.debug(f'Messages in history: {len(self.history.messages)}:')+ for m in self.history.messages:+ total_input_tokens += m.metadata.input_tokens+ logger.debug(f'{m.message.__class__.__name__} - Token count: {m.metadata.input_tokens}')+ logger.debug(f'Total input tokens: {total_input_tokens}')++ return msg++ 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)+ self.history.add_message(message, metadata)++ def _count_tokens(self, message: BaseMessage) -> int:+ """Count tokens in a message using the model's tokenizer"""+ tokens = 0+ if isinstance(message.content, list):+ for item in message.content:+ if 'image_url' in item:+ tokens += self.IMG_TOKENS+ elif isinstance(item, dict) and 'text' in item:+ tokens += self._count_text_tokens(item['text'])+ else:+ msg = message.content+ if hasattr(message, 'tool_calls'):+ msg += str(message.tool_calls) # type: ignore+ tokens += self._count_text_tokens(msg)+ return tokens++ def _count_text_tokens(self, text: str) -> int:+ """Count tokens in a text string"""+ if isinstance(self.llm, (ChatOpenAI, ChatAnthropic)):+ try:+ tokens = self.llm.get_num_tokens(text)+ except Exception:+ tokens = (+ len(text) // self.ESTIMATED_TOKENS_PER_CHARACTER+ ) # Rough estimate if no tokenizer available+ else:+ tokens = (+ len(text) // self.ESTIMATED_TOKENS_PER_CHARACTER+ ) # Rough estimate if no tokenizer available+ return tokensdef cut_messages(self):"""Get current message list, potentially trimmed to max tokens"""@@ -193,7 +239,7 @@ class MessageManager:proportion_to_remove = diff / msg.metadata.input_tokensif proportion_to_remove > 0.99:raise ValueError(- f'Max token limit reached - history is too long - reduce the system prompt or task less tasks or remove old messages. '+ f'Max token limit reached - history is too long - reduce the system prompt or task. 'f'proportion_to_remove: {proportion_to_remove}')logger.debug(@@ -216,37 +262,3 @@ class MessageManager:logger.debug(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:- """Add message with token count metadata"""- token_count = self._count_tokens(message)- metadata = MessageMetadata(input_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"""- tokens = 0- if isinstance(message.content, list):- for item in message.content:- if 'image_url' in item:- tokens += self.IMG_TOKENS- elif isinstance(item, dict) and 'text' in item:- tokens += self._count_text_tokens(item['text'])- else:- tokens += self._count_text_tokens(message.content)- return tokens-- def _count_text_tokens(self, text: str) -> int:- """Count tokens in a text string"""- if isinstance(self.llm, (ChatOpenAI, ChatAnthropic)):- try:- tokens = self.llm.get_num_tokens(text)- except Exception:- tokens = (- len(text) // self.ESTIMATED_TOKENS_PER_CHARACTER- ) # Rough estimate if no tokenizer available- else:- tokens = (- len(text) // self.ESTIMATED_TOKENS_PER_CHARACTER- ) # Rough estimate if no tokenizer available- return tokens