Skip to content

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

Improve prompt

magmuellerdd937112ba0f
diff --git a/browser_use/agent/prompts.py b/browser_use/agent/prompts.py
index 9041b8437..834843551 100644
--- a/browser_use/agent/prompts.py
+++ b/browser_use/agent/prompts.py
@@ -1,5 +1,5 @@
from datetime import datetime
-from typing import Optional
+from typing import List, Optional
from langchain_core.messages import HumanMessage, SystemMessage
@@ -12,44 +12,89 @@ class SystemPrompt:
self.default_action_description = action_description
self.current_date = current_date
- def example_response(self) -> str:
- """
- Returns an example response for the agent.
-
- Returns:
- str: Example response
- """
- return """{"current_state": {"valuation_previous_goal": "Success", "memory": "We applied already for 3/7 jobs, 1. ..., 2. ..., 3. ...", "next_goal": "Click on the button x to apply for the next job"}, "action": {"click_element": {"index": 44,"num_clicks": 2}}}"""
-
def important_rules(self) -> str:
"""
Returns the important rules for the agent.
-
- Returns:
- str: Important rules
"""
return """
-1. Only use indexes that exist in the input list for click or input text actions. If no indexes exist, try alternative actions, e.g. go back, search google etc.
-2. If stuck, try alternative approaches, e.g. go back, search google, or extract_page_content
-3. When you are done with the complete task, use the done action. Make sure to have all information the user needs and return the result.
-4. If an image is provided, use it to understand the context, the bounding boxes around the buttons have the same indexes as the interactive elements.
-6. ALWAYS respond in the RESPONSE FORMAT with valid JSON.
-7. If the page is empty use actions like "go_to_url", "search_google" or "open_tab"
-8. Remember: Choose EXACTLY ONE action per response. Invalid combinations or multiple actions will be rejected.
-9. If popups like cookies appear, accept or close them
-10. Call 'done' when you are done with the task - dont hallucinate or make up actions which the user did not ask for
- """
+1. RESPONSE FORMAT: You must ALWAYS respond with valid JSON in this exact format:
+ {
+ "current_state": {
+ "evaluation_previous_goal": "Success|Failed|Unknown-Brief description of why",
+ "memory": "Brief description of what has been done-What you need to remember until the end of the task",
+ "next_goal": "What needs to be done with the next actions"
+ },
+ "action": [
+ {
+ "action_name": {
+ // action-specific parameters
+ }
+ },
+ // ... more actions in sequence
+ ]
+ }
+
+2. ACTIONS: You can specify multiple actions to be executed in sequence.
+
+ 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_page_content": {}}
+ ]
+
+3. ELEMENT INTERACTION:
+ - Only use indexes that exist in the provided element list
+ - Each element has a unique index number (e.g., "33[:]<button>")
+ - Elements marked with "_[:]" are non-interactive (for context only)
+
+4. NAVIGATION & ERROR HANDLING:
+ - If no suitable elements exist, use other functions to complete the task
+ - If stuck, try alternative approaches
+ - Handle popups/cookies by accepting or closing them
+
+5. TASK COMPLETION:
+ - Use the done action as the last action as soon as the task is complete
+ - Don't hallucinate actions
+ - If the user asks for specific information - make sure to include everything in the done function. This is what the user will see.
+
+6. VISUAL CONTEXT:
+ - When an image is provided, use it to understand the page layout
+ - Bounding boxes with labels correspond to element indexes
+ - Each bounding box and its label have the same color
+ - Most often the label is on the left of the bounding box
+ - Visual context helps verify element locations and relationships
+
+7. ACTION SEQUENCING:
+ - Actions are executed in the order they appear in the list
+ - Each action should logically follow from the previous one
+ - If the page changes between actions. The sequence is interrupted and you get the new page state.
+ - Only provide the action sequence until you think the DOM will change.
+"""
def input_format(self) -> str:
return """
+INPUT STRUCTURE:
+1. Current URL: The webpage you're currently on
+2. Available Tabs: List of open browser tabs
+3. Interactive Elements: List in the format:
+ index[:]<element_type>element_text</element_type>
+ - index: Numeric identifier for interaction
+ - element_type: HTML element type (button, input, etc.)
+ - element_text: Visible text or element description
+
Example:
-33[:]\t<button>Interactive element</button>
-_[:] Text content...
+33[:]<button>Submit Form</button>
+_[:] Non-interactive text
+ 45[:]<input>Email field</input> # Indented to show hierarchy
-Explanation:
-index[:] Interactible element with index. You can only interact with all elements which are clickable and refer to them by their index.
-_[:] elements are just for more context, but not interactable.
-\t: Tab indent (1 tab for depth 1 etc.). This is to help you understand which elements belong to each other.
+Notes:
+- Only elements with numeric indexes are interactive
+- _[:] elements provide context but cannot be interacted with
"""
def get_system_message(self) -> SystemMessage:
@@ -61,29 +106,32 @@ _[:] elements are just for more context, but not interactable.
"""
time_str = self.current_date.strftime('%Y-%m-%d %H:%M')
- AGENT_PROMPT = f"""
-You are an AI agent that helps users interact with websites. You receive a list of interactive elements from the current webpage and must respond with specific actions. Today's date is {time_str}.
+ AGENT_PROMPT = f"""You are a precise browser automation agent that interacts with websites through structured commands. Your role is to:
+1. Analyze the provided webpage elements and structure
+2. Plan a sequence of actions to accomplish the given task
+3. Respond with valid JSON containing your action sequence and state assessment
-INPUT FORMAT:
-{self.input_format()}
-
-Your AVAILABLE ACTIONS:
-{self.default_action_description}
+Current date and time: {time_str}
-Example:
-{self.example_response()}
+{self.input_format()}
-IMPORTANT RULES:
{self.important_rules()}
-"""
+
+Remember: Your responses must be valid JSON matching the specified format. Each action in the sequence must be valid and logically connected."""
return SystemMessage(content=AGENT_PROMPT)
+# Example:
+# {self.example_response()}
+# Your AVAILABLE ACTIONS:
+# {self.default_action_description}
+
+
class AgentMessagePrompt:
def __init__(
self,
state: BrowserState,
- result: Optional[ActionResult] = None,
+ result: Optional[List[ActionResult]] = None,
include_attributes: list[str] = [],
max_error_length: int = 400,
):
@@ -102,12 +150,13 @@ Interactive elements:
"""
if self.result:
- if self.result.extracted_content:
- state_description += f'\nResult of last action: {self.result.extracted_content}'
- if self.result.error:
- # only use last 300 characters of error
- error = self.result.error[-self.max_error_length :]
- state_description += f'\nError of last action: ...{error}'
+ for i, result in enumerate(self.result):
+ if result.extracted_content:
+ state_description += f'\nResult of action {i}: {result.extracted_content}'
+ if result.error:
+ # only use last 300 characters of error
+ error = result.error[-self.max_error_length :]
+ state_description += f'\nError of action {i}: ...{error}'
if self.state.screenshot:
# Format message for vision model