Skip to content

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

Bridge Rust agent LLM providers

Magnus Müller5dd16abf9d14
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.md
index 60494ecd6..2ab05909d 100644
--- a/RUST_AGENT_INTEGRATION_FEATURES.md
+++ b/RUST_AGENT_INTEGRATION_FEATURES.md
@@ -1011,10 +1011,15 @@ Terminal core branch: `magnus/browser-use-rust-main-integration` at terminal mai
- Re-syncing the same history object is idempotent, while subsequent `run()`/`follow_up()` histories produce distinct conversation snapshot step suffixes and monotonic new-step callback numbers.
- Proof: `test_rust_agent_sync_state_counts_terminal_histories_monotonically`, `test_rust_agent_direct_follow_up_updates_task_state_and_transcript`.
+200. Rust Agent LLM provider command/env bridge parity
+ - Rust-backed runs now map supported Browser Use LLM objects to matching terminal provider commands for OpenAI, Anthropic, OpenRouter, and DeepSeek, including existing-session reruns.
+ - Explicit `llm.api_key` and supported `llm.base_url` fields project into the terminal subprocess environment like the Python LLM object would, while omitted credentials preserve the caller's existing environment.
+ - Proof: `test_rust_agent_bridges_llm_credentials_to_terminal_env`.
+
## Current Verification
- `python3 -m py_compile browser_use/agent/service.py browser_use/rust/service.py browser_use/rust/__init__.py browser_use/__init__.py tests/ci/test_rust_agent.py examples/rust_agent/basic.py examples/rust_agent/real_v8_smoke.py`
-- `uv run pytest -q tests/ci/test_rust_agent.py` (168 tests)
+- `uv run pytest -q tests/ci/test_rust_agent.py` (169 tests)
- `cargo build -q -p browser-use-cli` on terminal branch `magnus/browser-use-rust-main-integration`
- `cargo test -q -p browser-use-cli run_codex_session_command_accepts_task_id_and_model -- --nocapture`
- `CARGO_INCREMENTAL=0 cargo test -q -p browser-use-agent selected_remote_cdp_mode_allows_remote_cdp_connect -- --nocapture`
@@ -1091,6 +1096,9 @@ Terminal core branch: `magnus/browser-use-rust-main-integration` at terminal mai
- History load/rerun Python API end-to-end:
- Source `/home/exedev/.evaluation_tool_env`, set `BROWSER_USE_TERMINAL_BINARY=/home/exedev/Developer/terminal/target/debug/browser-use-terminal`, set `BROWSER_USE_RUST_BROWSER_MODE=managed-headless`, run one `Agent` to save history, then run `Agent.load_and_rerun(history_file, max_retries=2, delay_between_actions=0.1)`.
- Output: first run `Example Domain`; saved history file exists; rerun results include `Example Domain`.
+- LLM object provider/env bridge Python API end-to-end:
+ - Source `/home/exedev/.evaluation_tool_env`, remove `OPENAI_API_KEY`/`LLM_BROWSER_OPENAI_API_KEY` from `os.environ`, and construct `Agent(..., llm=ChatOpenAI(model="gpt-4o-mini", api_key=OPENAI_API_KEY_FROM_ENV), step_timeout=300)`.
+ - Output: terminal command `run-openai`, bridged `LLM_BROWSER_OPENAI_API_KEY` present in `_run_env()`, final result `The page title is **Example Domain**.`, and `history.is_successful()` is `True`.
- Parallel managed-headless Python API smoke batch:
- Source `/home/exedev/.evaluation_tool_env`, set `BROWSER_USE_TERMINAL_BINARY=/home/exedev/Developer/terminal/target/debug/browser-use-terminal`, set `BROWSER_USE_RUST_BROWSER_MODE=managed-headless`, and run two `uv run python - <<'PY' ...` Agent scripts in parallel.
- Follow-up/callback script output: `{"smoke": "python_api_followup_callbacks", "first": "Example Domain", "second": "example.com", "callback_kinds": ["step", "done", "step", "done"], "conversation_files": 2}`.
diff --git a/browser_use/rust/service.py b/browser_use/rust/service.py
index 84bf7e0bd..ec76e2fcd 100644
--- a/browser_use/rust/service.py
+++ b/browser_use/rust/service.py
@@ -572,6 +572,63 @@ def _warn_sensitive_data_domain_constraints(
)
+def _string_env_value(value: Any) -> str | None:
+ if value is None:
+ return None
+ text = str(value).strip()
+ return text or None
+
+
+def _llm_provider_name(llm: Any) -> str | None:
+ provider = getattr(llm, 'provider', None)
+ if callable(provider):
+ try:
+ provider = provider()
+ except TypeError:
+ provider = None
+ text = _string_env_value(provider)
+ return text.lower() if text else None
+
+
+def _llm_env_overrides(llm: Any) -> dict[str, str]:
+ provider = _llm_provider_name(llm)
+ if provider is None:
+ return {}
+ api_key = _string_env_value(getattr(llm, 'api_key', None))
+ base_url = _string_env_value(getattr(llm, 'base_url', None))
+ overrides: dict[str, str] = {}
+ if provider == 'openai':
+ if api_key:
+ overrides['LLM_BROWSER_OPENAI_API_KEY'] = api_key
+ if base_url:
+ overrides['LLM_BROWSER_OPENAI_BASE_URL'] = base_url
+ elif provider == 'anthropic':
+ if api_key:
+ overrides['LLM_BROWSER_ANTHROPIC_API_KEY'] = api_key
+ if base_url:
+ overrides['LLM_BROWSER_ANTHROPIC_BASE_URL'] = base_url
+ elif provider == 'openrouter':
+ if api_key:
+ overrides['OPENROUTER_API_KEY'] = api_key
+ if base_url:
+ overrides['OPENROUTER_BASE_URL'] = base_url
+ elif provider == 'deepseek' and api_key:
+ overrides['DEEPSEEK_API_KEY'] = api_key
+ return overrides
+
+
+def _llm_terminal_command(llm: Any, *, existing_session: bool = False) -> str:
+ provider = _llm_provider_name(llm)
+ commands = {
+ 'openai': ('run-openai', 'run-openai-session'),
+ 'anthropic': ('run-anthropic', 'run-anthropic-session'),
+ 'openrouter': ('run-openrouter', 'run-openrouter-session'),
+ 'deepseek': ('run-deepseek', 'run-deepseek-session'),
+ }
+ run_command, session_command = commands.get(provider, ('run-codex', 'run-codex-session'))
+ return session_command if existing_session else run_command
+
+
def _navigation_url_from_action(action: Any) -> str | None:
if not isinstance(action, dict):
return None
@@ -4030,7 +4087,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
f'max_turns={int(max_steps)}',
'-c',
f'browser_mode="{self._browser_mode()}"',
- 'run-codex',
+ _llm_terminal_command(self.llm),
self.task,
'--model',
self.model,
@@ -4189,7 +4246,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
f'max_turns={int(max_steps)}',
'-c',
f'browser_mode="{self._browser_mode()}"',
- 'run-codex-session',
+ _llm_terminal_command(self.llm, existing_session=True),
self.terminal_session_id,
'--model',
self.model,
@@ -4219,6 +4276,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
def _run_env(self) -> dict[str, str]:
env = os.environ.copy()
+ env.update(_llm_env_overrides(self.llm))
browser_mode = self._browser_mode()
env['LLM_BROWSER_BROWSER_MODE'] = browser_mode
cdp_url = _extract_cdp_url(self.browser_session) or _extract_profile_cdp_url(self.browser_profile)
diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.py
index 43c1d50b7..68ed4f093 100644
--- a/tests/ci/test_rust_agent.py
+++ b/tests/ci/test_rust_agent.py
@@ -1867,6 +1867,79 @@ def test_rust_agent_translates_browser_use_args_to_terminal(monkeypatch):
assert env['LLM_BROWSER_BROWSER_MODE'] == 'remote-cdp'
+def test_rust_agent_bridges_llm_credentials_to_terminal_env(monkeypatch):
+ from browser_use.rust import Agent
+
+ class LLM:
+ def __init__(self, provider, model, api_key=None, base_url=None):
+ self.provider = provider
+ self.model = model
+ self.api_key = api_key
+ self.base_url = base_url
+
+ monkeypatch.setenv('BROWSER_USE_TERMINAL_BINARY', '/tmp/browser-use-terminal')
+ for key in (
+ 'LLM_BROWSER_OPENAI_BASE_URL',
+ 'LLM_BROWSER_ANTHROPIC_BASE_URL',
+ 'LLM_BROWSER_OPENAI_COMPAT_API_KEY',
+ 'LLM_BROWSER_OPENAI_COMPAT_BASE_URL',
+ 'OPENROUTER_API_KEY',
+ 'OPENROUTER_BASE_URL',
+ 'DEEPSEEK_API_KEY',
+ ):
+ monkeypatch.delenv(key, raising=False)
+ monkeypatch.setenv('LLM_BROWSER_OPENAI_API_KEY', 'ambient-openai-key')
+ monkeypatch.setenv('LLM_BROWSER_ANTHROPIC_API_KEY', 'ambient-anthropic-key')
+
+ openai_env = Agent(
+ task='OpenAI credentials.',
+ llm=LLM('openai', 'gpt-test', api_key='llm-openai-key', base_url='https://openai.example/v1'),
+ )._run_env()
+ openai_agent = Agent(
+ task='OpenAI command.',
+ llm=LLM('openai', 'gpt-test', api_key='llm-openai-key'),
+ )
+ anthropic_agent = Agent(
+ task='Anthropic credentials.',
+ llm=LLM('anthropic', 'claude-test', api_key='llm-anthropic-key', base_url='https://anthropic.example'),
+ )
+ openrouter_agent = Agent(
+ task='OpenRouter credentials.',
+ llm=LLM('openrouter', 'openrouter/model', api_key='llm-openrouter-key', base_url='https://openrouter.example/api/v1'),
+ )
+ deepseek_agent = Agent(
+ task='DeepSeek credentials.',
+ llm=LLM('deepseek', 'deepseek-chat', api_key='llm-deepseek-key', base_url='https://ignored.example'),
+ )
+ ambient_env = Agent(
+ task='Ambient credentials.',
+ llm=LLM('anthropic', 'claude-test'),
+ )._run_env()
+ anthropic_env = anthropic_agent._run_env()
+ openrouter_env = openrouter_agent._run_env()
+ deepseek_env = deepseek_agent._run_env()
+
+ assert openai_env['LLM_BROWSER_OPENAI_API_KEY'] == 'llm-openai-key'
+ assert openai_env['LLM_BROWSER_OPENAI_BASE_URL'] == 'https://openai.example/v1'
+ assert anthropic_env['LLM_BROWSER_ANTHROPIC_API_KEY'] == 'llm-anthropic-key'
+ assert anthropic_env['LLM_BROWSER_ANTHROPIC_BASE_URL'] == 'https://anthropic.example'
+ assert openrouter_env['OPENROUTER_API_KEY'] == 'llm-openrouter-key'
+ assert openrouter_env['OPENROUTER_BASE_URL'] == 'https://openrouter.example/api/v1'
+ assert deepseek_env['DEEPSEEK_API_KEY'] == 'llm-deepseek-key'
+ assert 'LLM_BROWSER_OPENAI_COMPAT_BASE_URL' not in deepseek_env
+ assert ambient_env['LLM_BROWSER_ANTHROPIC_API_KEY'] == 'ambient-anthropic-key'
+
+ for agent, run_command, session_command in (
+ (openai_agent, 'run-openai', 'run-openai-session'),
+ (anthropic_agent, 'run-anthropic', 'run-anthropic-session'),
+ (openrouter_agent, 'run-openrouter', 'run-openrouter-session'),
+ (deepseek_agent, 'run-deepseek', 'run-deepseek-session'),
+ ):
+ agent.terminal_session_id = '12345678-1234-1234-1234-123456789abc'
+ assert agent._run_argv(max_steps=3)[-4] == run_command
+ assert agent._run_existing_argv(max_steps=3)[-4] == session_command
+
+
def test_rust_agent_translates_browser_profile_cdp_url(monkeypatch):
from browser_use.rust import Agent