Skip to content

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

Enhance observability in browser and agent services

Magnus Müllerface6a599b8f
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 125584af2..6b7bfb254 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -28,8 +28,8 @@ from browser_use.tokens.service import TokenCost
load_dotenv()
-# from lmnr.sdk.decorators import observe
from bubus import EventBus
+from lmnr.sdk.decorators import observe
from pydantic import ValidationError
from uuid_extensions import uuid7str
@@ -612,6 +612,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
# self.logger.debug('Agent paused after getting state')
raise InterruptedError
+ @observe(name='get_browser_state_with_recovery')
async def _get_browser_state_with_recovery(self, cache_clickable_elements_hashes: bool = True) -> BrowserStateSummary:
"""Get browser state with multiple fallback strategies for error recovery"""
@@ -626,6 +627,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
self.logger.warning('🔄 Falling back to minimal state summary')
return await self._get_minimal_state_summary()
+ @observe(name='get_minimal_state_summary')
async def _get_minimal_state_summary(self) -> BrowserStateSummary:
"""Get basic page info without DOM processing, but try to capture screenshot"""
from browser_use.browser.views import BrowserStateSummary
@@ -674,7 +676,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
browser_errors=[f'Page state retrieval failed, minimal recovery applied for {url}'],
)
- # @observe(name='agent.step', ignore_output=True, ignore_input=True)
+ @observe(name='agent.step', ignore_output=True, ignore_input=True)
@time_execution_async('--step')
async def step(self, step_info: AgentStepInfo | None = None) -> None:
"""Execute one step of the task"""
@@ -1158,7 +1160,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
return False, False
- # @observe(name='agent.run', ignore_output=True)
+ @observe(name='agent.run', metadata={'task': '{{task}}', 'debug': '{{debug}}'})
@time_execution_async('--run')
async def run(
self,
@@ -1366,7 +1368,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
await self.close()
- # @observe(name='controller.multi_act')
+ @observe(name='controller.multi_act')
@time_execution_async('--multi_act')
async def multi_act(
self,
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 0cc8a4f1f..1a6dd0bf1 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -16,6 +16,8 @@ from pathlib import Path
from typing import Any, Self
from urllib.parse import urlparse
+from lmnr import observe
+
from browser_use.config import CONFIG
from browser_use.utils import _log_pretty_path, _log_pretty_url
@@ -264,6 +266,7 @@ class BrowserSession(BaseModel):
# """
# return getattr(self.browser_profile, key)
+ @observe(name='browser.session.start')
async def start(self) -> Self:
"""
Starts the browser session by either connecting to an existing browser or launching a new one.
@@ -697,6 +700,7 @@ class BrowserSession(BaseModel):
# Launch new browser as last resort
await self.setup_new_browser_context()
+ @observe(ignore_output=True)
@retry(
wait=1, # wait 1s between attempts
retries=2, # 3 attempts
@@ -757,8 +761,9 @@ class BrowserSession(BaseModel):
except Exception as e:
raise Exception(f'Page assertion failed: {type(e).__name__}: {e}')
- await page.bring_to_front()
-
+ self.logger.info('Page is healthy, bringing to front')
+ # await asyncio.wait_for(page.bring_to_front(), timeout=3.0)
+ self.logger.info('Page brought to front, taking screenshot')
try:
# Reasonable timeout for screenshot
screenshot = await page.screenshot(
@@ -1410,6 +1415,7 @@ class BrowserSession(BaseModel):
f'⚠️ Failed to add visibility listener to existing tab, is it crashed or ignoring CDP commands?: [{page_idx}]{page.url}: {type(e).__name__}: {e}'
)
+ @observe(name='setup_viewports', ignore_output=True, ignore_input=True)
async def _setup_viewports(self) -> None:
"""Resize any existing page viewports to match the configured size, set up storage_state, permissions, geolocation, etc."""
@@ -1666,6 +1672,7 @@ class BrowserSession(BaseModel):
self.logger.error(f'❌ Failed to create parent directory for {path_name} {path_value}: {e}')
# --- Tab management ---
+ @observe(name='get_current_page', ignore_input=True)
async def get_current_page(self) -> Page:
"""Get the current page + ensure it's not None / closed"""
@@ -1735,6 +1742,7 @@ class BrowserSession(BaseModel):
page = await self.get_current_page()
await page.wait_for_selector(selector, state='visible', timeout=timeout)
+ @observe(name='remove_highlights', ignore_output=True, ignore_input=True)
@require_initialization
@time_execution_async('--remove_highlights')
async def remove_highlights(self):
@@ -1903,7 +1911,7 @@ class BrowserSession(BaseModel):
return tabs_info
- @retry(timeout=1, retries=0) # Single attempt with 1s timeout, no retries
+ @retry(timeout=2, retries=0) # Single attempt with 1s timeout, no retries
async def _get_page_title(self, page: Page) -> str:
"""Get page title with timeout protection."""
return await page.title()
@@ -2374,6 +2382,7 @@ class BrowserSession(BaseModel):
if elapsed > 1:
self.logger.debug(f'💤 Page network traffic calmed down after {now - start_time:.2f} seconds')
+ @observe()
async def _wait_for_page_and_frames_load(self, timeout_overwrite: float | None = None):
"""
Ensures page is fully loaded before continuing.
@@ -2627,6 +2636,7 @@ class BrowserSession(BaseModel):
structure = await page.evaluate(debug_script)
return structure
+ @observe(ignore_output=True)
@time_execution_async('--get_state_summary')
@require_initialization
async def get_state_summary(self, cache_clickable_elements_hashes: bool) -> BrowserStateSummary:
@@ -2670,6 +2680,7 @@ class BrowserSession(BaseModel):
return self._cached_browser_state_summary
+ @observe(name='get_updated_state')
async def _get_updated_state(self, focus_element: int = -1) -> BrowserStateSummary:
"""Update and return state."""
@@ -2794,6 +2805,7 @@ class BrowserSession(BaseModel):
raise
# region - Browser Actions
+ @observe(name='take_screenshot')
@require_initialization
@time_execution_async('--take_screenshot')
async def take_screenshot(self, full_page: bool = False) -> str:
@@ -3352,6 +3364,7 @@ class BrowserSession(BaseModel):
return page
+ @observe(name='create_new_tab')
@time_execution_async('--create_new_tab')
async def create_new_tab(self, url: str | None = None) -> Page:
"""Create a new tab and optionally navigate to a URL"""
@@ -3436,19 +3449,21 @@ class BrowserSession(BaseModel):
return new_page
# region - Helper methods for easier access to the DOM
-
+ @observe(name='get_selector_map')
@require_initialization
async def get_selector_map(self) -> SelectorMap:
if self._cached_browser_state_summary is None:
return {}
return self._cached_browser_state_summary.selector_map
+ @observe(name='get_element_by_index')
@require_initialization
async def get_element_by_index(self, index: int) -> ElementHandle | None:
selector_map = await self.get_selector_map()
element_handle = await self.get_locate_element(selector_map[index])
return element_handle
+ @observe(name='is_file_input_by_index')
async def is_file_input_by_index(self, index: int) -> bool:
try:
selector_map = await self.get_selector_map()
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index c480f8c4c..3c453784b 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -7,7 +7,9 @@ import re
from collections.abc import Awaitable, Callable
from typing import Any, Generic, TypeVar, cast
+from lmnr import Laminar
from pydantic import BaseModel
+from traitlets import observe
from browser_use.agent.views import ActionModel, ActionResult
from browser_use.browser import BrowserSession
@@ -84,6 +86,7 @@ class Controller(Generic[Context]):
self._register_done_action(output_model)
# Basic Navigation Actions
+ @observe('search_google')
@self.registry.action(
'Search the query in Google, the query should be a search query like humans search in Google, concrete and not vague or super long.',
param_model=SearchGoogleAction,
@@ -106,6 +109,7 @@ class Controller(Generic[Context]):
extracted_content=msg, include_in_memory=True, long_term_memory=f"Searched Google for '{params.query}'"
)
+ @observe('go_to_url')
@self.registry.action(
'Navigate to URL, set new_tab=True to open in new tab, False to navigate in current tab', param_model=GoToUrlAction
)
@@ -148,6 +152,7 @@ class Controller(Generic[Context]):
# Re-raise non-network errors (including URLNotAllowedError for unauthorized domains)
raise
+ @observe('go_back')
@self.registry.action('Go back', param_model=NoParamsAction)
async def go_back(_: NoParamsAction, browser_session: BrowserSession):
await browser_session.go_back()
@@ -156,6 +161,7 @@ class Controller(Generic[Context]):
return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory='Navigated back')
# wait for x seconds
+ @observe('wait')
@self.registry.action('Wait for x seconds default 3')
async def wait(seconds: int = 3):
msg = f'🕒 Waiting for {seconds} seconds'
@@ -164,6 +170,7 @@ class Controller(Generic[Context]):
return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=f'Waited for {seconds} seconds')
# Element Interaction Actions
+ @observe('click_element_by_index')
@self.registry.action('Click element by index', param_model=ClickElementAction)
async def click_element_by_index(params: ClickElementAction, browser_session: BrowserSession):
# Browser is now a BrowserSession itself
@@ -228,6 +235,7 @@ class Controller(Generic[Context]):
logger.warning(f'Element not clickable with index {params.index} - most likely the page changed')
return ActionResult(error=error_msg, success=False)
+ @observe('input_text')
@self.registry.action(
'Click and input text into a input interactive element',
param_model=InputTextAction,
@@ -256,6 +264,7 @@ class Controller(Generic[Context]):
long_term_memory=f"Input '{params.text}' into element {params.index}.",
)
+ @observe('upload_file')
@self.registry.action('Upload file to interactive element with file path', param_model=UploadFileAction)
async def upload_file(params: UploadFileAction, browser_session: BrowserSession, available_file_paths: list[str]):
if params.path not in available_file_paths:
@@ -295,6 +304,7 @@ class Controller(Generic[Context]):
return ActionResult(error=msg)
# Tab Management Actions
+ @observe('switch_tab')
@self.registry.action('Switch tab', param_model=SwitchTabAction)
async def switch_tab(params: SwitchTabAction, browser_session: BrowserSession):
await browser_session.switch_to_tab(params.page_id)
@@ -310,6 +320,7 @@ class Controller(Generic[Context]):
extracted_content=msg, include_in_memory=True, long_term_memory=f'Switched to tab {params.page_id}'
)
+ @observe('close_tab')
@self.registry.action('Close an existing tab', param_model=CloseTabAction)
async def close_tab(params: CloseTabAction, browser_session: BrowserSession):
await browser_session.switch_to_tab(params.page_id)
@@ -327,6 +338,7 @@ class Controller(Generic[Context]):
)
# Content Actions
+ @observe('extract_structured_data')
@self.registry.action(
"""Extract structured, semantic data (e.g. product description, price, all information about XYZ) from the current webpage based on a textual query.
Only use this for extracting info from a single product/article page, not for entire listings or search results pages.
@@ -481,6 +493,7 @@ Explain the content of the page and that the requested information is not availa
# include_extracted_content_only_once=True,
# )
+ @observe('scroll')
@self.registry.action(
'Scroll the page by one page (set down=True to scroll down, down=False to scroll up)',
param_model=ScrollAction,
@@ -517,6 +530,7 @@ Explain the content of the page and that the requested information is not availa
)
# send keys
+ @observe('send_keys')
@self.registry.action(
'Send strings of special keys to use Playwright page.keyboard.press - examples include Escape, Backspace, Insert, PageDown, Delete, Enter, or Shortcuts such as `Control+o`, `Control+Shift+T`',
param_model=SendKeysAction,
@@ -539,6 +553,7 @@ Explain the content of the page and that the requested information is not availa
logger.info(msg)
return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=f'Sent keys: {params.keys}')
+ @observe('scroll_to_text')
@self.registry.action(
description='Scroll to a text in the current page',
)
@@ -587,18 +602,21 @@ Explain the content of the page and that the requested information is not availa
return ActionResult(error=msg, include_in_memory=True)
# File System Actions
+ @observe('write_file')
@self.registry.action('Write content to file_name in file system, use only .md or .txt extensions.')
async def write_file(file_name: str, content: str, file_system: FileSystem):
result = await file_system.write_file(file_name, content)
logger.info(f'💾 {result}')
return ActionResult(extracted_content=result, include_in_memory=True, long_term_memory=result)
+ @observe('append_file')
@self.registry.action('Append content to file_name in file system')
async def append_file(file_name: str, content: str, file_system: FileSystem):
result = await file_system.append_file(file_name, content)
logger.info(f'💾 {result}')
return ActionResult(extracted_content=result, include_in_memory=True, long_term_memory=result)
+ @observe('read_file')
@self.registry.action('Read file_name from file system')
async def read_file(file_name: str, available_file_paths: list[str], file_system: FileSystem):
if available_file_paths and file_name in available_file_paths:
@@ -1014,24 +1032,24 @@ Explain the content of the page and that the requested information is not availa
for action_name, params in action.model_dump(exclude_unset=True).items():
if params is not None:
- # with Laminar.start_as_current_span(
- # name=action_name,
- # input={
- # 'action': action_name,
- # 'params': params,
- # },
- # span_type='TOOL',
- # ):
- result = await self.registry.execute_action(
- action_name=action_name,
- params=params,
- browser_session=browser_session,
- page_extraction_llm=page_extraction_llm,
- file_system=file_system,
- sensitive_data=sensitive_data,
- available_file_paths=available_file_paths,
- context=context,
- )
+ with Laminar.start_as_current_span(
+ name=action_name,
+ input={
+ 'action': action_name,
+ 'params': params,
+ },
+ span_type='TOOL',
+ ):
+ result = await self.registry.execute_action(
+ action_name=action_name,
+ params=params,
+ browser_session=browser_session,
+ page_extraction_llm=page_extraction_llm,
+ file_system=file_system,
+ sensitive_data=sensitive_data,
+ available_file_paths=available_file_paths,
+ context=context,
+ )
# Laminar.set_span_output(result)