Skip to content

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

Price Rust terminal usage summaries

Magnus Müllerc2b5a2682b7a
diff --git a/RUST_AGENT_INTEGRATION_FEATURES.md b/RUST_AGENT_INTEGRATION_FEATURES.md
index afabaafaf..0715f4507 100644
--- a/RUST_AGENT_INTEGRATION_FEATURES.md
+++ b/RUST_AGENT_INTEGRATION_FEATURES.md
@@ -1400,8 +1400,16 @@ Terminal core branch: `magnus/browser-use-rust-main-integration` at terminal mai
- This is a general judge-cost guard; the subsequent live gate still reproduced the Agent SDK gzip timeout on one long trajectory, so the judge-stage budget remains the effective protection for saved results.
- Proof: eval `.venv/bin/python -m pytest -q tests/test_service_cli.py -k 'agent_sdk_judge'`, eval `.venv/bin/python -m py_compile eval/judges/agent_sdk_judge.py tests/test_service_cli.py`, and eval `git diff --check -- eval/judges/agent_sdk_judge.py tests/test_service_cli.py`.
+269. Rust terminal usage-cost propagation
+ - Rust terminal `token_count` and `model.usage` events now populate Browser Use `UsageSummary` cost fields when callers enable `calculate_cost=True` or `BROWSER_USE_CALCULATE_COST=true`.
+ - Claude Sonnet/Opus 4.6 pricing is available through custom pricing so eval dashboard `usage.total_cost` can be calculated for Rust-core runs without waiting on remote LiteLLM pricing metadata.
+ - Custom model pricing is checked before remote pricing initialization, preventing per-task network/cache work from becoming an eval tail-latency source.
+ - Proof: `.venv/bin/python -m pytest -q tests/ci/test_rust_agent.py -k 'terminal_usage_prices_token_count_events or reconstructs_terminal_token_count_usage or reconstructs_terminal_nested_model_usage'` and `.venv/bin/python -m py_compile browser_use/rust/service.py browser_use/tokens/custom_pricing.py browser_use/tokens/service.py tests/ci/test_rust_agent.py`.
+
## Current Verification
+- `.venv/bin/python -m pytest -q tests/ci/test_rust_agent.py -k 'terminal_usage_prices_token_count_events or reconstructs_terminal_token_count_usage or reconstructs_terminal_nested_model_usage'`
+- `.venv/bin/python -m py_compile browser_use/rust/service.py browser_use/tokens/custom_pricing.py browser_use/tokens/service.py tests/ci/test_rust_agent.py`
- `uv run python -m py_compile browser_use/rust/service.py tests/ci/test_rust_agent.py` on browser-use commit `2fa61300`
- `uv run pytest -q tests/ci/test_rust_agent.py -k 'load_events_uses_bounded_terminal_timeout or follow_up_allows_timeout_overrides'` on browser-use commit `2fa61300`
- `.venv/bin/python -m py_compile eval/service.py tests/test_service_cli.py` on evaluations-internal commits `d3a9632` and `94300bf`
diff --git a/browser_use/rust/service.py b/browser_use/rust/service.py
index 14d3514ab..90f430cde 100644
--- a/browser_use/rust/service.py
+++ b/browser_use/rust/service.py
@@ -51,6 +51,7 @@ from browser_use.dom.views import DOMInteractedElement
from browser_use.filesystem.file_system import FileSystem
from browser_use.llm.base import BaseChatModel
from browser_use.llm.messages import BaseMessage, ContentPartImageParam, ContentPartTextParam
+from browser_use.llm.views import ChatInvokeUsage
from browser_use.observability import observe
from browser_use.screenshots.service import ScreenshotService
from browser_use.telemetry.service import ProductTelemetry
@@ -2266,11 +2267,46 @@ def _token_count_usage(payload: dict[str, Any]) -> dict[str, Any] | None:
return raw_usage if isinstance(raw_usage, dict) else None
+def _token_count_last_usage(payload: dict[str, Any]) -> dict[str, Any] | None:
+ info = payload.get('info')
+ if isinstance(info, dict):
+ raw_usage = info.get('last_token_usage') or info.get('total_token_usage')
+ else:
+ raw_usage = payload.get('last_token_usage') or payload.get('total_token_usage')
+ return raw_usage if isinstance(raw_usage, dict) else None
+
+
def _model_usage_payload(payload: dict[str, Any]) -> dict[str, Any]:
usage = payload.get('usage')
return usage if isinstance(usage, dict) else payload
+def _optional_positive_int(value: Any) -> int | None:
+ integer = _int_value(value)
+ return integer if integer > 0 else None
+
+
+def _chat_invoke_usage_from_payload(usage: dict[str, Any]) -> ChatInvokeUsage | None:
+ input_tokens = _int_value(usage.get('input_tokens'))
+ cached_input_tokens = _int_value(usage.get('input_cached_tokens') or usage.get('cached_input_tokens'))
+ completion_tokens = _usage_completion_tokens(usage)
+ total_tokens = _usage_total_tokens(usage, input_tokens, completion_tokens)
+ if input_tokens == 0 and completion_tokens == 0 and total_tokens == 0:
+ return None
+ return ChatInvokeUsage(
+ prompt_tokens=input_tokens,
+ prompt_cached_tokens=cached_input_tokens or None,
+ prompt_cache_creation_tokens=_optional_positive_int(
+ usage.get('prompt_cache_creation_tokens')
+ or usage.get('cache_creation_input_tokens')
+ or usage.get('input_cache_creation_tokens')
+ ),
+ prompt_image_tokens=_optional_positive_int(usage.get('prompt_image_tokens') or usage.get('image_tokens')),
+ completion_tokens=completion_tokens,
+ total_tokens=total_tokens,
+ )
+
+
def _reasoning_output_tokens(usage: dict[str, Any]) -> int:
return _int_value(
usage.get('reasoning_output_tokens')
@@ -2350,6 +2386,63 @@ def _usage_from_events(events: list[dict[str, Any]], model: str) -> UsageSummary
)
+async def _usage_from_events_with_costs(
+ events: list[dict[str, Any]],
+ model: str,
+ token_cost_service: TokenCost,
+) -> UsageSummary:
+ """Reconstruct usage from terminal events and price per-call usage when enabled."""
+ summary = _usage_from_events(events, model)
+ if not token_cost_service.include_cost:
+ return summary
+
+ total_prompt_cost = 0.0
+ total_completion_cost = 0.0
+ total_prompt_cached_cost = 0.0
+ total_cost = 0.0
+ priced_invocations = 0
+
+ for event in events:
+ event_type = _event_type(event)
+ payload = _event_payload(event)
+ raw_usage = None
+ if event_type == 'model.usage':
+ raw_usage = _model_usage_payload(payload)
+ elif event_type == 'token_count':
+ raw_usage = _token_count_last_usage(payload)
+ if not isinstance(raw_usage, dict):
+ continue
+ chat_usage = _chat_invoke_usage_from_payload(raw_usage)
+ if chat_usage is None:
+ continue
+ cost = await token_cost_service.calculate_cost(model, chat_usage)
+ if cost is None:
+ continue
+ priced_invocations += 1
+ total_prompt_cost += cost.prompt_cost
+ total_completion_cost += cost.completion_cost
+ total_prompt_cached_cost += cost.prompt_read_cached_cost or 0.0
+ total_cost += cost.total_cost
+
+ if priced_invocations == 0:
+ return summary
+
+ model_stats = dict(summary.by_model)
+ stats = model_stats.get(model) or ModelUsageStats(model=model)
+ stats.cost = total_cost
+ model_stats[model] = stats
+
+ return summary.model_copy(
+ update={
+ 'total_prompt_cost': total_prompt_cost,
+ 'total_prompt_cached_cost': total_prompt_cached_cost,
+ 'total_completion_cost': total_completion_cost,
+ 'total_cost': total_cost,
+ 'by_model': model_stats,
+ }
+ )
+
+
def _history_from_events(
events: list[dict[str, Any]],
*,
@@ -3086,6 +3179,15 @@ class Agent(Generic[Context, AgentStructuredOutput]):
"""Log Browser Use token usage summary for a completed Rust-backed run."""
await self.token_cost_service.log_usage_summary()
+ async def _apply_terminal_usage_costs(self, events: list[dict[str, Any]]) -> None:
+ """Populate cost fields for terminal-reconstructed usage."""
+ if self.history is None:
+ return
+ try:
+ self.history.usage = await _usage_from_events_with_costs(events, self.model, self.token_cost_service)
+ except Exception as exc:
+ self.logger.debug(f'Failed to price Rust terminal usage: {exc}', exc_info=True)
+
def _cloud_event_agent(self):
llm_model_name = getattr(getattr(self, 'llm', None), 'model_name', None)
if isinstance(llm_model_name, str) and llm_model_name:
@@ -3249,6 +3351,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
process_error='Rust agent stopped before terminal run.',
)
self.history = self.result
+ await self._apply_terminal_usage_costs([])
await self._log_run_usage_summary()
self._record_laminar_run_observability(
max_steps=max_steps,
@@ -3278,6 +3381,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
process_error='Rust agent stopped before terminal run.',
)
self.history = self.result
+ await self._apply_terminal_usage_costs([])
await self._log_run_usage_summary()
self._record_laminar_run_observability(
max_steps=max_steps,
@@ -3327,6 +3431,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
process_error=process_error,
)
self.history = self.result
+ await self._apply_terminal_usage_costs(events)
self._sync_state_from_history()
await self._log_run_usage_summary()
self._record_laminar_run_observability(
@@ -3366,6 +3471,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
process_error=process_error,
)
self.history = self.result
+ await self._apply_terminal_usage_costs(events)
self._sync_state_from_history()
await self._log_run_usage_summary()
self._record_laminar_run_observability(
@@ -3463,6 +3569,7 @@ class Agent(Generic[Context, AgentStructuredOutput]):
process_error=process_error,
)
self.history = self.result
+ await self._apply_terminal_usage_costs(self.last_events)
self._sync_state_from_history()
await self._log_run_usage_summary()
self._record_laminar_run_observability(
diff --git a/browser_use/tokens/custom_pricing.py b/browser_use/tokens/custom_pricing.py
index 2be330a86..752d95612 100644
--- a/browser_use/tokens/custom_pricing.py
+++ b/browser_use/tokens/custom_pricing.py
@@ -27,4 +27,40 @@ CUSTOM_MODEL_PRICING: dict[str, dict[str, Any]] = {
'max_input_tokens': None, # Not specified
'max_output_tokens': None, # Not specified
},
+ 'claude-sonnet-4-6': {
+ 'input_cost_per_token': 3.00 / 1_000_000,
+ 'output_cost_per_token': 15.00 / 1_000_000,
+ 'cache_read_input_token_cost': 0.30 / 1_000_000,
+ 'cache_creation_input_token_cost': 3.75 / 1_000_000,
+ 'max_tokens': None,
+ 'max_input_tokens': None,
+ 'max_output_tokens': None,
+ },
+ 'anthropic/claude-sonnet-4.6': {
+ 'input_cost_per_token': 3.00 / 1_000_000,
+ 'output_cost_per_token': 15.00 / 1_000_000,
+ 'cache_read_input_token_cost': 0.30 / 1_000_000,
+ 'cache_creation_input_token_cost': 3.75 / 1_000_000,
+ 'max_tokens': None,
+ 'max_input_tokens': None,
+ 'max_output_tokens': None,
+ },
+ 'claude-opus-4-6': {
+ 'input_cost_per_token': 5.00 / 1_000_000,
+ 'output_cost_per_token': 25.00 / 1_000_000,
+ 'cache_read_input_token_cost': 0.50 / 1_000_000,
+ 'cache_creation_input_token_cost': 6.25 / 1_000_000,
+ 'max_tokens': None,
+ 'max_input_tokens': None,
+ 'max_output_tokens': None,
+ },
+ 'anthropic/claude-opus-4.6': {
+ 'input_cost_per_token': 5.00 / 1_000_000,
+ 'output_cost_per_token': 25.00 / 1_000_000,
+ 'cache_read_input_token_cost': 0.50 / 1_000_000,
+ 'cache_creation_input_token_cost': 6.25 / 1_000_000,
+ 'max_tokens': None,
+ 'max_input_tokens': None,
+ 'max_output_tokens': None,
+ },
}
diff --git a/browser_use/tokens/service.py b/browser_use/tokens/service.py
index 8783c5d11..901a08552 100644
--- a/browser_use/tokens/service.py
+++ b/browser_use/tokens/service.py
@@ -160,10 +160,6 @@ class TokenCost:
async def get_model_pricing(self, model_name: str) -> ModelPricing | None:
"""Get pricing information for a specific model"""
- # Ensure we're initialized
- if not self._initialized:
- await self.initialize()
-
# Check custom pricing first
if model_name in CUSTOM_MODEL_PRICING:
data = CUSTOM_MODEL_PRICING[model_name]
@@ -178,6 +174,10 @@ class TokenCost:
cache_creation_input_token_cost=data.get('cache_creation_input_token_cost'),
)
+ # Ensure we're initialized before checking remote LiteLLM pricing.
+ if not self._initialized:
+ await self.initialize()
+
# Map model name to LiteLLM model name if needed
litellm_model_name = MODEL_TO_LITELLM.get(model_name, model_name)
diff --git a/tests/ci/test_rust_agent.py b/tests/ci/test_rust_agent.py
index 71646c077..2fca10da6 100644
--- a/tests/ci/test_rust_agent.py
+++ b/tests/ci/test_rust_agent.py
@@ -1659,6 +1659,70 @@ def test_rust_history_reconstructs_terminal_nested_model_usage():
assert history.usage.by_model['gpt-test'].cost == 0.0123
+async def test_rust_terminal_usage_prices_token_count_events(monkeypatch):
+ from browser_use.rust.service import _usage_from_events_with_costs
+ from browser_use.tokens.service import TokenCost
+
+ async def fail_fetch(_self):
+ raise AssertionError('custom model pricing should not fetch remote pricing')
+
+ monkeypatch.setattr(TokenCost, '_fetch_and_cache_pricing_data', fail_fetch)
+
+ events = [
+ {
+ 'event_type': 'token_count',
+ 'payload': {
+ 'info': {
+ 'last_token_usage': {
+ 'cached_input_tokens': 20,
+ 'input_tokens': 100,
+ 'output_tokens': 10,
+ 'total_tokens': 110,
+ },
+ 'total_token_usage': {
+ 'cached_input_tokens': 20,
+ 'input_tokens': 100,
+ 'output_tokens': 10,
+ 'total_tokens': 110,
+ },
+ },
+ },
+ },
+ {
+ 'event_type': 'token_count',
+ 'payload': {
+ 'info': {
+ 'last_token_usage': {
+ 'cached_input_tokens': 0,
+ 'input_tokens': 200,
+ 'output_tokens': 20,
+ 'total_tokens': 220,
+ },
+ 'total_token_usage': {
+ 'cached_input_tokens': 20,
+ 'input_tokens': 300,
+ 'output_tokens': 30,
+ 'total_tokens': 330,
+ },
+ },
+ },
+ },
+ ]
+
+ summary = await _usage_from_events_with_costs(events, 'claude-sonnet-4-6', TokenCost(include_cost=True))
+
+ assert summary.total_prompt_tokens == 300
+ assert summary.total_prompt_cached_tokens == 20
+ assert summary.total_completion_tokens == 30
+ assert summary.total_tokens == 330
+ assert summary.entry_count == 2
+ assert summary.total_prompt_cost == pytest.approx(0.000846)
+ assert summary.total_prompt_cached_cost == pytest.approx(0.000006)
+ assert summary.total_completion_cost == pytest.approx(0.00045)
+ assert summary.total_cost == pytest.approx(0.001296)
+ assert summary.by_model['claude-sonnet-4-6'].cost == pytest.approx(0.001296)
+
+
def test_rust_history_supports_structured_output():
from browser_use.rust.service import _history_from_events