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
Merge branch 'main' into hot-fix/max-token-message-manager
magmueller8aa4321efe60
diff --cc browser_use/agent/service.pyindex 5f92f2aa0,98ed90a56..8e99a90b3--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@@ -81,20 -74,11 +82,20 @@@ 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 variables- self.history: list[AgentHistory] = []+ self.history: AgentHistoryList = AgentHistoryList(history=[])self.n_steps = 1self.consecutive_failures = 0self.max_failures = max_failures@@@ -145,14 -139,13 +145,13 @@@error=result.error,))-- # Update messages with result- self.message_manager.update_with_action_result(result)- self._make_history_item(model_output, state, result)+ if state:+ self._update_messages_with_result(result)+ self._make_history_item(model_output, state, result)- def _handle_step_error(self, error: Exception) -> ActionResult:+ def _handle_step_error(self, error: Exception, state: BrowserState) -> ActionResult:"""Handle all types of errors that can occur during a step"""- error_msg = AgentError.format_error(error)+ error_msg = AgentError.format_error(error, include_trace=True)prefix = f'❌ Result failed {self.consecutive_failures + 1}/{self.max_failures} times:\n 'if isinstance(error, (ValidationError, ValueError)):@@@ -176,58 -176,8 +175,58 @@@) -> None:"""Create and store history item"""history_item = AgentHistory(model_output=model_output, result=result, state=state)- self.history.append(history_item)+ self.history.history.append(history_item)+ @time_execution_sync('--cut_input_messages')+ def _cut_input_messages(self, input_messages: list[BaseMessage]) -> list[BaseMessage]:+ """Cut input messages to max input tokens"""++ # NOTE: Tools are not included in token count for now+ token_count = self._calc_token_count(input_messages)+ # error checking if first and last message are too long together++ # check system message too long+ if token_count[0] > self.max_input_tokens:+ raise ValueError('System message is too long')++ # check current message too long+ if token_count[0] + token_count[-1] > self.max_input_tokens:+ current_message = input_messages[-1]+ system_message = input_messages[0]++ # cut current message+ available_tokens = self.max_input_tokens - token_count[0]++ # binary search to find the longest message that can be cut+ message_content = get_buffer_string([current_message])+ low = 0+ high = len(current_message.content)+ while low < high:+ mid = (low + high) // 2+ if self.llm.get_num_tokens(message_content[:mid]) > available_tokens:+ high = mid+ else:+ low = mid + 1+ current_message.content = current_message.content[:low]+ input_messages = [system_message, current_message]+ self.messages = [system_message]+ return input_messages++ # remove messages from 1 to -2 until token count is less than max input tokens+ while sum(token_count) > self.max_input_tokens:+ token_count.pop(1)+ input_messages.pop(1)+ logger.debug(f'Cutting history message to reduce token count: {input_messages[1]}')++ # update messages+ self.messages = input_messages[:-1]++ return input_messages++ def _calc_token_count(self, messages: list[BaseMessage]) -> list[int]:+ """Calculate token count of messages"""+ return [self.llm.get_num_tokens(get_buffer_string([m])) for m in messages]+@time_execution_async('--get_next_action')async def get_next_action(self, state: BrowserState) -> AgentOutput:"""Get next action from LLM based on current state"""diff --cc browser_use/agent/views.pyindex cc9c32d4d,c329398d8..b06c0be18--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@@ -99,20 -198,10 +199,11 @@@ class AgentErrorNO_VALID_ACTION = 'No valid action found'@staticmethod- def format_error(error: Exception) -> str:- """Format error message based on error type"""+ def format_error(error: Exception, include_trace: bool = False) -> str:+ """Format error message based on error type and optionally include trace"""+ message = ''if isinstance(error, ValidationError):- message = f'{AgentError.VALIDATION_ERROR}\nDetails: {str(error)}'- elif isinstance(error, RateLimitError):- message = AgentError.RATE_LIMIT_ERROR- else:- message = f'Unexpected error: {str(error)}'-- if include_trace:- import traceback-- trace = ''.join(traceback.format_exception(type(error), error, error.__traceback__))- message += f'\nTrace: {trace}'-- return message+ return f'{AgentError.VALIDATION_ERROR}\nDetails: {str(error)}'+ if isinstance(error, RateLimitError):+ return AgentError.RATE_LIMIT_ERROR+ return f'Unexpected error: {str(error)}\nStacktrace:\n{traceback.format_exc()}'diff --cc browser_use/controller/service.pyindex ef9e62d19,bd95e2311..a03e5eff3--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@@ -166,39 -134,29 +134,41 @@@ class Controller@self.registry.action('Scroll down the page by pixel amount - if no amount is specified, scroll down one page',- param_model=ScrollDownAction,+ param_model=ScrollAction,requires_browser=True,)- def scroll_down(params: ScrollDownAction, browser: Browser):- driver = browser._get_driver()+ async def scroll_down(params: ScrollAction, browser: Browser):+ page = await browser.get_current_page()if params.amount is not None:- driver.execute_script(f'window.scrollBy(0, {params.amount});')+ await page.evaluate(f'window.scrollBy(0, {params.amount});')else:- body = driver.find_element(By.TAG_NAME, 'body')- body.send_keys(Keys.PAGE_DOWN)+ await page.keyboard.press('PageDown')+ amount = params.amount if params.amount is not None else 'one page'+ return ActionResult(+ extracted_content=f'Scrolled down the page by {amount} pixels',+ include_in_memory=True,+ )+# scroll up@self.registry.action('Scroll up the page by pixel amount',- param_model=ScrollDownAction,+ param_model=ScrollAction,requires_browser=True,)- def scroll_up(params: ScrollDownAction, browser: Browser):- driver = browser._get_driver()- driver.execute_script(f'window.scrollBy(0, -{params.amount});')+ async def scroll_up(params: ScrollAction, browser: Browser):+ page = await browser.get_current_page()+ if params.amount is not None:+ await page.evaluate(f'window.scrollBy(0, -{params.amount});')+ else:+ await page.keyboard.press('PageUp')+ amount = params.amount if params.amount is not None else 'one page'+ return ActionResult(+ extracted_content=f'Scrolled up the page by {amount} pixels',+ include_in_memory=True,+ )+def action(self, description: str, **kwargs):"""Decorator for registering custom actionsdiff --cc tests/test_stress.pyindex 5b5234775,142e7566e..03dcfc970--- a/tests/test_stress.py+++ b/tests/test_stress.py@@@ -48,63 -21,17 +44,63 @@@ async def controller()yield controllerfinally:if controller.browser:- controller.browser.close(force=True)+ await controller.browser.close(force=True)+async def test_token_limit_with_large_extraction(llm, controller):+ """Test handling of large extracted content exceeding token limit"""+ # Generate large text that will exceed token limit++ agent = Agent(+ task='Concatenate strings a and b with function',+ llm=llm,+ controller=controller,+ max_input_tokens=5000,+ save_conversation_path='tmp/stress_test/test_token_limit_with_large_extraction.json',+ )++ history = await agent.run(max_steps=3)+ actions = [h.model_output.action for h in history if h.model_output]+ assert 'concatenate_strings' in actions+ assert 'done' in actions+++async def test_token_limit_with_multiple_extractions(llm, controller):+ """Test handling of multiple smaller extractions accumulating tokens"""++ agent = Agent(+ task='Give me the special text 5 times',+ 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)+ if history[-1].model_output:+ last_action = history[-1].model_output.action+ assert last_action == 'done'++ # ckeck if 5 times called get_special_text+ calls = [+ h.model_output.action+ for h in history+ if h.model_output and h.model_output.action == 'get_special_text'+ ]+ assert len(calls) == 5++# should get rate limited@pytest.mark.asyncioasync def test_open_10_tabs_and_extract_content(llm, controller):"""Stress test: Open 10 tabs and extract content"""agent = Agent(- task='Open new tabs with example.com, example.net, example.org, and seven more example sites. Then, extract the content from each.',+ task='Open new tabs with example.com, example.net, example.org. 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)