Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

First draft multi-action runs

magmuellerc581a1b25198
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 9c33f0989..21242feff 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -121,6 +121,7 @@ class Agent:
"""Execute one step of the task"""
logger.info(f'\nπŸ“ Step {self.n_steps}')
state = None
+ model_output = None
try:
state = await self.controller.browser.get_state(use_vision=self.use_vision)
@@ -131,33 +132,34 @@ class Agent:
self.message_manager._remove_last_state_message() # we dont want the whole state in the chat history
self.message_manager.add_model_output(model_output)
- result = await self.controller.act(model_output.action)
- self._last_result = result
+ result: list[ActionResult] = await self.controller.multi_act(model_output.action)
+ self._last_result = result[-1]
- if result.extracted_content:
- logger.info(f'πŸ“„ Result: {result.extracted_content}')
- if result.is_done:
- logger.result(f'{result.extracted_content}') # type: ignore
+ for r in result:
+ if r.is_done:
+ logger.result(f'{r.extracted_content}')
+ elif r.extracted_content:
+ logger.info(f'πŸ“„ Result: {r.extracted_content}')
self.consecutive_failures = 0
except Exception as e:
result = self._handle_step_error(e)
- self._last_result = result
+ self._last_result = result[-1]
- if result.error:
- self.telemetry.capture(
- AgentStepErrorTelemetryEvent(
- agent_id=self.agent_id,
- error=result.error,
- )
- )
- model_output = None
finally:
+ for r in result:
+ if r.error:
+ self.telemetry.capture(
+ AgentStepErrorTelemetryEvent(
+ agent_id=self.agent_id,
+ error=r.error,
+ )
+ )
if state:
self._make_history_item(model_output, state, result)
- def _handle_step_error(self, error: Exception) -> ActionResult:
+ def _handle_step_error(self, error: Exception) -> list[ActionResult]:
"""Handle all types of errors that can occur during a step"""
error_msg = AgentError.format_error(error, include_trace=True)
prefix = f'❌ Result failed {self.consecutive_failures + 1}/{self.max_failures} times:\n '
@@ -180,27 +182,30 @@ class Agent:
logger.error(f'{prefix}{error_msg}')
self.consecutive_failures += 1
- return ActionResult(error=error_msg, include_in_memory=True)
+ return [ActionResult(error=error_msg, include_in_memory=True)]
def _make_history_item(
self,
model_output: AgentOutput | None,
state: BrowserState,
- result: ActionResult,
+ result: list[ActionResult],
) -> None:
"""Create and store history item"""
+ interacted_element = None
+ len_result = len(result)
+
if model_output:
- interacted_element = AgentHistory.get_interacted_element(
+ interacted_elements = AgentHistory.get_interacted_element(
model_output, state.selector_map
)
else:
- interacted_element = None
+ interacted_elements = [None]
state_history = BrowserStateHistory(
url=state.url,
title=state.title,
tabs=state.tabs,
- interacted_element=interacted_element,
+ interacted_element=interacted_elements,
)
history_item = AgentHistory(model_output=model_output, result=result, state=state_history)
@@ -221,7 +226,7 @@ class Agent:
return parsed
- def _log_response(self, response: Any) -> None:
+ def _log_response(self, response: AgentOutput) -> None:
"""Log the model's response"""
if 'Success' in response.current_state.valuation_previous_goal:
emoji = 'πŸ‘'
@@ -233,7 +238,8 @@ class Agent:
logger.info(f'{emoji} Evaluation: {response.current_state.valuation_previous_goal}')
logger.info(f'🧠 Memory: {response.current_state.memory}')
logger.info(f'🎯 Next Goal: {response.current_state.next_goal}')
- logger.info(f'πŸ› οΈ Action: {response.action.model_dump_json(exclude_unset=True)}')
+ for action in response.action:
+ logger.info(f'πŸ› οΈ Action: {action.model_dump_json(exclude_unset=True)}')
def _save_conversation(self, input_messages: list[BaseMessage], response: Any) -> None:
"""Save conversation history to file if path is specified"""
@@ -389,7 +395,11 @@ class Agent:
)
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:
+ if (
+ not history_item.model_output
+ or not history_item.model_output.action
+ or history_item.model_output.action == [None]
+ ):
logger.warning(f'Step {i + 1}: No action to replay, skipping')
results.append(ActionResult(error='No action to replay'))
continue
@@ -398,7 +408,7 @@ class Agent:
while retry_count < max_retries:
try:
result = await self._execute_history_step(history_item, delay_between_actions)
- results.append(result)
+ results.extend(result)
break
except Exception as e:
@@ -417,23 +427,27 @@ class Agent:
return results
- async def _execute_history_step(self, history_item: AgentHistory, delay: float) -> ActionResult:
+ async def _execute_history_step(
+ self, history_item: AgentHistory, delay: float
+ ) -> list[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_actions = []
+ for i, action in enumerate(history_item.model_output.action):
+ updated_action = await self._update_action_indices(
+ history_item.state.interacted_element[i],
+ action,
+ state,
+ )
+ updated_actions.append(updated_action)
- 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')
+ if updated_action is None:
+ raise ValueError(f'Could not find matching element {i} in current page')
- result = await self.controller.act(updated_action)
+ result = await self.controller.multi_act(updated_actions)
await asyncio.sleep(delay)
return result
diff --git a/browser_use/agent/views.py b/browser_use/agent/views.py
index fcc3d4659..ea338a447 100644
--- a/browser_use/agent/views.py
+++ b/browser_use/agent/views.py
@@ -44,7 +44,7 @@ class AgentOutput(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
current_state: AgentBrain
- action: ActionModel
+ action: list[ActionModel]
@staticmethod
def type_with_custom_actions(custom_actions: Type[ActionModel]) -> Type['AgentOutput']:
@@ -52,7 +52,7 @@ class AgentOutput(BaseModel):
return create_model(
'AgentOutput',
__base__=AgentOutput,
- action=(custom_actions, Field(...)), # Properly annotated field with no default
+ action=(list[custom_actions], Field(...)), # Properly annotated field with no default
__module__=AgentOutput.__module__,
)
@@ -61,7 +61,7 @@ class AgentHistory(BaseModel):
"""History item for agent actions"""
model_output: AgentOutput | None
- result: ActionResult
+ result: list[ActionResult]
state: BrowserStateHistory
model_config = ConfigDict(arbitrary_types_allowed=True, protected_namespaces=())
@@ -69,13 +69,16 @@ class AgentHistory(BaseModel):
@staticmethod
def get_interacted_element(
model_output: AgentOutput, selector_map: SelectorMap
- ) -> DOMHistoryElement | None:
- index = model_output.action.get_index()
- if index:
- el: DOMElementNode = selector_map[index]
- return HistoryTreeProcessor.convert_dom_element_to_history_element(el)
-
- return None
+ ) -> list[DOMHistoryElement | None]:
+ elements = []
+ for action in model_output.action:
+ index = action.get_index()
+ if index:
+ el: DOMElementNode = selector_map[index]
+ elements.append(HistoryTreeProcessor.convert_dom_element_to_history_element(el))
+ else:
+ elements.append(None)
+ return elements
def model_dump(self, **kwargs) -> Dict[str, Any]:
"""Custom serialization handling circular references"""
@@ -147,23 +150,26 @@ class AgentHistoryList(BaseModel):
def last_action(self) -> None | dict:
"""Last action in history"""
if self.history and self.history[-1].model_output:
- return self.history[-1].model_output.action.model_dump(exclude_none=True)
+ return self.history[-1].model_output.action[-1].model_dump(exclude_none=True)
return None
def errors(self) -> list[str]:
"""Get all errors from history"""
- return [h.result.error for h in self.history if h.result.error]
+ errors = []
+ for h in self.history:
+ errors.extend([r.error for r in h.result if r.error])
+ return errors
def final_result(self) -> None | str:
"""Final result from history"""
- if self.history and self.history[-1].result.extracted_content:
- return self.history[-1].result.extracted_content
+ if self.history and self.history[-1].result[-1].extracted_content:
+ return self.history[-1].result[-1].extracted_content
return None
def is_done(self) -> bool:
"""Check if the agent is done"""
- if self.history and self.history[-1].result.is_done:
- return self.history[-1].result.is_done
+ if self.history and self.history[-1].result[-1].is_done:
+ return self.history[-1].result[-1].is_done
return False
def has_errors(self) -> bool:
@@ -197,18 +203,24 @@ class AgentHistoryList(BaseModel):
for h in self.history:
if h.model_output:
- output = h.model_output.action.model_dump(exclude_none=True)
-
- outputs.append(output)
+ for action in h.model_output.action:
+ output = action.model_dump(exclude_none=True)
+ outputs.append(output)
return outputs
def action_results(self) -> list[ActionResult]:
"""Get all results from history"""
- return [h.result for h in self.history if h.result]
+ results = []
+ for h in self.history:
+ results.extend([r for r in h.result if r])
+ return results
def extracted_content(self) -> list[str]:
"""Get all extracted content from history"""
- return [h.result.extracted_content for h in self.history if h.result.extracted_content]
+ content = []
+ for h in self.history:
+ content.extend([r.extracted_content for r in h.result if r.extracted_content])
+ return content
def model_actions_filtered(self, include: list[str] = []) -> list[dict]:
"""Get all model actions from history as JSON"""
diff --git a/browser_use/browser/views.py b/browser_use/browser/views.py
index ae7b1c8e7..2953d564f 100644
--- a/browser_use/browser/views.py
+++ b/browser_use/browser/views.py
@@ -29,16 +29,16 @@ class BrowserStateHistory:
url: str
title: str
tabs: list[TabInfo]
- interacted_element: Optional[DOMHistoryElement] = None
+ interacted_element: list[DOMHistoryElement | None] | list[None]
screenshot: Optional[str] = None
def to_dict(self) -> dict[str, Any]:
data = {}
data['tabs'] = [tab.model_dump() for tab in self.tabs]
data['screenshot'] = self.screenshot
- data['interacted_element'] = (
- self.interacted_element.to_dict() if self.interacted_element else None
- )
+ data['interacted_element'] = [
+ el.to_dict() if el else None for el in self.interacted_element
+ ]
data['url'] = self.url
data['title'] = self.title
return data
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index 14f7da990..ea638495a 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -16,7 +16,7 @@ from browser_use.controller.views import (
SearchGoogleAction,
SwitchTabAction,
)
-from browser_use.utils import time_execution_sync
+from browser_use.utils import time_execution_async, time_execution_sync
logger = logging.getLogger(__name__)
@@ -179,6 +179,16 @@ class Controller:
"""
return self.registry.action(description, **kwargs)
+ @time_execution_async('--multi-act')
+ async def multi_act(self, actions: list[ActionModel]) -> list[ActionResult]:
+ """Execute multiple actions"""
+ results = []
+ for action in actions:
+ results.append(await self.act(action))
+ if results[-1].is_done or results[-1].error:
+ break
+ return results
+
@time_execution_sync('--act')
async def act(self, action: ActionModel) -> ActionResult:
"""Execute an action"""