Skip to content

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

work in progress

Gregor Žuničc01317b31ce1
diff --git a/README.md b/README.md
index 422e37415..3279bbc77 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,20 @@
-# Interfaces for agents
+# Website Use
-This repository contains the interfaces for agents.
+This repository contains an agent that can plan and execute actions on a website with or without a vision model.
+
+# Installation
+
+```bash
+pip install website-use
+```
+
+# Supported models
+
+- GPT-4o
+- GPT-4o Mini
+- Claude 3.5 Sonnet
+
+<!-- We plan to add more models in the future (LLama 3). -->
# Codebase Structure
@@ -54,8 +68,6 @@ Single file; if too long → split into multiple files (one prompt per file or s
Never split into more than one file
-
-
## Requirements
```bash
@@ -63,5 +75,5 @@ uv pip install -r requirements.txt
```
```bash
-uv pipreqs --ignore .venv --force
+uv pipreqs --ignore .venv --force
```
diff --git a/requirements.txt b/requirements.txt
index 4966d4bdf..548b57f13 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,22 +1,16 @@
-beautifulsoup4==4.12.3
-litellm==1.51.3
-pydantic==2.9.2
-pytest==8.3.3
-python-dotenv==1.0.1
-Requests==2.32.3
+MainContentExtractor==0.0.4
Screenshot==1.0.0
-selenium==4.26.1
-tokencost==0.1.16
-webdriver_manager==4.0.2
+Selenium-Screenshot==2.1.0
+beautifulsoup4==4.12.3
+langchain==0.3.7
+# langchain-core==0.3.15
+langchain-openai==0.2.5
litellm==1.51.3
pydantic==2.9.2
pytest==8.3.3
+pytest-asyncio==0.24.0
python-dotenv==1.0.1
requests==2.32.3
-Screenshot==1.0.0
selenium==4.26.1
tokencost==0.1.16
-webdriver-manager==4.0.2
-MainContentExtractor==0.0.4
-Selenium-Screenshot==2.1.0
-pytest-asyncio==0.24.0
+webdriver-manager==4.0.2
\ No newline at end of file
diff --git a/src/__init__.py b/src/__init__.py
index e69de29bb..6a9e10885 100644
--- a/src/__init__.py
+++ b/src/__init__.py
@@ -0,0 +1,4 @@
+from src.planning.service import PlaningService as PlanningAgent
+from src.agent.service import AgentService as WebAgent
+
+__all__ = ['PlanningAgent', 'WebAgent']
diff --git a/src/actions/action_validator.py b/src/actions/action_validator.py
deleted file mode 100644
index 32d313e06..000000000
--- a/src/actions/action_validator.py
+++ /dev/null
@@ -1,36 +0,0 @@
-from selenium import webdriver
-from selenium.common.exceptions import TimeoutException, WebDriverException
-
-
-class ActionValidator:
- def __init__(self, driver: webdriver.Chrome):
- self.driver = driver
-
- def is_action_successful(self, action: dict) -> bool:
- """
- Checks if the action was executed successfully.
-
- Args:
- action (dict): The action that was attempted
-
- Returns:
- bool: True if action was successful, False otherwise
- """
- try:
- return True
-
- except (TimeoutException, WebDriverException):
- return False
-
- def check_ambiguity(self, action: dict) -> bool:
- """
- Determines if the action is ambiguous and requires clarification.
-
- Args:
- action (dict): The action to check for ambiguity
-
- Returns:
- bool: True if action is ambiguous, False otherwise
- """
- # Implementation will use LLM to check for ambiguity
- return False
diff --git a/src/actions/browser_actions.py b/src/actions/browser_actions.py
deleted file mode 100644
index 3c5f40c29..000000000
--- a/src/actions/browser_actions.py
+++ /dev/null
@@ -1,276 +0,0 @@
-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
-from selenium.webdriver.support import expected_conditions as EC
-from selenium.webdriver.support.ui import WebDriverWait
-
-
-# Pydantic Models
-class ActionParams(BaseModel):
- text: Optional[str] = None
- url: Optional[str] = None
- id: Optional[int] = None
-
-
-class Action(BaseModel):
- valuation_previous_goal: str
- goal: str
- action: str
- params: Optional[ActionParams] = None
-
- @property
- def is_valid(self) -> bool:
- if self.action == 'click':
- return self.params is not None and self.params.id is not None
- return True
-
-
-class ActionResult(BaseModel):
- done: bool = False
- extracted_content: str = ''
- user_input: str = ''
- error: Optional[str] = None
-
-
-class BrowserActions:
- def __init__(self, driver: webdriver.Chrome):
- self.driver = driver
- self.wait = WebDriverWait(driver, 10)
- self.selector_map: Dict[int, str] = {}
-
- def update_selector_map(self, selector_map: Dict[int, str]):
- """Update the current selector map"""
- self.selector_map = selector_map
-
- def execute_action(self, action: Action, selector_map: Dict[int, str]):
- # print(action.model_dump().keys())
- print(action.model_dump_json(indent=4))
- action_name = action.action
- self.update_selector_map(selector_map)
-
- # params = action.params.model_dump() if action.params else {}
- output = ActionResult()
- try:
- if action_name == 'search_google':
- 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':
- pass
- elif action_name == 'go_to_url':
- if action.params and action.params.url:
- self.go_to_url(action.params.url)
- else:
- raise Exception('Url is required for go_to_url action')
- elif action_name == 'go_back':
- self.go_back()
- elif action_name == 'done':
- 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:
- raise Exception('Id and text are required for input action')
- elif action_name == 'click':
- if action.params and (action.params.id or action.params.id == 0):
- 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')
-
- except Exception as e:
- output.error = str(e)
-
- return output
-
- def done(self):
- print('\n' + '=' * 50)
- print('✅ Task completed successfully!')
- print('=' * 50)
- 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.
- """
- if int(index) not in self.selector_map:
- print(f'Selector map: {self.selector_map}')
- raise Exception(f'Element index {index} not found in selector map')
-
- xpath = self.selector_map[int(index)]
- # print(f'Trying to click element with xpath: {xpath}')
-
- # Wait for any overlays/popups to disappear
- time.sleep(0.5) # Brief wait for page to stabilize
-
- try:
- # Try multiple strategies to find the element
- for strategy in [
- lambda: self.wait.until(EC.element_to_be_clickable((By.XPATH, xpath))),
- lambda: self.wait.until(EC.presence_of_element_located((By.XPATH, xpath))),
- lambda: self.driver.find_element(By.XPATH, xpath),
- # Try with simplified XPath
- lambda: self.wait.until(
- EC.element_to_be_clickable(
- (
- By.XPATH,
- f"//*[@id='{xpath.split('id=')[-1].split(']')[0]}']"
- if 'id=' in xpath
- else xpath,
- )
- )
- ),
- # Try finding by any visible matching element
- lambda: next(
- elem
- for elem in self.driver.find_elements(
- By.XPATH, "//*[not(ancestor-or-self::*[@style='display: none'])]"
- )
- if elem.is_displayed() and elem.is_enabled()
- ),
- ]:
- try:
- element = strategy()
- if element and element.is_displayed() and element.is_enabled():
- # Scroll into view with JavaScript
- self.driver.execute_script(
- "arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});",
- element,
- )
- time.sleep(0.5) # Wait for scroll to complete
-
- # Try both JavaScript click and regular click
- try:
- self.driver.execute_script('arguments[0].click();', element)
- except:
- element.click()
- return
- except:
- continue
-
- raise Exception(f'Could not find clickable element with xpath: {xpath}')
-
- except Exception as e:
- print(f'Failed to click element. Error: {str(e)}')
- raise Exception(f'Failed to click element with index {index}, xpath: {xpath}')
-
- def input_text_by_index(self, index: int, text: str):
- 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:
- # 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):
- """
- Performs a Google search with the provided query using direct URL.
- """
- # Encode the query for URL
-
- encoded_query = urllib.parse.quote(query)
-
- search_url = f'https://www.google.com/search?q={encoded_query}'
- self.driver.get(search_url)
-
- def go_to_url(self, url: str):
- """
- Navigates the browser to the specified URL.
- """
- self.driver.get(url)
-
- def go_back(self):
- """
- Navigates back in the browser history.
- """
- 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': 'text: string',
- 'go_to_url': 'url: string',
- 'done': '',
- 'go_back': '',
- 'click': 'id: int',
- '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/service.py b/src/agent/service.py
new file mode 100644
index 000000000..b34de5df8
--- /dev/null
+++ b/src/agent/service.py
@@ -0,0 +1,63 @@
+from src.agent.views import AgentActionResult, AgentActions, AgentPageState
+from src.browser.service import BrowserService
+
+
+class AgentService:
+ """
+ Agent service that interacts with the browser.
+
+ Right now this is just a LLM friendly wrapper around the browser service.
+ In the future we can add the functionality that this is a self-contained agent that can plan and act single steps.
+
+ TODO: easy hanging fruit: pass in a list of actions, compare html that changed and self assess if goal is done -> makes clicking MUCH MUCH faster and cheaper.
+
+ TODO#2: from the state generate functions that can be passed directly into the LLM as function calls. Then it could actually in the same call request for example multiple actions and new state.
+ """
+
+ def __init__(self):
+ self.browser = BrowserService()
+
+ def get_current_state(self, screenshot: bool = False) -> AgentPageState:
+ browser_state = self.browser.get_updated_state()
+ screenshot_b64 = None
+ if screenshot:
+ screenshot_b64 = self.browser.take_screenshot()
+
+ return AgentPageState(
+ items=browser_state.items,
+ url=browser_state.url,
+ title=browser_state.title,
+ selector_map=browser_state.selector_map,
+ screenshot=screenshot_b64,
+ )
+
+ def act(self, action: AgentActions) -> AgentActionResult:
+ try:
+ if action.search_google:
+ self.browser.search_google(action.search_google.query)
+ elif action.go_to_url:
+ self.browser.go_to_url(action.go_to_url.url)
+ elif action.nothing:
+ # self.browser.nothing()
+ # TODO: implement
+ pass
+ elif action.go_back:
+ self.browser.go_back()
+ elif action.done:
+ # TODO: implement
+ # self.browser.done()
+ pass
+ elif action.click_element:
+ self.browser.click_element_by_index(action.click_element.id)
+ elif action.input_text:
+ self.browser.input_text_by_index(action.input_text.id, action.input_text.text)
+ elif action.extract_page_content:
+ content = self.browser.extract_page_content()
+ return AgentActionResult(done=True, extracted_content=content)
+ else:
+ return AgentActionResult(done=False)
+
+ return AgentActionResult(done=True)
+
+ except Exception as e:
+ return AgentActionResult(done=False, error=str(e))
diff --git a/src/agent/views.py b/src/agent/views.py
new file mode 100644
index 000000000..35dd015f4
--- /dev/null
+++ b/src/agent/views.py
@@ -0,0 +1,47 @@
+from typing import Literal, Optional
+
+from pydantic import BaseModel
+
+from src.browser.views import BrowserState
+
+
+class SearchGoogleAgentAction(BaseModel):
+ query: str
+
+
+class GoToUrlAgentAction(BaseModel):
+ url: str
+
+
+class ClickElementAgentAction(BaseModel):
+ id: int
+
+
+class InputTextAgentAction(BaseModel):
+ id: int
+ text: str
+
+
+class AgentActions(BaseModel):
+ """
+ Agent actions you can use to interact with the agent.
+ """
+
+ search_google: Optional[SearchGoogleAgentAction] = None
+ go_to_url: Optional[GoToUrlAgentAction] = None
+ nothing: Optional[Literal[True]] = None
+ go_back: Optional[Literal[True]] = None
+ done: Optional[Literal[True]] = None
+ click_element: Optional[ClickElementAgentAction] = None
+ input_text: Optional[InputTextAgentAction] = None
+ extract_page_content: Optional[Literal[True]] = None
+
+
+class AgentActionResult(BaseModel):
+ done: bool
+ extracted_content: Optional[str] = None
+ error: Optional[str] = None
+
+
+class AgentPageState(BrowserState):
+ screenshot: Optional[str] = None
diff --git a/src/agent_interface/planing_agent.py b/src/agent_interface/planing_agent.py
deleted file mode 100644
index 8be71572e..000000000
--- a/src/agent_interface/planing_agent.py
+++ /dev/null
@@ -1,144 +0,0 @@
-import decimal
-
-from dotenv import load_dotenv
-from tokencost import calculate_all_costs_and_tokens
-
-from src.actions.browser_actions import Action
-from src.llm.service import LLM, AvailableModel
-from src.state_manager.utils import encode_image, save_conversation
-
-
-class PlaningAgent:
- def __init__(self, task: str, default_actions: str, model: AvailableModel):
- load_dotenv()
- self.model = model
- self.llm = LLM(model=self.model)
- self.system_prompt = [
- {'role': 'system', 'content': self.get_system_prompt(task, default_actions)}
- ]
- self.messages_all = []
- self.messages = []
-
- async def chat(self, task: str, store_conversation: str = '', images: str = '') -> Action:
- # TODO: include state, actions, etc.
-
- # select next functions to call
- if images:
- # Format message for vision model
- combined_input = [
- {'type': 'text', 'text': task},
- {
- 'type': 'image_url',
- 'image_url': {
- 'url': f'data:image/png;base64,{encode_image(images)}',
- },
- },
- ]
- else:
- combined_input = [{'type': 'text', 'text': task}]
- input_messages = (
- self.system_prompt + self.messages + [{'role': 'user', 'content': combined_input}]
- )
-
- response = await self.llm.create_chat_completion(input_messages, 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()})
-
- try:
- # Calculate total cost for all messages
-
- # check if multiple input
-
- # can not handly list of content
- output = calculate_all_costs_and_tokens(
- self.system_prompt + self.messages + [{'role': 'user', 'content': task}],
- response.model_dump_json(),
- self.model,
- )
- if images:
- # resolution 1512 x 767
- image_cost = 0.000213
- total_cost = (
- output['prompt_cost']
- + output['completion_cost']
- + decimal.Decimal(str(image_cost))
- )
- print(
- f'Text ${output["prompt_cost"]:,.4f} + Image ${image_cost:,.4f} = ${total_cost:,.4f} for {output["prompt_tokens"] + output["completion_tokens"]} tokens'
- )
- else:
- total_cost = output['prompt_cost'] + output['completion_cost']
- print(
- f'Total cost: ${total_cost:,.4f} for {output["prompt_tokens"] + output["completion_tokens"]} tokens'
- )
-
- except Exception as e:
- print(f'Error calculating prompt cost: {e}')
-
- # keep newest 20 messages
- if len(self.messages) > 20:
- self.messages = self.messages[-20:]
-
- 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.
-
- Args:
- task: The task description
- default_actions: Available default actions
-
- Returns:
- str: Formatted system prompt
- """
- # System prompts for the agent
- output_format = """
- {"action": "action_name", "params": {"param_name": "param_value"}, "goal": "short description what you want to achieve", "valuation_previous_goal": "Success if completed, else short sentence of why not successful."}
- """
-
- AGENT_PROMPT = f"""
- You are an AI agent that helps users interact with websites.
-
- Your input are all the interactive elements of the current page from which you can choose which to click or input.
-
- This is how an input looks like:
- 1:Interactive element
- 3: <a href="https://www.example.de/"></a>
- 9:<div>Interactive element</div>
-
- Additional you get a list of previous actions and their results.
-
- Available actions:
- {default_actions}
-
- In the beginning the list will be empty so you have to do google search or go to url.
- To interact with elements, use their index number in the click() or text_input() actions. Make sure the index exists in the list of interactive elements.
- 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, 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.
-
- Make sure after filling a field if you need to click a suggestion or if the field is already filled.
-
- Response format:
- {output_format}
-
- """
- return AGENT_PROMPT
-
- # Remember:
- # 1. Always check if elements exist before trying to interact with them
- # 2. Use the exact index numbers shown in the elements list
- # 3. If you need to accept cookies, use the accept_cookies action first
- # 4. If you can't find what you're looking for, consider scrolling or navigating to a different page
diff --git a/src/agent_interface/prompts.py b/src/agent_interface/prompts.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/src/browser/service.py b/src/browser/service.py
new file mode 100644
index 000000000..b405288e0
--- /dev/null
+++ b/src/browser/service.py
@@ -0,0 +1,279 @@
+"""
+Selenium browser on steroids.
+"""
+
+import base64
+import os
+import tempfile
+from typing import Literal
+
+from main_content_extractor import MainContentExtractor
+from Screenshot import Screenshot
+from selenium import webdriver
+from selenium.webdriver.chrome.options import Options
+from selenium.webdriver.chrome.service import Service
+from selenium.webdriver.common.action_chains import ActionChains
+from selenium.webdriver.common.by import By
+from selenium.webdriver.support import expected_conditions as EC
+from selenium.webdriver.support.ui import WebDriverWait
+from webdriver_manager.chrome import ChromeDriverManager
+
+from src.browser.views import BrowserException, BrowserState
+from src.dom.service import DomService
+
+
+class BrowserService:
+ def __init__(self, headless: bool = False):
+ self.headless = headless
+ self.driver: webdriver.Chrome | None = None
+ self._ob = Screenshot.Screenshot()
+
+ def init(self) -> webdriver.Chrome:
+ """
+ Sets up and returns a Selenium WebDriver instance with anti-detection measures.
+
+ Returns:
+ webdriver.Chrome: Configured Chrome WebDriver instance
+ """
+ chrome_options = Options()
+ if self.headless:
+ chrome_options.add_argument('--headless')
+
+ # Anti-detection measures
+ chrome_options.add_argument('--disable-blink-features=AutomationControlled')
+ chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
+ chrome_options.add_experimental_option('useAutomationExtension', False)
+
+ # Additional stealth settings
+ chrome_options.add_argument('--start-maximized')
+ chrome_options.add_argument('--disable-extensions')
+ chrome_options.add_argument('--no-sandbox')
+ chrome_options.add_argument('--disable-infobars')
+
+ # Initialize the Chrome driver
+ driver = webdriver.Chrome(
+ service=Service(ChromeDriverManager().install()), options=chrome_options
+ )
+
+ # Execute stealth scripts
+ driver.execute_cdp_cmd(
+ 'Page.addScriptToEvaluateOnNewDocument',
+ {
+ 'source': """
+ Object.defineProperty(navigator, 'webdriver', {
+ get: () => undefined
+ });
+
+ Object.defineProperty(navigator, 'languages', {
+ get: () => ['en-US', 'en']
+ });
+
+ Object.defineProperty(navigator, 'plugins', {
+ get: () => [1, 2, 3, 4, 5]
+ });
+
+ window.chrome = {
+ runtime: {}
+ };
+
+ Object.defineProperty(navigator, 'permissions', {
+ get: () => ({
+ query: Promise.resolve.bind(Promise)
+ })
+ });
+ """
+ },
+ )
+
+ self.driver = driver
+ return driver
+
+ def _get_driver(self) -> webdriver.Chrome:
+ if self.driver is None:
+ raise BrowserException('Driver not initialized. Call `init()` first.')
+ return self.driver
+
+ def get_updated_state(self) -> BrowserState:
+ """
+ Update and return state.
+ """
+ driver = self._get_driver()
+ dom_service = DomService(driver)
+ content = dom_service.get_clickable_elements()
+ self.current_state = BrowserState(
+ items=content.items,
+ selector_map=content.selector_map,
+ url=driver.current_url,
+ title=driver.title,
+ )
+ return self.current_state
+
+ def close(self):
+ driver = self._get_driver()
+ driver.quit()
+ self.driver = None
+
+ # region - Browser Actions
+
+ def search_google(self, query: str):
+ """
+ @dev TODO: add serp api call here
+ """
+ driver = self._get_driver()
+ driver.get(f'https://www.google.com/search?q={query}')
+
+ def go_to_url(self, url: str):
+ driver = self._get_driver()
+ driver.get(url)
+
+ def go_back(self):
+ driver = self._get_driver()
+ driver.back()
+
+ def refresh(self):
+ driver = self._get_driver()
+ driver.refresh()
+
+ def extract_page_content(self, value: Literal['text', 'markdown'] = 'markdown') -> str:
+ """
+ TODO: switch to a better parser/extractor
+ """
+ driver = self._get_driver()
+ content = MainContentExtractor.extract(driver.page_source, output_format=value) # type: ignore TODO
+ return content
+
+ def take_screenshot(self, full_page: bool = False) -> str:
+ """
+ Returns a base64 encoded screenshot of the current page.
+ """
+ driver = self._get_driver()
+ if full_page:
+ # Create temp directory
+ temp_dir = tempfile.mkdtemp()
+ screenshot = self._ob.full_screenshot(
+ driver,
+ save_path=temp_dir,
+ image_name='temp.png',
+ is_load_at_runtime=True,
+ load_wait_time=1,
+ )
+
+ # Read file as base64
+ with open(os.path.join(temp_dir, 'temp.png'), 'rb') as img:
+ screenshot = base64.b64encode(img.read()).decode('utf-8')
+
+ # Cleanup temp directory
+ os.remove(os.path.join(temp_dir, 'temp.png'))
+ os.rmdir(temp_dir)
+ else:
+ screenshot = driver.get_screenshot_as_base64()
+ return screenshot
+
+ # endregion
+
+ # region - User Actions
+ def _webdriver_wait(self):
+ driver = self._get_driver()
+ return WebDriverWait(driver, 10)
+
+ def _input_text_by_xpath(self, xpath: str, text: str):
+ driver = self._get_driver()
+
+ try:
+ # Wait for element to be both present and interactable
+ element = self._webdriver_wait().until(EC.element_to_be_clickable((By.XPATH, xpath)))
+
+ # Scroll element into view using ActionChains for smoother scrolling
+ actions = ActionChains(driver)
+ actions.move_to_element(element).perform()
+
+ # Try to clear using JavaScript first
+ 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 xpath: {xpath}. Error: {str(e)}'
+ )
+
+ def input_text_by_index(self, index: int, text: str):
+ state = self.get_updated_state()
+
+ if index not in state.selector_map:
+ raise Exception(f'Element index {index} not found in selector map')
+
+ xpath = state.selector_map[index]
+ self._input_text_by_xpath(xpath, text)
+
+ def _click_element_by_xpath(self, xpath: str):
+ """
+ Internal method to click an element using its xpath with improved element finding strategies.
+ """
+ driver = self._get_driver()
+ wait = self._webdriver_wait()
+
+ # Wait for any overlays/popups to disappear
+ # time.sleep(0.5) # Brief wait for page to stabilize
+
+ try:
+ # Try multiple strategies to find the element
+ for strategy in [
+ lambda: wait.until(EC.element_to_be_clickable((By.XPATH, xpath))),
+ lambda: wait.until(EC.presence_of_element_located((By.XPATH, xpath))),
+ lambda: driver.find_element(By.XPATH, xpath),
+ # Try with simplified XPath
+ lambda: wait.until(
+ EC.element_to_be_clickable(
+ (
+ By.XPATH,
+ f"//*[@id='{xpath.split('id=')[-1].split(']')[0]}']"
+ if 'id=' in xpath
+ else xpath,
+ )
+ )
+ ),
+ # Try finding by any visible matching element
+ lambda: next(
+ elem
+ for elem in driver.find_elements(
+ By.XPATH, "//*[not(ancestor-or-self::*[@style='display: none'])]"
+ )
+ if elem.is_displayed() and elem.is_enabled()
+ ),
+ ]:
+ try:
+ element = strategy()
+ if element and element.is_displayed() and element.is_enabled():
+ # Scroll element into view using ActionChains for smoother scrolling
+ actions = ActionChains(driver)
+ actions.move_to_element(element).perform()
+
+ # Try both JavaScript click and regular click
+ try:
+ driver.execute_script('arguments[0].click();', element)
+ except Exception:
+ element.click()
+ return
+ except Exception:
+ continue
+
+ raise Exception(f'Could not find clickable element with xpath: {xpath}')
+
+ except Exception as e:
+ raise Exception(f'Failed to click element with xpath: {xpath}. Error: {str(e)}')
+
+ def click_element_by_index(self, index: int):
+ """
+ Clicks an element using its index from the selector map.
+ """
+ state = self.get_updated_state()
+
+ if index not in state.selector_map:
+ raise Exception(f'Element index {index} not found in selector map')
+
+ xpath = state.selector_map[index]
+ self._click_element_by_xpath(xpath)
+
+ # endregion
diff --git a/src/browser/tests/screenshot_test.py b/src/browser/tests/screenshot_test.py
new file mode 100644
index 000000000..875a0fe5c
--- /dev/null
+++ b/src/browser/tests/screenshot_test.py
@@ -0,0 +1,32 @@
+import base64
+import pytest
+
+from src.browser.service import BrowserService
+
+
+def browser():
+ browser_service = BrowserService(headless=True)
+ browser_service.init()
+ yield browser_service
+ browser_service.close()
+
+
[email protected](reason='takes too long')
+def test_take_full_page_screenshot(browser):
+ # Go to a test page
+ browser.go_to_url('https://example.com')
+
+ # Take full page screenshot
+ screenshot_b64 = browser.take_screenshot(full_page=True)
+
+ # Verify screenshot is not empty and is valid base64
+ assert screenshot_b64 is not None
+ assert isinstance(screenshot_b64, str)
+ assert len(screenshot_b64) > 0
+
+ # Test we can decode the base64 string
+ try:
+ base64.b64decode(screenshot_b64)
+ except Exception as e:
+ pytest.fail(f'Failed to decode base64 screenshot: {str(e)}')
diff --git a/src/browser/views.py b/src/browser/views.py
new file mode 100644
index 000000000..f14593fea
--- /dev/null
+++ b/src/browser/views.py
@@ -0,0 +1,12 @@
+from src.dom.views import ProcessedDomContent
+
+
+# Exceptions
+class BrowserException(Exception):
+ pass
+
+
+# Pydantic
+class BrowserState(ProcessedDomContent):
+ url: str
+ title: str
diff --git a/src/dom/service.py b/src/dom/service.py
index 11bd08cab..31f3f8780 100644
--- a/src/dom/service.py
+++ b/src/dom/service.py
@@ -1,22 +1,15 @@
-"""
-Dom Service
-"""
-
from bs4 import BeautifulSoup, NavigableString, PageElement, Tag
-from pydantic import BaseModel
-from selenium import webdriver
+from selenium import webdriver
-class ProcessedDomContent(BaseModel):
- output_string: str
- selector_map: dict[int, str]
+from src.dom.views import DomContentItem, ProcessedDomContent
class DomService:
def __init__(self, driver: webdriver.Chrome):
self.driver = driver
- def get_current_state(self) -> ProcessedDomContent:
+ def get_clickable_elements(self) -> ProcessedDomContent:
html_content = self.driver.page_source
return self._process_content(html_content)
@@ -27,6 +20,8 @@ class DomService:
html_content: Raw HTML string to process
Returns:
ProcessedDomContent: Processed DOM content
+
+ @dev TODO: instead of of using enumerated index, use random 4 digit numbers -> a bit more tokens BUT updates on the screen wont click on incorrect items -> tricky because you have to consider that same elements need to have the same index ...
"""
soup = BeautifulSoup(html_content, 'html.parser')
candidate_elements: list[Tag | NavigableString] = []
@@ -88,7 +83,7 @@ class DomService:
# Process candidates
selector_map: dict[int, str] = {}
- output_string = ''
+ output_items: list[DomContentItem] = []
for index, element in enumerate(candidate_elements):
xpath = xpath_cache.get(element)
@@ -105,7 +100,7 @@ class DomService:
if isinstance(element, NavigableString):
text_content = element.strip()
if text_content:
- output_string += f'{index}:{text_content}\n'
+ output_items.append(DomContentItem(index=index, text=text_content))
else:
text_content = self._extract_text_from_all_children(element)
@@ -115,11 +110,13 @@ class DomService:
opening_tag = f"<{tag_name}{' ' + attributes if attributes else ''}>"
closing_tag = f'</{tag_name}>'
- output_string += f'{index}:{opening_tag}{text_content}{closing_tag}\n'
+ output_items.append(
+ DomContentItem(index=index, text=f'{opening_tag}{text_content}{closing_tag}')
+ )
selector_map[index] = xpath
- return ProcessedDomContent(output_string=output_string, selector_map=selector_map)
+ return ProcessedDomContent(items=output_items, selector_map=selector_map)
def _extract_text_from_all_children(self, element: Tag) -> str:
# Tell BeautifulSoup that button tags can contain content
diff --git a/src/dom/tests/__init__.py b/src/dom/tests/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/src/dom/tests/service.py b/src/dom/tests/service.py
new file mode 100644
index 000000000..8e7f036ef
--- /dev/null
+++ b/src/dom/tests/service.py
@@ -0,0 +1,40 @@
+# import time
+
+# import pytest
+# from selenium.webdriver.common.by import By
+# from selenium.webdriver.support import expected_conditions as EC
+# from selenium.webdriver.support.ui import WebDriverWait
+# from tokencost import count_string_tokens
+
+# from src.dom.service import DomService
+
+
+# @pytest.mark.skip
+# def test_process_html_file():
+# driver = DriverService(headless=False).get_driver()
+
+# driver.get('https://www.kayak.ch')
+# # driver.get('https://example.com/')
+
+# # driver.implicitly_wait(5)
+
+# # Wait for accept cookies button to appear
+# accept_cookies_button = WebDriverWait(driver, 10).until(
+# EC.presence_of_element_located(
+# (By.XPATH, '/html/body/div[4]/div/div[2]/div/div/div[3]/div/div[1]/button[1]/div/div')
+# )
+# )
+# accept_cookies_button.click()
+
+# # Wait for banner to disappear
+# time.sleep(1)
+
+# # Process the HTML file
+# dom_service = DomService(driver)
+# result = dom_service.get_clickable_elements()
+
+# # Add assertions based on expected content of page.html
+# print(f'Processed DOM content: {result.output_html}')
+# # print(f'Selector map: {result.selector_map}')
+
+# print('Tokens:', count_string_tokens(result.output_html, 'gpt-4o'))
diff --git a/src/dom/tests/service_test.py b/src/dom/tests/service_test.py
deleted file mode 100644
index c23f109e4..000000000
--- a/src/dom/tests/service_test.py
+++ /dev/null
@@ -1,39 +0,0 @@
-import time
-
-from selenium.webdriver.common.by import By
-from selenium.webdriver.support import expected_conditions as EC
-from selenium.webdriver.support.ui import WebDriverWait
-from tokencost import count_string_tokens
-
-from src.dom.service import DomService
-from src.driver.service import DriverService
-
-
-def test_process_html_file():
- driver = DriverService(headless=False).get_driver()
-
- driver.get('https://www.kayak.ch')
- # driver.get('https://example.com/')
-
- # driver.implicitly_wait(5)
-
- # Wait for accept cookies button to appear
- accept_cookies_button = WebDriverWait(driver, 10).until(
- EC.presence_of_element_located(
- (By.XPATH, '/html/body/div[4]/div/div[2]/div/div/div[3]/div/div[1]/button[1]/div/div')
- )
- )
- accept_cookies_button.click()
-
- # Wait for banner to disappear
- time.sleep(1)
-
- # Process the HTML file
- dom_service = DomService(driver)
- result = dom_service.get_current_state()
-
- # Add assertions based on expected content of page.html
- print(f'Processed DOM content: {result.output_string}')
- # print(f'Selector map: {result.selector_map}')
-
- print('Tokens:', count_string_tokens(result.output_string, 'gpt-4o'))
diff --git a/src/dom/views.py b/src/dom/views.py
new file mode 100644
index 000000000..ae21113b4
--- /dev/null
+++ b/src/dom/views.py
@@ -0,0 +1,15 @@
+from pydantic import BaseModel
+
+
+class DomContentItem(BaseModel):
+ index: int
+ text: str
+
+
+class ProcessedDomContent(BaseModel):
+ items: list[DomContentItem]
+ selector_map: dict[int, str]
+
+ def items_to_string(self) -> str:
+ """Convert the processed DOM content to HTML."""
+ return '\n'.join([item.text for item in self.items])
diff --git a/src/driver/service.py b/src/driver/service.py
deleted file mode 100644
index 6ed9e3da4..000000000
--- a/src/driver/service.py
+++ /dev/null
@@ -1,72 +0,0 @@
-"""
-Driver Service
-"""
-
-from selenium import webdriver
-from selenium.webdriver.chrome.options import Options
-from selenium.webdriver.chrome.service import Service
-from webdriver_manager.chrome import ChromeDriverManager
-
-
-class DriverService:
- def __init__(self, headless: bool = False):
- self.headless = headless
-
- def get_driver(self) -> webdriver.Chrome:
- """
- Sets up and returns a Selenium WebDriver instance with anti-detection measures.
-
- Returns:
- webdriver.Chrome: Configured Chrome WebDriver instance
- """
- chrome_options = Options()
- if self.headless:
- chrome_options.add_argument('--headless')
-
- # Anti-detection measures
- chrome_options.add_argument('--disable-blink-features=AutomationControlled')
- chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
- chrome_options.add_experimental_option('useAutomationExtension', False)
-
- # Additional stealth settings
- chrome_options.add_argument('--start-maximized')
- chrome_options.add_argument('--disable-extensions')
- chrome_options.add_argument('--no-sandbox')
- chrome_options.add_argument('--disable-infobars')
-
- # Initialize the Chrome driver
- driver = webdriver.Chrome(
- service=Service(ChromeDriverManager().install()), options=chrome_options
- )
-
- # Execute stealth scripts
- driver.execute_cdp_cmd(
- 'Page.addScriptToEvaluateOnNewDocument',
- {
- 'source': """
- Object.defineProperty(navigator, 'webdriver', {
- get: () => undefined
- });
-
- Object.defineProperty(navigator, 'languages', {
- get: () => ['en-US', 'en']
- });
-
- Object.defineProperty(navigator, 'plugins', {
- get: () => [1, 2, 3, 4, 5]
- });
-
- window.chrome = {
- runtime: {}
- };
-
- Object.defineProperty(navigator, 'permissions', {
- get: () => ({
- query: Promise.resolve.bind(Promise)
- })
- });
- """
- },
- )
-
- return driver
diff --git a/src/llm/service.py b/src/llm/service.py
deleted file mode 100644
index efb472a91..000000000
--- a/src/llm/service.py
+++ /dev/null
@@ -1,46 +0,0 @@
-import logging
-from typing import List, Literal, TypeVar
-
-from litellm import LiteLLM, acompletion
-from pydantic import BaseModel
-
-logger = logging.getLogger(__name__)
-logger.setLevel(logging.INFO)
-
-
-AvailableModel = Literal[
- 'gpt-4o',
- 'gpt-4o-mini',
- 'gpt-4o-2024-08-06',
- 'claude-3-5-sonnet-latest',
- 'claude-3-5-sonnet-20241022',
- 'claude-3-5-sonnet-20240620',
-]
-
-
-class ChatCompletionResponseMessage(BaseModel):
- role: Literal['user', 'assistant', 'system']
- content: str
-
-
-ResponseModel = TypeVar('ResponseModel', bound=BaseModel)
-
-
-class LLM:
- def __init__(self, model: AvailableModel):
- self.logger = logger
- self.model = model
- self.llm = LiteLLM()
-
- async def create_chat_completion(
- self,
- messages: list,
- response_model: type[ResponseModel],
- ) -> ResponseModel:
- response = await acompletion(
- self.model, messages, response_format=response_model, stream=False
- )
- content: str = response.choices[0].message.content # type: ignore
- # Access the completion content directly from the response
-
- return response_model.model_validate_json(content)
diff --git a/src/llm/tests/service_test.py b/src/llm/tests/service_test.py
deleted file mode 100644
index 6b6bc5baa..000000000
--- a/src/llm/tests/service_test.py
+++ /dev/null
@@ -1,24 +0,0 @@
-from pydantic import BaseModel
-import pytest
-
-from src.llm.service import LLM
-
-
-# @pytest.mark.skip(reason='openai costs')
-async def test_completion():
- messages = [{'role': 'user', 'content': 'List 2 important events in the XIX century'}]
-
- class CalendarEvent(BaseModel):
- name: str
- date: str
- participants: list[str]
-
- class EventsList(BaseModel):
- events: list[CalendarEvent]
-
- # llm = LLM(model='gpt-4o-2024-08-06')
- llm = LLM(model='claude-3-5-sonnet-20240620')
-
- resp = await llm.create_chat_completion(messages, EventsList)
-
- print('Received={}'.format(resp))
diff --git a/src/planning/prompts.py b/src/planning/prompts.py
new file mode 100644
index 000000000..e27543a37
--- /dev/null
+++ b/src/planning/prompts.py
@@ -0,0 +1,57 @@
+from langchain_core.messages import SystemMessage
+
+
+class PlanningSystemPrompt:
+ def __init__(self, task: str, default_actions: str):
+ self.task = task
+ self.default_actions = default_actions
+
+ def get_system_message(self) -> SystemMessage:
+ """
+ Get the system prompt for the agent.
+
+ Returns:
+ str: Formatted system prompt
+ """
+ # System prompts for the agent
+ output_format = """
+ {"action": "action_name", "params": {"param_name": "param_value"}, "goal": "short description what you want to achieve", "valuation_previous_goal": "Success if completed, else short sentence of why not successful."}
+ """
+
+ AGENT_PROMPT = f"""
+ You are an AI agent that helps users interact with websites.
+
+ Your input are all the interactive elements of the current page from which you can choose which to click or input.
+
+ This is how an input looks like:
+ 1:Interactive element
+ 3: <a href="https://www.example.de/"></a>
+ 9:<div>Interactive element</div>
+
+ Additional you get a list of previous actions and their results.
+
+ Available actions:
+ {self.default_actions}
+
+ In the beginning the list will be empty so you have to do google search or go to url.
+ To interact with elements, use their index number in the click() or text_input() actions. Make sure the index exists in the list of interactive elements.
+ 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, 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.
+
+ Make sure after filling a field if you need to click a suggestion or if the field is already filled.
+
+ Response format:
+ {output_format}
+
+ """
+ return SystemMessage(content=AGENT_PROMPT)
+
+ # Remember:
+ # 1. Always check if elements exist before trying to interact with them
+ # 2. Use the exact index numbers shown in the elements list
+ # 3. If you need to accept cookies, use the accept_cookies action first
+ # 4. If you can't find what you're looking for, consider scrolling or navigating to a different page
diff --git a/src/planning/service.py b/src/planning/service.py
new file mode 100644
index 000000000..1ccab7ecc
--- /dev/null
+++ b/src/planning/service.py
@@ -0,0 +1,106 @@
+import decimal
+
+from dotenv import load_dotenv
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.messages import BaseMessage, HumanMessage, AIMessage
+from tokencost import calculate_all_costs_and_tokens
+
+from src.browser.service import BrowserService
+
+# from src.llm.service import LLM, AvailableModel
+from src.planning.prompts import PlanningSystemPrompt
+from src.planning.views import PlanningAgentAction
+from src.state_manager.utils import encode_image, save_conversation
+
+load_dotenv()
+
+
+class PlaningService:
+ def __init__(self, task: str, model: BaseChatModel, browser: BrowserService | None = None):
+ """
+ Planning service.
+
+ Args:
+ task (str): Task to be performed.
+ model (AvailableModel): Model to be used.
+ browser (BrowserService | None): You can reuse an existing browser service or (automatically) create a new one.
+ """
+ self.browser = browser or BrowserService()
+
+ self.model = model
+ # self.system_prompt = [
+ # {'role': 'system', 'content': PlanningSystemPrompt(task, default_actions).get_prompt()}
+ # ]
+ self.messages_all: list[BaseMessage] = []
+ self.messages: list[BaseMessage] = []
+
+ async def chat(
+ self, task: str, store_conversation: str = '', images: str = ''
+ ) -> PlanningAgentAction:
+ # TODO: include state, actions, etc.
+
+ # select next functions to call
+ if images:
+ # Format message for vision model
+ new_message = HumanMessage(content=[task])
+ # combined_input = [
+ # {'type': 'text', 'text': task},
+ # {
+ # 'type': 'image_url',
+ # 'image_url': {
+ # 'url': f'data:image/png;base64,{encode_image(images)}',
+ # },
+ # },
+ # ]
+ else:
+ new_message = HumanMessage(content=task)
+ combined_input = [new_message]
+ input_messages = (
+ self.system_prompt + self.messages + [{'role': 'user', 'content': combined_input}]
+ )
+
+ response = await self.llm.create_chat_completion(input_messages, 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()})
+
+ try:
+ # Calculate total cost for all messages
+
+ # check if multiple input
+
+ # can not handly list of content
+ output = calculate_all_costs_and_tokens(
+ self.system_prompt + self.messages + [{'role': 'user', 'content': task}],
+ response.model_dump_json(),
+ self.model,
+ )
+ if images:
+ # resolution 1512 x 767
+ image_cost = 0.000213
+ total_cost = (
+ output['prompt_cost']
+ + output['completion_cost']
+ + decimal.Decimal(str(image_cost))
+ )
+ print(
+ f'Text ${output["prompt_cost"]:,.4f} + Image ${image_cost:,.4f} = ${total_cost:,.4f} for {output["prompt_tokens"] + output["completion_tokens"]} tokens'
+ )
+ else:
+ total_cost = output['prompt_cost'] + output['completion_cost']
+ print(
+ f'Total cost: ${total_cost:,.4f} for {output["prompt_tokens"] + output["completion_tokens"]} tokens'
+ )
+
+ except Exception as e:
+ print(f'Error calculating prompt cost: {e}')
+
+ # keep newest 20 messages
+ if len(self.messages) > 20:
+ self.messages = self.messages[-20:]
+
+ return response
diff --git a/src/planning/views.py b/src/planning/views.py
new file mode 100644
index 000000000..adbe549d4
--- /dev/null
+++ b/src/planning/views.py
@@ -0,0 +1,13 @@
+from typing import Optional
+
+from pydantic import BaseModel
+
+from src.agent.views import AgentActions
+
+
+class AskHumanPlanningAgentAction(BaseModel):
+ question: str
+
+
+class PlanningAgentAction(AgentActions):
+ ask_human: Optional[AskHumanPlanningAgentAction] = None
diff --git a/src/state_manager/state.py b/src/state_manager/state.py
deleted file mode 100644
index 45eaed60b..000000000
--- a/src/state_manager/state.py
+++ /dev/null
@@ -1,90 +0,0 @@
-from typing import Dict, List
-
-import requests
-from pydantic import BaseModel
-from Screenshot import Screenshot
-from selenium import webdriver
-
-from src.dom.service import DomService
-
-
-class ProcessedContent(BaseModel):
- output_string: str
- selector_map: Dict[int, str]
-
-
-class PageState(BaseModel):
- current_url: str
- page_title: str
- interactable_elements: str
- selector_map: Dict[int, str]
- screenshot: str
-
-
-class StateManager:
- def __init__(self, driver: webdriver.Chrome):
- self.driver = driver
- self.dom_service = DomService(driver)
- self.ob = Screenshot.Screenshot()
-
- def get_current_state(
- self, run_folder: str, full_page_screenshot: bool = False, step: int = 0
- ) -> PageState:
- """
- Retrieves current URL and interactable elements from processed HTML.
-
- Returns:
- PageState: Current state including URL, page title, interactable elements and selector map
- """
- processed_content = self.dom_service.get_current_state()
-
- if full_page_screenshot:
- # this takes longer because of scrolling
- screenshot = self.ob.full_screenshot(
- self.driver,
- save_path=run_folder,
- image_name=f'selenium_full_screenshot_{step}.png',
- is_load_at_runtime=True,
- load_wait_time=1,
- )
- screenshot = run_folder + f'/selenium_full_screenshot_{step}.png'
- else:
- file_name = run_folder + f'/window_screenshot_{step}.png'
- screenshot = self.driver.get_screenshot_as_file(file_name)
- screenshot = file_name if screenshot else ''
-
- print(screenshot)
- return PageState(
- current_url=self.driver.current_url,
- page_title=self.driver.title,
- interactable_elements=processed_content.output_string,
- selector_map=processed_content.selector_map,
- screenshot=screenshot,
- )
-
- def get_functions(self) -> List[Dict]:
- """
- Retrieves available functions from cleaned HTML.
- """
- return []
-
- def get_main_content(self) -> ProcessedContent:
- """
- Retrieves main content from the page.
- """
- try:
- # Get HTML using requests
- response = requests.get(self.driver.current_url)
- response.encoding = 'utf-8'
- content = response.text
-
- # Process content using DomService
- processed_content = self.dom_service._process_content(content)
- return ProcessedContent(
- output_string=processed_content.output_string,
- selector_map=processed_content.selector_map,
- )
-
- except Exception as e:
- print(f'Error getting main content: {e}')
- return ProcessedContent(output_string='', selector_map={})
diff --git a/src/tests/test_kayak_search.py b/src/tests/test_kayak_search.py
index e2cd7ce20..cbf444047 100644
--- a/src/tests/test_kayak_search.py
+++ b/src/tests/test_kayak_search.py
@@ -20,19 +20,28 @@ async def setup():
driver.quit()
@pytest.mark.asyncio
async def test_kayak_flight_search(setup):
driver, actions, state_manager = setup
# Create run folder
- timestamp = 'flight_search_bali_to_kirgistan'
- task = 'find a flight from Bali to Kirgistan on 2024-11-25 for 2 people one way.'
+ timestamp = 'testing_prompts'
+ # task = 'go to kayak.com andfind a flight from Bali to Kirgistan on 2024-11-25 for 2 people one way.'
+ task = 'apply to a role at google for a SWE internship this summer.'
vision = True
run_folder = f'temp/{timestamp}'
if not os.path.exists(run_folder):
os.makedirs(run_folder)
+ else:
+ # Remove run folder if it exists
+ for file in os.listdir(run_folder):
+ os.remove(os.path.join(run_folder, file))
+ os.rmdir(run_folder)
+ os.makedirs(run_folder)
+
print('\n' + '=' * 50)
print('🚀 Starting flight search task')
print('=' * 50)
@@ -66,6 +75,8 @@ async def test_kayak_flight_search(setup):
if output.error:
state_text += f', Previous action error: {output.error}'
+ input('Press Enter to continue...')
+
action = await agent.chat(
state_text,
images=current_state.screenshot,