Skip to content

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

Add Rust agent model output helper parity

Magnus Müller8e59061942f5
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.md
index 08d0f9d7e..d0b54a3b2 100644
--- a/RUST_AGENT_INTEGRATION_FEATURES.md
+++ b/RUST_AGENT_INTEGRATION_FEATURES.md
@@ -501,10 +501,15 @@ Terminal core branch: `magnus/browser-use-rust-integration` at terminal main `ee
- Initial actions execute through `multi_act` and are recorded as step 0, while history replay remaps moved DOM indices by element hash before routing actions through the Rust-backed action path.
- Proof: `test_rust_agent_exposes_action_replay_helper_methods`.
+99. Rust Agent model output helper parity
+ - The Rust-backed `Agent` now exposes Browser Use's `get_model_output(...)`, `_get_model_output_with_retry(...)`, `_handle_post_llm_processing(...)`, `_get_next_action(...)`, and `_execute_actions()` helpers.
+ - The helpers preserve long-URL restoration in parsed LLM actions, max-action truncation, empty-action retry, step callbacks, conversation saving, and action execution through the Rust-backed `multi_act` path.
+ - Proof: `test_rust_agent_exposes_model_output_helper_methods`.
+
## Current Verification
- `python3 -m py_compile 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` (72 tests)
+- `uv run pytest -q tests/ci/test_rust_agent.py` (73 tests)
- `cargo build -q -p browser-use-cli`
- `CARGO_INCREMENTAL=0 cargo test -q -p browser-use-agent selected_remote_cdp_mode_allows_remote_cdp_connect -- --nocapture`
- `CARGO_INCREMENTAL=0 cargo test -q -p browser-use-agent bare_browser_connect_resolves_to_selected_managed_mode_with_launch_args -- --nocapture`
diff --git a/browser_use/rust/service.py b/browser_use/rust/service.py
index a94b4bb43..4b35e8cc3 100644
--- a/browser_use/rust/service.py
+++ b/browser_use/rust/service.py
@@ -21,6 +21,7 @@ from pydantic import BaseModel, ValidationError
from typing_extensions import TypeVar
from uuid_extensions import uuid7str
+from browser_use.agent.message_manager.utils import save_conversation
from browser_use.agent.message_manager.service import MessageManager
from browser_use.agent.prompts import SystemPrompt
from browser_use.agent.views import (
@@ -1787,6 +1788,102 @@ class Agent(Generic[AgentStructuredOutput]):
"""Save current Browser Use file system state back onto AgentState."""
self.state.file_system_state = self.file_system.get_state()
+ async def get_model_output(self, input_messages: list[Any]) -> AgentOutput:
+ """Get next Browser Use action output from the configured Python LLM."""
+ if self.llm is None or not hasattr(self.llm, 'ainvoke'):
+ raise ValueError('A Browser Use-compatible llm with ainvoke(...) is required for get_model_output().')
+
+ urls_replaced = self._process_messsages_and_replace_long_urls_shorter_ones(input_messages)
+ response = await self.llm.ainvoke(input_messages, output_format=self.AgentOutput)
+ parsed: AgentOutput = getattr(response, 'completion', response)
+
+ if urls_replaced:
+ self._recursive_process_all_strings_inside_pydantic_model(parsed, urls_replaced)
+
+ actions = getattr(parsed, 'action', None)
+ if actions and len(actions) > self.settings.max_actions_per_step:
+ parsed.action = actions[: self.settings.max_actions_per_step]
+
+ self._log_next_action_summary(parsed)
+ return parsed
+
+ async def _get_model_output_with_retry(self, input_messages: list[Any]) -> AgentOutput:
+ """Get model output, retrying once when the model returns no usable action."""
+ model_output = await self.get_model_output(input_messages)
+
+ def has_empty_actions(output: AgentOutput) -> bool:
+ actions = getattr(output, 'action', None)
+ if not actions or not isinstance(actions, list):
+ return True
+ return all(getattr(action, 'model_dump', lambda **kwargs: {})() == {} for action in actions)
+
+ if has_empty_actions(model_output):
+ from browser_use.llm.messages import UserMessage
+
+ clarification_message = UserMessage(
+ content='You forgot to return an action. Please respond with a valid JSON action according to the expected schema with your assessment and next actions.'
+ )
+ model_output = await self.get_model_output(input_messages + [clarification_message])
+ if has_empty_actions(model_output):
+ try:
+ done_action = self.DoneActionModel(done={'success': False, 'text': 'No next action returned by LLM!'})
+ except Exception:
+ done_action = self.ActionModel()
+ setattr(done_action, 'done', {'success': False, 'text': 'No next action returned by LLM!'})
+ model_output.action = [done_action]
+
+ return model_output
+
+ async def _handle_post_llm_processing(self, browser_state_summary: Any, input_messages: list[Any]) -> None:
+ """Handle Browser Use callbacks and conversation saving after an LLM response."""
+ if self.register_new_step_callback and self.state.last_model_output:
+ if inspect.iscoroutinefunction(self.register_new_step_callback):
+ await self.register_new_step_callback(
+ browser_state_summary,
+ self.state.last_model_output,
+ self.state.n_steps,
+ )
+ else:
+ self.register_new_step_callback(
+ browser_state_summary,
+ self.state.last_model_output,
+ self.state.n_steps,
+ )
+
+ if self.settings.save_conversation_path and self.state.last_model_output:
+ conversation_dir = Path(self.settings.save_conversation_path)
+ conversation_filename = f'conversation_{self.id}_{self.state.n_steps}.txt'
+ target = conversation_dir / conversation_filename
+ await save_conversation(
+ input_messages,
+ self.state.last_model_output,
+ target,
+ self.settings.save_conversation_path_encoding,
+ )
+
+ async def _get_next_action(self, browser_state_summary: Any) -> None:
+ """Fetch the next model output and run Browser Use post-LLM hooks."""
+ input_messages = self._message_manager.get_messages()
+ try:
+ model_output = await asyncio.wait_for(
+ self._get_model_output_with_retry(input_messages), timeout=self.settings.llm_timeout
+ )
+ except TimeoutError:
+ raise TimeoutError(
+ f'LLM call timed out after {self.settings.llm_timeout} seconds. Keep your thinking and output short.'
+ )
+
+ self.state.last_model_output = model_output
+ await self._check_stop_or_pause()
+ await self._handle_post_llm_processing(browser_state_summary, input_messages)
+ await self._check_stop_or_pause()
+
+ async def _execute_actions(self) -> None:
+ """Execute actions from the last model output through the Rust-backed action path."""
+ if self.state.last_model_output is None:
+ raise ValueError('No model output to execute actions from')
+ self.state.last_result = await self.multi_act(self.state.last_model_output.action)
+
async def _make_history_item(
self,
model_output: AgentOutput | None,
diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.py
index 6290f244e..fb4481c29 100644
--- a/tests/ci/test_rust_agent.py
+++ b/tests/ci/test_rust_agent.py
@@ -1808,6 +1808,111 @@ async def test_rust_agent_exposes_action_replay_helper_methods():
) is None
+async def test_rust_agent_exposes_model_output_helper_methods(tmp_path):
+ from types import SimpleNamespace
+
+ from browser_use.agent.views import ActionResult
+ from browser_use.llm.messages import UserMessage
+ from browser_use.rust import Agent
+
+ original_url = 'https://example.com/path?abcdefghijklmnopqrstuvwxyz#section'
+
+ class LLM:
+ model = 'gpt-test'
+ provider = 'test-provider'
+
+ def __init__(self):
+ self.agent = None
+ self.calls = []
+
+ async def ainvoke(self, messages, output_format=None, **kwargs):
+ self.calls.append((messages, output_format))
+ shortened_text = messages[0].content
+ return SimpleNamespace(
+ usage=None,
+ completion=self.agent.AgentOutput(
+ evaluation_previous_goal='ok',
+ memory='remember',
+ next_goal='finish',
+ action=[
+ self.agent.ActionModel(done={'text': shortened_text, 'success': True}),
+ self.agent.ActionModel(done={'text': 'extra action', 'success': True}),
+ ],
+ )
+ )
+
+ seen_callbacks = []
+
+ async def new_step_callback(browser_state, model_output, step_number):
+ seen_callbacks.append((browser_state, model_output, step_number))
+
+ llm = LLM()
+ agent = Agent(
+ task='Use LLM helpers.',
+ llm=llm,
+ max_actions_per_step=1,
+ _url_shortening_limit=8,
+ save_conversation_path=tmp_path / 'conversations',
+ register_new_step_callback=new_step_callback,
+ )
+ llm.agent = agent
+ input_messages = [UserMessage(content=f'Open {original_url} now.')]
+ browser_state = SimpleNamespace(url='https://example.com')
+ agent._message_manager.get_messages = lambda: input_messages
+
+ await agent._get_next_action(browser_state)
+
+ assert llm.calls[0][1] is agent.AgentOutput
+ assert original_url not in llm.calls[0][0][0].content
+ assert len(agent.state.last_model_output.action) == 1
+ assert agent.state.last_model_output.action[0].model_dump(exclude_unset=True)['done']['text'] == f'Open {original_url} now.'
+ assert seen_callbacks == [(browser_state, agent.state.last_model_output, agent.state.n_steps)]
+ assert list((tmp_path / 'conversations').glob(f'conversation_{agent.id}_{agent.state.n_steps}.txt'))
+
+ seen_actions = []
+
+ async def fake_multi_act(actions):
+ seen_actions.append(actions)
+ return [ActionResult(extracted_content='executed')]
+
+ agent.multi_act = fake_multi_act
+ await agent._execute_actions()
+
+ assert seen_actions == [agent.state.last_model_output.action]
+ assert agent.state.last_result[0].extracted_content == 'executed'
+
+ class RetryLLM(LLM):
+ async def ainvoke(self, messages, output_format=None, **kwargs):
+ self.calls.append((messages, output_format))
+ if len(self.calls) == 1:
+ return SimpleNamespace(
+ usage=None,
+ completion=self.agent.AgentOutput(
+ evaluation_previous_goal='empty',
+ memory='none',
+ next_goal='retry',
+ action=[],
+ )
+ )
+ return SimpleNamespace(
+ usage=None,
+ completion=self.agent.AgentOutput(
+ evaluation_previous_goal='ok',
+ memory='remember',
+ next_goal='finish',
+ action=[self.agent.ActionModel(done={'text': 'retried action', 'success': True})],
+ )
+ )
+
+ retry_llm = RetryLLM()
+ retry_agent = Agent(task='Retry LLM helpers.', llm=retry_llm)
+ retry_llm.agent = retry_agent
+ retry_output = await retry_agent._get_model_output_with_retry([UserMessage(content='Retry with an action.')])
+
+ assert len(retry_llm.calls) == 2
+ assert retry_output.action
+
+
async def test_rust_agent_trace_and_cloud_auth_helpers():
from browser_use.rust import Agent
from browser_use.rust.service import _history_from_events