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
feat(llm): accept provider-prefixed models in ChatBrowserUse
Saurav Panda4cbc5dfa4d35
diff --git a/README.md b/README.mdindex c44a72641..cc06a6f7d 100644--- a/README.md+++ b/README.md@@ -226,6 +226,21 @@ We optimized **ChatBrowserUse()** specifically for browser automation tasks. OnFor other LLM providers, see our [supported models documentation](https://docs.browser-use.com/supported-models).</details>+<details>+<summary><b>Can I use Claude / GPT / Gemini through ChatBrowserUse?</b></summary>++Yes. `ChatBrowserUse` accepts provider-prefixed model ids, so a single `BROWSER_USE_API_KEY` reaches all of them — no separate OpenAI/Anthropic/Google keys required:++```python+from browser_use import Agent, ChatBrowserUse++llm = ChatBrowserUse(model='anthropic/claude-sonnet-4-6') # or 'openai/gpt-5.5', 'google/gemini-3-pro'+agent = Agent(task='...', llm=llm)+```++For the best speed and cost we still recommend the default `bu-*` models.+</details>+<details><summary><b>Should I use the Browser Use system prompt with the open-source preview model?</b></summary>diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex e746e5cbf..fe325c74a 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -241,10 +241,11 @@ class Agent(Generic[Context, AgentStructuredOutput]):if flash_mode:enable_planning = False- # Auto-configure llm_screenshot_size for Claude Sonnet models+ # Auto-configure llm_screenshot_size for Claude Sonnet, including gateway ids like+ # 'anthropic/claude-sonnet-4-6' (rsplit drops the provider prefix before matching).if llm_screenshot_size is None:model_name = getattr(llm, 'model', '')- if isinstance(model_name, str) and model_name.startswith('claude-sonnet'):+ if isinstance(model_name, str) and model_name.rsplit('/', 1)[-1].startswith('claude-sonnet'):llm_screenshot_size = (1400, 850)logger.info('🖼️ Auto-configured LLM screenshot size for Claude Sonnet: 1400x850')diff --git a/browser_use/beta/service.py b/browser_use/beta/service.pyindex 9b15588a2..f7a20f134 100644--- a/browser_use/beta/service.py+++ b/browser_use/beta/service.py@@ -4310,7 +4310,9 @@ class Agent(Generic[Context, AgentStructuredOutput]):enable_planning = Falseif llm_screenshot_size is None:model_name = getattr(llm, 'model', '')- if isinstance(model_name, str) and model_name.startswith('claude-sonnet'):+ # rsplit drops the provider prefix so gateway ids like 'anthropic/claude-sonnet-4-6'+ # get the same screenshot auto-config as direct Claude Sonnet models.+ if isinstance(model_name, str) and model_name.rsplit('/', 1)[-1].startswith('claude-sonnet'):llm_screenshot_size = (1400, 850)if page_extraction_llm is None:page_extraction_llm = llmdiff --git a/browser_use/llm/browser_use/chat.py b/browser_use/llm/browser_use/chat.pyindex a854e7b45..c67385533 100644--- a/browser_use/llm/browser_use/chat.py+++ b/browser_use/llm/browser_use/chat.py@@ -63,6 +63,8 @@ class ChatBrowserUse(BaseChatModel):- 'bu-3-max': Most capable model- 'bu-1-0': Previous generation model- 'browser-use/bu-30b-a3b-preview': Browser Use Open Source Model+ - Provider-prefixed ids resolved by the gateway, e.g. 'anthropic/claude-sonnet-4-6',+ 'openai/gpt-5.5', 'google/gemini-3-pro'.api_key: API key for browser-use cloud. Defaults to BROWSER_USE_API_KEY env var.base_url: Base URL for the API. Defaults to BROWSER_USE_LLM_URL env var or production URL.timeout: Request timeout in seconds.@@ -70,11 +72,16 @@ class ChatBrowserUse(BaseChatModel):retry_base_delay: Base delay in seconds for exponential backoff (default: 1.0).retry_max_delay: Maximum delay in seconds between retries (default: 60.0)."""- # Validate model name - allow bu-* and browser-use/* patterns- valid_models = ['bu-latest', 'bu-1-0', 'bu-2-0', 'bu-3', 'bu-3-max']- is_valid = model in valid_models or model.startswith('browser-use/')+ # Accept 'bu-*' aliases and any provider-prefixed id; the gateway resolves the+ # latter (anthropic/*, openai/*, google/*, browser-use/*), so we don't enumerate them.+ bu_aliases = ['bu-latest', 'bu-1-0', 'bu-2-0', 'bu-3', 'bu-3-max']+ is_valid = model in bu_aliases or '/' in modelif not is_valid:- raise ValueError(f"Invalid model: '{model}'. Must be one of {valid_models} or start with 'browser-use/'")+ raise ValueError(+ f"Invalid model: '{model}'. Use a 'bu-*' alias ({', '.join(bu_aliases)}) "+ "or a provider-prefixed id like 'anthropic/claude-sonnet-4-6', "+ "'openai/gpt-5.5', or 'google/gemini-3-pro'."+ )# Normalize bu-latest to the current latest modelif model == 'bu-latest':diff --git a/examples/models/browser_use_llm.py b/examples/models/browser_use_llm.pyindex b5b00a4e8..4e38698e9 100644--- a/examples/models/browser_use_llm.py+++ b/examples/models/browser_use_llm.py@@ -20,6 +20,9 @@ if not os.getenv('BROWSER_USE_API_KEY'):async def main():+ # `bu-2-0` is the optimized default. ChatBrowserUse can also route to+ # provider-prefixed models (e.g. 'anthropic/claude-sonnet-4-6', 'openai/gpt-5.5',+ # 'google/gemini-3-pro') through the same gateway - see browser_use_provider_models.py.agent = Agent(task='Find the number of stars of the browser-use repo',llm=ChatBrowserUse(model='bu-2-0'),diff --git a/examples/models/browser_use_provider_models.py b/examples/models/browser_use_provider_models.pynew file mode 100644index 000000000..7201ef96a--- /dev/null+++ b/examples/models/browser_use_provider_models.py@@ -0,0 +1,46 @@+"""+Point ChatBrowserUse at provider-prefixed models via the Browser Use gateway.++`ChatBrowserUse` isn't limited to the `bu-*` models - it also accepts+provider-prefixed ids:++ - 'anthropic/claude-sonnet-4-6'+ - 'openai/gpt-5.5'+ - 'google/gemini-3-pro'++A single `BROWSER_USE_API_KEY` reaches Claude, GPT, and Gemini without+juggling separate OpenAI / Anthropic / Google keys. For the best speed and+cost, the default `bu-*` models are still recommended.++Setup:+1. Get your API key from https://cloud.browser-use.com/new-api-key+2. Set environment variable: export BROWSER_USE_API_KEY="your-key"+"""++import asyncio+import os++from dotenv import load_dotenv++from browser_use import Agent, ChatBrowserUse++load_dotenv()++if not os.getenv('BROWSER_USE_API_KEY'):+ raise ValueError('BROWSER_USE_API_KEY is not set')++# Swap this for any provider-prefixed id the gateway supports, e.g.+# 'openai/gpt-5.5' or 'google/gemini-3-pro'+MODEL = 'anthropic/claude-sonnet-4-6'+++async def main():+ agent = Agent(+ task='Find the number of stars of the browser-use repo',+ llm=ChatBrowserUse(model=MODEL),+ )+ await agent.run()+++if __name__ == '__main__':+ asyncio.run(main())diff --git a/tests/ci/models/test_llm_browseruse.py b/tests/ci/models/test_llm_browseruse.pyindex 4955eb043..8b5f9d1c0 100644--- a/tests/ci/models/test_llm_browseruse.py+++ b/tests/ci/models/test_llm_browseruse.py@@ -1,8 +1,15 @@-"""Test Browser Use model button click."""+"""Tests for the ChatBrowserUse cloud client."""++import pytestfrom browser_use.llm.browser_use.chat import ChatBrowserUse+from browser_use.llm.messages import UserMessagefrom tests.ci.models.model_test_helper import run_model_button_click_test+# A syntactically-valid key so the constructor doesn't bail before we reach the+# code under test. These unit tests never hit the network.+TEST_API_KEY = 'test-key-not-real'+async def test_browseruse_bu_latest(httpserver):"""Test Browser Use bu-latest can click a button."""@@ -13,3 +20,99 @@ async def test_browseruse_bu_latest(httpserver):extra_kwargs={},httpserver=httpserver,)+++# --- Model validation -------------------------------------------------------+++def test_default_model_is_bu_2_0():+ chat = ChatBrowserUse(api_key=TEST_API_KEY)+ assert chat.model == 'bu-2-0'+ assert chat.provider == 'browser-use'++[email protected]('alias', ['bu-1-0', 'bu-2-0', 'bu-3', 'bu-3-max'])+def test_bu_aliases_are_accepted(alias):+ chat = ChatBrowserUse(model=alias, api_key=TEST_API_KEY)+ assert chat.model == alias+ assert chat.name == alias+ assert chat.provider == 'browser-use'+++def test_bu_latest_normalizes_to_bu_2_0():+ chat = ChatBrowserUse(model='bu-latest', api_key=TEST_API_KEY)+ assert chat.model == 'bu-2-0'+ assert chat.name == 'bu-2-0'+++ 'model',+ [+ 'anthropic/claude-sonnet-4-6',+ 'openai/gpt-5.5',+ 'google/gemini-3-pro',+ 'browser-use/bu-30b-a3b-preview',+ ],+)+def test_provider_prefixed_models_are_accepted(model):+ """Provider-prefixed ids are accepted and forwarded verbatim (the gateway resolves them)."""+ chat = ChatBrowserUse(model=model, api_key=TEST_API_KEY)+ assert chat.model == model+ assert chat.name == model+ # Always routes through the browser-use gateway, whatever the target model.+ assert chat.provider == 'browser-use'++[email protected]('model', ['gpt-5', 'claude-sonnet-4-6', 'bu-9-9', 'random-model'])+def test_bare_model_ids_are_rejected(model):+ """Bare ids (no bu-* alias, no provider/ prefix) are rejected."""+ with pytest.raises(ValueError, match='Invalid model'):+ ChatBrowserUse(model=model, api_key=TEST_API_KEY)+++async def test_provider_prefixed_model_forwarded_in_payload(httpserver):+ """The provider-prefixed id must be sent verbatim in the request body."""+ httpserver.expect_request('/v1/chat/completions', method='POST').respond_with_json({'completion': 'hello from gateway'})++ chat = ChatBrowserUse(+ model='anthropic/claude-sonnet-4-6',+ api_key=TEST_API_KEY,+ base_url=httpserver.url_for('/').rstrip('/'),+ )+ result = await chat.ainvoke([UserMessage(content='hi')])++ assert result.completion == 'hello from gateway'++ # Check the posted body.+ request, _ = httpserver.log[-1]+ body = request.get_json()+ assert body['model'] == 'anthropic/claude-sonnet-4-6'+ assert body['request_type'] == 'browser_agent'+++# --- Agent screenshot auto-config -------------------------------------------+++# Both the classic and beta agents auto-config the Claude screenshot size, so both+# must strip the provider prefix for gateway ids.[email protected]('agent_path', ['classic', 'beta'])+ 'model,expected_size',+ [+ # Claude Sonnet via the gateway keeps the auto-config; the prefix must not break detection.+ ('anthropic/claude-sonnet-4-6', (1400, 850)),+ # Non-Claude models keep the default.+ ('bu-2-0', None),+ ('openai/gpt-5.5', None),+ ],+)+def test_claude_sonnet_screenshot_autoconfig_through_gateway(agent_path, model, expected_size):+ if agent_path == 'classic':+ from browser_use.agent.service import Agent+ else:+ from browser_use.beta import Agent++ llm = ChatBrowserUse(model=model, api_key=TEST_API_KEY)+ agent = Agent(task='test', llm=llm)+ assert agent.browser_session is not None+ assert agent.browser_session.llm_screenshot_size == expected_size