
    HFg1                         d dl Z d dlmZmZ d dlmZmZ d dlmZm	Z	 d dl
mZ d dlmZmZ d dlmZ dd	lmZ  G d
 de      Z G d de      Zy)    N)ListOptional)SystemPromptAgentMessagePrompt)ActionResultActionModel)BrowserState)HumanMessageSystemMessage)datetime   )CustomAgentStepInfoc                   $    e Zd ZdefdZdefdZy)CustomSystemPromptreturnc                 0    d}|d| j                    dz  }|S )z<
        Returns the important rules for the agent.
        aK  
CRITICAL: Your response MUST be a valid JSON object (not an array) with the exact structure shown below. Failure to follow this format will cause errors.

1. RESPONSE FORMAT: You must ALWAYS respond with valid JSON in this exact format:
   {
     "current_state": {
       "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.",
       "important_contents": "Output important contents closely related to user\'s instruction on the current page. If there is, please output the contents. If not, please output empty string ''.",
       "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.",
       "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.",
       "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.",
       "summary": "Please generate a brief natural language description for the operation in next actions based on your Thought."
     },
     "action": [
       * actions in sequences, please refer to **Common action sequences**. Each output action MUST be formated as: \{action_name\: action_params\}* 
     ]
   }

EXTREMELY IMPORTANT JSON RULES:
- Your ENTIRE response must be a single valid JSON object
- DO NOT include any text, explanations, or comments outside the JSON structure
- "current_state" MUST be an object, not an array or string
- "action" MUST be an array of objects, even if there's only one action
- Make sure all JSON keys and values are properly quoted with double quotes
- Ensure all brackets, braces, and quotes are properly balanced
- DO NOT use single quotes for JSON keys or values, use double quotes
- NEVER return a plain string or a list as your top-level response
- NEVER omit the "current_state" or "action" fields
- ALWAYS include all required fields in "current_state"
- ALWAYS wrap your response in a JSON object with { } at the top level
- DO NOT include markdown formatting like ```json or ``` around your response

EXAMPLE OF CORRECT JSON FORMAT:
{
  "current_state": {
    "prev_action_evaluation": "Success - The page loaded correctly",
    "important_contents": "Search results for OpenAI",
    "task_progress": "1. Navigated to Google. 2. Entered search term.",
    "future_plans": "1. Click on the first search result.",
    "thought": "I need to click on the first search result to complete the task.",
    "summary": "Will click on the first search result for OpenAI."
  },
  "action": [
    {"click_element": {"index": 5}}
  ]
}

EXAMPLES OF INCORRECT JSON FORMAT (DO NOT DO THESE):

1. DO NOT return a list:
[
  {
    "current_state": {...},
    "action": [...]
  }
]

2. DO NOT return a plain string:
"I will navigate to Google and search for OpenAI"

3. DO NOT include markdown formatting:
```json
{
  "current_state": {...},
  "action": [...]
}
```

4. DO NOT include explanations outside the JSON:
Here's my response:
{
  "current_state": {...},
  "action": [...]
}

5. DO NOT use single quotes:
{
  'current_state': {...},
  'action': [...]
}

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
   - Use scroll to find elements you are looking for

5. TASK COMPLETION:
   - 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.
   - Don't hallucinate actions.
   - If the task requires specific information - make sure to include everything in the done function. This is what the user will see.
   - If you are running out of steps (current step), think about speeding it up, and ALWAYS use the done action as the last action.
   - 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.

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 inside the bounding box, on the top right
   - Visual context helps verify element locations and relationships
   - sometimes labels overlap, so use the context to verify the correct element

7. Form filling:
   - 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.

8. 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 after an action, the sequence is interrupted and you get the new state.
   - If content only disappears the sequence continues.
   - Only provide the action sequence until you think the page will change.
   - Try to be efficient, e.g. fill forms at once, or chain actions where nothing changes on the page like saving, extracting, checkboxes...
   - only use multiple actions if it makes sense. 

9. Extraction:
    - If your task is to find information or do research - call extract_content on the specific pages to get and store the information.

z   - use maximum z actions per sequence)max_actions_per_step)selftexts     H/Users/kosar/src/browser-use-projects/web-ui/src/agent/custom_prompts.pyimportant_rulesz"CustomSystemPrompt.important_rules   s.    HR 	#D$=$=#>>STT    c                      y)Na*  
INPUT STRUCTURE:
1. Task: The user's instructions you need to complete.
2. Hints(Optional): Some hints to help you complete the user's instructions.
3. Memory: Important contents are recorded during historical operations for use in subsequent operations.
4. Current URL: The webpage you're currently on
5. Available Tabs: List of open browser tabs
6. 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]<button>Submit Form</button>
[] Non-interactive text


Notes:
- Only elements with numeric indexes inside [] are interactive
- [] elements provide context but cannot be interacted with
     )r   s    r   input_formatzCustomSystemPrompt.input_format   s    r   N)__name__
__module____qualname__strr   r   r   r   r   r   r      s    N N`c r   r   c                   z     e Zd Zddg ddfdedeee      deee      dee	   de
dee   f fd	Zdd
edefdZ xZS )CustomAgentMessagePromptNi  stateactionsresultinclude_attributesmax_error_length	step_infoc                 D    t         t        |   |||||       || _        y )N)r"   r$   r%   r&   r'   )superr!   __init__r#   )r   r"   r#   r$   r%   r&   r'   	__class__s          r   r*   z!CustomAgentMessagePrompt.__init__   s1     	&6U>DJ\HXAJ	 	7 	9 r   
use_visionr   c                    | j                   r2d| j                   j                   d| j                   j                   d}nd}t        j                         j                  d      }|d| z  }| j                  j                  j                  | j                        }| j                  j                  xs ddkD  }| j                  j                  xs ddkD  }|dk7  rI|rd	| j                  j                   d
| }nd| }|r| d| j                  j                   d}n| d}nd}d| d| j                   j                   d| j                   j                   d| j                   j                   d| j                  j                   d| j                  j                    d| d}| j"                  r>| j$                  r1|dz  }|d| j                   j                  dz
   d| j                   j                   dz  }t'        | j$                        D ]  \  }}	| j"                  |   }
|d|dz    dt)        | j$                         d|
j+                  d       dz  }|	j,                  sW|	j.                  r/|d|dz    dt)        | j$                         d|	j.                   dz  }|	j0                  s|	j0                  | j2                   d  }|d |dz    dt)        | j$                         d!| dz  } | j                  j4                  r2|dk(  r-t7        d"|d#d$d%d&| j                  j4                   id'g(      S t7        |(      S ))NzCurrent step: /
 z%Y-%m-%d %H:%MzCurrent date and time: )r%   r   z... z: pixels above - scroll or extract content to see more ...
z[Start of page]
z
... z9 pixels below - scroll or extract content to see more ...z
[End of page]z
empty pagez

1. Task: z. 
2. Hints(Optional): 
z
3. Memory: 
z
4. Current url: z
5. Available tabs:
z
6. Interactive elements:
z	
        z
 **Previous Actions** 
zPrevious step: r   z 
zPrevious action z: T)exclude_unsetzResult of previous action zError of previous action z: ...r   )typer   	image_urlurlzdata:image/png;base64,)r2   r3   )content)r'   step_number	max_stepsr   nowstrftimer"   element_treeclickable_elements_to_stringr%   pixels_abovepixels_belowtask	add_infosmemoryr4   tabsr#   r$   	enumeratelenmodel_dump_jsoninclude_in_memoryextracted_contenterrorr&   
screenshotr
   )r   r,   step_info_descriptiontime_strelements_texthas_content_abovehas_content_belowstate_descriptionir$   actionrG   s               r   get_user_messagez)CustomAgentMessagePrompt.get_user_message   s   >>&4T^^5O5O4PPQRVR`R`RjRjQkkm$n!$&!<<>**+;<#:8*!EE

//LL`d`w`wLx!ZZ449Q>!ZZ449Q>B 4::2233no|n}~  #4M? C $oVDJJ,C,C+DD}~  $1/ A(M!  

..

	       !   	 <<DKK!==?4>>3M3Ma3O2PPQRVR`R`RjRjQkkn!oo&t{{3 	6a!'7AwaDKK@P?QQSTZTjTjy}TjT~S  @B  &C  C!++//)/I!a%PQRUVZVaVaRbQcceflf~f~e  @B  .C  C)|| &d.C.C-C-D E)7AwaDKK@P?QQVW\V]]_`) ::  Z4%7#->? +&+/EdjjF[F[E\-]%^  $566r   )T)r   r   r   r	   r   r   r   r   listr   intr   r*   boolr
   rQ   __classcell__)r+   s   @r   r!   r!      s     4837,.$'7; d;/0 T,/0	
 !%S	 "   34"H74 H7< H7r   r!   )pdbtypingr   r   browser_use.agent.promptsr   r   browser_use.agent.viewsr   r   browser_use.browser.viewsr	   langchain_core.messagesr
   r   r   custom_viewsr   r   r!   r   r   r   <module>r]      s;    
 ! F = 2 ?  -g gTZ71 Z7r   