Josedcape commited on
Commit
bafd1e6
·
verified ·
1 Parent(s): acdb322

Update src/agent/custom_prompts.py

Browse files
Files changed (1) hide show
  1. src/agent/custom_prompts.py +120 -208
src/agent/custom_prompts.py CHANGED
@@ -1,208 +1,120 @@
1
- import pdb
2
- from typing import List, Optional
3
-
4
- from browser_use.agent.prompts import SystemPrompt
5
- from browser_use.agent.views import ActionResult
6
- from browser_use.browser.views import BrowserState
7
- from langchain_core.messages import HumanMessage, SystemMessage
8
-
9
- from .custom_views import CustomAgentStepInfo
10
-
11
-
12
- class CustomSystemPrompt(SystemPrompt):
13
- def important_rules(self) -> str:
14
- """
15
- Returns the important rules for the agent.
16
- """
17
- text = """
18
- 1. RESPONSE FORMAT: You must ALWAYS respond with valid JSON in this exact format:
19
- {
20
- "current_state": {
21
- "prev_action_evaluation": "Success|Failed|Unknown - Analyze the current elements and the image to check if the previous goals/actions are successful like intended by the task. Ignore the action result. The website is the ground truth. Also mention if something unexpected happened like new suggestions in an input field. Shortly state why/why not. Note that the result you output must be consistent with the reasoning you output afterwards. If you consider it to be 'Failed,' you should reflect on this during your thought.",
22
- "important_contents": "Output important contents closely related to user\'s instruction or task on the current page. If there is, please output the contents. If not, please output empty string ''.",
23
- "task_progress": "Task Progress is a general summary of the current contents that have been completed. Just summarize the contents that have been actually completed based on the content at current step and the history operations. Please list each completed item individually, such as: 1. Input username. 2. Input Password. 3. Click confirm button. Please return string type not a list.",
24
- "future_plans": "Based on the user's request and the current state, outline the remaining steps needed to complete the task. This should be a concise list of actions yet to be performed, such as: 1. Select a date. 2. Choose a specific time slot. 3. Confirm booking. Please return string type not a list.",
25
- "thought": "Think about the requirements that have been completed in previous operations and the requirements that need to be completed in the next one operation. If your output of prev_action_evaluation is 'Failed', please reflect and output your reflection here.",
26
- "summary": "Please generate a brief natural language description for the operation in next actions based on your Thought."
27
- },
28
- "action": [
29
- {
30
- "action_name": {
31
- // action-specific parameters
32
- }
33
- },
34
- // ... more actions in sequence
35
- ]
36
- }
37
-
38
- 2. ACTIONS: You can specify multiple actions to be executed in sequence.
39
-
40
- Common action sequences:
41
- - Form filling: [
42
- {"input_text": {"index": 1, "text": "username"}},
43
- {"input_text": {"index": 2, "text": "password"}},
44
- {"click_element": {"index": 3}}
45
- ]
46
- - Navigation and extraction: [
47
- {"open_new_tab": {}},
48
- {"go_to_url": {"url": "https://example.com"}},
49
- {"extract_page_content": {}}
50
- ]
51
-
52
-
53
- 3. ELEMENT INTERACTION:
54
- - Only use indexes that exist in the provided element list
55
- - Each element has a unique index number (e.g., "33[:]<button>")
56
- - Elements marked with "_[:]" are non-interactive (for context only)
57
-
58
- 4. NAVIGATION & ERROR HANDLING:
59
- - If no suitable elements exist, use other functions to complete the task
60
- - If stuck, try alternative approaches
61
- - Handle popups/cookies by accepting or closing them
62
- - Use scroll to find elements you are looking for
63
-
64
- 5. TASK COMPLETION:
65
- - If you think all the requirements of user\'s instruction have been completed and no further operation is required, output the done action to terminate the operation process.
66
- - Don't hallucinate actions.
67
- - If the task requires specific information - make sure to include everything in the done function. This is what the user will see.
68
- - If you are running out of steps (current step), think about speeding it up, and ALWAYS use the done action as the last action.
69
- - Note that you must verify if you've truly fulfilled the user's request by examining the actual page content, not just by looking at the actions you output but also whether the action is executed successfully. Pay particular attention when errors occur during action execution.
70
-
71
- 6. VISUAL CONTEXT:
72
- - When an image is provided, use it to understand the page layout
73
- - Bounding boxes with labels correspond to element indexes
74
- - Each bounding box and its label have the same color
75
- - Most often the label is inside the bounding box, on the top right
76
- - Visual context helps verify element locations and relationships
77
- - sometimes labels overlap, so use the context to verify the correct element
78
-
79
- 7. Form filling:
80
- - If you fill an input field and your action sequence is interrupted, most often a list with suggestions poped up under the field and you need to first select the right element from the suggestion list.
81
-
82
- 8. ACTION SEQUENCING:
83
- - Actions are executed in the order they appear in the list
84
- - Each action should logically follow from the previous one
85
- - If the page changes after an action, the sequence is interrupted and you get the new state.
86
- - If content only disappears the sequence continues.
87
- - Only provide the action sequence until you think the page will change.
88
- - Try to be efficient, e.g. fill forms at once, or chain actions where nothing changes on the page like saving, extracting, checkboxes...
89
- - only use multiple actions if it makes sense.
90
- """
91
- text += f" - use maximum {self.max_actions_per_step} actions per sequence"
92
- return text
93
-
94
- def input_format(self) -> str:
95
- return """
96
- INPUT STRUCTURE:
97
- 1. Task: The user\'s instructions you need to complete.
98
- 2. Hints(Optional): Some hints to help you complete the user\'s instructions.
99
- 3. Memory: Important contents are recorded during historical operations for use in subsequent operations.
100
- 4. Current URL: The webpage you're currently on
101
- 5. Available Tabs: List of open browser tabs
102
- 6. Interactive Elements: List in the format:
103
- index[:]<element_type>element_text</element_type>
104
- - index: Numeric identifier for interaction
105
- - element_type: HTML element type (button, input, etc.)
106
- - element_text: Visible text or element description
107
-
108
- Example:
109
- 33[:]<button>Submit Form</button>
110
- _[:] Non-interactive text
111
-
112
-
113
- Notes:
114
- - Only elements with numeric indexes are interactive
115
- - _[:] elements provide context but cannot be interacted with
116
- """
117
-
118
- def get_system_message(self) -> SystemMessage:
119
- """
120
- Get the system prompt for the agent.
121
-
122
- Returns:
123
- str: Formatted system prompt
124
- """
125
- time_str = self.current_date.strftime("%Y-%m-%d %H:%M")
126
-
127
- AGENT_PROMPT = f"""You are a precise browser automation agent that interacts with websites through structured commands. Your role is to:
128
- 1. Analyze the provided webpage elements and structure
129
- 2. Plan a sequence of actions to accomplish the given task
130
- 3. Respond with valid JSON containing your action sequence and state assessment
131
-
132
- Current date and time: {time_str}
133
-
134
- {self.input_format()}
135
-
136
- {self.important_rules()}
137
-
138
- Functions:
139
- {self.default_action_description}
140
-
141
- Remember: Your responses must be valid JSON matching the specified format. Each action in the sequence must be valid."""
142
- return SystemMessage(content=AGENT_PROMPT)
143
-
144
-
145
- class CustomAgentMessagePrompt:
146
- def __init__(
147
- self,
148
- state: BrowserState,
149
- result: Optional[List[ActionResult]] = None,
150
- include_attributes: list[str] = [],
151
- max_error_length: int = 400,
152
- step_info: Optional[CustomAgentStepInfo] = None,
153
- ):
154
- self.state = state
155
- self.result = result
156
- self.max_error_length = max_error_length
157
- self.include_attributes = include_attributes
158
- self.step_info = step_info
159
-
160
- def get_user_message(self) -> HumanMessage:
161
- if self.step_info:
162
- step_info_description = f'Current step: {self.step_info.step_number + 1}/{self.step_info.max_steps}'
163
- else:
164
- step_info_description = ''
165
-
166
- elements_text = self.state.element_tree.clickable_elements_to_string(include_attributes=self.include_attributes)
167
- if not elements_text:
168
- elements_text = 'empty page'
169
- state_description = f"""
170
- {step_info_description}
171
- 1. Task: {self.step_info.task}
172
- 2. Hints(Optional):
173
- {self.step_info.add_infos}
174
- 3. Memory:
175
- {self.step_info.memory}
176
- 4. Current url: {self.state.url}
177
- 5. Available tabs:
178
- {self.state.tabs}
179
- 6. Interactive elements:
180
- {elements_text}
181
- """
182
-
183
- if self.result:
184
- for i, result in enumerate(self.result):
185
- if result.extracted_content:
186
- state_description += f"\nResult of action {i + 1}/{len(self.result)}: {result.extracted_content}"
187
- if result.error:
188
- # only use last 300 characters of error
189
- error = result.error[-self.max_error_length:]
190
- state_description += (
191
- f"\nError of action {i + 1}/{len(self.result)}: ...{error}"
192
- )
193
-
194
- if self.state.screenshot:
195
- # Format message for vision model
196
- return HumanMessage(
197
- content=[
198
- {"type": "text", "text": state_description},
199
- {
200
- "type": "image_url",
201
- "image_url": {
202
- "url": f"data:image/png;base64,{self.state.screenshot}"
203
- },
204
- },
205
- ]
206
- )
207
-
208
- return HumanMessage(content=state_description)
 
1
+ import pdb
2
+ from typing import List, Optional
3
+
4
+ from browser_use.agent.prompts import SystemPrompt
5
+ from browser_use.agent.views import ActionResult
6
+ from browser_use.browser.views import BrowserState
7
+ from langchain_core.messages import HumanMessage, SystemMessage
8
+
9
+ from .custom_views import CustomAgentStepInfo
10
+
11
+ class CustomSystemPrompt(SystemPrompt):
12
+ def important_rules(self) -> str:
13
+ text = """
14
+ 1. RESPONSE FORMAT: You must ALWAYS respond with valid JSON in this exact format:
15
+ {
16
+ "current_state": {
17
+ "prev_action_evaluation": "Success|Failed|Unknown - Analyze the current elements and the image to check if the previous goals/actions are successful like intended by the task. Ignore the action result. The website is the ground truth. Also mention if something unexpected happened like new suggestions in an input field. Shortly state why/why not. Note that the result you output must be consistent with the reasoning you output afterwards. If you consider it to be 'Failed,' you should reflect on this during your thought.",
18
+ "important_contents": "Output important contents closely related to user\'s instruction or task on the current page. If there is, please output the contents. If not, please output empty string ''.",
19
+ "task_progress": "Task Progress is a general summary of the current contents that have been completed. Just summarize the contents that have been actually completed based on the content at current step and the history operations. Please list each completed item individually, such as: 1. Input username. 2. Input Password. 3. Click confirm button. Please return string type not a list.",
20
+ "future_plans": "Based on the user's request and the current state, outline the remaining steps needed to complete the task. This should be a concise list of actions yet to be performed, such as: 1. Select a date. 2. Choose a specific time slot. 3. Confirm booking. Please return string type not a list.",
21
+ "thought": "Think about the requirements that have been completed in previous operations and the requirements that need to be completed in the next one operation. If your output of prev_action_evaluation is 'Failed', please reflect and output your reflection here.",
22
+ "summary": "Please generate a brief natural language description for the operation in next actions based on your Thought."
23
+ },
24
+ "action": [
25
+ {
26
+ "action_name": {
27
+ // action-specific parameters
28
+ }
29
+ }
30
+ ]
31
+ }
32
+
33
+ 2. ACTIONS: Specify multiple actions to be executed in sequence if needed.
34
+
35
+ 3. ELEMENT INTERACTION:
36
+ - Only use indexes that exist in the provided element list.
37
+ - Ensure each action is valid based on the current page state.
38
+
39
+ 4. NAVIGATION & ERROR HANDLING:
40
+ - Handle popups/cookies by accepting or closing them.
41
+ - If no suitable elements exist, use alternative methods to proceed.
42
+
43
+ 5. TASK COMPLETION:
44
+ - Ensure the task is fully completed before returning a 'done' action.
45
+ - Always validate your output with the actual page content.
46
+
47
+ 6. VISUAL CONTEXT:
48
+ - Use visual context when provided to verify layout and relationships.
49
+
50
+ 7. ACTION SEQUENCING:
51
+ - Plan and execute actions efficiently, minimizing unnecessary steps.
52
+ """
53
+ text += f" - Use a maximum of {self.max_actions_per_step} actions per sequence."
54
+ return text
55
+
56
+ def input_format(self) -> str:
57
+ return """
58
+ INPUT STRUCTURE:
59
+ 1. Task: The user\'s instructions you need to complete.
60
+ 2. Memory: Important contents recorded during historical operations.
61
+ 3. Current URL: The webpage currently being viewed.
62
+ 4. Interactive Elements: List in the format:
63
+ index[:]<element_type>element_text</element_type>
64
+ """
65
+
66
+ def get_system_message(self) -> SystemMessage:
67
+ time_str = self.current_date.strftime("%Y-%m-%d %H:%M")
68
+
69
+ AGENT_PROMPT = f"""You are a precise browser automation agent. Your role is to:
70
+ 1. Analyze the provided webpage elements and structure.
71
+ 2. Plan a sequence of actions to accomplish the task.
72
+ 3. Respond with valid JSON containing your action sequence and state assessment.
73
+
74
+ Current date and time: {time_str}
75
+
76
+ {self.input_format()}
77
+
78
+ {self.important_rules()}
79
+ """
80
+ return SystemMessage(content=AGENT_PROMPT)
81
+
82
+ class CustomAgentMessagePrompt:
83
+ def __init__(
84
+ self,
85
+ state: BrowserState,
86
+ result: Optional[List[ActionResult]] = None,
87
+ include_attributes: list[str] = [],
88
+ max_error_length: int = 400,
89
+ step_info: Optional[CustomAgentStepInfo] = None,
90
+ ):
91
+ self.state = state
92
+ self.result = result
93
+ self.max_error_length = max_error_length
94
+ self.include_attributes = include_attributes
95
+ self.step_info = step_info
96
+
97
+ def get_user_message(self) -> HumanMessage:
98
+ step_info_description = f'Current step: {self.step_info.step_number + 1}/{self.step_info.max_steps}' if self.step_info else ''
99
+
100
+ elements_text = self.state.element_tree.clickable_elements_to_string(include_attributes=self.include_attributes)
101
+ if not elements_text:
102
+ elements_text = 'empty page'
103
+
104
+ state_description = f"""
105
+ {step_info_description}
106
+ 1. Task: {self.step_info.task if self.step_info else 'No task provided.'}
107
+ 2. Memory: {self.step_info.memory if self.step_info else 'No memory available.'}
108
+ 3. Current URL: {self.state.url}
109
+ 4. Interactive elements: {elements_text}
110
+ """
111
+
112
+ if self.result:
113
+ for i, result in enumerate(self.result):
114
+ if result.extracted_content:
115
+ state_description += f"\nResult of action {i + 1}/{len(self.result)}: {result.extracted_content}"
116
+ if result.error:
117
+ error = result.error[-self.max_error_length:]
118
+ state_description += f"\nError of action {i + 1}/{len(self.result)}: ...{error}"
119
+
120
+ return HumanMessage(content=state_description)