Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
lazy imports and bump some versions
mertunsallce5bfe6195f9
diff --git a/browser_use/__init__.py b/browser_use/__init__.pyindex 1635b1e79..0c079efe7 100644--- a/browser_use/__init__.py+++ b/browser_use/__init__.py@@ -1,4 +1,5 @@import os+from typing import TYPE_CHECKINGfrom browser_use.logging_config import setup_logging@@ -13,21 +14,6 @@ else:# Monkeypatch BaseSubprocessTransport.__del__ to handle closed event loops gracefullyfrom asyncio import base_subprocess-from browser_use.agent.prompts import SystemPrompt-from browser_use.agent.service import Agent-from browser_use.agent.views import ActionModel, ActionResult, AgentHistoryList-from browser_use.browser import Browser, BrowserConfig, BrowserContext, BrowserContextConfig, BrowserProfile, BrowserSession-from browser_use.controller.service import Controller-from browser_use.dom.service import DomService-from browser_use.llm import (- ChatAnthropic,- ChatAzureOpenAI,- ChatGoogle,- ChatGroq,- ChatOllama,- ChatOpenAI,-)-_original_del = base_subprocess.BaseSubprocessTransport.__del__@@ -50,6 +36,71 @@ def _patched_del(self):base_subprocess.BaseSubprocessTransport.__del__ = _patched_del+# Type stubs for lazy imports - fixes linter warnings+if TYPE_CHECKING:+ from browser_use.agent.prompts import SystemPrompt+ from browser_use.agent.service import Agent+ from browser_use.agent.views import ActionModel, ActionResult, AgentHistoryList+ from browser_use.browser import Browser, BrowserConfig, BrowserContext, BrowserContextConfig, BrowserProfile, BrowserSession+ from browser_use.controller.service import Controller+ from browser_use.dom.service import DomService+ from browser_use.llm.anthropic.chat import ChatAnthropic+ from browser_use.llm.azure.chat import ChatAzureOpenAI+ from browser_use.llm.google.chat import ChatGoogle+ from browser_use.llm.groq.chat import ChatGroq+ from browser_use.llm.ollama.chat import ChatOllama+ from browser_use.llm.openai.chat import ChatOpenAI+++# Lazy imports mapping - only import when actually accessed+_LAZY_IMPORTS = {+ # Agent service (heavy due to dependencies)+ 'Agent': ('browser_use.agent.service', 'Agent'),+ # System prompt (moderate weight due to agent.views imports)+ 'SystemPrompt': ('browser_use.agent.prompts', 'SystemPrompt'),+ # Agent views (very heavy - over 1 second!)+ 'ActionModel': ('browser_use.agent.views', 'ActionModel'),+ 'ActionResult': ('browser_use.agent.views', 'ActionResult'),+ 'AgentHistoryList': ('browser_use.agent.views', 'AgentHistoryList'),+ # Browser components (heavy due to playwright/patchright)+ 'Browser': ('browser_use.browser', 'Browser'),+ 'BrowserConfig': ('browser_use.browser', 'BrowserConfig'),+ 'BrowserSession': ('browser_use.browser', 'BrowserSession'),+ 'BrowserProfile': ('browser_use.browser', 'BrowserProfile'),+ 'BrowserContext': ('browser_use.browser', 'BrowserContext'),+ 'BrowserContextConfig': ('browser_use.browser', 'BrowserContextConfig'),+ # Controller (moderate weight)+ 'Controller': ('browser_use.controller.service', 'Controller'),+ # DOM service (moderate weight)+ 'DomService': ('browser_use.dom.service', 'DomService'),+ # Chat models (very heavy imports)+ 'ChatOpenAI': ('browser_use.llm.openai.chat', 'ChatOpenAI'),+ 'ChatGoogle': ('browser_use.llm.google.chat', 'ChatGoogle'),+ 'ChatAnthropic': ('browser_use.llm.anthropic.chat', 'ChatAnthropic'),+ 'ChatGroq': ('browser_use.llm.groq.chat', 'ChatGroq'),+ 'ChatAzureOpenAI': ('browser_use.llm.azure.chat', 'ChatAzureOpenAI'),+ 'ChatOllama': ('browser_use.llm.ollama.chat', 'ChatOllama'),+}+++def __getattr__(name: str):+ """Lazy import mechanism - only import modules when they're actually accessed."""+ if name in _LAZY_IMPORTS:+ module_path, attr_name = _LAZY_IMPORTS[name]+ try:+ from importlib import import_module++ module = import_module(module_path)+ attr = getattr(module, attr_name)+ # Cache the imported attribute in the module's globals+ globals()[name] = attr+ return attr+ except ImportError as e:+ raise ImportError(f'Failed to import {name} from {module_path}: {e}') from e++ raise AttributeError(f"module '{__name__}' has no attribute '{name}'")++__all__ = ['Agent','Browser',diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 2fd2a7d84..da243ab7e 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -34,7 +34,8 @@ from bubus import EventBusfrom pydantic import ValidationErrorfrom uuid_extensions import uuid7str-from browser_use.agent.gif import create_history_gif+# Lazy import for gif to avoid heavy agent.views import at startup+# from browser_use.agent.gif import create_history_giffrom browser_use.agent.message_manager.service import (MessageManager,)@@ -1329,6 +1330,9 @@ class Agent(Generic[Context, AgentStructuredOutput]):if isinstance(self.settings.generate_gif, str):output_path = self.settings.generate_gif+ # Lazy import gif module to avoid heavy startup cost+ from browser_use.agent.gif import create_history_gif+create_history_gif(task=self.task, history=self.state.history, output_path=output_path)# Emit output file generated event for GIFdiff --git a/browser_use/browser/__init__.py b/browser_use/browser/__init__.pyindex eaea05808..d6c13f2d6 100644--- a/browser_use/browser/__init__.py+++ b/browser_use/browser/__init__.py@@ -1,6 +1,41 @@-from .browser import Browser, BrowserConfig-from .context import BrowserContext, BrowserContextConfig-from .profile import BrowserProfile-from .session import BrowserSession+from typing import TYPE_CHECKING++# Type stubs for lazy imports+if TYPE_CHECKING:+ from .browser import Browser, BrowserConfig+ from .context import BrowserContext, BrowserContextConfig+ from .profile import BrowserProfile+ from .session import BrowserSession++# Lazy imports mapping for heavy browser components+_LAZY_IMPORTS = {+ 'Browser': ('.browser', 'Browser'),+ 'BrowserConfig': ('.browser', 'BrowserConfig'),+ 'BrowserContext': ('.context', 'BrowserContext'),+ 'BrowserContextConfig': ('.context', 'BrowserContextConfig'),+ 'BrowserProfile': ('.profile', 'BrowserProfile'),+ 'BrowserSession': ('.session', 'BrowserSession'),+}+++def __getattr__(name: str):+ """Lazy import mechanism for heavy browser components."""+ if name in _LAZY_IMPORTS:+ module_path, attr_name = _LAZY_IMPORTS[name]+ try:+ from importlib import import_module++ # Use relative import for current package+ full_module_path = f'browser_use.browser{module_path}'+ module = import_module(full_module_path)+ attr = getattr(module, attr_name)+ # Cache the imported attribute in the module's globals+ globals()[name] = attr+ return attr+ except ImportError as e:+ raise ImportError(f'Failed to import {name} from {full_module_path}: {e}') from e++ raise AttributeError(f"module '{__name__}' has no attribute '{name}'")+__all__ = ['Browser', 'BrowserConfig', 'BrowserContext', 'BrowserContextConfig', 'BrowserSession', 'BrowserProfile']diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex e22a1d699..b4cfa5665 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -51,8 +51,10 @@ from browser_use.browser.views import (TabInfo,URLNotAllowedError,)-from browser_use.dom.clickable_element_processor.service import ClickableElementProcessor-from browser_use.dom.service import DomService++# Lazy imports for heavy DOM services to improve startup time+# from browser_use.dom.clickable_element_processor.service import ClickableElementProcessor+# from browser_use.dom.service import DomServicefrom browser_use.dom.views import DOMElementNode, SelectorMapfrom browser_use.utils import (is_new_tab_page,@@ -3103,6 +3105,9 @@ class BrowserSession(BaseModel):# Find out which elements are new# Do this only if url has not changedif cache_clickable_elements_hashes:+ # Lazy import heavy DOM service+ from browser_use.dom.clickable_element_processor.service import ClickableElementProcessor+# if we are on the same url as the last state, we can use the cached hashesif self._cached_clickable_element_hashes and self._cached_clickable_element_hashes.url == updated_state.url:# Pointers, feel free to edit in place@@ -3195,6 +3200,8 @@ class BrowserSession(BaseModel):self.logger.debug(f'PDF auto-download check failed: {type(e).__name__}: {e}')self.logger.debug('🌳 Starting DOM processing...')+ from browser_use.dom.service import DomService+dom_service = DomService(page, logger=self.logger)try:content = await asyncio.wait_for(diff --git a/browser_use/llm/__init__.py b/browser_use/llm/__init__.pyindex 59169ba34..f409f1839 100644--- a/browser_use/llm/__init__.py+++ b/browser_use/llm/__init__.py@@ -4,14 +4,10 @@ We have switched all of our code from langchain to openai.types.chat.chat_compleFor easier transition we have"""-from browser_use.llm.anthropic.chat import ChatAnthropic-from browser_use.llm.aws.chat_anthropic import ChatAnthropicBedrock-from browser_use.llm.aws.chat_bedrock import ChatAWSBedrock-from browser_use.llm.azure.chat import ChatAzureOpenAI+from typing import TYPE_CHECKING++# Lightweight imports that are commonly usedfrom browser_use.llm.base import BaseChatModel-from browser_use.llm.deepseek.chat import ChatDeepSeek-from browser_use.llm.google.chat import ChatGoogle-from browser_use.llm.groq.chat import ChatGroqfrom browser_use.llm.messages import (AssistantMessage,BaseMessage,@@ -27,11 +23,52 @@ from browser_use.llm.messages import (from browser_use.llm.messages import (ContentPartTextParam as ContentText,)-from browser_use.llm.ollama.chat import ChatOllama-from browser_use.llm.openai.chat import ChatOpenAI-from browser_use.llm.openrouter.chat import ChatOpenRouter-# Make better names for the message+# Type stubs for lazy imports+if TYPE_CHECKING:+ from browser_use.llm.anthropic.chat import ChatAnthropic+ from browser_use.llm.aws.chat_anthropic import ChatAnthropicBedrock+ from browser_use.llm.aws.chat_bedrock import ChatAWSBedrock+ from browser_use.llm.azure.chat import ChatAzureOpenAI+ from browser_use.llm.deepseek.chat import ChatDeepSeek+ from browser_use.llm.google.chat import ChatGoogle+ from browser_use.llm.groq.chat import ChatGroq+ from browser_use.llm.ollama.chat import ChatOllama+ from browser_use.llm.openai.chat import ChatOpenAI+ from browser_use.llm.openrouter.chat import ChatOpenRouter++# Lazy imports mapping for heavy chat models+_LAZY_IMPORTS = {+ 'ChatAnthropic': ('browser_use.llm.anthropic.chat', 'ChatAnthropic'),+ 'ChatAnthropicBedrock': ('browser_use.llm.aws.chat_anthropic', 'ChatAnthropicBedrock'),+ 'ChatAWSBedrock': ('browser_use.llm.aws.chat_bedrock', 'ChatAWSBedrock'),+ 'ChatAzureOpenAI': ('browser_use.llm.azure.chat', 'ChatAzureOpenAI'),+ 'ChatDeepSeek': ('browser_use.llm.deepseek.chat', 'ChatDeepSeek'),+ 'ChatGoogle': ('browser_use.llm.google.chat', 'ChatGoogle'),+ 'ChatGroq': ('browser_use.llm.groq.chat', 'ChatGroq'),+ 'ChatOllama': ('browser_use.llm.ollama.chat', 'ChatOllama'),+ 'ChatOpenAI': ('browser_use.llm.openai.chat', 'ChatOpenAI'),+ 'ChatOpenRouter': ('browser_use.llm.openrouter.chat', 'ChatOpenRouter'),+}+++def __getattr__(name: str):+ """Lazy import mechanism for heavy chat model imports."""+ if name in _LAZY_IMPORTS:+ module_path, attr_name = _LAZY_IMPORTS[name]+ try:+ from importlib import import_module++ module = import_module(module_path)+ attr = getattr(module, attr_name)+ # Cache the imported attribute in the module's globals+ globals()[name] = attr+ return attr+ except ImportError as e:+ raise ImportError(f'Failed to import {name} from {module_path}: {e}') from e++ raise AttributeError(f"module '{__name__}' has no attribute '{name}'")+__all__ = [# Message types -> for easier transition from langchaindiff --git a/browser_use/llm/aws/__init__.py b/browser_use/llm/aws/__init__.pyindex 69afb3a95..cb2def920 100644--- a/browser_use/llm/aws/__init__.py+++ b/browser_use/llm/aws/__init__.py@@ -1,5 +1,34 @@-from browser_use.llm.aws.chat_anthropic import ChatAnthropicBedrock-from browser_use.llm.aws.chat_bedrock import ChatAWSBedrock+from typing import TYPE_CHECKING++# Type stubs for lazy imports+if TYPE_CHECKING:+ from browser_use.llm.aws.chat_anthropic import ChatAnthropicBedrock+ from browser_use.llm.aws.chat_bedrock import ChatAWSBedrock++# Lazy imports mapping for AWS chat models+_LAZY_IMPORTS = {+ 'ChatAnthropicBedrock': ('browser_use.llm.aws.chat_anthropic', 'ChatAnthropicBedrock'),+ 'ChatAWSBedrock': ('browser_use.llm.aws.chat_bedrock', 'ChatAWSBedrock'),+}+++def __getattr__(name: str):+ """Lazy import mechanism for AWS chat models."""+ if name in _LAZY_IMPORTS:+ module_path, attr_name = _LAZY_IMPORTS[name]+ try:+ from importlib import import_module++ module = import_module(module_path)+ attr = getattr(module, attr_name)+ # Cache the imported attribute in the module's globals+ globals()[name] = attr+ return attr+ except ImportError as e:+ raise ImportError(f'Failed to import {name} from {module_path}: {e}') from e++ raise AttributeError(f"module '{__name__}' has no attribute '{name}'")+__all__ = ['ChatAWSBedrock',diff --git a/browser_use/mcp/__init__.py b/browser_use/mcp/__init__.pyindex 08c759377..fe97674b4 100644--- a/browser_use/mcp/__init__.py+++ b/browser_use/mcp/__init__.py@@ -3,16 +3,38 @@This module provides integration with MCP servers and clients for browser automation."""-from browser_use.mcp.client import MCPClient-from browser_use.mcp.controller import MCPToolWrapper+from typing import TYPE_CHECKING++# Type stubs for lazy imports+if TYPE_CHECKING:+ from browser_use.mcp.client import MCPClient+ from browser_use.mcp.controller import MCPToolWrapper+ from browser_use.mcp.server import BrowserUseServer++# Lazy imports mapping+_LAZY_IMPORTS = {+ 'MCPClient': ('browser_use.mcp.client', 'MCPClient'),+ 'MCPToolWrapper': ('browser_use.mcp.controller', 'MCPToolWrapper'),+ 'BrowserUseServer': ('browser_use.mcp.server', 'BrowserUseServer'),+}-__all__ = ['MCPClient', 'MCPToolWrapper', 'BrowserUseServer']+def __getattr__(name: str):+ """Lazy import to avoid importing heavy modules when not needed."""+ if name in _LAZY_IMPORTS:+ module_path, attr_name = _LAZY_IMPORTS[name]+ try:+ from importlib import import_module-def __getattr__(name):- """Lazy import to avoid importing server module when only client is needed."""- if name == 'BrowserUseServer':- from browser_use.mcp.server import BrowserUseServer+ module = import_module(module_path)+ attr = getattr(module, attr_name)+ # Cache the imported attribute in the module's globals+ globals()[name] = attr+ return attr+ except ImportError as e:+ raise ImportError(f'Failed to import {name} from {module_path}: {e}') from e- return BrowserUseServerraise AttributeError(f"module '{__name__}' has no attribute '{name}'")+++__all__ = ['MCPClient', 'MCPToolWrapper', 'BrowserUseServer']diff --git a/browser_use/telemetry/__init__.py b/browser_use/telemetry/__init__.pyindex 40282dc9e..222bc9ba1 100644--- a/browser_use/telemetry/__init__.py+++ b/browser_use/telemetry/__init__.py@@ -2,18 +2,50 @@Telemetry for Browser Use."""-from browser_use.telemetry.service import ProductTelemetry-from browser_use.telemetry.views import (- BaseTelemetryEvent,- CLITelemetryEvent,- MCPClientTelemetryEvent,- MCPServerTelemetryEvent,-)+from typing import TYPE_CHECKING++# Type stubs for lazy imports+if TYPE_CHECKING:+ from browser_use.telemetry.service import ProductTelemetry+ from browser_use.telemetry.views import (+ BaseTelemetryEvent,+ CLITelemetryEvent,+ MCPClientTelemetryEvent,+ MCPServerTelemetryEvent,+ )++# Lazy imports mapping+_LAZY_IMPORTS = {+ 'ProductTelemetry': ('browser_use.telemetry.service', 'ProductTelemetry'),+ 'BaseTelemetryEvent': ('browser_use.telemetry.views', 'BaseTelemetryEvent'),+ 'CLITelemetryEvent': ('browser_use.telemetry.views', 'CLITelemetryEvent'),+ 'MCPClientTelemetryEvent': ('browser_use.telemetry.views', 'MCPClientTelemetryEvent'),+ 'MCPServerTelemetryEvent': ('browser_use.telemetry.views', 'MCPServerTelemetryEvent'),+}+++def __getattr__(name: str):+ """Lazy import mechanism for telemetry components."""+ if name in _LAZY_IMPORTS:+ module_path, attr_name = _LAZY_IMPORTS[name]+ try:+ from importlib import import_module++ module = import_module(module_path)+ attr = getattr(module, attr_name)+ # Cache the imported attribute in the module's globals+ globals()[name] = attr+ return attr+ except ImportError as e:+ raise ImportError(f'Failed to import {name} from {module_path}: {e}') from e++ raise AttributeError(f"module '{__name__}' has no attribute '{name}'")+__all__ = ['BaseTelemetryEvent','ProductTelemetry',+ 'CLITelemetryEvent','MCPClientTelemetryEvent','MCPServerTelemetryEvent',- 'CLITelemetryEvent',]diff --git a/pyproject.toml b/pyproject.tomlindex 47fc212dd..9d3cbb632 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -31,10 +31,10 @@ dependencies = ["typing-extensions>=4.12.2","uuid7>=0.1.0","authlib>=1.6.0",- "google-genai>=1.21.1",- "openai>=1.81.0",- "anthropic>=0.54.0",- "groq>=0.28.0",+ "google-genai>=1.26.0",+ "openai>=1.97.0",+ "anthropic>=0.58.2",+ "groq>=0.30.0","ollama>=0.5.1","google-api-python-client>=2.174.0","google-auth>=2.40.3",