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
add helper function for getting agent trace, remove references to deprecated gpt-4o
Alezander918876f222e4e
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 6b0194bde..c6a7f1e96 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -9,9 +9,11 @@ import sysimport tempfileimport timefrom collections.abc import Awaitable, Callable+from datetime import datetimefrom pathlib import Pathfrom typing import Any, Generic, Literal, TypeVarfrom urllib.parse import urlparse+import subprocessfrom dotenv import load_dotenv@@ -72,6 +74,7 @@ from browser_use.telemetry.views import AgentTelemetryEventfrom browser_use.utils import (_log_pretty_path,get_browser_use_version,+ get_git_info,time_execution_async,time_execution_sync,)@@ -1727,3 +1730,73 @@ class Agent(Generic[Context, AgentStructuredOutput]):self.DoneAgentOutput = AgentOutput.type_with_custom_actions(self.DoneActionModel)else:self.DoneAgentOutput = AgentOutput.type_with_custom_actions_no_thinking(self.DoneActionModel)++ def get_trace_object(self) -> dict[str, Any]:+ """Get the trace and trace_details objects for the agent"""++ def extract_task_website(task_text: str) -> str | None:+ url_pattern = r'https?://[^\s<>"\']+|www\.[^\s<>"\']+|[^\s<>"\']+\.[a-z]{2,}(?:/[^\s<>"\']*)?'+ match = re.search(url_pattern, task_text, re.IGNORECASE)+ return match.group(0) if match else None++ # Generate autogenerated fields+ trace_id = uuid7str()+ timestamp = datetime.now().isoformat()++ # Only declare variables that are used multiple times+ structured_output = self.state.history.structured_output+ final_result = self.state.history.final_result()++ return {+ 'trace': {+ # Autogenerated fields+ 'trace_id': trace_id,+ 'timestamp': timestamp,+ 'browser_use_version': get_browser_use_version(),+ 'git_info': json.dumps(get_git_info()) if get_git_info() else None,++ # Direct agent properties+ 'model': self.llm.model,+ 'settings': json.dumps(self.settings.model_dump()) if self.settings else None,+ 'task_id': self.task_id,+ 'task_truncated': self.task[:20000] if len(self.task) > 20000 else self.task,+ 'task_website': extract_task_website(self.task),++ # AgentHistoryList methods+ 'structured_output_truncated': (+ (json.dumps(structured_output.model_dump())[:20000]+ if len(json.dumps(structured_output.model_dump())) > 20000+ else json.dumps(structured_output.model_dump()))+ if structured_output else None+ ),+ 'action_history_truncated': (+ json.dumps(self.state.history.action_history())[:20000]+ if len(json.dumps(self.state.history.action_history())) > 20000+ else json.dumps(self.state.history.action_history())+ ) if self.state.history.action_history() else None,+ 'action_errors': json.dumps(self.state.history.errors()) if self.state.history.errors() else None,+ 'urls': json.dumps(self.state.history.urls()) if self.state.history.urls() else None,+ 'final_result_response_truncated': (+ final_result[:20000] if final_result and len(final_result) > 20000 else final_result+ ),+ 'self_report_completed': 1 if self.state.history.is_done() else 0,+ 'self_report_success': 1 if self.state.history.is_successful() else 0,+ 'duration': self.state.history.total_duration_seconds(),+ 'steps_taken': self.state.history.number_of_steps(),+ 'usage': json.dumps(self.state.history.usage.model_dump()) if self.state.history.usage else None,+ },+ 'trace_details': {+ # Autogenerated fields (ensure same as trace)+ 'trace_id': trace_id,+ 'timestamp': timestamp,++ # Direct agent properties+ 'task': self.task,++ # AgentHistoryList methods+ 'structured_output': json.dumps(structured_output.model_dump()) if structured_output else None,+ 'final_result_response': final_result,+ 'complete_history': json.dumps(self.state.history.model_dump()),+ 'action_history': json.dumps(self.state.history.action_history()) if self.state.history.action_history() else None,+ }+ }diff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex 20353950d..faf1ea5b5 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -488,6 +488,27 @@ class AgentHistoryList(BaseModel, Generic[AgentStructuredOutput]):outputs.append(output)return outputs+ def action_history(self) -> list[list[dict]]:+ """Get action history structured by steps, including results"""+ step_outputs = []++ for h in self.history:+ step_actions = []+ if h.model_output:+ # Zip actions with interacted elements and results+ for action, interacted_element, result in zip(+ h.model_output.action,+ h.state.interacted_element,+ h.result+ ):+ action_output = action.model_dump(exclude_none=True)+ action_output['interacted_element'] = interacted_element+ action_output['result'] = result.model_dump(exclude_none=True) if result else None+ step_actions.append(action_output)+ step_outputs.append(step_actions)++ return step_outputs+def action_results(self) -> list[ActionResult]:"""Get all results from history"""results = []diff --git a/browser_use/utils.py b/browser_use/utils.pyindex 76e5e2f3f..cd80da020 100644--- a/browser_use/utils.py+++ b/browser_use/utils.py@@ -574,6 +574,55 @@ def get_browser_use_version() -> str:return 'unknown'+@cache+def get_git_info() -> dict[str, str] | None:+ """Get git information if installed from git repository"""+ try:+ import subprocess++ package_root = Path(__file__).parent.parent+ git_dir = package_root / '.git'+ if not git_dir.exists():+ return None++ # Get git commit hash+ commit_hash = subprocess.check_output(+ ['git', 'rev-parse', 'HEAD'],+ cwd=package_root,+ stderr=subprocess.DEVNULL+ ).decode().strip()++ # Get git branch+ branch = subprocess.check_output(+ ['git', 'rev-parse', '--abbrev-ref', 'HEAD'],+ cwd=package_root,+ stderr=subprocess.DEVNULL+ ).decode().strip()++ # Get remote URL+ remote_url = subprocess.check_output(+ ['git', 'config', '--get', 'remote.origin.url'],+ cwd=package_root,+ stderr=subprocess.DEVNULL+ ).decode().strip()++ # Get commit timestamp+ commit_timestamp = subprocess.check_output(+ ['git', 'show', '-s', '--format=%ci', 'HEAD'],+ cwd=package_root,+ stderr=subprocess.DEVNULL+ ).decode().strip()++ return {+ 'commit_hash': commit_hash,+ 'branch': branch,+ 'remote_url': remote_url,+ 'commit_timestamp': commit_timestamp+ }+ except Exception:+ return None++def _log_pretty_path(path: str | Path | None) -> str:"""Pretty-print a path, shorten home dir to ~ and cwd to ."""diff --git a/examples/getting_started/01_basic_search.py b/examples/getting_started/01_basic_search.pyindex 76daeae3d..ccd256a6e 100644--- a/examples/getting_started/01_basic_search.py+++ b/examples/getting_started/01_basic_search.py@@ -26,7 +26,7 @@ from browser_use.llm.openai.chat import ChatOpenAIasync def main():# Initialize the model- llm = ChatOpenAI(model='gpt-4o-mini')+ llm = ChatOpenAI(model='gpt-4.1-mini')# Define a simple search tasktask = "Search Google for 'what is browser automation' and tell me the top 3 results"diff --git a/examples/getting_started/02_form_filling.py b/examples/getting_started/02_form_filling.pyindex 3be128861..d9e18a687 100644--- a/examples/getting_started/02_form_filling.py+++ b/examples/getting_started/02_form_filling.py@@ -27,7 +27,7 @@ from browser_use.llm.openai.chat import ChatOpenAIasync def main():# Initialize the model- llm = ChatOpenAI(model='gpt-4o-mini')+ llm = ChatOpenAI(model='gpt-4.1-mini')# Define a form filling tasktask = """diff --git a/examples/getting_started/03_data_extraction.py b/examples/getting_started/03_data_extraction.pyindex 146cb9446..54344cc90 100644--- a/examples/getting_started/03_data_extraction.py+++ b/examples/getting_started/03_data_extraction.py@@ -27,7 +27,7 @@ from browser_use.llm.openai.chat import ChatOpenAIasync def main():# Initialize the model- llm = ChatOpenAI(model='gpt-4o-mini')+ llm = ChatOpenAI(model='gpt-4.1-mini')# Define a data extraction tasktask = """diff --git a/examples/getting_started/04_multi_step_task.py b/examples/getting_started/04_multi_step_task.pyindex e54302bb0..2d64e2e58 100644--- a/examples/getting_started/04_multi_step_task.py+++ b/examples/getting_started/04_multi_step_task.py@@ -27,7 +27,7 @@ from browser_use.llm.openai.chat import ChatOpenAIasync def main():# Initialize the model- llm = ChatOpenAI(model='gpt-4o-mini')+ llm = ChatOpenAI(model='gpt-4.1-mini')# Define a multi-step tasktask = """diff --git a/examples/getting_started/test.py b/examples/getting_started/test.pynew file mode 100644index 000000000..266d644d4--- /dev/null+++ b/examples/getting_started/test.py@@ -0,0 +1,53 @@+"""+Getting Started Example 3: Data Extraction++This example demonstrates how to:+- Navigate to a website with structured data+- Extract specific information from the page+- Process and organize the extracted data+- Return structured results++This builds on previous examples by showing how to get valuable data from websites.+"""++import asyncio+import os+import sys++# Add the parent directory to the path so we can import browser_use+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++from dotenv import load_dotenv++load_dotenv()++from browser_use import Agent+from browser_use.llm.openai.chat import ChatOpenAI+++async def main():+ # Initialize the model+ llm = ChatOpenAI(model='gpt-4.1-mini')++ # Define a data extraction task+ task = """+ Go to https://quotes.toscrape.com/ and extract the following information:+ - The first 5 quotes on the page+ - The author of each quote+ - The tags associated with each quote++ Present the information in a clear, structured format like:+ Quote 1: "[quote text]" - Author: [author name] - Tags: [tag1, tag2, ...]+ Quote 2: "[quote text]" - Author: [author name] - Tags: [tag1, tag2, ...]+ etc.+ """++ # Create and run the agent+ agent = Agent(task=task, llm=llm)+ await agent.run()+++++if __name__ == '__main__':+ asyncio.run(main())diff --git a/examples/mcp/advanced_client.py b/examples/mcp/advanced_client.pyindex da220db31..b58e4ac7a 100644--- a/examples/mcp/advanced_client.py+++ b/examples/mcp/advanced_client.py@@ -54,7 +54,7 @@ async def main():# Create agent with extended system prompt for using multiple MCP serversagent = Agent(task='Sign up for a new Anthropic account using the email [email protected], save the registration details to a file',- llm=ChatOpenAI(model='gpt-4o'),+ llm=ChatOpenAI(model='gpt-4.1-mini'),controller=controller,extend_system_message="""You have access to both Gmail and Filesystem tools through MCP servers. When signing up for accounts:diff --git a/examples/mcp/simple_client.py b/examples/mcp/simple_client.pyindex b65022f31..6e9c3fd7a 100644--- a/examples/mcp/simple_client.py+++ b/examples/mcp/simple_client.py@@ -29,7 +29,7 @@ async def main():# Create agent with MCP-enabled controlleragent = Agent(task='List all files on the Desktop and read the content of any .txt files you find',- llm=ChatOpenAI(model='gpt-4o'),+ llm=ChatOpenAI(model='gpt-4.1-mini'),controller=controller,)