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
added usage data to agent history and evals
Gregor Žuničb37e026f89ba
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 7116caf1d..2ecf36200 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -1187,12 +1187,17 @@ class Agent(Generic[Context]):self.logger.info(f'❌ {agent_run_error}')+ self.state.history.usage = await self.token_cost_service.get_usage_summary()+return self.state.historyexcept KeyboardInterrupt:# Already handled by our signal handler, but catch any direct KeyboardInterrupt as wellself.logger.info('Got KeyboardInterrupt during execution, returning current history')agent_run_error = 'KeyboardInterrupt'++ self.state.history.usage = await self.token_cost_service.get_usage_summary()+return self.state.historyexcept Exception as e:diff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex 2caf88d46..f538e2a25 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -21,6 +21,7 @@ from browser_use.dom.history_tree_processor.service import (from browser_use.dom.views import SelectorMapfrom browser_use.filesystem.file_system import FileSystemStatefrom browser_use.llm.base import BaseChatModel+from browser_use.tokens.views import UsageSummaryclass AgentSettings(BaseModel):@@ -68,7 +69,7 @@ class AgentState(BaseModel):n_steps: int = 1consecutive_failures: int = 0last_result: list[ActionResult] | None = None- history: AgentHistoryList = Field(default_factory=lambda: AgentHistoryList(history=[]))+ history: AgentHistoryList = Field(default_factory=lambda: AgentHistoryList(history=[], usage=None))last_plan: str | None = Nonelast_model_output: AgentOutput | None = Nonepaused: bool = False@@ -261,6 +262,7 @@ class AgentHistoryList(BaseModel):"""List of AgentHistory messages, i.e. the history of the agent's actions and thoughts."""history: list[AgentHistory]+ usage: UsageSummary | Nonedef total_duration_seconds(self) -> float:"""Get total duration of all steps in seconds"""diff --git a/browser_use/tokens/service.py b/browser_use/tokens/service.pyindex 265470ca7..c7a159260 100644--- a/browser_use/tokens/service.py+++ b/browser_use/tokens/service.py@@ -426,7 +426,6 @@ class TokenCost:total_tokens=total_tokens,total_cost=total_prompt_cost + total_completion_cost + total_prompt_cached_cost,entry_count=len(filtered_usage),- models=models,by_model=model_stats,)diff --git a/browser_use/tokens/views.py b/browser_use/tokens/views.pyindex b044a7dad..dfa55179a 100644--- a/browser_use/tokens/views.py+++ b/browser_use/tokens/views.py@@ -104,5 +104,5 @@ class UsageSummary(BaseModel):total_tokens: inttotal_cost: floatentry_count: int- models: list[str] = Field(default_factory=list)+by_model: dict[str, ModelUsageStats] = Field(default_factory=dict)diff --git a/eval/service.py b/eval/service.pyindex a39675c56..2b1944c7e 100644--- a/eval/service.py+++ b/eval/service.py@@ -589,6 +589,7 @@ class TaskResult:'steps': format_data.get('steps'),'maxSteps': self.max_steps,'tokensUsed': format_data.get('tokensUsed'),+ 'usage': format_data.get('usage'), # Add usage data'completeHistory': format_data.get('complete_history', []), # Add complete step history})@@ -1025,6 +1026,11 @@ async def reformat_agent_history(if include_result and final_result and final_result.strip():action_history = action_history + [final_result]+ # Extract usage data from agent history+ usage_data = None+ if agent_history.usage:+ usage_data = agent_history.usage.model_dump()+# Create results structure with new fieldsresults = {'task_id': task_id,@@ -1040,6 +1046,7 @@ async def reformat_agent_history('task_duration': task_duration,'steps': len(complete_history),'tokensUsed': total_tokens_used, # Add total tokens used+ 'usage': usage_data, # Add usage data}# Save results file@@ -1341,6 +1348,7 @@ async def run_agent_with_browser(planner_llm=planner_llm,planner_interval=planner_interval,source='eval_platform',+ calculate_cost=True,)# get last messageawait agent.run(max_steps=max_steps)