Skip to content

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

Agent history tests included

magmuellere5d7dc2e3f52
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 7bc4c9745..1da87c2cc 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -21,6 +21,7 @@ from browser_use.agent.views import (
ActionResult,
AgentError,
AgentHistory,
+ AgentHistoryList,
AgentOutput,
ModelPricingCatalog,
TokenDetails,
@@ -77,7 +78,7 @@ class Agent:
self._initialize_messages()
# Tracking variables
- self.history: list[AgentHistory] = []
+ self.history: AgentHistoryList = AgentHistoryList(history=[])
self.n_steps = 1
self.consecutive_failures = 0
self.max_failures = max_failures
@@ -173,7 +174,7 @@ class Agent:
) -> None:
"""Create and store history item"""
history_item = AgentHistory(model_output=model_output, result=result, state=state)
- self.history.append(history_item)
+ self.history.history.append(history_item)
@time_execution_async('--get_next_action')
async def get_next_action(self, state: BrowserState) -> AgentOutput:
@@ -373,7 +374,7 @@ class Agent:
f.write(' RESPONSE\n')
f.write(json.dumps(json.loads(response.model_dump_json(exclude_unset=True)), indent=2))
- async def run(self, max_steps: int = 100) -> list[AgentHistory]:
+ async def run(self, max_steps: int = 100) -> AgentHistoryList:
"""Execute the task with maximum number of steps"""
try:
logger.info(f'🚀 Starting task: {self.task}')
@@ -405,7 +406,7 @@ class Agent:
agent_id=self.agent_id,
task=self.task,
success=self._is_task_complete(),
- steps=len(self.history),
+ steps=len(self.history.history),
)
)
if not self.controller_injected:
@@ -420,4 +421,4 @@ class Agent:
def _is_task_complete(self) -> bool:
"""Check if the task has been completed successfully"""
- return bool(self.history and self.history[-1].result.is_done)
+ return bool(self.history.history and self.history.history[-1].result.is_done)
diff --git a/browser_use/agent/tests.py b/browser_use/agent/tests.py
new file mode 100644
index 000000000..abed9bd4b
--- /dev/null
+++ b/browser_use/agent/tests.py
@@ -0,0 +1,197 @@
+import pytest
+
+from browser_use.agent.views import (
+ ActionResult,
+ AgentBrain,
+ AgentHistory,
+ AgentHistoryList,
+ AgentOutput,
+)
+from browser_use.browser.views import BrowserState, TabInfo
+from browser_use.controller.registry.service import Registry
+from browser_use.controller.registry.views import ActionModel
+from browser_use.controller.views import ClickElementAction, DoneAction, ExtractPageContentAction
+from browser_use.dom.views import DomContentItem, ProcessedDomContent
+
+
+def sample_browser_state():
+ return BrowserState(
+ url='https://example.com',
+ title='Example Page',
+ current_tab_handle='tab1',
+ tabs=[TabInfo(handle='tab1', url='https://example.com', title='Example Page')],
+ screenshot='screenshot1.png',
+ items=[
+ DomContentItem(index=1, text='Click me', is_text_only=False, depth=0),
+ DomContentItem(index=2, text='Some text', is_text_only=True, depth=1),
+ ],
+ selector_map={1: '//button[1]', 2: '//div[1]'},
+ )
+
+
+def action_registry():
+ registry = Registry()
+
+ # Register the actions we need for testing
+ @registry.action(description='Click an element', requires_browser=True)
+ def click_element(params: ClickElementAction, browser=None):
+ pass
+
+ @registry.action(description='Extract page content', requires_browser=True)
+ def extract_page_content(params: ExtractPageContentAction, browser=None):
+ pass
+
+ @registry.action(description='Mark task as done')
+ def done(params: DoneAction):
+ pass
+
+ # Create the dynamic ActionModel with all registered actions
+ return registry.create_action_model()
+
+
+def sample_history(action_registry):
+ # Create actions with nested params structure
+ click_action = action_registry(click_element={'params': {'index': 1, 'num_clicks': 1}})
+
+ extract_action = action_registry(extract_page_content={'params': {'value': 'text'}})
+
+ done_action = action_registry(done={'params': {'text': 'Task completed'}})
+
+ histories = [
+ AgentHistory(
+ model_output=AgentOutput(
+ current_state=AgentBrain(
+ valuation_previous_goal='None', memory='Started task', next_goal='Click button'
+ ),
+ action=click_action,
+ ),
+ result=ActionResult(is_done=False),
+ state=BrowserState(
+ url='https://example.com',
+ title='Page 1',
+ current_tab_handle='tab1',
+ tabs=[TabInfo(handle='tab1', url='https://example.com', title='Page 1')],
+ screenshot='screenshot1.png',
+ items=[DomContentItem(index=1, text='Button', is_text_only=False, depth=0)],
+ selector_map={1: '//button[1]'},
+ ),
+ ),
+ AgentHistory(
+ model_output=AgentOutput(
+ current_state=AgentBrain(
+ valuation_previous_goal='Clicked button',
+ memory='Button clicked',
+ next_goal='Extract content',
+ ),
+ action=extract_action,
+ ),
+ result=ActionResult(
+ is_done=False,
+ extracted_content='Extracted text',
+ error='Failed to extract completely',
+ ),
+ state=BrowserState(
+ url='https://example.com/page2',
+ title='Page 2',
+ current_tab_handle='tab1',
+ tabs=[TabInfo(handle='tab1', url='https://example.com/page2', title='Page 2')],
+ screenshot='screenshot2.png',
+ items=[DomContentItem(index=2, text='Content', is_text_only=True, depth=0)],
+ selector_map={2: '//div[1]'},
+ ),
+ ),
+ AgentHistory(
+ model_output=AgentOutput(
+ current_state=AgentBrain(
+ valuation_previous_goal='Extracted content',
+ memory='Content extracted',
+ next_goal='Finish task',
+ ),
+ action=done_action,
+ ),
+ result=ActionResult(is_done=True, extracted_content='Task completed', error=None),
+ state=BrowserState(
+ url='https://example.com/page2',
+ title='Page 2',
+ current_tab_handle='tab1',
+ tabs=[TabInfo(handle='tab1', url='https://example.com/page2', title='Page 2')],
+ screenshot='screenshot3.png',
+ items=[DomContentItem(index=3, text='Final', is_text_only=True, depth=0)],
+ selector_map={3: '//div[2]'},
+ ),
+ ),
+ ]
+ return AgentHistoryList(history=histories)
+
+
+def test_last_model_output(sample_history: AgentHistoryList):
+ last_output = sample_history.last_model_output()
+ print(last_output)
+ assert last_output == {'done': {'params': {'text': 'Task completed'}}}
+
+
+def test_get_errors(sample_history: AgentHistoryList):
+ errors = sample_history.get_errors()
+ assert len(errors) == 1
+ assert errors[0] == 'Failed to extract completely'
+
+
+def test_final_result(sample_history: AgentHistoryList):
+ assert sample_history.final_result() == 'Task completed'
+
+
+def test_is_done(sample_history: AgentHistoryList):
+ assert sample_history.is_done() == True
+
+
+def test_unique_urls(sample_history: AgentHistoryList):
+ urls = sample_history.unique_urls()
+ assert len(urls) == 2
+ assert 'https://example.com' in urls
+ assert 'https://example.com/page2' in urls
+
+
+def test_all_screenshots(sample_history: AgentHistoryList):
+ screenshots = sample_history.all_screenshots()
+ assert len(screenshots) == 3
+ assert screenshots == ['screenshot1.png', 'screenshot2.png', 'screenshot3.png']
+
+
+def test_all_model_outputs(sample_history: AgentHistoryList):
+ outputs = sample_history.all_model_outputs()
+ assert len(outputs) == 3
+ assert outputs[0] == {
+ 'click_element': {'params': {'index': 1, 'xpath': '//button[1]', 'num_clicks': 1}}
+ }
+ assert outputs[1] == {'extract_page_content': {'params': {'value': 'text'}}}
+ assert outputs[2] == {'done': {'params': {'text': 'Task completed'}}}
+
+
+def test_all_model_outputs_filtered(sample_history: AgentHistoryList):
+ filtered = sample_history.all_model_outputs_filtered(include=['click_element'])
+ assert len(filtered) == 1
+ assert filtered[0]['click_element']['params']['index'] == 1
+
+
+def test_empty_history():
+ empty_history = AgentHistoryList(history=[])
+ assert empty_history.last_model_output() is None
+ assert empty_history.final_result() is None
+ assert empty_history.is_done() == False
+ assert len(empty_history.unique_urls()) == 0
+
+
+# Add a test to verify action creation
+def test_action_creation(action_registry):
+ click_action = action_registry(click_element={'params': {'index': 1, 'num_clicks': 1}})
+
+ assert click_action.model_dump(exclude_none=True) == {
+ 'click_element': {'params': {'index': 1, 'num_clicks': 1}}
+ }
+
+
+# run this with:
+# pytest browser_use/agent/tests.py
diff --git a/browser_use/agent/views.py b/browser_use/agent/views.py
index 7dc49ead1..f64717d6e 100644
--- a/browser_use/agent/views.py
+++ b/browser_use/agent/views.py
@@ -90,6 +90,85 @@ class AgentHistory(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True, protected_namespaces=())
+class AgentHistoryList(BaseModel):
+ """List of agent history items"""
+
+ history: list[AgentHistory]
+
+ def last_model_output(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 None
+
+ def get_errors(self) -> list[str]:
+ """Get all errors from history"""
+ return [h.result.error for h in self.history if h.result.error]
+
+ 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
+ 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
+ return False
+
+ def has_errors(self) -> bool:
+ """Check if the agent has any errors"""
+ return len(self.get_errors()) > 0
+
+ def unique_urls(self) -> list[str]:
+ """Get all unique URLs from history"""
+ return list(set([h.state.url for h in self.history if h.state.url]))
+
+ def all_screenshots(self) -> list[str]:
+ """Get all screenshots from history"""
+ return [h.state.screenshot for h in self.history if h.state.screenshot]
+
+ # get all actions
+ def all_model_outputs(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
+ key = list(output.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 outputs
+
+ def all_results(self) -> list[dict]:
+ """Get all results from history"""
+ return [h.result.model_dump(exclude_none=True) for h in self.history if h.result]
+
+ def all_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]
+
+ def all_model_outputs_filtered(self, include: list[str] = []) -> list[dict]:
+ """Get all model outputs from history as JSON"""
+ outputs = self.all_model_outputs()
+ result = []
+ for o in outputs:
+ for i in include:
+ if i == list(o.keys())[0]:
+ result.append(o)
+ return result
+
+
class AgentError:
"""Container for agent error handling"""
diff --git a/browser_use/controller/registry/views.py b/browser_use/controller/registry/views.py
index 72eeaa54f..b11f6375e 100644
--- a/browser_use/controller/registry/views.py
+++ b/browser_use/controller/registry/views.py
@@ -32,6 +32,10 @@ class RegisteredAction(BaseModel):
class ActionModel(BaseModel):
"""Base model for dynamically created action models"""
+ # this will have all the registered actions, e.g.
+ # click_element = param_model = ClickElementParams
+ # done = param_model = None
+ #
model_config = ConfigDict(arbitrary_types_allowed=True)
diff --git a/tests/test_agent_actions.py b/tests/test_agent_actions.py
index 95e1c2d95..699491938 100644
--- a/tests/test_agent_actions.py
+++ b/tests/test_agent_actions.py
@@ -189,6 +189,7 @@ async def test_captcha_solver(llm, agent_with_controller, captcha: CaptchaTest):
llm=llm,
controller=agent_with_controller,
)
+ from browser_use.agent.views import AgentHistoryList
history = await agent.run(max_steps=10)
diff --git a/tests/test_core_functionality.py b/tests/test_core_functionality.py
index e47c296dc..903af072b 100644
--- a/tests/test_core_functionality.py
+++ b/tests/test_core_functionality.py
@@ -183,6 +183,9 @@ async def test_scroll_down(llm, controller):
# Validate that the 'scroll_down' action was executed
history = agent.history
- actions = [h.model_output.action for h in history if h.model_output and h.model_output.action]
- action_names = [list(action.model_dump(exclude_unset=True).keys())[0] for action in actions]
- assert 'scroll_down' in action_names
+ model_output = history.all_model_outputs()
+ if model_output:
+ keys = [key for key in model_output[0].keys()]
+ assert 'scroll_down' in keys
+ else:
+ pytest.fail('No model outputs found')