Skip to content

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

Add LLM models module and update agent initialization for default LLM

Magnus Müller570b15d26ae7
diff --git a/browser_use/__init__.py b/browser_use/__init__.py
index bac3988eb..c3a4e551d 100644
--- a/browser_use/__init__.py
+++ b/browser_use/__init__.py
@@ -51,6 +51,7 @@ if TYPE_CHECKING:
from browser_use.browser import BrowserProfile, BrowserSession
from browser_use.browser import BrowserSession as Browser
from browser_use.dom.service import DomService
+ from browser_use.llm import models as llm
from browser_use.llm.anthropic.chat import ChatAnthropic
from browser_use.llm.azure.chat import ChatAzureOpenAI
from browser_use.llm.google.chat import ChatGoogle
@@ -85,6 +86,8 @@ _LAZY_IMPORTS = {
'ChatGroq': ('browser_use.llm.groq.chat', 'ChatGroq'),
'ChatAzureOpenAI': ('browser_use.llm.azure.chat', 'ChatAzureOpenAI'),
'ChatOllama': ('browser_use.llm.ollama.chat', 'ChatOllama'),
+ # LLM models module
+ 'llm': ('browser_use.llm.models', None),
}
@@ -96,7 +99,11 @@ def __getattr__(name: str):
from importlib import import_module
module = import_module(module_path)
- attr = getattr(module, attr_name)
+ if attr_name is None:
+ # For modules like 'llm', return the module itself
+ attr = module
+ else:
+ attr = getattr(module, attr_name)
# Cache the imported attribute in the module's globals
globals()[name] = attr
return attr
@@ -126,4 +133,6 @@ __all__ = [
'ChatOllama',
'Tools',
'Controller',
+ # LLM models module
+ 'llm',
]
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 6c693d075..b9b035591 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -128,7 +128,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
def __init__(
self,
task: str,
- llm: BaseChatModel = ChatOpenAI(model='gpt-4.1-mini'),
+ llm: BaseChatModel | None = None,
# Optional parameters
browser_profile: BrowserProfile | None = None,
browser_session: BrowserSession | None = None,
@@ -181,6 +181,23 @@ class Agent(Generic[Context, AgentStructuredOutput]):
include_recent_events: bool = False,
**kwargs,
):
+ if llm is None:
+ default_llm_name = CONFIG.DEFAULT_LLM
+ if default_llm_name:
+ try:
+ from browser_use.llm.models import get_llm_by_name
+
+ llm = get_llm_by_name(default_llm_name)
+ except (ImportError, ValueError) as e:
+ # Use the logger that's already imported at the top of the module
+ logger.warning(
+ f'Failed to create default LLM "{default_llm_name}": {e}. Falling back to ChatOpenAI(model="gpt-4.1-mini")'
+ )
+ llm = ChatOpenAI(model='gpt-4.1-mini')
+ else:
+ # No default LLM specified, use the original default
+ llm = ChatOpenAI(model='gpt-4.1-mini')
+
if page_extraction_llm is None:
page_extraction_llm = llm
if available_file_paths is None:
diff --git a/browser_use/config.py b/browser_use/config.py
index 4114ab93b..e2a3b4194 100644
--- a/browser_use/config.py
+++ b/browser_use/config.py
@@ -159,6 +159,10 @@ class OldConfig:
def SKIP_LLM_API_KEY_VERIFICATION(self) -> bool:
return os.getenv('SKIP_LLM_API_KEY_VERIFICATION', 'false').lower()[:1] in 'ty1'
+ @property
+ def DEFAULT_LLM(self) -> str:
+ return os.getenv('DEFAULT_LLM', '')
+
# Runtime hints
@property
def IN_DOCKER(self) -> bool:
@@ -203,6 +207,7 @@ class FlatEnvConfig(BaseSettings):
AZURE_OPENAI_ENDPOINT: str = Field(default='')
AZURE_OPENAI_KEY: str = Field(default='')
SKIP_LLM_API_KEY_VERIFICATION: bool = Field(default=False)
+ DEFAULT_LLM: str = Field(default='')
# Runtime hints
IN_DOCKER: bool | None = Field(default=None)
diff --git a/browser_use/llm/__init__.py b/browser_use/llm/__init__.py
index f409f1839..2216a3d33 100644
--- a/browser_use/llm/__init__.py
+++ b/browser_use/llm/__init__.py
@@ -37,6 +37,9 @@ if TYPE_CHECKING:
from browser_use.llm.openai.chat import ChatOpenAI
from browser_use.llm.openrouter.chat import ChatOpenRouter
+# Import all models from models.py
+from browser_use.llm.models import *
+
# Lazy imports mapping for heavy chat models
_LAZY_IMPORTS = {
'ChatAnthropic': ('browser_use.llm.anthropic.chat', 'ChatAnthropic'),
diff --git a/browser_use/llm/models.py b/browser_use/llm/models.py
new file mode 100644
index 000000000..d09cd4c36
--- /dev/null
+++ b/browser_use/llm/models.py
@@ -0,0 +1,171 @@
+"""
+Convenient access to LLM models.
+
+Usage:
+ from browser_use import llm
+
+ # Simple model access
+ model = llm.azure_gpt_4_1_mini
+ model = llm.openai_gpt_4o
+ model = llm.google_gemini_2_5_pro
+"""
+
+import os
+from typing import TYPE_CHECKING
+
+from browser_use.llm.azure.chat import ChatAzureOpenAI
+from browser_use.llm.google.chat import ChatGoogle
+from browser_use.llm.openai.chat import ChatOpenAI
+
+if TYPE_CHECKING:
+ from browser_use.llm.base import BaseChatModel
+
+# Type stubs for IDE autocomplete
+openai_gpt_4o: 'BaseChatModel'
+openai_gpt_4o_mini: 'BaseChatModel'
+openai_gpt_4_1_mini: 'BaseChatModel'
+openai_o1: 'BaseChatModel'
+openai_o1_mini: 'BaseChatModel'
+openai_o1_pro: 'BaseChatModel'
+openai_o3: 'BaseChatModel'
+openai_o3_mini: 'BaseChatModel'
+openai_o3_pro: 'BaseChatModel'
+openai_o4_mini: 'BaseChatModel'
+openai_gpt_5: 'BaseChatModel'
+openai_gpt_5_mini: 'BaseChatModel'
+openai_gpt_5_nano: 'BaseChatModel'
+
+azure_gpt_4o: 'BaseChatModel'
+azure_gpt_4o_mini: 'BaseChatModel'
+azure_gpt_4_1_mini: 'BaseChatModel'
+azure_o1: 'BaseChatModel'
+azure_o1_mini: 'BaseChatModel'
+azure_o1_pro: 'BaseChatModel'
+azure_o3: 'BaseChatModel'
+azure_o3_mini: 'BaseChatModel'
+azure_o3_pro: 'BaseChatModel'
+azure_gpt_5: 'BaseChatModel'
+azure_gpt_5_mini: 'BaseChatModel'
+
+google_gemini_2_0_flash: 'BaseChatModel'
+google_gemini_2_0_pro: 'BaseChatModel'
+google_gemini_2_5_pro: 'BaseChatModel'
+google_gemini_2_5_flash: 'BaseChatModel'
+google_gemini_2_5_flash_lite: 'BaseChatModel'
+
+
+def get_llm_by_name(model_name: str):
+ """
+ Factory function to create LLM instances from string names with API keys from environment.
+
+ Args:
+ model_name: String name like 'azure_gpt_4_1_mini', 'openai_gpt_4o', etc.
+
+ Returns:
+ LLM instance with API keys from environment variables
+
+ Raises:
+ ValueError: If model_name is not recognized
+ """
+ if not model_name:
+ raise ValueError('Model name cannot be empty')
+
+ # Parse model name
+ parts = model_name.split('_', 1)
+ if len(parts) < 2:
+ raise ValueError(f"Invalid model name format: '{model_name}'. Expected format: 'provider_model_name'")
+
+ provider = parts[0]
+ model_part = parts[1]
+
+ # Convert underscores back to dots/dashes for actual model names
+ if 'gpt_4_1_mini' in model_part:
+ model = model_part.replace('gpt_4_1_mini', 'gpt-4.1-mini')
+ elif 'gpt_4o_mini' in model_part:
+ model = model_part.replace('gpt_4o_mini', 'gpt-4o-mini')
+ elif 'gpt_4o' in model_part:
+ model = model_part.replace('gpt_4o', 'gpt-4o')
+ elif 'gemini_2_0' in model_part:
+ model = model_part.replace('gemini_2_0', 'gemini-2.0').replace('_', '-')
+ elif 'gemini_2_5' in model_part:
+ model = model_part.replace('gemini_2_5', 'gemini-2.5').replace('_', '-')
+ else:
+ model = model_part.replace('_', '-')
+
+ # OpenAI Models
+ if provider == 'openai':
+ api_key = os.getenv('OPENAI_API_KEY')
+ return ChatOpenAI(model=model, api_key=api_key)
+
+ # Azure OpenAI Models
+ elif provider == 'azure':
+ api_key = os.getenv('AZURE_OPENAI_KEY') or os.getenv('AZURE_OPENAI_API_KEY')
+ azure_endpoint = os.getenv('AZURE_OPENAI_ENDPOINT')
+ return ChatAzureOpenAI(model=model, api_key=api_key, azure_endpoint=azure_endpoint)
+
+ # Google Models
+ elif provider == 'google':
+ api_key = os.getenv('GOOGLE_API_KEY')
+ return ChatGoogle(model=model, api_key=api_key)
+
+ else:
+ available_providers = ['openai', 'azure', 'google']
+ raise ValueError(f"Unknown provider: '{provider}'. Available providers: {', '.join(available_providers)}")
+
+
+# Pre-configured model instances (lazy loaded via __getattr__)
+def __getattr__(name: str) -> 'BaseChatModel':
+ """Create model instances on demand with API keys from environment."""
+ # Handle chat classes first
+ if name == 'ChatOpenAI':
+ return ChatOpenAI # type: ignore
+ elif name == 'ChatAzureOpenAI':
+ return ChatAzureOpenAI # type: ignore
+ elif name == 'ChatGoogle':
+ return ChatGoogle # type: ignore
+
+ # Handle model instances - these are the main use case
+ try:
+ return get_llm_by_name(name)
+ except ValueError:
+ raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
+
+
+__all__ = [
+ 'ChatOpenAI',
+ 'ChatAzureOpenAI',
+ 'ChatGoogle',
+ 'get_llm_by_name',
+ # OpenAI instances - created on demand
+ 'openai_gpt_4o',
+ 'openai_gpt_4o_mini',
+ 'openai_gpt_4_1_mini',
+ 'openai_o1',
+ 'openai_o1_mini',
+ 'openai_o1_pro',
+ 'openai_o3',
+ 'openai_o3_mini',
+ 'openai_o3_pro',
+ 'openai_o4_mini',
+ 'openai_gpt_5',
+ 'openai_gpt_5_mini',
+ 'openai_gpt_5_nano',
+ # Azure instances - created on demand
+ 'azure_gpt_4o',
+ 'azure_gpt_4o_mini',
+ 'azure_gpt_4_1_mini',
+ 'azure_o1',
+ 'azure_o1_mini',
+ 'azure_o1_pro',
+ 'azure_o3',
+ 'azure_o3_mini',
+ 'azure_o3_pro',
+ 'azure_gpt_5',
+ 'azure_gpt_5_mini',
+ # Google instances - created on demand
+ 'google_gemini_2_0_flash',
+ 'google_gemini_2_0_pro',
+ 'google_gemini_2_5_pro',
+ 'google_gemini_2_5_flash',
+ 'google_gemini_2_5_flash_lite',
+]