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
Reload history in agent
magmuellerd6e684f66f5e
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 0641f9c32..0be276663 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -6,6 +6,7 @@ import loggingimport osimport timeimport uuid+from pathlib import Pathfrom typing import Any, Optional, Tuple, Type, TypeVarfrom dotenv import load_dotenv@@ -375,6 +376,7 @@ class Agent:if not history_item.model_output or not history_item.model_output.action:logger.warning(f'Step {i + 1}: No action to replay, skipping')+ results.append(ActionResult(error='No action to replay'))continueretry_count = 0@@ -390,8 +392,8 @@ class Agent:error_msg = f'Step {i + 1} failed after {max_retries} attempts: {str(e)}'logger.error(error_msg)if not skip_failures:+ results.append(ActionResult(error=error_msg))raise RuntimeError(error_msg)- results.append(ActionResult(error=error_msg))else:logger.warning(f'Step {i + 1} failed (attempt {retry_count}/{max_retries}), retrying...'@@ -442,12 +444,14 @@ class Agent:if old_index != current_element.highlight_index:action.set_index(current_element.highlight_index)logger.info(- f'Updated element index from {old_index} to {current_element.highlight_index}'+ f'Element moved in DOM, updated index from {old_index} to {current_element.highlight_index}')return action- async def load_and_rerun(self, history_file: str, **kwargs) -> list[ActionResult]:+ async def load_and_rerun(+ self, history_file: Optional[str | Path] = None, **kwargs+ ) -> list[ActionResult]:"""Load history from file and rerun it.@@ -455,9 +459,13 @@ class Agent:history_file: Path to the history file**kwargs: Additional arguments passed to rerun_history"""+ if not history_file:+ history_file = 'AgentHistory.json'history = AgentHistoryList.load_from_file(history_file, self.AgentOutput)return await self.rerun_history(history, **kwargs)- def save_history(self, file_path: str) -> None:+ def save_history(self, file_path: Optional[str | Path] = None) -> None:"""Save the history to a file"""+ if not file_path:+ file_path = 'AgentHistory.json'self.history.save_to_file(file_path)diff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex fa8b0c8ab..6a8cba8b6 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -113,6 +113,7 @@ class AgentHistoryList(BaseModel):def save_to_file(self, filepath: str | Path) -> None:"""Save history to JSON file with proper serialization"""try:+ Path(filepath).parent.mkdir(parents=True, exist_ok=True)data = self.model_dump()with open(filepath, 'w', encoding='utf-8') as f:json.dump(data, f, indent=2)diff --git a/examples/file_upload.py b/examples/file_upload.pyindex 1d6d0c735..1de24a768 100644--- a/examples/file_upload.py+++ b/examples/file_upload.py@@ -38,20 +38,25 @@ async def main():sites = ['https://practice.expandtesting.com/upload',]- # task = f'go to {", ".join(sites)} and Upload my file then subbmit and stop '- task = f'go to {" ".join(sites)} each in new tabs and Upload my file then subbmit extract the page content and go to google and find elon musk '+ task = f'go to {" ".join(sites)} each in new tabs and Upload my file then subbmit extract the page content and go to google and find elon musk and stop'- model = ChatOpenAI(model='gpt-4o-mini')+ model = ChatOpenAI(model='gpt-4o')agent = Agent(task=task,llm=model,controller=controller,- save_conversation_path='tmp/examples/file_upload',- max_input_tokens=32000,)await agent.run()+ history_file_path = 'AgentHistoryList.json'+ agent.save_history(file_path=history_file_path)++ agent2 = Agent(llm=model, controller=controller, task='')+ await agent2.load_and_rerun(history_file_path)++ input('Press Enter to close...')+if __name__ == '__main__':asyncio.run(main())diff --git a/examples/flight_search.py b/examples/flight_search.pyindex 60e93aec2..e68f94361 100644--- a/examples/flight_search.py+++ b/examples/flight_search.py@@ -32,24 +32,14 @@ async def secret_text(secret_text: str) -> None:agent = Agent(- # task='Go to kayak.com and search for flights from Zurich to Beijing and then done.',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',llm=llm,controller=controller,)async def main():- # history: AgentHistoryList = await agent.run(5)- # await controller.browser.close(force=True)-- history_file_path = 'AgentHistoryList.json'- # agent.save_history(file_path=history_file_path)-- agent2 = Agent(llm=llm, controller=controller, task='')- await agent2.load_and_rerun(history_file_path)-+ history: AgentHistoryList = await agent.run(20)await controller.browser.close(force=True)