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
now history is cached
mertunsalleb833d34d90e
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.pyindex 9275b754f..0d37c2f56 100644--- a/browser_use/agent/message_manager/service.py+++ b/browser_use/agent/message_manager/service.py@@ -20,6 +20,7 @@ from browser_use.llm.messages import (BaseMessage,ContentPartTextParam,SystemMessage,+ UserMessage,)from browser_use.observability import observe_debugfrom browser_use.utils import match_url_with_domain_pattern, time_execution_sync@@ -127,43 +128,15 @@ class MessageManager:self.last_input_messages = []# Only initialize messages if state is emptyif len(self.state.history.get_messages()) == 0:- self._add_message_with_type(self.system_prompt, 'system')+ self._set_state_message(self.system_prompt, 'system')- @property- def agent_history_description(self) -> str:- """Build agent history description from list of items, respecting max_history_items limit"""- if self.max_history_items is None:- # Include all items- return '\n'.join(item.to_string() for item in self.state.agent_history_items)-- total_items = len(self.state.agent_history_items)-- # If we have fewer items than the limit, just return all items- if total_items <= self.max_history_items:- return '\n'.join(item.to_string() for item in self.state.agent_history_items)-- # We have more items than the limit, so we need to omit some- omitted_count = total_items - self.max_history_items-- # Show first item + omitted message + most recent (max_history_items - 1) items- # The omitted message doesn't count against the limit, only real history items do- recent_items_count = self.max_history_items - 1 # -1 for first item-- items_to_include = [- self.state.agent_history_items[0].to_string(), # Keep first item (initialization)- f'<sys>[... {omitted_count} previous steps omitted...]</sys>',- ]- # Add most recent items- items_to_include.extend([item.to_string() for item in self.state.agent_history_items[-recent_items_count:]])-- return '\n'.join(items_to_include)+ # Removed agent_history_description property - now using separate cached history messagesdef add_new_task(self, new_task: str) -> None:self.task = new_tasktask_update_item = HistoryItem(system_message=f'User updated <user_request> to: {new_task}')self.state.agent_history_items.append(task_update_item)- @observe_debug(ignore_input=True, ignore_output=True, name='update_agent_history_description')def _update_agent_history_description(self,model_output: AgentOutput | None = None,@@ -245,9 +218,9 @@ class MessageManager:return ''- @observe_debug(ignore_input=True, ignore_output=True, name='add_state_message')- @time_execution_sync('--add_state_message')- def add_state_message(+ @observe_debug(ignore_input=True, ignore_output=True, name='create_state_messages')+ @time_execution_sync('--create_state_messages')+ def create_state_messages(self,browser_state_summary: BrowserStateSummary,model_output: AgentOutput | None = None,@@ -259,8 +232,12 @@ class MessageManager:agent_history_list: AgentHistoryList | None = None, # Pass AgentHistoryList from agentavailable_file_paths: list[str] | None = None, # Always pass current available_file_paths) -> None:- """Add browser state as human message"""+ """Reconstruct all state messages from scratch for optimal caching"""+ # Clear contextual messages from previous steps to prevent accumulation+ self.state.history.context_messages.clear()++ # First, update the agent history items with the latest step resultsself._update_agent_history_description(model_output, result, step_info)if sensitive_data:self.sensitive_data_description = self._get_sensitive_data_description(browser_state_summary.url)@@ -276,12 +253,11 @@ class MessageManager:if browser_state_summary.screenshot:screenshots.append(browser_state_summary.screenshot)- # otherwise add state message and result to next message (which will not stay in memory)+ # Create the message prompt helperassert browser_state_summary- state_message = AgentMessagePrompt(+ message_prompt = AgentMessagePrompt(browser_state_summary=browser_state_summary,file_system=self.file_system,- agent_history_description=self.agent_history_description,read_state_description=self.state.read_state_description,task=self.task,include_attributes=self.include_attributes,@@ -290,9 +266,28 @@ class MessageManager:sensitive_data=self.sensitive_data_description,available_file_paths=available_file_paths,screenshots=screenshots,- ).get_user_message(use_vision)+ )++ # Fully reconstruct all messages every time for optimal caching:++ # 1. Rebuild cached history messages from history items+ self._rebuild_history_messages()++ # 2. Create fresh agent state message (not cached - changes every step)+ agent_state_message = message_prompt.get_agent_state_message()- self._add_message_with_type(state_message, 'state')+ # 3. Create fresh browser state message with vision (not cached - changes every step)+ browser_state_message = message_prompt.get_browser_state_message(use_vision)++ # 4. Create fresh read state message (cached - only changes when new content extracted)+ read_state_message = message_prompt.get_read_state_message()++ # Replace all state messages+ self._set_state_message(agent_state_message, 'agent_state')+ self._set_state_message(browser_state_message, 'browser_state')+ # read state message is optional+ if read_state_message:+ self._set_state_message(read_state_message, 'read_state')def _log_history_lines(self) -> str:"""Generate a formatted log string of message history for debugging / printing to terminal"""@@ -340,21 +335,66 @@ class MessageManager:self.last_input_messages = self.state.history.get_messages()return self.last_input_messages- def _add_message_with_type(self, message: BaseMessage, message_type: Literal['system', 'state', 'consistent']) -> None:- """Add message to history"""+ def _create_history_message_from_item(self, item: HistoryItem) -> UserMessage:+ """Convert a HistoryItem into a cached UserMessage"""+ content = item.to_string()+ return UserMessage(content=content, cache=True)++ def _rebuild_history_messages(self) -> None:+ """Rebuild the history messages from agent_history_items, respecting max_history_items limit"""+ history_items = self.state.agent_history_items+ if self.max_history_items is None:+ # Include all items+ items_to_include = history_items+ else:+ total_items = len(history_items)++ # If we have fewer items than the limit, just return all items+ if total_items <= self.max_history_items:+ items_to_include = history_items+ else:+ # We have more items than the limit, so we need to omit some+ omitted_count = total_items - self.max_history_items+ recent_items_count = self.max_history_items - 1 # -1 for first item++ # Include first item + most recent items+ items_to_include = [history_items[0]] + history_items[-recent_items_count:]++ # Create an omitted message and insert it between first and recent items+ if omitted_count > 0:+ omitted_item = HistoryItem(system_message=f'[... {omitted_count} previous steps omitted...]')+ items_to_include = [history_items[0], omitted_item] + history_items[-recent_items_count:]++ # Convert items to cached messages+ self.state.history.history_messages = [self._create_history_message_from_item(item) for item in items_to_include]++ def _set_state_message(+ self, message: BaseMessage, message_type: Literal['system', 'agent_state', 'browser_state', 'read_state']+ ) -> None:+ """Replace a specific state message slot with a new message"""# filter out sensitive data from the messageif self.sensitive_data:message = self._filter_sensitive_data(message)if message_type == 'system':self.state.history.system_message = message- elif message_type == 'state':- self.state.history.state_message = message- elif message_type == 'consistent':- self.state.history.consistent_messages.append(message)+ elif message_type == 'agent_state':+ self.state.history.agent_state_message = message+ elif message_type == 'browser_state':+ self.state.history.browser_state_message = message+ elif message_type == 'read_state':+ self.state.history.read_state_message = messageelse:- raise ValueError(f'Invalid message type: {message_type}')+ raise ValueError(f'Invalid state message type: {message_type}')++ def _add_context_message(self, message: BaseMessage) -> None:+ """Add a contextual message that persists across steps (e.g., page-specific actions, final step warnings)"""+ # filter out sensitive data from the message+ if self.sensitive_data:+ message = self._filter_sensitive_data(message)++ self.state.history.context_messages.append(message)@time_execution_sync('--filter_sensitive_data')def _filter_sensitive_data(self, message: BaseMessage) -> BaseMessage:diff --git a/browser_use/agent/message_manager/views.py b/browser_use/agent/message_manager/views.pyindex 587a692a1..f5b2d8885 100644--- a/browser_use/agent/message_manager/views.py+++ b/browser_use/agent/message_manager/views.py@@ -71,18 +71,26 @@ class MessageHistory(BaseModel):"""History of messages"""system_message: BaseMessage | None = None- state_message: BaseMessage | None = None- consistent_messages: list[BaseMessage] = Field(default_factory=list)+ history_messages: list[BaseMessage] = Field(default_factory=list)+ agent_state_message: BaseMessage | None = None+ browser_state_message: BaseMessage | None = None+ read_state_message: BaseMessage | None = None+ context_messages: list[BaseMessage] = Field(default_factory=list)model_config = ConfigDict(arbitrary_types_allowed=True)def get_messages(self) -> list[BaseMessage]:- """Get all messages"""+ """Get all messages in the correct order: system -> history -> agent_state -> browser_state -> read_state -> contextual"""messages = []if self.system_message:messages.append(self.system_message)- if self.state_message:- messages.append(self.state_message)- messages.extend(self.consistent_messages)+ messages.extend(self.history_messages)+ if self.agent_state_message:+ messages.append(self.agent_state_message)+ if self.browser_state_message:+ messages.append(self.browser_state_message)+ if self.read_state_message:+ messages.append(self.read_state_message)+ messages.extend(self.context_messages)return messagesdiff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.pyindex 2b8a8bbdb..95b86bfe8 100644--- a/browser_use/agent/prompts.py+++ b/browser_use/agent/prompts.py@@ -79,7 +79,6 @@ class AgentMessagePrompt:self,browser_state_summary: 'BrowserStateSummary',file_system: 'FileSystem',- agent_history_description: str | None = None,read_state_description: str | None = None,task: str | None = None,include_attributes: list[str] | None = None,@@ -92,7 +91,6 @@ class AgentMessagePrompt:):self.browser_state: 'BrowserStateSummary' = browser_state_summaryself.file_system: 'FileSystem | None' = file_system- self.agent_history_description: str | None = agent_history_descriptionself.read_state_description: str | None = read_state_descriptionself.task: str | None = taskself.include_attributes = include_attributes@@ -104,7 +102,6 @@ class AgentMessagePrompt:self.screenshots = screenshots or []assert self.browser_state- @observe_debug(ignore_input=True, ignore_output=True, name='_deduplicate_screenshots')def _deduplicate_screenshots(self, screenshots: list[str]) -> list[str]:"""Remove consecutive duplicate screenshots, keeping only the most recent of each.@@ -134,7 +131,6 @@ class AgentMessagePrompt:return unique_screenshots- @observe_debug(ignore_input=True, ignore_output=True, name='_get_browser_state_description')def _get_browser_state_description(self) -> str:elements_text = self.browser_state.element_tree.clickable_elements_to_string(include_attributes=self.include_attributes)@@ -237,8 +233,13 @@ Interactive elements from top layer of the current page inside the viewport{trunagent_state += '<available_file_paths>\n' + '\n'.join(self.available_file_paths) + '\n</available_file_paths>\n'return agent_state- @observe_debug(ignore_input=True, ignore_output=True, name='get_user_message')- def get_user_message(self, use_vision: bool = True) -> UserMessage:+ def get_agent_state_message(self) -> UserMessage:+ """Get agent state as a separate message (not cached - changes every step)"""+ agent_state_content = '<agent_state>\n' + self._get_agent_state_description().strip('\n') + '\n</agent_state>'+ return UserMessage(content=agent_state_content, cache=False)++ def get_browser_state_message(self, use_vision: bool = True) -> UserMessage:+ """Get browser state as a separate message, optionally with screenshots"""# Don't pass screenshot to model if page is a new tab page, step is 0, and there's only one tabif (is_new_tab_page(self.browser_state.url)@@ -248,25 +249,16 @@ Interactive elements from top layer of the current page inside the viewport{trun):use_vision = False- state_description = (- '<agent_history>\n'- + (self.agent_history_description.strip('\n') if self.agent_history_description else '')- + '\n</agent_history>\n'- )- state_description += '<agent_state>\n' + self._get_agent_state_description().strip('\n') + '\n</agent_state>\n'- state_description += '<browser_state>\n' + self._get_browser_state_description().strip('\n') + '\n</browser_state>\n'- state_description += (- '<read_state>\n'- + (self.read_state_description.strip('\n') if self.read_state_description else '')- + '\n</read_state>\n'- )+ browser_state_content = '<browser_state>\n' + self._get_browser_state_description().strip('\n') + '\n</browser_state>'+if self.page_filtered_actions:- state_description += 'For this page, these additional actions are available:\n'- state_description += self.page_filtered_actions + '\n'+ browser_state_content += '\n<page_specific_actions>\n'+ browser_state_content += self.page_filtered_actions + '\n'+ browser_state_content += '</page_specific_actions>\n'if use_vision is True and self.screenshots:# Start with text description- content_parts: list[ContentPartTextParam | ContentPartImageParam] = [ContentPartTextParam(text=state_description)]+ content_parts: list[ContentPartTextParam | ContentPartImageParam] = [ContentPartTextParam(text=browser_state_content)]# Deduplicate screenshots, keeping only the most recent of each unique imageunique_screenshots = self._deduplicate_screenshots(self.screenshots)@@ -292,6 +284,44 @@ Interactive elements from top layer of the current page inside the viewport{trun))- return UserMessage(content=content_parts)+ return UserMessage(content=content_parts, cache=False)++ return UserMessage(content=browser_state_content, cache=False)++ def get_read_state_message(self) -> UserMessage | None:+ """Get read state as a separate cached message"""+ if not self.read_state_description:+ return None+ if not self.read_state_description.strip('\n').strip():+ return None++ read_state_content = '<read_state>\n' + self.read_state_description.strip('\n') + '\n</read_state>'+ return UserMessage(content=read_state_content, cache=False)++ @observe_debug(ignore_input=True, ignore_output=True, name='get_user_message')+ def get_user_message(self, use_vision: bool = True) -> UserMessage:+ """+ DEPRECATED: This method is kept for backward compatibility but should not be used.+ Use get_agent_state_message(), get_browser_state_message(), and get_read_state_message() instead.+ """+ # For backward compatibility, return all messages concatenated in a single message+ agent_state_message = self.get_agent_state_message()+ browser_state_message = self.get_browser_state_message(use_vision)+ read_state_message = self.get_read_state_message()++ # Flatten the three message objects into a single list of content parts,+ # handling both raw-text (`str`) and already-structured (`list[...]`) cases.+ content_parts: list[ContentPartTextParam | ContentPartImageParam] = []++ for msg in (agent_state_message, browser_state_message, read_state_message):+ if msg is None:+ continue++ if isinstance(msg.content, list):+ # Message is already a list of content parts – reuse as-is.+ content_parts.extend(msg.content)+ else:+ # Wrap plain text in a ContentPartTextParam.+ content_parts.append(ContentPartTextParam(text=str(msg.content)))- return UserMessage(content=state_description)+ return UserMessage(content=content_parts, cache=True)diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 6f5cbd9a6..df6b7fbcf 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -710,13 +710,9 @@ class Agent(Generic[Context, AgentStructuredOutput]):# Get page-specific filtered actionspage_filtered_actions = self.controller.registry.get_prompt_description(current_page)- # If there are page-specific actions, add them as a special message for this step only- if page_filtered_actions:- page_action_message = f'For this page, these additional actions are available:\n{page_filtered_actions}'- self._message_manager._add_message_with_type(UserMessage(content=page_action_message), 'consistent')-- self.logger.debug(f'💬 Step {self.state.n_steps + 1}: Adding state message to context...')- self._message_manager.add_state_message(+ # Page-specific actions will be included directly in the browser_state message+ self.logger.debug(f'💬 Step {self.state.n_steps + 1}: Creating state messages for context...')+ self._message_manager.create_state_messages(browser_state_summary=browser_state_summary,model_output=self.state.last_model_output,result=self.state.last_result,@@ -881,7 +877,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):msg += '\nIf the task is fully finished, set success in "done" to true.'msg += '\nInclude everything you found out for the ultimate task in the done text.'self.logger.info('Last step finishing up')- self._message_manager._add_message_with_type(UserMessage(content=msg), 'consistent')+ self._message_manager._add_context_message(UserMessage(content=msg))self.AgentOutput = self.DoneAgentOutputasync def _get_model_output_with_retry(self, input_messages: list[BaseMessage]) -> AgentOutput:diff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex c5f1e210b..975234cfb 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -4,7 +4,10 @@ import jsonimport loggingimport osimport re-from typing import Generic, TypeVar, cast+from typing import TYPE_CHECKING, Generic, TypeVar, cast++if TYPE_CHECKING:+ from browser_use.browser.types import Pagetry:from lmnr import Laminar # type: ignore@@ -15,7 +18,6 @@ from pydantic import BaseModelfrom browser_use.agent.views import ActionModel, ActionResultfrom browser_use.browser import BrowserSession-from browser_use.browser.types import Pagefrom browser_use.browser.views import BrowserErrorfrom browser_use.controller.registry.service import Registryfrom browser_use.controller.views import (@@ -296,7 +298,7 @@ Only use this for specific queries for information retrieval from the page. Don'async def extract_structured_data(query: str,extract_links: bool,- page: Page,+ page: 'Page',page_extraction_llm: BaseChatModel,file_system: FileSystem,):@@ -609,7 +611,7 @@ Explain the content of the page and that the requested information is not availa'Send strings of special keys to use Playwright page.keyboard.press - examples include Escape, Backspace, Insert, PageDown, Delete, Enter, or Shortcuts such as `Control+o`, `Control+Shift+T`',param_model=SendKeysAction,)- async def send_keys(params: SendKeysAction, page: Page):+ async def send_keys(params: SendKeysAction, page: 'Page'):try:await page.keyboard.press(params.keys)except Exception as e:@@ -630,7 +632,7 @@ Explain the content of the page and that the requested information is not availa@self.registry.action(description='Scroll to a text in the current page',)- async def scroll_to_text(text: str, page: Page): # type: ignore+ async def scroll_to_text(text: str, page: 'Page'): # type: ignoretry:# Try different locator strategieslocators = [@@ -913,7 +915,7 @@ Explain the content of the page and that the requested information is not availaraise BrowserError(msg)@self.registry.action('Google Sheets: Get the contents of the entire sheet', domains=['https://docs.google.com'])- async def read_sheet_contents(page: Page):+ async def read_sheet_contents(page: 'Page'):# select all cellsawait page.keyboard.press('Enter')await page.keyboard.press('Escape')@@ -979,7 +981,7 @@ Explain the content of the page and that the requested information is not availa)@self.registry.action('Google Sheets: Select a specific cell or range of cells', domains=['https://docs.google.com'])- async def select_cell_or_range(cell_or_range: str, page: Page):+ async def select_cell_or_range(cell_or_range: str, page: 'Page'):await page.keyboard.press('Enter') # make sure we dont delete current cell contents if we were last editingawait page.keyboard.press('Escape') # to clear current focus (otherwise select range popup is additive)await asyncio.sleep(0.1)@@ -1003,7 +1005,7 @@ Explain the content of the page and that the requested information is not availa'Google Sheets: Fallback method to type text into (only one) currently selected cell',domains=['https://docs.google.com'],)- async def fallback_input_into_single_selected_cell(text: str, page: Page):+ async def fallback_input_into_single_selected_cell(text: str, page: 'Page'):await page.keyboard.type(text, delay=0.1)await page.keyboard.press('Enter') # make sure to commit the input so it doesn't get overwritten by the next actionawait page.keyboard.press('ArrowUp')diff --git a/browser_use/llm/tests/test_single_step.py b/browser_use/llm/tests/test_single_step.pyindex 10c0c0a94..3613b5e07 100644--- a/browser_use/llm/tests/test_single_step.py+++ b/browser_use/llm/tests/test_single_step.py@@ -70,7 +70,6 @@ def create_mock_state_message(temp_dir: str):agent_prompt = AgentMessagePrompt(browser_state_summary=mock_browser_state,file_system=mock_file_system, # Now using actual FileSystem instance- agent_history_description='', # Empty historyread_state_description='', # Empty read statetask='Click the button on the page',include_attributes=['id'],@@ -111,7 +110,7 @@ async def test_single_step_parametrized(llm_class, model_name):# Create mock state messagemock_message = create_mock_state_message(temp_dir)- agent.message_manager._add_message_with_type(mock_message, 'state')+ agent.message_manager._set_state_message(mock_message, 'agent_state')messages = agent.message_manager.get_messages()@@ -152,7 +151,7 @@ async def test_single_step():print(mock_message.content)print('\n' + '=' * 50 + '\n')- agent.message_manager._add_message_with_type(mock_message, 'state')+ agent.message_manager._set_state_message(mock_message, 'agent_state')messages = agent.message_manager.get_messages()