Skip to content

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

cleanup

Matic Zavadlal7a50c50be874
diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.py
index f526bb8ac..dc65333da 100644
--- a/browser_use/agent/prompts.py
+++ b/browser_use/agent/prompts.py
@@ -219,7 +219,7 @@ Interactive elements from current page:
error = result.error[-self.max_error_length :]
state_description += f'\nAction error {i + 1}/{len(self.result)}: ...{error}'
- if self.state.screenshot and use_vision:
+ if self.state.screenshot and use_vision == True:
# Format message for vision model
return HumanMessage(
content=[
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 034778fcb..2dcad7d43 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -2,7 +2,6 @@ from __future__ import annotations
import asyncio
import base64
-import gc
import io
import json
import logging
@@ -10,13 +9,11 @@ import os
import platform
import re
import textwrap
-import tracemalloc
import uuid
from io import BytesIO
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Type, TypeVar
-import psutil
from dotenv import load_dotenv
from google.api_core.exceptions import ResourceExhausted
from langchain_core.language_models.chat_models import BaseChatModel
@@ -201,8 +198,6 @@ class Agent:
self.action_descriptions = self.controller.registry.get_prompt_description()
- self._memory_tracker = None
-
def _set_version_and_source(self) -> None:
try:
import pkg_resources
@@ -536,9 +531,6 @@ class Agent:
@observe(name='agent.run', ignore_output=True)
async def run(self, max_steps: int = 100) -> AgentHistoryList:
"""Execute the task with maximum number of steps"""
- self._start_memory_tracking()
- self._log_memory_usage('start')
-
try:
self._log_agent_run()
@@ -601,13 +593,6 @@ class Agent:
self.create_history_gif(output_path=output_path)
- self._log_memory_usage('end')
- # Force garbage collection
- gc.collect()
- self._log_memory_usage('after gc')
-
- tracemalloc.stop()
-
def _too_many_failures(self) -> bool:
"""Check if we should stop due to too many failures"""
if self.consecutive_failures >= self.max_failures:
@@ -1289,41 +1274,3 @@ class Agent:
logger.info(f'Plan: {plan}')
return plan
-
- def _start_memory_tracking(self):
- """Start tracking memory usage"""
- tracemalloc.start()
- self._memory_tracker = psutil.Process(os.getpid())
- self._initial_memory = self._memory_tracker.memory_info().rss
-
- def _log_memory_usage(self, stage: str):
- """Log memory usage at different stages"""
- if self._memory_tracker:
- current_memory = self._memory_tracker.memory_info().rss
- delta = current_memory - self._initial_memory
- logger.info(f'Memory usage at {stage}: {current_memory / 1024 / 1024:.2f} MB (Delta: {delta / 1024 / 1024:.2f} MB)')
-
- # Get memory snapshot
- snapshot = tracemalloc.take_snapshot()
- top_stats = snapshot.statistics('lineno')
- logger.debug('Top 10 memory allocations:')
- for stat in top_stats[:10]:
- logger.debug(stat)
-
- async def __aenter__(self):
- """Async context manager entry"""
- return self
-
- async def __aexit__(self, exc_type, exc_val, exc_tb):
- """Async context manager exit with cleanup"""
- await self.cleanup()
-
- async def cleanup(self):
- """Cleanup resources"""
- if not self.injected_browser_context:
- await self.browser_context.close()
- if not self.injected_browser and self.browser:
- await self.browser.close()
-
- # Clear references that might hold memory
- print('Cleaning up')
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index f6a8633b9..dd8a716f7 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -25,8 +25,6 @@ class DomService:
self.page = page
self.xpath_cache = {}
- self._iter = 0
-
self.js_code = resources.read_text('browser_use.dom', 'buildDomTree.js')
# region - Clickable elements
@@ -53,9 +51,6 @@ class DomService:
focus_element: int,
viewport_expansion: int,
) -> tuple[DOMElementNode, SelectorMap]:
- self._iter += 1
- logger.info(f'Iteration {self._iter} --------------------------------')
-
# NOTE: We execute JS code in the browser to extract important DOM information.
# The returned hash map contains information about the DOM tree and the
# relationship between the DOM elements.
@@ -83,14 +78,17 @@ class DomService:
if isinstance(node, DOMElementNode) and node.highlight_index is not None:
selector_map[node.highlight_index] = node
- # NOTE: We know that we are building the tree bottom up!
- for child_id in children_ids:
- child_node = node_map[child_id]
+ # NOTE: We know that we are building the tree bottom up
+ # and all children are already processed.
+ if isinstance(node, DOMElementNode):
+ for child_id in children_ids:
+ if child_id not in node_map:
+ continue
- if child_id not in node_map:
- continue
+ child_node = node_map[child_id]
- node_map[id].children.append(child_node)
+ child_node.parent = node
+ node.children.append(child_node)
html_to_dict = node_map[js_root_id]
diff --git a/examples/explorations.py b/examples/explorations.py
deleted file mode 100644
index 8bf7714fd..000000000
--- a/examples/explorations.py
+++ /dev/null
@@ -1,108 +0,0 @@
-import asyncio
-import gc
-import logging
-import os
-import time
-
-import psutil
-from dotenv import load_dotenv
-from langchain_openai import ChatOpenAI
-
-from browser_use import Agent
-
-logging.basicConfig(
- level=logging.INFO,
- format='%(asctime)s - %(levelname)s - %(message)s',
- handlers=[logging.StreamHandler(), logging.FileHandler('memory_usage.log')],
-)
-
-logger = logging.getLogger(__name__)
-
-
-def log_current_memory():
- process = psutil.Process(os.getpid())
- memory_mb = process.memory_info().rss / 1024 / 1024
- logger.info(f'Current memory usage: {memory_mb:.2f} MB')
- return memory_mb
-
-
-async def monitor_idle_memory(duration_seconds: int = 60, interval_seconds: int = 1):
- end_time = time.time() + duration_seconds
- while time.time() < end_time:
- log_current_memory()
- await asyncio.sleep(interval_seconds)
-
-
-def memory_intensive_operation():
- print('Starting memory-intensive operation...')
-
- # Create a large list to capture a lot of memory
- large_list = [0] * 10_000_000 # List with 10 million integers
-
- print('Memory-intensive operation complete. Large list created.')
- time.sleep(2) # Pause to observe memory usage
-
- # Release the memory by deleting the list
- del large_list
- print('Large list deleted.')
-
- # Force garbage collection
- time.sleep(2) # Pause to observe memory usage
-
-
-async def main():
- load_dotenv()
-
- # Log initial memory
- logger.info('=== Initial Memory ===')
- initial_memory = log_current_memory()
-
- # Run the agent
-
- logger.info('\n=== Running Agent ===')
-
- for i in range(10):
- logger.info(f'=== Running Agent {i} ===')
-
- llm = ChatOpenAI(model='gpt-4o', temperature=0.0)
- task = 'Find the founders of browser-use and draft them a short personalized message'
-
- async with Agent(task=task, llm=llm) as agent:
- await agent.run()
- # Log post-run memory
- logger.info(f'\n=== Post-Run Memory {i} ===')
- post_run_memory = log_current_memory()
-
- gc.collect()
-
- # memory_intensive_operation()
-
- # Log post-run memory
- logger.info('\n=== Post-Run Memory ===')
- post_run_memory = log_current_memory()
-
- # Force garbage collection
- gc.collect()
-
- logger.info('\n=== After GC Memory ===')
- post_gc_memory = log_current_memory()
-
- # Monitor idle period
- logger.info('\n=== Starting Idle Monitoring (60 seconds) ===')
- await monitor_idle_memory(duration_seconds=60) # Monitor for 1 minute
-
- # Final memory check
- logger.info('\n=== Final Memory ===')
- final_memory = log_current_memory()
-
- # Print summary
- logger.info('\n=== Memory Usage Summary ===')
- logger.info(f'Initial Memory: {initial_memory:.2f} MB')
- logger.info(f'Post-Run Memory: {post_run_memory:.2f} MB')
- logger.info(f'Post-GC Memory: {post_gc_memory:.2f} MB')
- logger.info(f'Final Memory: {final_memory:.2f} MB')
- logger.info(f'Total Change: {final_memory - initial_memory:.2f} MB')
-
-
-if __name__ == '__main__':
- asyncio.run(main())
diff --git a/examples/memory.py b/examples/memory.py
deleted file mode 100644
index 8f8499f64..000000000
--- a/examples/memory.py
+++ /dev/null
@@ -1,73 +0,0 @@
-import asyncio
-import gc
-import logging
-import resource
-
-# Set up logging (both console and file output are enabled)
-logging.basicConfig(
- level=logging.INFO,
- format='%(asctime)s - %(levelname)s - %(message)s',
- handlers=[logging.StreamHandler(), logging.FileHandler('memory_usage_simple.log')],
-)
-logger = logging.getLogger(__name__)
-
-
-def log_current_memory(context: str = '') -> float:
- # ru_maxrss returns KB on Unix; convert to MB.
- memory_mb = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024
- # Label the log line with a clear marker "CurrentMemory:" for easy extraction:
- logger.info(f'{context}CurrentMemory: {memory_mb:.2f} MB')
- return memory_mb
-
-
-async def memory_intensive_task(task_id: int):
- logger.info(f'Task {task_id}: Starting memory allocation.')
- # Allocate a large list to increase memory usage.
- data = [0] * 10_000_000 # List with 10 million integers.
- logger.info(f'Task {task_id}: Memory allocated, list size: {len(data)}')
-
- # Simulate some async work.
- await asyncio.sleep(1)
-
- logger.info(f'Task {task_id}: Releasing allocated memory.')
- # Delete the large data structure to free memory.
- del data
- gc.collect() # Force garbage collection.
-
- await asyncio.sleep(1)
- log_current_memory(f'Task {task_id}: ')
-
-
-async def main():
- # Log initial memory usage.
- logger.info('=== Initial Memory ===')
- initial_memory = log_current_memory('Initial: ')
-
- # Run a series of batches of asynchronous tasks.
- batches = 5 # Define the number of batches.
- tasks_per_batch = 5 # Number of concurrent tasks in each batch.
-
- for batch in range(batches):
- logger.info(f'=== Batch {batch} starting ===')
-
- tasks = [asyncio.create_task(memory_intensive_task(task_id)) for task_id in range(tasks_per_batch)]
- await asyncio.gather(*tasks)
-
- gc.collect() # Additional garbage collection after a batch.
- logger.info(f'=== Batch {batch} complete ===')
- log_current_memory(f'After Batch {batch}: ')
-
- await asyncio.sleep(2) # Pause between batches.
-
- # Final memory check.
- final_memory = log_current_memory('Final: ')
-
- # Log summary.
- logger.info('=== Memory Usage Summary ===')
- logger.info(f'Initial Memory: {initial_memory:.2f} MB')
- logger.info(f'Final Memory: {final_memory:.2f} MB')
- logger.info(f'Total Change: {final_memory - initial_memory:.2f} MB')
-
-
-if __name__ == '__main__':
- asyncio.run(main())
diff --git a/examples/ping.py b/examples/ping.py
deleted file mode 100644
index 0048a43ee..000000000
--- a/examples/ping.py
+++ /dev/null
@@ -1,77 +0,0 @@
-import asyncio
-import sys
-import time
-
-import aiohttp
-
-
-async def ping(session: aiohttp.ClientSession, url: str) -> float:
- """
- Send a GET request and return the elapsed time in milliseconds.
- If the request fails, returns None.
- """
- start = time.perf_counter()
- try:
- async with session.get(url) as response:
- # Await the complete response text (optional)
- await response.text()
- status = response.status
- except Exception as e:
- print(f'Failed to request {url}. Reason: {e}')
- return None
-
- elapsed_ms = (time.perf_counter() - start) * 1000 # Convert to milliseconds
- # print(f'Ping to {url}: {elapsed_ms:.2f} ms (Status Code: {status})')
- return elapsed_ms
-
-
-async def stress_test(url: str, requests_per_second: int = 200) -> None:
- """
- Continuously send a batch of parallel requests per second.
- After each batch, log the average response time and estimated throughput.
- """
- # Using unlimited connections; adjust if necessary
- connector = aiohttp.TCPConnector(limit=0)
- async with aiohttp.ClientSession(connector=connector) as session:
- batch_num = 0
- while True:
- batch_num += 1
- batch_start = time.perf_counter()
- # Launch batch of tasks
- tasks = [asyncio.create_task(ping(session, url)) for _ in range(requests_per_second)]
- results = await asyncio.gather(*tasks)
- batch_elapsed = time.perf_counter() - batch_start
-
- # Filter out any failed requests (None values)
- valid_results = [res for res in results if res is not None]
- if valid_results:
- avg_response_time = sum(valid_results) / len(valid_results)
- else:
- avg_response_time = float('nan')
-
- # Throughput: how many requests completed per second in this batch:
- throughput = len(valid_results) / batch_elapsed
-
- print(
- f'Batch {batch_num}: '
- f'Average Response Time = {avg_response_time:.2f} ms, '
- f'Estimated Throughput = {throughput:.2f} req/sec '
- f'(batch elapsed time: {batch_elapsed:.2f} sec)'
- )
-
- # Sleep to maintain the desired rate of requests per second
- sleep_time = max(0, 1 - batch_elapsed)
- if sleep_time:
- await asyncio.sleep(sleep_time)
-
-
-if __name__ == '__main__':
- # Get URL from command-line (default to Google)
- url = sys.argv[1] if len(sys.argv) > 1 else 'https://www.google.com'
- # Optionally get number of requests per second (default: 200)
- try:
- rps = int(sys.argv[2]) if len(sys.argv) > 2 else 200
- except ValueError:
- rps = 200
-
- asyncio.run(stress_test(url, requests_per_second=rps))