Skip to content

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

Add step metadata tracking with timing and token information

Magnus Müllere503f586f017
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 158f7f985..239eb177b 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -4,6 +4,7 @@ import asyncio
import json
import logging
import re
+import time
from pathlib import Path
from typing import Any, Awaitable, Callable, Dict, Generic, List, Optional, Type, TypeVar
@@ -31,6 +32,7 @@ from browser_use.agent.views import (
AgentSettings,
AgentState,
AgentStepInfo,
+ StepMetadata,
ToolCallingMethod,
)
from browser_use.browser.browser import Browser
@@ -301,6 +303,7 @@ class Agent(Generic[Context]):
state = None
model_output = None
result: list[ActionResult] = []
+ step_start_time = time.time()
try:
state = await self.browser_context.get_state()
@@ -361,6 +364,7 @@ class Agent(Generic[Context]):
self.state.last_result = result
finally:
+ step_end_time = time.time()
actions = [a.model_dump(exclude_unset=True) for a in model_output.action] if model_output else []
self.telemetry.capture(
AgentStepTelemetryEvent(
@@ -375,7 +379,12 @@ class Agent(Generic[Context]):
return
if state:
- self._make_history_item(model_output, state, result)
+ metadata = StepMetadata(
+ step_start_time=step_start_time,
+ step_end_time=step_end_time,
+ total_tokens=self._message_manager.state.history.total_tokens,
+ )
+ self._make_history_item(model_output, state, result, metadata)
@time_execution_async('--handle_step_error (agent)')
async def _handle_step_error(self, error: Exception) -> list[ActionResult]:
@@ -417,6 +426,7 @@ class Agent(Generic[Context]):
model_output: AgentOutput | None,
state: BrowserState,
result: list[ActionResult],
+ metadata: Optional[StepMetadata] = None,
) -> None:
"""Create and store history item"""
@@ -433,7 +443,7 @@ class Agent(Generic[Context]):
screenshot=state.screenshot,
)
- history_item = AgentHistory(model_output=model_output, result=result, state=state_history)
+ history_item = AgentHistory(model_output=model_output, result=result, state=state_history, metadata=metadata)
self.state.history.history.append(history_item)
diff --git a/browser_use/agent/views.py b/browser_use/agent/views.py
index 4bdc1175a..87db997b7 100644
--- a/browser_use/agent/views.py
+++ b/browser_use/agent/views.py
@@ -93,6 +93,19 @@ class ActionResult(BaseModel):
include_in_memory: bool = False # whether to include in past messages as context or not
+class StepMetadata(BaseModel):
+ """Metadata for a single step including timing and token information"""
+
+ step_start_time: float
+ step_end_time: float
+ total_tokens: int # Approximate tokens from message manager for this step
+
+ @property
+ def duration_seconds(self) -> float:
+ """Calculate step duration in seconds"""
+ return self.step_end_time - self.step_start_time
+
+
class AgentBrain(BaseModel):
"""Current state of the agent"""
@@ -135,6 +148,7 @@ class AgentHistory(BaseModel):
model_output: AgentOutput | None
result: list[ActionResult]
state: BrowserStateHistory
+ metadata: Optional[StepMetadata] = None
model_config = ConfigDict(arbitrary_types_allowed=True, protected_namespaces=())
@@ -166,6 +180,7 @@ class AgentHistory(BaseModel):
'model_output': model_output_dump,
'result': [r.model_dump(exclude_none=True) for r in self.result],
'state': self.state.to_dict(),
+ 'metadata': self.metadata.model_dump() if self.metadata else None,
}
@@ -174,6 +189,28 @@ class AgentHistoryList(BaseModel):
history: list[AgentHistory]
+ @property
+ def total_duration_seconds(self) -> float:
+ """Get total duration of all steps in seconds"""
+ total = 0.0
+ for h in self.history:
+ if h.metadata:
+ total += h.metadata.duration_seconds
+ return total
+
+ @property
+ def total_tokens(self) -> int:
+ """
+ Get total tokens used across all steps.
+ Note: These are from the approximate token counting of the message manager.
+ For accurate token counting, use tools like LangChain Smith or OpenAI's token counters.
+ """
+ total = 0
+ for h in self.history:
+ if h.metadata:
+ total += h.metadata.total_tokens
+ return total
+
def __str__(self) -> str:
"""Representation of the AgentHistoryList object"""
return f'AgentHistoryList(all_results={self.action_results()}, all_model_outputs={self.model_actions()})'
diff --git a/browser_use/telemetry/views.py b/browser_use/telemetry/views.py
index 75a4068ad..588b2e399 100644
--- a/browser_use/telemetry/views.py
+++ b/browser_use/telemetry/views.py
@@ -1,8 +1,6 @@
from abc import ABC, abstractmethod
from dataclasses import asdict, dataclass
-from typing import Any, Dict, Optional
-
-from browser_use.controller.registry.views import ActionModel
+from typing import Any, Dict, Sequence
@dataclass
@@ -57,5 +55,5 @@ class AgentEndTelemetryEvent(BaseTelemetryEvent):
steps: int
max_steps_reached: bool
success: bool
- errors: list[str]
+ errors: Sequence[str | None]
name: str = 'agent_end'