Skip to content

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

User interaction works

magmueller0af061b19829
diff --git a/src/actions/browser_actions.py b/src/actions/browser_actions.py
index 9e46c39ad..d83993d48 100644
--- a/src/actions/browser_actions.py
+++ b/src/actions/browser_actions.py
@@ -2,6 +2,10 @@ import time
import urllib.parse
from typing import Dict, Optional, Union
+import requests
+
+# MainContentExtractor
+from main_content_extractor import MainContentExtractor
from pydantic import BaseModel
from selenium import webdriver
from selenium.webdriver.common.by import By
@@ -11,10 +15,9 @@ from selenium.webdriver.support.ui import WebDriverWait
# Pydantic Models
class ActionParams(BaseModel):
- query: Optional[str] = None
+ text: Optional[str] = None
url: Optional[str] = None
id: Optional[int] = None
- text: Optional[str] = None
class Action(BaseModel):
@@ -30,6 +33,12 @@ class Action(BaseModel):
return True
+class ActionResult(BaseModel):
+ done: bool = False
+ extracted_content: str = ''
+ user_input: str = ''
+
+
class BrowserActions:
def __init__(self, driver: webdriver.Chrome):
self.driver = driver
@@ -47,10 +56,10 @@ class BrowserActions:
self.update_selector_map(selector_map)
# params = action.params.model_dump() if action.params else {}
-
+ output = ActionResult()
if action_name == 'search_google':
- if action.params and action.params.query:
- self.search_google(action.params.query)
+ if action.params and action.params.text:
+ self.search_google(action.params.text)
else:
raise Exception('Query is required for search_google action')
elif action_name == 'nothing':
@@ -63,8 +72,9 @@ class BrowserActions:
elif action_name == 'go_back':
self.go_back()
elif action_name == 'done':
- return True
- elif action_name == 'input':
+ output.done = True
+
+ elif action_name == 'text_input':
if action.params and action.params.id and action.params.text:
self.input_text_by_index(action.params.id, action.params.text)
else:
@@ -74,11 +84,28 @@ class BrowserActions:
self.click_element_by_index(action.params.id)
else:
raise Exception('Id is required for click action')
+ elif action_name == 'ask_user':
+ if action.params and action.params.text:
+ output.user_input = self.ask_user(action.params.text)
+ else:
+ raise Exception('Question is required for ask_user action')
+ elif action_name == 'send_user_text':
+ if action.params and action.params.text:
+ self.send_user_text(action.params.text)
+ else:
+ raise Exception('Text is required for send_user_text action')
+ elif action_name == 'extract_page_content':
+ output.extracted_content = self.extract_page_content()
# elif action_name == 'accept_cookies':
# self.driver.accept_cookies()
else:
raise Exception(f'Action {action_name} not found')
+ return output
+
+ def done(self):
+ return True
+
def click_element_by_index(self, index: int):
"""
Clicks an element using its index from the selector map with improved element finding strategies.
@@ -145,29 +172,31 @@ class BrowserActions:
raise Exception(f'Failed to click element with index {index}, xpath: {xpath}')
def input_text_by_index(self, index: int, text: str):
- """
- Inputs text into a field using its index from the selector map.
- """
if int(index) not in self.selector_map:
raise Exception(f'Element index {index} not found in selector map')
xpath = self.selector_map[int(index)]
try:
- # First try: Direct XPath
- element = self.wait.until(EC.presence_of_element_located((By.XPATH, xpath)))
- except:
- try:
- # Second try: Simplified XPath
- clean_xpath = xpath.replace('[document]/', '')
- if not clean_xpath.startswith('//'):
- clean_xpath = '//' + clean_xpath
- element = self.wait.until(EC.presence_of_element_located((By.XPATH, clean_xpath)))
- except:
- raise Exception(f'Failed to find input element with index {index}, xpath: {xpath}')
-
- element.clear()
- element.send_keys(text)
+ # Wait for element to be both present and interactable
+ element = self.wait.until(EC.element_to_be_clickable((By.XPATH, xpath)))
+
+ # Scroll element into view
+ self.driver.execute_script(
+ "arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});", element
+ )
+ time.sleep(0.5) # Wait for scroll
+
+ # Try to clear using JavaScript first
+ self.driver.execute_script("arguments[0].value = '';", element)
+
+ # Then send keys
+ element.send_keys(text)
+
+ except Exception as e:
+ raise Exception(
+ f'Failed to input text into element with index {index}, xpath: {xpath}. Error: {str(e)}'
+ )
# default actions
def search_google(self, query: str):
@@ -193,14 +222,47 @@ class BrowserActions:
"""
self.driver.back()
+ def extract_page_content(self):
+ """
+ Extracts the page content.
+ """
+ try:
+ response = requests.get(self.driver.current_url)
+ response.encoding = 'utf-8'
+ content = response.text
+ extracted_markdown = MainContentExtractor.extract(content, output_format='markdown')
+ return extracted_markdown
+ except Exception as e:
+ print(f'Error getting main content: {e}')
+ return ''
+
+ def ask_user(self, question: str):
+ """
+ Talks to the user.
+ """
+ print(question)
+ print('--------------------------------\nInput: \n ')
+ user_input = input()
+ return user_input
+
+ def send_user_text(self, text: str):
+ """
+ Sends text to the user.
+ """
+ print(text)
+ print('--------------------------------')
+
def get_default_actions(self) -> dict[str, str]:
return {
- 'search_google': 'query: string',
+ 'search_google': 'text: string',
'go_to_url': 'url: string',
'done': '',
'go_back': '',
'click': 'id: int',
- 'input': 'id: int, text: string',
+ 'text_input': 'id: int, text: string',
'nothing': '',
+ 'extract_page_content': '',
+ 'ask_user': 'text: string',
+ 'send_user_text': 'text: string',
}
# 'accept_cookies': '',
diff --git a/src/agent_interface/planing_agent.py b/src/agent_interface/planing_agent.py
index b58cd0eac..b8647ab91 100644
--- a/src/agent_interface/planing_agent.py
+++ b/src/agent_interface/planing_agent.py
@@ -3,6 +3,7 @@ from tokencost import calculate_prompt_cost, count_string_tokens
from src.actions.browser_actions import Action
from src.llm.service import LLM, AvailableModel
+from src.state_manager.utils import save_conversation
class PlaningAgent:
@@ -16,7 +17,9 @@ class PlaningAgent:
self.messages_all = []
self.messages = []
- async def chat(self, task: str, skip_call: bool = False) -> Action:
+ async def chat(
+ self, task: str, skip_call: bool = False, store_conversation: str = ''
+ ) -> Action:
# TODO: include state, actions, etc.
# select next functions to call
@@ -42,7 +45,10 @@ class PlaningAgent:
response = await self.llm.create_chat_completion(input_messages, Action)
- self.messages.append({'role': 'user', 'content': '... execute action ...'})
+ # self.messages.append({'role': 'user', 'content': '... execute action ...'})
+ if store_conversation:
+ # save conversation
+ save_conversation(input_messages, response.model_dump_json(), store_conversation)
# Only append the output message
self.messages.append({'role': 'assistant', 'content': response.model_dump_json()})
@@ -53,6 +59,9 @@ class PlaningAgent:
return response
+ def update_system_prompt(self, user_input: str):
+ self.system_prompt.append({'role': 'user', 'content': user_input})
+
def get_system_prompt(self, task: str, default_actions: str) -> str:
"""
Get the system prompt for the agent.
@@ -70,32 +79,34 @@ class PlaningAgent:
"""
AGENT_PROMPT = f"""
- You are an AI agent that helps users navigate websites and perform actions. Your task is: {task}
+ You are an AI agent that helps users interact with websites.
- Available actions:
- {default_actions}
+ Your input are all the interactive elements of the current page from which you can choose which to click or input. They will be provided like this:
+ 0:Chat-Fenster
+ 1:Skip to Main Content.
+ 2:<a href="https://www.example.de/"></a>
+ 3:<button>Book now</button>
+ 4:<div>Book now</div>
+ 26:<span>Other interactive elements</span>
- Input:
- The page content will be provided as numbered elements like this:
- 0:<button>Click me</button>
- 1:<a href="/test">Link text</a>
- 2:Some visible text content
-
Additional you get a list of previous actions and their results.
- To interact with elements, use their index number in the click() or input() actions. Make 100% sure that the index is ALWAYS present if you use the click() or input() actions.
- Each element has a unique index that can be used to interact with it.
-
- Provide your next action based on the available actions and visible elements.
+ Available actions:
+ {default_actions}
+
+ To interact with elements, use their index number in the click() or text_input() actions.
+
+ If you need more than the interactive elements from the page you can use the extract_content action.
+
Validate if the previous goal is achieved, if not, try to achieve it with the next action.
If you get stuck, try to find a new element that can help you achieve your goal or if persistent, go back or reload the page.
- Respond with a valid JSON object containing the action and any required parameters and your current goal of this action.
+ Respond with a valid JSON object containing the action, any required parameters and your current goal of this action.
+ You can send_user_text or ask_user for clarification if you are completely stuck.
Response format:
{output_format}
"""
-
return AGENT_PROMPT
# Remember:
diff --git a/src/state_manager/utils.py b/src/state_manager/utils.py
index 9ad5cb1da..c8f0ac842 100644
--- a/src/state_manager/utils.py
+++ b/src/state_manager/utils.py
@@ -1,6 +1,7 @@
-from bs4 import BeautifulSoup
import os
+from bs4 import BeautifulSoup
+
def save_formatted_html(html_content, output_file_name):
"""
@@ -23,6 +24,15 @@ def save_formatted_html(html_content, output_file_name):
f.write(formatted_html)
+def save_conversation(input_messages, model_output, output_file_name):
+ if not os.path.exists('temp'):
+ os.makedirs('temp')
+ with open('temp/' + output_file_name, 'w', encoding='utf-8') as f:
+ for message in input_messages:
+ f.write(f'{message["role"]}: {message["content"]}\n')
+ f.write(f'\n\nModel output:\n{model_output}')
+
+
def save_markdown(markdown_content, output_file_name):
"""Save markdown content to a file"""
if not os.path.exists('temp'):
diff --git a/src/tests/test_kayak_search.py b/src/tests/test_kayak_search.py
index 866654138..ae36e2618 100644
--- a/src/tests/test_kayak_search.py
+++ b/src/tests/test_kayak_search.py
@@ -2,7 +2,7 @@ import time
import pytest
-from src.actions.browser_actions import BrowserActions
+from src.actions.browser_actions import ActionResult, BrowserActions
from src.agent_interface.planing_agent import PlaningAgent
from src.driver.service import DriverService
from src.state_manager.state import StateManager
@@ -26,34 +26,47 @@ async def test_kayak_flight_search(setup):
print('🚀 Starting flight search task')
print('=' * 50)
- task = (
- ' find a flight from Zürich to Bali on 2024-11-25 with return on 2024-12-09 for 2 people.'
- )
+ task = ' find a flight from Zürich to (ask the user for the destination) on 2024-11-25 with return on 2024-12-09 for 2 people.'
default_actions = actions.get_default_actions()
agent = PlaningAgent(task, str(default_actions), 'gpt-4o')
- url_history = []
+ agent.update_system_prompt(f'Your task is: {task}')
+ url_history = []
+ extracted_content = ''
+ user_input = ''
max_steps = 50
for i in range(max_steps):
print(f'\n📍 Step {i+1}')
current_state = state_manager.get_current_state()
save_formatted_html(current_state.interactable_elements, f'current_state_{i}.html')
- # print(f'Current state map: {current_state.selector_map}')
- # save_markdown(current_state["main_content"], f"current_state_{i}.md")
- # Get next action from agent
+
url_history.append(driver.current_url)
+
state_text = f'Elements: {current_state.interactable_elements}, Url history: {url_history}'
+ if extracted_content:
+ state_text += f', Extracted content: {extracted_content}'
+ if user_input:
+ state_text += f', User input: {user_input}'
- action = await agent.chat(state_text, skip_call=False)
- out = actions.execute_action(action, current_state.selector_map)
+ action = await agent.chat(
+ state_text, skip_call=False, store_conversation=f'conversation_{i}.txt'
+ )
+ output: ActionResult = actions.execute_action(action, current_state.selector_map)
- if out:
+ # check if output is exactly True (boolean)
+ if output.done:
print('\n' + '=' * 50)
print('✅ Task completed successfully!')
print('=' * 50)
break
+ if output.extracted_content:
+ extracted_content = output.extracted_content
+ if output.user_input:
+ # update system prompt
+ agent.update_system_prompt(output.user_input)
+ user_input = output.user_input
time.sleep(0.5)
else: