Skip to content

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

address cubic comments

Alezander987ab3c20fbc5
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 8f9ad0f37..8969acf56 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -13,7 +13,6 @@ from datetime import datetime
from pathlib import Path
from typing import Any, Generic, Literal, TypeVar
from urllib.parse import urlparse
-import subprocess
from dotenv import load_dotenv
@@ -1730,58 +1729,59 @@ 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
-
+
def _get_complete_history_without_screenshots(history_data: dict[str, Any]) -> str:
if 'history' in history_data:
for item in history_data['history']:
if 'state' in item and 'screenshot' in item['state']:
item['state']['screenshot'] = None
-
+
return json.dumps(history_data)
-
+
# 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
+ structured_output_json = json.dumps(structured_output.model_dump()) if structured_output else None
final_result = self.state.history.final_result()
-
+ git_info = get_git_info()
+ action_history = self.state.history.action_history()
+ action_errors = self.state.history.errors()
+ urls = self.state.history.urls()
+ usage = self.state.history.usage
-
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,
-
+ 'git_info': json.dumps(git_info) if 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
+ structured_output_json[:20000]
+ if structured_output_json and len(structured_output_json) > 20000
+ else structured_output_json
),
- 'action_history_truncated': 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,
+ 'action_history_truncated': json.dumps(action_history) if action_history else None,
+ 'action_errors': json.dumps(action_errors) if action_errors else None,
+ 'urls': json.dumps(urls) if urls else None,
'final_result_response_truncated': (
final_result[:20000] if final_result and len(final_result) > 20000 else final_result
),
@@ -1789,19 +1789,17 @@ class Agent(Generic[Context, AgentStructuredOutput]):
'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,
+ 'usage': json.dumps(usage.model_dump()) if usage else None,
},
'trace_details': {
# Autogenerated fields (ensure same as trace)
'trace_id': trace_id,
'timestamp': timestamp,
-
- # Direct agent properties
+ # Direct agent properties
'task': self.task,
-
# AgentHistoryList methods
- 'structured_output': json.dumps(structured_output.model_dump()) if structured_output else None,
+ 'structured_output': structured_output_json,
'final_result_response': final_result,
'complete_history': _get_complete_history_without_screenshots(self.state.history.model_dump()),
- }
+ },
}
diff --git a/browser_use/agent/views.py b/browser_use/agent/views.py
index 5170e62e3..044b23af0 100644
--- a/browser_use/agent/views.py
+++ b/browser_use/agent/views.py
@@ -482,7 +482,9 @@ class AgentHistoryList(BaseModel, Generic[AgentStructuredOutput]):
for h in self.history:
if h.model_output:
- for action, interacted_element in zip(h.model_output.action, h.state.interacted_element):
+ # Guard against None interacted_element before zipping
+ interacted_elements = h.state.interacted_element or [None] * len(h.model_output.action)
+ for action, interacted_element in zip(h.model_output.action, interacted_elements):
output = action.model_dump(exclude_none=True)
output['interacted_element'] = interacted_element
outputs.append(output)
@@ -491,23 +493,21 @@ class AgentHistoryList(BaseModel, Generic[AgentStructuredOutput]):
def action_history(self) -> list[list[dict]]:
"""Get truncated action history with only essential fields"""
step_outputs = []
-
+
for h in self.history:
step_actions = []
if h.model_output:
+ # Guard against None interacted_element before zipping
+ interacted_elements = h.state.interacted_element or [None] * len(h.model_output.action)
# Zip actions with interacted elements and results
- for action, interacted_element, result in zip(
- h.model_output.action,
- h.state.interacted_element,
- h.result
- ):
+ for action, interacted_element, result in zip(h.model_output.action, interacted_elements, h.result):
action_output = action.model_dump(exclude_none=True)
action_output['interacted_element'] = interacted_element
# Only keep long_term_memory from result
action_output['result'] = result.long_term_memory if result and result.long_term_memory else None
step_actions.append(action_output)
step_outputs.append(step_actions)
-
+
return step_outputs
def action_results(self) -> list[ActionResult]:
diff --git a/browser_use/utils.py b/browser_use/utils.py
index cd80da020..678fa7c38 100644
--- a/browser_use/utils.py
+++ b/browser_use/utils.py
@@ -579,47 +579,41 @@ 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()
-
+ 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()
-
+ 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()
-
+ 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:
+ 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 as e:
+ logger.debug(f'Error getting git info: {type(e).__name__}: {e}')
return None