Skip to content

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

mem

Matic Zavadlal76f7516e9bd8
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 2dcad7d43..c4ce7864c 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -24,6 +24,7 @@ from langchain_core.messages import (
SystemMessage,
)
from lmnr import observe
+from memory_profiler import profile
from openai import RateLimitError
from PIL import Image, ImageDraw, ImageFont
from pydantic import BaseModel, ValidationError
@@ -267,6 +268,7 @@ class Agent:
@observe(name='agent.step', ignore_output=True, ignore_input=True)
@time_execution_async('--step')
+ @profile
async def step(self, step_info: Optional[AgentStepInfo] = None) -> None:
"""Execute one step of the task"""
logger.info(f'📍 Step {self.n_steps}')
@@ -529,6 +531,7 @@ class Agent:
)
@observe(name='agent.run', ignore_output=True)
+ @profile
async def run(self, max_steps: int = 100) -> AgentHistoryList:
"""Execute the task with maximum number of steps"""
try:
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.py
index 80cdbbb02..c56e50db5 100644
--- a/browser_use/browser/context.py
+++ b/browser_use/browser/context.py
@@ -13,6 +13,7 @@ import uuid
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Optional, TypedDict
+from memory_profiler import profile
from playwright.async_api import Browser as PlaywrightBrowser
from playwright.async_api import (
BrowserContext as PlaywrightBrowserContext,
@@ -597,6 +598,7 @@ class BrowserContext:
return await page.evaluate(script)
@time_execution_sync('--get_state') # This decorator might need to be updated to handle async
+ @profile
async def get_state(self) -> BrowserState:
"""Get the current state of the browser"""
await self._wait_for_page_and_frames_load()
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index e887d5290..8aebc9f50 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -3,6 +3,7 @@ import logging
from importlib import resources
from typing import Optional
+from memory_profiler import profile
from playwright.async_api import Page
from browser_use.dom.history_tree_processor.view import Coordinates
@@ -27,6 +28,8 @@ class DomService:
self.js_code = resources.read_text('browser_use.dom', 'buildDomTree.js')
# region - Clickable elements
+
+ @profile
async def get_clickable_elements(
self,
highlight_elements: bool = True,
diff --git a/browser_use/dom/views.py b/browser_use/dom/views.py
index 9d33e64cd..54cd19e81 100644
--- a/browser_use/dom/views.py
+++ b/browser_use/dom/views.py
@@ -9,14 +9,14 @@ if TYPE_CHECKING:
from .views import DOMElementNode
-@dataclass(slots=True, frozen=False)
+@dataclass(frozen=False)
class DOMBaseNode:
is_visible: bool
# Use None as default and set parent later to avoid circular reference issues
parent: Optional['DOMElementNode']
-@dataclass(slots=True, frozen=False)
+@dataclass(frozen=False)
class DOMTextNode(DOMBaseNode):
text: str
type: str = 'TEXT_NODE'
@@ -30,7 +30,7 @@ class DOMTextNode(DOMBaseNode):
return False
-@dataclass(slots=True, frozen=False)
+@dataclass(frozen=False)
class DOMElementNode(DOMBaseNode):
"""
xpath: the xpath of the element from the last root node (shadow root or iframe OR document if no shadow root or iframe).
@@ -158,10 +158,33 @@ class DOMElementNode(DOMBaseNode):
return BrowserContext._enhanced_css_selector_for_element(self)
+class ElementTreeSerializer:
+ @staticmethod
+ def serialize_clickable_elements(element_tree: DOMElementNode) -> str:
+ return element_tree.clickable_elements_to_string()
+
+ @staticmethod
+ def dom_element_node_to_json(element_tree: DOMElementNode) -> dict:
+ def node_to_dict(node: DOMBaseNode) -> dict:
+ if isinstance(node, DOMTextNode):
+ return {'type': 'text', 'text': node.text}
+ elif isinstance(node, DOMElementNode):
+ return {
+ 'type': 'element',
+ 'tag_name': node.tag_name,
+ 'attributes': node.attributes,
+ 'highlight_index': node.highlight_index,
+ 'children': [node_to_dict(child) for child in node.children],
+ }
+ return {}
+
+ return node_to_dict(element_tree)
+
+
SelectorMap = dict[int, DOMElementNode]
-@dataclass(slots=True, frozen=False)
+@dataclass
class DOMState:
element_tree: DOMElementNode
selector_map: SelectorMap
diff --git a/examples/simple.py b/examples/simple.py
index 0d586b8bf..cd3c34c7e 100644
--- a/examples/simple.py
+++ b/examples/simple.py
@@ -2,6 +2,7 @@ import asyncio
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
+from memory_profiler import profile
from browser_use import Agent
@@ -12,11 +13,12 @@ llm = ChatOpenAI(
model='gpt-4o',
temperature=0.0,
)
-task = 'Find the founders of browser-use and draft them a short personalized message'
+task = 'Go to apple.com and find the latest iphone model and return the link so i can buy it.'
agent = Agent(task=task, llm=llm)
+@profile
async def main():
await agent.run()