Skip to content

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

switched to better representations

Gregor Žuničee0f96142959
diff --git a/browser_use/agent/system_prompt.md b/browser_use/agent/system_prompt.md
index 5f7eff0a1..fe2436487 100644
--- a/browser_use/agent/system_prompt.md
+++ b/browser_use/agent/system_prompt.md
@@ -1,30 +1,34 @@
You are an AI agent designed to automate browser tasks. Your goal is to accomplish the ultimate task following the rules.
# Input Format
+
Task
Previous steps
Current URL
Open Tabs
Interactive Elements
[index]<type>text</type>
+
- index: Numeric identifier for interaction
- type: HTML element type (button, input, etc.)
- text: Element description
-Example:
-[33]<button>Submit Form</button>
+ Example:
+ [33]<button>Submit Form</button>
- Only elements with numeric indexes in [] are interactive
-- elements without [] provide only context
+- (stacked) indentation is important and means that the element is a child of the element above (with a lower index)
# Response Rules
+
1. RESPONSE FORMAT: You must ALWAYS respond with valid JSON in this exact format:
-{{"current_state": {{"evaluation_previous_goal": "Success|Failed|Unknown - Analyze the current elements and the image to check if the previous goals/actions are successful like intended by the task. Mention if something unexpected happened. Shortly state why/why not",
-"memory": "Description of what has been done and what you need to remember. Be very specific. Count here ALWAYS how many times you have done something and how many remain. E.g. 0 out of 10 websites analyzed. Continue with abc and xyz",
-"next_goal": "What needs to be done with the next immediate action"}},
-"action":[{{"one_action_name": {{// action-specific parameter}}}}, // ... more actions in sequence]}}
+ {{"current_state": {{"evaluation_previous_goal": "Success|Failed|Unknown - Analyze the current elements and the image to check if the previous goals/actions are successful like intended by the task. Mention if something unexpected happened. Shortly state why/why not",
+ "memory": "Description of what has been done and what you need to remember. Be very specific. Count here ALWAYS how many times you have done something and how many remain. E.g. 0 out of 10 websites analyzed. Continue with abc and xyz",
+ "next_goal": "What needs to be done with the next immediate action"}},
+ "action":[{{"one_action_name": {{// action-specific parameter}}}}, // ... more actions in sequence]}}
2. ACTIONS: You can specify multiple actions in the list to be executed in sequence. But always specify only one action name per item. Use maximum {{max_actions}} actions per sequence.
-Common action sequences:
+ Common action sequences:
+
- Form filling: [{{"input_text": {{"index": 1, "text": "username"}}}}, {{"input_text": {{"index": 2, "text": "password"}}}}, {{"click_element": {{"index": 3}}}}]
- Navigation and extraction: [{{"go_to_url": {{"url": "https://example.com"}}}}, {{"extract_content": {{"goal": "extract the names"}}}}]
- Actions are executed in the given order
@@ -34,10 +38,11 @@ Common action sequences:
- only use multiple actions if it makes sense.
3. ELEMENT INTERACTION:
+
- Only use indexes of the interactive elements
-- Elements marked with "[]Non-interactive text" are non-interactive
4. NAVIGATION & ERROR HANDLING:
+
- If no suitable elements exist, use other functions to complete the task
- If stuck, try alternative approaches - like going back to a previous page, new search, new tab etc.
- Handle popups/cookies by accepting or closing them
@@ -47,6 +52,7 @@ Common action sequences:
- If the page is not fully loaded, use wait action
5. TASK COMPLETION:
+
- Use the done action as the last action as soon as the ultimate task is complete
- Dont use "done" before you are done with everything the user asked you, except you reach the last step of max_steps.
- If you reach your last step, use the done action even if the task is not fully finished. Provide all the information you have gathered so far. If the ultimate task is completely finished set success to true. If not everything the user asked for is completed set success in done to false!
@@ -55,16 +61,20 @@ Common action sequences:
- Make sure you include everything you found out for the ultimate task in the done text parameter. Do not just say you are done, but include the requested information of the task.
6. VISUAL CONTEXT:
+
- When an image is provided, use it to understand the page layout
- Bounding boxes with labels on their top right corner correspond to element indexes
7. Form filling:
+
- If you fill an input field and your action sequence is interrupted, most often something changed e.g. suggestions popped up under the field.
8. Long tasks:
+
- Keep track of the status and subresults in the memory.
- You are provided with procedural memory summaries that condense previous task history (every N steps). Use these summaries to maintain context about completed actions, current progress, and next steps. The summaries appear in chronological order and contain key information about navigation history, findings, errors encountered, and current state. Refer to these summaries to avoid repeating actions and to ensure consistent progress toward the task goal.
9. Extraction:
+
- If your task is to find information - call extract_content on the specific pages to get and store the information.
-Your responses must be always JSON with the specified format.
+ Your responses must be always JSON with the specified format.
diff --git a/browser_use/dom/buildDomTree.js b/browser_use/dom/buildDomTree.js
index f7ebed289..8437f7cf7 100644
--- a/browser_use/dom/buildDomTree.js
+++ b/browser_use/dom/buildDomTree.js
@@ -679,7 +679,7 @@
const interactiveRoles = new Set([
'button', // Directly clickable element
// 'link', // Clickable link
- 'menuitem', // Clickable menu item
+ // 'menuitem', // Clickable menu item
'menuitemradio', // Radio-style menu item (selectable)
'menuitemcheckbox', // Checkbox-style menu item (toggleable)
'radio', // Radio button (selectable)
@@ -691,7 +691,7 @@
'combobox', // Dropdown with text input
'searchbox', // Search input field
'textbox', // Text input field
- 'listbox', // Selectable list
+ // 'listbox', // Selectable list
'option', // Selectable option in a list
'scrollbar' // Scrollable control
]);
@@ -990,8 +990,8 @@
} else {
highlightElement(node, nodeData.highlightIndex, parentIframe);
}
+ return true; // Successfully highlighted
}
- return true; // Successfully highlighted
} else {
// console.log(`Skipping highlight for ${nodeData.tagName} (outside viewport)`);
}
@@ -1167,7 +1167,9 @@
}
// Handle regular elements
for (const child of node.childNodes) {
- const domElement = buildDomTree(child, parentIframe, nodeWasHighlighted);
+ // Pass the highlighted status of the *current* node to its children
+ const passHighlightStatusToChild = nodeWasHighlighted || isParentHighlighted;
+ const domElement = buildDomTree(child, parentIframe, passHighlightStatusToChild);
if (domElement) nodeData.children.push(domElement);
}
}
diff --git a/browser_use/dom/tests/extraction_test.py b/browser_use/dom/tests/extraction_test.py
index 1a442aee1..7c0f8aa92 100644
--- a/browser_use/dom/tests/extraction_test.py
+++ b/browser_use/dom/tests/extraction_test.py
@@ -196,40 +196,48 @@ async def test_focus_vs_all_elements():
# f.write(json.dumps(all_elements_state.element_tree.__json__(), indent=2))
# print('Clickable elements written to ./tmp/clickable_elements.json')
- answer = input("Enter element index to click, text to input (after click), or 'q' to quit: ")
+ answer = input("Enter element index to click, 'index,text' to input, or 'q' to quit: ")
if answer.lower() == 'q':
break
try:
- # Try clicking based on index
- clicked_index = int(answer)
- if clicked_index in selector_map:
- element_node = selector_map[clicked_index]
- print(f'Clicking element {clicked_index}: {element_node.tag_name}')
- await context._click_element_node(element_node)
- last_clicked_index = clicked_index # Remember index for potential input
- print('Click successful.')
- else:
- print(f'Invalid index: {clicked_index}')
- last_clicked_index = None # Reset if index was invalid
- except ValueError:
- # If not an integer, try inputting text
- if last_clicked_index is not None:
- if last_clicked_index in selector_map:
- element_node = selector_map[last_clicked_index]
- print(f"Inputting text '{answer}' into element {last_clicked_index}: {element_node.tag_name}")
- await context._input_text_element_node(element_node, answer.split(',')[1])
- last_clicked_index = None # Reset after input
- print('Input successful.')
+ if ',' in answer:
+ # Input text format: index,text
+ parts = answer.split(',', 1)
+ if len(parts) == 2:
+ try:
+ target_index = int(parts[0].strip())
+ text_to_input = parts[1]
+ if target_index in selector_map:
+ element_node = selector_map[target_index]
+ print(
+ f"Inputting text '{text_to_input}' into element {target_index}: {element_node.tag_name}"
+ )
+ await context._input_text_element_node(element_node, text_to_input)
+ print('Input successful.')
+ else:
+ print(f'Invalid index: {target_index}')
+ except ValueError:
+ print(f'Invalid index format: {parts[0]}')
else:
- print(f'Error: Last clicked index {last_clicked_index} no longer valid.')
- last_clicked_index = None
+ print("Invalid input format. Use 'index,text'.")
else:
- print('Please click an element (enter its index) before inputting text.')
+ # Click element format: index
+ try:
+ clicked_index = int(answer)
+ if clicked_index in selector_map:
+ element_node = selector_map[clicked_index]
+ print(f'Clicking element {clicked_index}: {element_node.tag_name}')
+ await context._click_element_node(element_node)
+ print('Click successful.')
+ else:
+ print(f'Invalid index: {clicked_index}')
+ except ValueError:
+ print(f"Invalid input: '{answer}'. Enter an index, 'index,text', or 'q'.")
+
except Exception as action_e:
print(f'Action failed: {action_e}')
- last_clicked_index = None # Reset on failure
# No explicit highlight removal here, get_state handles it at the start of the loop
diff --git a/browser_use/dom/views.py b/browser_use/dom/views.py
index 2691f5072..17c9b9983 100644
--- a/browser_use/dom/views.py
+++ b/browser_use/dom/views.py
@@ -148,38 +148,64 @@ class DOMElementNode(DOMBaseNode):
formatted_text = []
def process_node(node: DOMBaseNode, depth: int) -> None:
+ next_depth = int(depth)
+ depth_str = depth * '\t'
+
if isinstance(node, DOMElementNode):
# Add element with highlight_index
if node.highlight_index is not None:
- attributes_str = ''
+ next_depth += 1
+
text = node.get_all_text_till_next_clickable_element()
+ attributes_html_str = ''
if include_attributes:
- attributes = list(
- set(
- [
- str(value)
- for key, value in node.attributes.items()
- if key in include_attributes and value != node.tag_name
- ]
- )
- )
- if text in attributes:
- attributes.remove(text)
- attributes_str = ';'.join(attributes)
- line = f'[{node.highlight_index}]<{node.tag_name} '
- if attributes_str:
- line += f'{attributes_str}'
+ attributes_to_include = {
+ key: str(value) for key, value in node.attributes.items() if key in include_attributes
+ }
+
+ # Easy LLM optimizations
+ # if tag == role attribute, don't include it
+ if node.tag_name == attributes_to_include.get('role'):
+ del attributes_to_include['role']
+
+ # if aria-label == text of the node, don't include it
+ if (
+ attributes_to_include.get('aria-label')
+ and attributes_to_include.get('aria-label', '').strip() == text.strip()
+ ):
+ del attributes_to_include['aria-label']
+
+ # if placeholder == text of the node, don't include it
+ if (
+ attributes_to_include.get('placeholder')
+ and attributes_to_include.get('placeholder', '').strip() == text.strip()
+ ):
+ del attributes_to_include['placeholder']
+
+ if attributes_to_include:
+ # Format as key1='value1' key2='value2'
+ attributes_html_str = ' '.join(f"{key}='{value}'" for key, value in attributes_to_include.items())
+
+ # Build the line
+ line = f'{depth_str}[{node.highlight_index}]<{node.tag_name}'
+ if attributes_html_str:
+ line += f' {attributes_html_str}'
+
if text:
- if attributes_str:
- line += f'>{text}'
- else:
- line += f'{text}'
- line += '/>'
+ # Add space before >text only if there were NO attributes added before
+ if not attributes_html_str:
+ line += ' '
+ line += f'>{text}'
+ # Add space before /> only if neither attributes NOR text were added
+ elif not attributes_html_str:
+ line += ' '
+
+ line += ' />' # 1 token
formatted_text.append(line)
# Process children regardless
for child in node.children:
- process_node(child, depth + 1)
+ process_node(child, next_depth)
elif isinstance(node, DOMTextNode):
# Add text only if it doesn't have a highlighted parent
@@ -189,7 +215,7 @@ class DOMElementNode(DOMBaseNode):
and node.parent.is_visible
and node.parent.is_top_element
): # and node.is_parent_top_element()
- formatted_text.append(f'{node.text}')
+ formatted_text.append(f'{depth_str}{node.text}')
process_node(self, 0)
return '\n'.join(formatted_text)