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
History is saved and loaded
magmuellerde7e38b75c20
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 4afe62d24..56868e2d4 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -177,7 +177,19 @@ class Agent:result: ActionResult,) -> None:"""Create and store history item"""+ selector_map = state.selector_map+ model_output = model_output+ if model_output and selector_map:+ interacted_element = AgentHistory.get_interacted_element(model_output, selector_map)+ else:+ interacted_element = None++ state.interacted_element = interacted_element+ state.element_tree = None+ state.selector_map = None+history_item = AgentHistory(model_output=model_output, result=result, state=state)+self.history.history.append(history_item)@time_execution_async('--get_next_action')diff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex 87c14a5e5..704c7b981 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -10,6 +10,12 @@ from pydantic import BaseModel, ConfigDict, Field, ValidationError, create_modelfrom browser_use.browser.views import BrowserStatefrom browser_use.controller.registry.views import ActionModel+from browser_use.dom.history_tree_processor import (+ DOMElementNode,+ DOMHistoryElement,+ HistoryTreeProcessor,+)+from browser_use.dom.views import SelectorMapclass ActionResult(BaseModel):@@ -60,13 +66,40 @@ class AgentHistory(BaseModel):model_config = ConfigDict(arbitrary_types_allowed=True, protected_namespaces=())+ @staticmethod+ def get_interacted_element(+ model_output: AgentOutput, selector_map: SelectorMap+ ) -> DOMHistoryElement | None:+ if model_output:+ # check if action has index param+ action_values = model_output.action.model_dump(exclude_unset=True).values()+ params = next(iter(action_values))++ index_exists = 'index' in params+ if index_exists:+ index = params['index']+ el: DOMElementNode = selector_map[index]+ return HistoryTreeProcessor.convert_dom_element_to_history_element(el)++ return None+def model_dump(self, **kwargs) -> Dict[str, Any]:- """Custom serialization to handle dynamic ActionModel"""- data = super().model_dump(**kwargs)+ """Custom serialization handling circular references"""++ # Handle action serialization+ model_output_dump = Noneif self.model_output:- # Serialize model_output directly using its own dump method- data['model_output'] = self.model_output.model_dump(**kwargs)- return data+ action_dump = self.model_output.action.model_dump(exclude_none=True)+ model_output_dump = {+ 'current_state': self.model_output.current_state.model_dump(),+ 'action': action_dump, # This preserves the actual action data+ }++ return {+ 'model_output': model_output_dump,+ 'result': self.result.model_dump(exclude_none=True),+ 'state': self.state.to_dict(),+ }class AgentHistoryList(BaseModel):@@ -82,18 +115,20 @@ class AgentHistoryList(BaseModel):"""Representation of the AgentHistoryList object"""return self.__str__()- def model_dump(self, **kwargs) -> Dict[str, Any]:- """Custom serialization to handle nested AgentHistory items"""- data = super().model_dump(**kwargs)- # Manually serialize each history item using its custom model_dump- data['history'] = [h.model_dump(**kwargs) if h else None for h in self.history]- return data-def save_to_file(self, filepath: str | Path) -> None:"""Save history to JSON file with proper serialization"""- data = self.model_dump(exclude_none=True)- with open(filepath, 'w', encoding='utf-8') as f:- json.dump(data, f, indent=2)+ try:+ data = self.model_dump()+ with open(filepath, 'w', encoding='utf-8') as f:+ json.dump(data, f, indent=2)+ except Exception as e:+ raise e++ def model_dump(self, **kwargs) -> Dict[str, Any]:+ """Custom serialization that properly uses AgentHistory's model_dump"""+ return {+ 'history': [h.model_dump(**kwargs) for h in self.history],+ }@classmethoddef load_from_file(@@ -105,8 +140,16 @@ class AgentHistoryList(BaseModel):# loop through history and validate output_model actions to enrich with custom actionsfor h in data['history']:if h['model_output']:- h['model_output'] = output_model.model_validate(h['model_output'])- return cls.model_validate(data)+ if isinstance(h['model_output'], dict):+ h['model_output'] = output_model.model_validate(h['model_output'])+ else:+ h['model_output'] = None+ h['state']['selector_map'] = None+ h['state']['element_tree'] = None+ if 'interacted_element' not in h['state']:+ h['state']['interacted_element'] = None+ history = cls.model_validate(data)+ return historydef last_action(self) -> None | dict:"""Last action in history"""@@ -158,21 +201,10 @@ class AgentHistoryList(BaseModel):def model_actions(self) -> list[dict]:"""Get all actions from history"""outputs = []+for h in self.history:if h.model_output:output = h.model_output.action.model_dump(exclude_none=True)- # should have only one key and param_model- keys = list(output.keys())- assert len(keys) == 1, 'should have only one key'- key = keys[0]- params = output[key]-- # convert index to xpath if available- if 'index' in params:- selector_map = h.state.selector_map- index = params['index']- if index in selector_map:- params['xpath'] = selector_map[index]outputs.append(output)return outputsdiff --git a/browser_use/browser/service.py b/browser_use/browser/service.pyindex e72089950..3202060fb 100644--- a/browser_use/browser/service.py+++ b/browser_use/browser/service.py@@ -75,6 +75,7 @@ class Browser:title=await page.title(),screenshot=None,tabs=[],+ interacted_element=None,)self.session = BrowserSession(@@ -326,6 +327,7 @@ class Browser:title=await page.title(),tabs=await self.get_tabs_info(),screenshot=screenshot_b64,+ interacted_element=content.interacted_element,)return self.current_statediff --git a/browser_use/browser/tests/test_clicks.py b/browser_use/browser/tests/test_clicks.pyindex 3c66205d9..c89dab994 100644--- a/browser_use/browser/tests/test_clicks.py+++ b/browser_use/browser/tests/test_clicks.py@@ -8,6 +8,7 @@ from browser_use.dom.views import ElementTreeSerializerfrom browser_use.utils import time_execution_sync+# run with: pytest browser_use/browser/tests/test_clicks.py@pytest.mark.asyncioasync def test_highlight_elements():browser = Browser(headless=False, keep_open=False, disable_security=True)@@ -18,7 +19,8 @@ async def test_highlight_elements():page = await browser.get_current_page()# await page.goto('https://immobilienscout24.de')- await page.goto('https://help.sap.com/docs/sap-ai-core/sap-ai-core-service-guide/service-plans')+ # await page.goto('https://help.sap.com/docs/sap-ai-core/sap-ai-core-service-guide/service-plans')+ await page.goto('https://google.com/search?q=elon+musk')# await page.goto('https://kayak.com')# await page.goto('https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_iframe')diff --git a/browser_use/browser/views.py b/browser_use/browser/views.pyindex 0e1ab239f..be801c24e 100644--- a/browser_use/browser/views.py+++ b/browser_use/browser/views.py@@ -1,5 +1,5 @@from dataclasses import dataclass-from typing import Optional+from typing import Any, Optionalfrom pydantic import BaseModel@@ -22,14 +22,15 @@ class BrowserState(DOMState):tabs: list[TabInfo]screenshot: Optional[str] = None- # def model_dump(self) -> dict:- # dump = super().model_dump()- # # Add a summary of available tabs- # if self.tabs:- # dump['available_tabs'] = [- # f'Tab {i+1}: {tab.title} ({tab.url})' for i, tab in enumerate(self.tabs)- # ]- # return dump+ def to_dict(self) -> dict[str, Any]:+ data = {}+ data['tabs'] = [tab.model_dump() for tab in self.tabs]+ data['screenshot'] = self.screenshot+ data['element_tree'] = None+ data['interacted_element'] = None+ data['url'] = self.url+ data['title'] = self.title+ return dataclass BrowserError(Exception):diff --git a/browser_use/dom/history_tree_processor.py b/browser_use/dom/history_tree_processor.pyindex 5a98e1838..c01ccc238 100644--- a/browser_use/dom/history_tree_processor.py+++ b/browser_use/dom/history_tree_processor.py@@ -25,6 +25,16 @@ class DOMHistoryElement:attributes: dict[str, str]shadow_root: bool = False+ def model_dump(self) -> dict:+ return {+ 'tag_name': self.tag_name,+ 'xpath': self.xpath,+ 'highlight_index': self.highlight_index,+ 'entire_parent_branch_path': self.entire_parent_branch_path,+ 'attributes': self.attributes,+ 'shadow_root': self.shadow_root,+ }+class HistoryTreeProcessor:""" "diff --git a/browser_use/dom/service.py b/browser_use/dom/service.pyindex 6058bd13d..0d7751a31 100644--- a/browser_use/dom/service.py+++ b/browser_use/dom/service.py@@ -24,7 +24,9 @@ class DomService:element_tree = await self._build_dom_tree(highlight_elements)selector_map = self._create_selector_map(element_tree)- return DOMState(element_tree=element_tree, selector_map=selector_map)+ return DOMState(+ element_tree=element_tree, selector_map=selector_map, interacted_element=None+ )async def _build_dom_tree(self, highlight_elements: bool) -> DOMElementNode:with open('browser_use/dom/buildDomTree.js', 'r') as f:diff --git a/browser_use/dom/views.py b/browser_use/dom/views.pyindex 53895b79a..8936c0001 100644--- a/browser_use/dom/views.py+++ b/browser_use/dom/views.py@@ -140,8 +140,11 @@ class ElementTreeSerializer:SelectorMap = dict[int, DOMElementNode]+from browser_use.dom.history_tree_processor import DOMHistoryElement+@dataclassclass DOMState:- element_tree: DOMElementNode- selector_map: SelectorMap+ element_tree: DOMElementNode | None+ interacted_element: DOMHistoryElement | None+ selector_map: SelectorMap | Nonediff --git a/examples/flight_search.py b/examples/flight_search.pyindex de16c15e4..6018b7eb0 100644--- a/examples/flight_search.py+++ b/examples/flight_search.py@@ -23,6 +23,13 @@ from browser_use.agent.views import AgentOutputllm = ChatOpenAI(model='gpt-4o-mini')controller = Controller(keep_open=False)++[email protected](description='Prints the secret text')+async def secret_text(secret_text: str) -> None:+ print(secret_text)++agent = Agent(# task='Find flights on kayak.com from Zurich to Beijing on 25.12.2024 to 02.02.2025',task='Search for elon musk on google and click the first result scroll down',@@ -34,7 +41,7 @@ agent = Agent(async def main():history: AgentHistoryList = await agent.run(2)# agent.save_history(file)- await controller.browser.close()+ await controller.browser.close(force=True)history.save_to_file('AgentHistoryList.json')@@ -70,18 +77,39 @@ async def rerun_task():if ouput and ouput.action:try:# check if state is the same as previous- selector_map: SelectorMap = history_item.state.selector_map+ prev_selector_map: SelectorMap = history_item.state.selector_mapstate = await controller2.browser.get_state()current_selector_map: SelectorMap = state.selector_map+ # check which values are different+ diff = [+ v1+ for v1, v2 in zip(prev_selector_map.values(), current_selector_map.values())+ if v1 != v2+ ]# keys unique difference- diff = selector_map.keys() - current_selector_map.keys()+ diff = prev_selector_map.keys() - current_selector_map.keys()if diff:print(f'diff: {diff}')continue- action_model = await controller2.act(ouput.action)+ # get exclude unset=True field in action+ action = ouput.action.model_dump(exclude_unset=True)+ # get index of clicked if index param in output.action e.g. click_element(index=0), input(index=0, value='test'),+ # check if index is in param of action {'click_element': {'index': 9, 'num_clicks': 1}}+ params = dict(action.values())+ index_exists = 'index' in params+ if index_exists:+ index = params['index']+ # get element with index from prev selector map+ prev_element = prev_selector_map[index]+ # get element with index from current selector map+ current_element = current_selector_map[index]+ if prev_element != current_element:+ print(f'element changed: {prev_element} -> {current_element}')+ continue+ action_model = await controller2.act(action)except Exception as e:- print(f'error executing action {ouput.action}: {e}')+ print(f'Error executing action {ouput.action}: {e}')# waitawait asyncio.sleep(2)