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
Rerun in agent
magmueller85bdf707f7d8
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 56868e2d4..0641f9c32 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -1,11 +1,12 @@from __future__ import annotations+import asyncioimport jsonimport loggingimport osimport timeimport uuid-from typing import Any, Optional, Type, TypeVar+from typing import Any, Optional, Tuple, Type, TypeVarfrom dotenv import load_dotenvfrom langchain_core.language_models.chat_models import BaseChatModel@@ -27,7 +28,10 @@ from browser_use.agent.views import (AgentOutput,)from browser_use.browser.views import BrowserState+from browser_use.controller.registry.views import ActionModelfrom browser_use.controller.service import Controller+from browser_use.dom.history_tree_processor import DOMHistoryElement, HistoryTreeProcessor+from browser_use.dom.views import DOMElementNodefrom browser_use.telemetry.service import ProductTelemetryfrom browser_use.telemetry.views import (AgentEndTelemetryEvent,@@ -339,3 +343,121 @@ class Agent:else:logger.info(f'✅ Validator decision: {parsed.reason}')return is_valid++ async def rerun_history(+ self,+ history: AgentHistoryList,+ max_retries: int = 3,+ skip_failures: bool = True,+ delay_between_actions: float = 2.0,+ ) -> list[ActionResult]:+ """+ Rerun a saved history of actions with error handling and retry logic.++ Args:+ history: The history to replay+ max_retries: Maximum number of retries per action+ skip_failures: Whether to skip failed actions or stop execution+ delay_between_actions: Delay between actions in seconds++ Returns:+ List of action results+ """+ results = []++ for i, history_item in enumerate(history.history):+ goal = (+ history_item.model_output.current_state.next_goal+ if history_item.model_output+ else ''+ )+ logger.info(f'Replaying step {i + 1}/{len(history.history)}: goal: {goal}')++ if not history_item.model_output or not history_item.model_output.action:+ logger.warning(f'Step {i + 1}: No action to replay, skipping')+ continue++ retry_count = 0+ while retry_count < max_retries:+ try:+ result = await self._execute_history_step(history_item, delay_between_actions)+ results.append(result)+ break++ except Exception as e:+ retry_count += 1+ if retry_count == max_retries:+ error_msg = f'Step {i + 1} failed after {max_retries} attempts: {str(e)}'+ logger.error(error_msg)+ if not skip_failures:+ raise RuntimeError(error_msg)+ results.append(ActionResult(error=error_msg))+ else:+ logger.warning(+ f'Step {i + 1} failed (attempt {retry_count}/{max_retries}), retrying...'+ )+ await asyncio.sleep(delay_between_actions)++ return results++ async def _execute_history_step(self, history_item: AgentHistory, delay: float) -> ActionResult:+ """Execute a single step from history with element validation"""++ state = await self.controller.browser.get_state()+ if not state or not history_item.model_output:+ raise ValueError('Invalid state or model output')++ updated_action = await self._update_action_indices(+ history_item.state.interacted_element, history_item.model_output.action, state+ )++ if updated_action is None:+ raise ValueError('Could not find matching element in current page')++ result = await self.controller.act(updated_action)+ await asyncio.sleep(delay)+ return result++ async def _update_action_indices(+ self,+ historical_element: Optional[DOMHistoryElement],+ action: ActionModel, # Type this properly based on your action model+ current_state: BrowserState,+ ) -> Optional[ActionModel]:+ """+ Update action indices based on current page state.+ Returns updated action or None if element cannot be found.+ """+ if not historical_element or not current_state.element_tree:+ return action++ current_element = HistoryTreeProcessor.find_history_element_in_tree(+ historical_element, current_state.element_tree+ )++ if not current_element or current_element.highlight_index is None:+ return None++ old_index = action.get_index()+ 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}'+ )++ return action++ async def load_and_rerun(self, history_file: str, **kwargs) -> list[ActionResult]:+ """+ Load history from file and rerun it.++ Args:+ history_file: Path to the history file+ **kwargs: Additional arguments passed to rerun_history+ """+ history = AgentHistoryList.load_from_file(history_file, self.AgentOutput)+ return await self.rerun_history(history, **kwargs)++ def save_history(self, file_path: str) -> None:+ """Save the history to a file"""+ self.history.save_to_file(file_path)diff --git a/browser_use/browser/service.py b/browser_use/browser/service.pyindex 3202060fb..beada470e 100644--- a/browser_use/browser/service.py+++ b/browser_use/browser/service.py@@ -236,8 +236,7 @@ class Browser:if self.session is None:return- if self.cookies_file:- await self.save_cookies()+ await self.save_cookies()if force and not self.keep_open:session = await self.get_session()@@ -557,4 +556,4 @@ class Browser:with open(self.cookies_file, 'w') as f:json.dump(cookies, f)except Exception as e:- logger.error(f'Failed to save cookies: {str(e)}')+ logger.warning(f'Failed to save cookies: {str(e)}')diff --git a/examples/flight_search.py b/examples/flight_search.pyindex 92ca63df8..60e93aec2 100644--- a/examples/flight_search.py+++ b/examples/flight_search.py@@ -41,75 +41,16 @@ agent = Agent(async def main():- history: AgentHistoryList = await agent.run(5)- # agent.save_history(file)- await controller.browser.close(force=True)+ # 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)- history.save_to_file('AgentHistoryList.json')-- await rerun_task()---async def rerun_task():- # create new controller and agent- controller2 = Controller(keep_open=False, cookies_path='cookies.json')- agent2 = Agent(- task='',- llm=llm,- controller=controller2,- )- output_model = agent2.AgentOutput-- history2 = AgentHistoryList.load_from_file('AgentHistoryList.json', output_model)-- # pydantic model for actions-- print(f'rerun task')- actions = history2.action_names()- outputs = history2.model_outputs()- print(actions)-- # close controller- # get all interacted elements- interacted_elements = [h.state.interacted_element for h in history2.history]- for i, history_item in enumerate(history2.history):- print(f'{i} {actions[i]} ')- ouput = history_item.model_output- if ouput and ouput.action:- goal = ouput.current_state.next_goal- print(f'goal: {goal}')- try:- # check if state is the same as previous- old_el = history_item.state.interacted_element- state = await controller2.browser.get_state()- tree = state.element_tree-- if old_el and tree:- element: DOMElementNode | None = (- HistoryTreeProcessor.find_history_element_in_tree(old_el, tree)- )- if element:- index = element.highlight_index- old_index = ouput.action.get_index()- print(f'same element found with index: {index} and old index: {old_index}')-- if old_index != index and index is not None:- ouput.action.set_index(index)- else:- print(f'old element not found in new tree')- continue-- action_result = await controller2.act(ouput.action)- if action_result.error:- print(f'Step {i} failed: {action_result.error}')- else:- print(f'Step {i} succeeded: {action_result.extracted_content}')- except Exception as e:- print(f'Error executing action {ouput.action}: {e}')-- # wait- await asyncio.sleep(2)- print(f'done')+ agent2 = Agent(llm=llm, controller=controller, task='')+ await agent2.load_and_rerun(history_file_path)++ await controller.browser.close(force=True)asyncio.run(main())