Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
work in progress
Gregor Žuničd57495a79946
diff --git a/.vscode/settings.json b/.vscode/settings.jsonnew file mode 100644index 000000000..dc3f727ca--- /dev/null+++ b/.vscode/settings.json@@ -0,0 +1,3 @@+{+ "python.analysis.typeCheckingMode": "basic"+}diff --git a/README.md b/README.mdindex cb2432d4f..0b85e263e 100644--- a/README.md+++ b/README.md@@ -1,3 +1,55 @@# Interfaces for agentsThis repository contains the interfaces for agents.++# Codebase Structure++> The code structure inspired by https://github.com/Netflix/dispatch.++Very good structure on how to make a scalable codebase is also in [this repo](https://github.com/zhanymkanov/fastapi-best-practices).++Just a brief document about how we should structure our backend codebase.++## Code Structure++```markdown+src/+/<service name>/+models.py+services.py+prompts.py+views.py+utils.py+routers.py++ /_<subservice name>/+```++### Service.py++Always a single file, except if it becomes too long - more than ~500 lines, split it into \_subservices++### Views.py++Always split the views into two parts++```python+# All+...++# Requests+...++# Responses+...+```++If too long → split into multiple files++### Prompts.py++Single file; if too long → split into multiple files (one prompt per file or so)++### Routers.py++Never split into more than one filediff --git a/conftest.py b/conftest.pynew file mode 100644index 000000000..8828c5269--- /dev/null+++ b/conftest.py@@ -0,0 +1,6 @@+import os+import sys++# Get the absolute path to the project root+project_root = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, project_root)diff --git a/pyproject.toml b/pyproject.tomlindex 8888fb0e7..d2a1b924a 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -5,3 +5,11 @@ description = "Testing agent interfaces"readme = "README.md"requires-python = ">=3.11"dependencies = []++[tool.ruff]+line-length = 100++[tool.ruff.format]+quote-style = "single"+indent-style = "tab"+docstring-code-format = true\ No newline at end of filediff --git a/sample.ipynb b/sample.ipynbindex 245f966ee..da6f620ff 100644--- a/sample.ipynb+++ b/sample.ipynb@@ -45,7 +45,7 @@"driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)\n","# Configure Chrome to appear as a regular browser\n","chrome_options.add_argument('--disable-blink-features=AutomationControlled')\n",- "chrome_options.add_experimental_option(\"excludeSwitches\", [\"enable-automation\"])\n",+ "chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])\n","chrome_options.add_experimental_option('useAutomationExtension', False)\n","\n","\n",@@ -53,7 +53,7 @@"# url = 'https://www.google.com/travel/flights'\n","# url = \"https://www.kayak.com/flights\"\n","# url = \"https://docs.google.com/spreadsheets/d/1iwaV2GmQPZcyMWwxZu-rGPEIzo-Ac7j_rFslLXqVjok/edit?usp=sharing\"\n",- "url = \"https://groq.com/pricing/\"\n",+ "url = 'https://groq.com/pricing/'\n","\n","driver.get(url)\n","\n",@@ -92,9 +92,9 @@"html_content = driver.page_source\n","\n","# Take a screenshot and save it\n",- "screenshot_path = \"temp/screenshot.png\"\n",+ "screenshot_path = 'temp/screenshot.png'\n","driver.save_screenshot(screenshot_path)\n",- "print(f\"Screenshot saved to: {screenshot_path}\")\n"+ "print(f'Screenshot saved to: {screenshot_path}')"]},{@@ -113,21 +113,22 @@"# Format and save HTML content to file\n","from bs4 import BeautifulSoup\n","\n",+ "\n","def save_formatted_html(html_content, output_file_name):\n",- " \"\"\"\n",- " Format HTML content using BeautifulSoup and save to file\n",- " \n",- " Args:\n",- " html_content (str): Raw HTML content to format\n",- " output_file_name (str): Name of the file where formatted HTML will be saved\n",- " \"\"\"\n",- " # Format HTML with BeautifulSoup for nice indentation\n",- " soup = BeautifulSoup(html_content, 'html.parser')\n",- " formatted_html = soup.prettify()\n",- "\n",- " # Save formatted HTML to file\n",- " with open(\"temp/\"+output_file_name, 'w', encoding='utf-8') as f:\n",- " f.write(formatted_html)"+ "\t\"\"\"\n",+ "\tFormat HTML content using BeautifulSoup and save to file\n",+ "\n",+ "\tArgs:\n",+ "\t html_content (str): Raw HTML content to format\n",+ "\t output_file_name (str): Name of the file where formatted HTML will be saved\n",+ "\t\"\"\"\n",+ "\t# Format HTML with BeautifulSoup for nice indentation\n",+ "\tsoup = BeautifulSoup(html_content, 'html.parser')\n",+ "\tformatted_html = soup.prettify()\n",+ "\n",+ "\t# Save formatted HTML to file\n",+ "\twith open('temp/' + output_file_name, 'w', encoding='utf-8') as f:\n",+ "\t\tf.write(formatted_html)"]},{@@ -153,19 +154,23 @@"html_content\n","\n","# model = \"gpt-4o\"\n",- "model = \"gpt-4o\"\n",+ "model = 'gpt-4o'\n","\n","print(\n",- " \"Pure html cost: \", f\"${calculate_prompt_cost(html_content, model):,.2f}\",\n",- " \"Tokens: \", f\"{count_string_tokens(html_content, model):,}\",\n",+ "\t'Pure html cost: ',\n",+ "\tf'${calculate_prompt_cost(html_content, model):,.2f}',\n",+ "\t'Tokens: ',\n",+ "\tf'{count_string_tokens(html_content, model):,}',\n",")\n","\n","cleaned_html = cleanup_html(html_content)\n",- "save_formatted_html(cleaned_html, \"cleaned_html.html\")\n",+ "save_formatted_html(cleaned_html, 'cleaned_html.html')\n","\n","print(\n",- " \"Cleaned html cost: \", f\"${calculate_prompt_cost(cleaned_html, model):,.2f}\",\n",- " \"Tokens: \", f\"{count_string_tokens(cleaned_html, model):,}\",\n",+ "\t'Cleaned html cost: ',\n",+ "\tf'${calculate_prompt_cost(cleaned_html, model):,.2f}',\n",+ "\t'Tokens: ',\n",+ "\tf'{count_string_tokens(cleaned_html, model):,}',\n",")"]},diff --git a/src/__init__.py b/src/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/src/actions/action_validator.py b/src/actions/action_validator.pyindex ce3e51c66..f95e5db7b 100644--- a/src/actions/action_validator.py+++ b/src/actions/action_validator.py@@ -3,34 +3,34 @@ from selenium.common.exceptions import TimeoutException, WebDriverExceptionclass ActionValidator:- def __init__(self, driver: webdriver.Chrome):- self.driver = driver+ def __init__(self, driver: webdriver.Chrome):+ self.driver = driver- def is_action_successful(self, action: dict) -> bool:- """- Checks if the action was executed successfully.+ def is_action_successful(self, action: dict) -> bool:+ """+ Checks if the action was executed successfully.- Args:- action (dict): The action that was attempted+ Args:+ action (dict): The action that was attempted- Returns:- bool: True if action was successful, False otherwise- """- try:- pass+ Returns:+ bool: True if action was successful, False otherwise+ """+ try:+ pass- except (TimeoutException, WebDriverException):- return False+ except (TimeoutException, WebDriverException):+ return False- def check_ambiguity(self, action: dict) -> bool:- """- Determines if the action is ambiguous and requires clarification.+ 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+ 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- pass+ Returns:+ bool: True if action is ambiguous, False otherwise+ """+ # Implementation will use LLM to check for ambiguity+ passdiff --git a/src/actions/browser_actions.py b/src/actions/browser_actions.pyindex 584c889d0..85a974c74 100644--- a/src/actions/browser_actions.py+++ b/src/actions/browser_actions.py@@ -5,87 +5,83 @@ from selenium.webdriver.support import expected_conditions as ECclass BrowserActions:- def __init__(self, driver: webdriver.Chrome):- self.driver = driver- self.wait = WebDriverWait(driver, 10)+ def __init__(self, driver: webdriver.Chrome):+ self.driver = driver+ self.wait = WebDriverWait(driver, 10)- def execute_action(self, action: dict):- print(action.keys())- action_name = action["action"]+ def execute_action(self, action: dict):+ print(action.keys())+ action_name = action['action']- if "params" in action:- params = action["params"]- else:- params = {}+ if 'params' in action:+ params = action['params']+ else:+ params = {}- if action_name == "search_google":- self.search_google(params["query"])- elif action_name == "go_to_url":- self.go_to_url(params["url"])- elif action_name == "go_back":- self.go_back()- elif action_name == "done":- return True- elif action_name == "input":- self.input_text_by_c(params["c"], params["text"])- elif action_name == "click":- self.click_element_by_c(params["c"])- elif action_name == "accept_cookies":- self.driver.accept_cookies()- else:- raise Exception(f"Action {action_name} not found")+ if action_name == 'search_google':+ self.search_google(params['query'])+ elif action_name == 'go_to_url':+ self.go_to_url(params['url'])+ elif action_name == 'go_back':+ self.go_back()+ elif action_name == 'done':+ return True+ elif action_name == 'input':+ self.input_text_by_c(params['c'], params['text'])+ elif action_name == 'click':+ self.click_element_by_c(params['c'])+ elif action_name == 'accept_cookies':+ self.driver.accept_cookies()+ else:+ raise Exception(f'Action {action_name} not found')- # default actions- def search_google(self, query: str):- """- Performs a Google search with the provided query.- """- # TODO: replace with search api- self.driver.get("https://www.google.com")- search_box = self.wait.until(- EC.presence_of_element_located((By.NAME, "q"))- )- search_box.send_keys(query)- search_box.submit()+ # default actions+ def search_google(self, query: str):+ """+ Performs a Google search with the provided query.+ """+ # TODO: replace with search api+ self.driver.get('https://www.google.com')+ search_box = self.wait.until(EC.presence_of_element_located((By.NAME, 'q')))+ search_box.send_keys(query)+ search_box.submit()- def go_to_url(self, url: str):- """- Navigates the browser to the specified URL.- """- self.driver.get(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 go_back(self):+ """+ Navigates back in the browser history.+ """+ self.driver.back()- def click_element_by_c(self, c_value: str):- """- Clicks an element identified by its c attribute.- """- element = self.wait.until(- EC.element_to_be_clickable((By.CSS_SELECTOR, f'[c="{c_value}"]'))- )- element.click()+ def click_element_by_c(self, c_value: str):+ """+ Clicks an element identified by its c attribute.+ """+ element = self.wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, f'[c="{c_value}"]')))+ element.click()- def input_text_by_c(self, c_value: str, text: str):- """- Inputs text into a field identified by its c attribute.- """- element = self.wait.until(- EC.presence_of_element_located((By.CSS_SELECTOR, f'[c="{c_value}"]'))- )- element.clear()- element.send_keys(text)+ def input_text_by_c(self, c_value: str, text: str):+ """+ Inputs text into a field identified by its c attribute.+ """+ element = self.wait.until(+ EC.presence_of_element_located((By.CSS_SELECTOR, f'[c="{c_value}"]'))+ )+ element.clear()+ element.send_keys(text)- def get_default_actions(self) -> dict[str, str]:- return {- "search_google": "query: string",- "go_to_url": "url: string",- "done": "",- "go_back": "",- "click": "c: int",- "input": "c: int, text: string",- "accept_cookies": "",- }+ def get_default_actions(self) -> dict[str, str]:+ return {+ 'search_google': 'query: string',+ 'go_to_url': 'url: string',+ 'done': '',+ 'go_back': '',+ 'click': 'c: int',+ 'input': 'c: int, text: string',+ 'accept_cookies': '',+ }diff --git a/src/agent_interface/planing_agent.py b/src/agent_interface/planing_agent.pyindex 53caab47a..75fa19d26 100644--- a/src/agent_interface/planing_agent.py+++ b/src/agent_interface/planing_agent.py@@ -7,45 +7,47 @@ from tokencost import calculate_prompt_cost, count_string_tokensclass PlaningAgent:- def __init__(self, task: str, default_actions: str):- load_dotenv()- self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))- self.model = "gpt-4o"- self.messages = [{"role": "system", "content": self.get_system_prompt(task, default_actions)}]-- def chat(self, task: str) -> Dict:- # TODO: include state, actions, etc.-- # select next functions to call- messages = self.messages + [{"role": "user", "content": task}]-- # Calculate total cost for all messages- total_cost = calculate_prompt_cost(messages, self.model)- total_tokens = count_string_tokens(" ".join([m["content"] for m in messages]), self.model)- print(- "Total prompt cost: ", f"${total_cost:,.2f}",- "Total tokens: ", f"{total_tokens:,}",- )-- response = self.client.chat.completions.create(- model=self.model,- messages=messages,- response_format={"type": "json_object"}- )-- # Only append the output message- self.messages.append({"role": "assistant", "content": response.choices[0].message.content})-- # parse the response- return json.loads(response.choices[0].message.content)-- def get_system_prompt(self, task: str, default_actions: str) -> str:- # System prompts for the agent- output_format = """+ def __init__(self, task: str, default_actions: str):+ load_dotenv()+ self.client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))+ self.model = 'gpt-4o'+ self.messages = [+ {'role': 'system', 'content': self.get_system_prompt(task, default_actions)}+ ]++ def chat(self, task: str) -> Dict:+ # TODO: include state, actions, etc.++ # select next functions to call+ messages = self.messages + [{'role': 'user', 'content': task}]++ # Calculate total cost for all messages+ total_cost = calculate_prompt_cost(messages, self.model)+ total_tokens = count_string_tokens(' '.join([m['content'] for m in messages]), self.model)+ print(+ 'Total prompt cost: ',+ f'${total_cost:,.2f}',+ 'Total tokens: ',+ f'{total_tokens:,}',+ )++ response = self.client.chat.completions.create(+ model=self.model, messages=messages, response_format={'type': 'json_object'}+ )++ # Only append the output message+ self.messages.append({'role': 'assistant', 'content': response.choices[0].message.content})++ # parse the response+ return json.loads(response.choices[0].message.content)++ def get_system_prompt(self, task: str, default_actions: str) -> str:+ # System prompts for the agent+ output_format = """{"action": "action_name", "params": {"param_name": "param_value"}}"""- AGENT_PROMPT = f"""+ AGENT_PROMPT = f"""You are a web scraping agent. Your task is to control the browser where, for every step,you get the current state and a list of actions you can take as dictionary.If you want to click on an element or input text, you need to specify the element id (c="") from the cleaned HTML.@@ -59,4 +61,4 @@ class PlaningAgent:{default_actions}"""- return AGENT_PROMPT+ return AGENT_PROMPTdiff --git a/src/dom/__init__.py b/src/dom/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/src/dom/__tests__/__init__.py b/src/dom/__tests__/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/src/dom/__tests__/service_test.py b/src/dom/__tests__/service_test.pynew file mode 100644index 000000000..190311bf7--- /dev/null+++ b/src/dom/__tests__/service_test.py@@ -0,0 +1,23 @@+import os+from src.dom.service import DomService+++def test_process_html_file():+ # Get the absolute path to the test file+ current_dir = os.path.dirname(os.path.abspath(__file__))+ test_file_path = os.path.join(current_dir, '..', '..', '..', 'temp', 'page.html')++ # Ensure test file exists+ assert os.path.exists(test_file_path), f'Test file not found at {test_file_path}'++ # Read the HTML file content+ with open(test_file_path, 'r', encoding='utf-8') as file:+ html_content = file.read()++ # Process the HTML file+ dom_service = DomService()+ result = dom_service.process_content(html_content)++ # Add assertions based on expected content of page.html+ print(f'Processed DOM content: {result.output_string}')+ # print(f'Selector map: {result.selector_map}')diff --git a/src/dom/service.py b/src/dom/service.pynew file mode 100644index 000000000..594a2e426--- /dev/null+++ b/src/dom/service.py@@ -0,0 +1,220 @@+"""+Dom Service+"""++from bs4 import BeautifulSoup, NavigableString, Tag+from pydantic import BaseModel+++class ProcessedDomContent(BaseModel):+ output_string: str+ selector_map: dict+++class DomService:+ def process_content(self, html_content: str) -> ProcessedDomContent:+ """+ Process HTML content to extract and clean relevant elements.+ Args:+ html_content: Raw HTML string to process+ Returns:+ ProcessedDomContent: Processed DOM content+ """+ # Parse HTML content using BeautifulSoup+ soup = BeautifulSoup(html_content, 'html.parser')++ candidate_elements: list[Tag | NavigableString] = []+ dom_queue = list(soup.body.children) if soup.body else []+ xpath_cache = {}++ # Find candidate elements+ while dom_queue:+ element = dom_queue.pop()+ should_add_element = False++ # Handle both Tag elements and text nodes+ if isinstance(element, Tag):+ # Add children to queue in reverse order+ for child in reversed(list(element.children)):+ dom_queue.append(child)++ # Check if element is interactive or leaf element+ if self._is_interactive_element(element) or self._is_leaf_element(element):+ should_add_element = True++ elif isinstance(element, NavigableString) and element.strip():+ should_add_element = True++ if should_add_element:+ if not isinstance(element, (Tag, NavigableString)):+ continue+ candidate_elements.append(element)++ # Process candidates+ selector_map = {}+ output_string = ''++ for index, element in enumerate(candidate_elements):+ xpath = xpath_cache.get(element)+ if not xpath:+ xpath = self._generate_xpath(element)+ xpath_cache[element] = xpath++ if isinstance(element, str):+ text_content = element.strip()+ if text_content:+ output_string += f'{index}:{text_content}\n'+ else:+ tag_name = element.name+ attributes = self._get_essential_attributes(element)++ opening_tag = f"<{tag_name}{' ' + attributes if attributes else ''}>"+ closing_tag = f'</{tag_name}>'+ text_content = element.get_text().strip() or ''++ output_string += f'{index}:{opening_tag}{text_content}{closing_tag}\n'++ selector_map[index] = xpath++ return ProcessedDomContent(output_string=output_string, selector_map=selector_map)++ def _is_interactive_element(self, element: Tag) -> bool:+ """Check if element is interactive based on tag name and attributes."""+ interactive_elements = {+ 'a',+ 'button',+ 'details',+ 'embed',+ 'input',+ 'label',+ 'menu',+ 'menuitem',+ 'object',+ 'select',+ 'textarea',+ 'summary',+ }+ interactive_roles = {+ 'button',+ 'menu',+ 'menuitem',+ 'link',+ 'checkbox',+ 'radio',+ 'slider',+ 'tab',+ 'tabpanel',+ 'textbox',+ 'combobox',+ 'grid',+ 'listbox',+ 'option',+ 'progressbar',+ 'scrollbar',+ 'searchbox',+ 'switch',+ 'tree',+ 'treeitem',+ 'spinbutton',+ 'tooltip',+ }++ return (+ element.name in interactive_elements+ or element.get('role') in interactive_roles+ or element.get('aria-role') in interactive_roles+ )++ def _is_leaf_element(self, element: Tag) -> bool:+ """Check if element is a leaf element."""+ leaf_element_deny_list = {'svg', 'iframe', 'script', 'style', 'link'}++ if not element.get_text(strip=True):+ return False++ if not list(element.children):+ return element.name not in leaf_element_deny_list++ # Check for simple text-only elements+ children = list(element.children)+ if len(children) == 1 and isinstance(children[0], str):+ return True++ return False++ def _generate_xpath(self, element: Tag | NavigableString) -> str:+ """Generate XPath for given element."""+ # Handle NavigableString - return parent's xpath+ if isinstance(element, NavigableString):+ if element.parent:+ return self._generate_xpath(element.parent)+ return ''++ # Handle elements that may not have all Tag methods+ if not hasattr(element, 'name'):+ return ''++ # Check for ID using getattr to handle elements without get() method+ element_id = getattr(element, 'get', lambda x: None)('id')+ if element_id:+ return f"//*[@id='{element_id}']"++ parts = []+ current = element++ while current and getattr(current, 'name', None):+ # Safely get parent and children+ parent = getattr(current, 'parent', None)+ siblings = list(parent.children) if parent and hasattr(parent, 'children') else []++ # Filter siblings that are elements with matching names+ same_type_siblings = [+ s for s in siblings if hasattr(s, 'name') and s.name == current.name+ ]++ if len(same_type_siblings) > 1:+ try:+ index = same_type_siblings.index(current) + 1+ parts.insert(0, f'{current.name}[{index}]')+ except ValueError:+ parts.insert(0, current.name)+ else:+ parts.insert(0, current.name)++ current = parent++ return '/' + '/'.join(parts) if parts else ''++ def _get_essential_attributes(self, element: Tag) -> str:+ """+ Collects essential attributes from an element.+ Args:+ element: The BeautifulSoup PageElement+ Returns:+ A string of formatted essential attributes+ """+ essential_attributes = [+ 'id',+ 'class',+ 'href',+ 'src',+ 'aria-label',+ 'aria-name',+ 'aria-role',+ 'aria-description',+ 'aria-expanded',+ 'aria-haspopup',+ ]++ # Collect essential attributes that have values+ attrs = []+ for attr in essential_attributes:+ if attr in element.attrs:+ attrs.append(f'{attr}="{element[attr]}"')++ # Collect data- attributes+ for attr in element.attrs:+ if attr.startswith('data-'):+ attrs.append(f'{attr}="{element[attr]}"')++ return ' '.join(attrs)diff --git a/src/state_manager/state.py b/src/state_manager/state.pyindex 380b1fde5..1a7719301 100644--- a/src/state_manager/state.py+++ b/src/state_manager/state.py@@ -8,49 +8,49 @@ from main_content_extractor import MainContentExtractorclass StateManager:- def __init__(self, driver: webdriver.Chrome):- self.driver = driver-- def get_current_state(self) -> Dict:- """- Retrieves current URL and interactable elements from cleaned HTML.-- Returns:- Dict: Current state including URL, page title, and interactable elements- """- html_content = self.driver.page_source- cleaned_content = cleanup_html(html_content)-- return {- "current_url": self.driver.current_url,- "page_title": self.driver.title,- "interactable_elements": cleaned_content["html"],- # "main_content": cleaned_content["main_content"]- }-- def get_functions(self) -> List[Dict]:- """- Retrieves available functions from cleaned HTML.- """- return []-- def get_main_content(self) -> str:- """- Retrieves main content from cleaned Markdown.- """- try:- # Get HTML using requests- response = requests.get(self.driver.current_url)- response.encoding = 'utf-8'- content = response.text-- # Get HTML with main content extracted from HTML- # extracted_html = MainContentExtractor.extract(content)-- # Get HTML with main content extracted from Markdown- extracted_markdown = MainContentExtractor.extract(content, output_format="markdown")-- return extracted_markdown- except Exception as e:- print(f"Error getting main content: {e}")- return ""+ def __init__(self, driver: webdriver.Chrome):+ self.driver = driver++ def get_current_state(self) -> Dict:+ """+ Retrieves current URL and interactable elements from cleaned HTML.++ Returns:+ Dict: Current state including URL, page title, and interactable elements+ """+ html_content = self.driver.page_source+ cleaned_content = cleanup_html(html_content)++ return {+ 'current_url': self.driver.current_url,+ 'page_title': self.driver.title,+ 'interactable_elements': cleaned_content['html'],+ # "main_content": cleaned_content["main_content"]+ }++ def get_functions(self) -> List[Dict]:+ """+ Retrieves available functions from cleaned HTML.+ """+ return []++ def get_main_content(self) -> str:+ """+ Retrieves main content from cleaned Markdown.+ """+ try:+ # Get HTML using requests+ response = requests.get(self.driver.current_url)+ response.encoding = 'utf-8'+ content = response.text++ # Get HTML with main content extracted from HTML+ # extracted_html = MainContentExtractor.extract(content)++ # Get HTML with main content extracted from Markdown+ extracted_markdown = MainContentExtractor.extract(content, output_format='markdown')++ return extracted_markdown+ except Exception as e:+ print(f'Error getting main content: {e}')+ return ''diff --git a/src/state_manager/utils.py b/src/state_manager/utils.pyindex a581ab117..9fc7744c6 100644--- a/src/state_manager/utils.py+++ b/src/state_manager/utils.py@@ -4,146 +4,177 @@ import osdef save_formatted_html(html_content, output_file_name):- """- Format HTML content using BeautifulSoup and save to file+ """+ Format HTML content using BeautifulSoup and save to file- Args:- html_content (str): Raw HTML content to format- output_file_name (str): Name of the file where formatted HTML will be saved- """- # Format HTML with BeautifulSoup for nice indentation- soup = BeautifulSoup(html_content, 'html.parser')- formatted_html = soup.prettify()+ Args:+ html_content (str): Raw HTML content to format+ output_file_name (str): Name of the file where formatted HTML will be saved+ """+ # Format HTML with BeautifulSoup for nice indentation+ soup = BeautifulSoup(html_content, 'html.parser')+ formatted_html = soup.prettify()- # create temp folder if it doesn't exist- if not os.path.exists("temp"):- os.makedirs("temp")+ # create temp folder if it doesn't exist+ if not os.path.exists('temp'):+ os.makedirs('temp')- # Save formatted HTML to file- with open("temp/"+output_file_name, 'w', encoding='utf-8') as f:- f.write(formatted_html)+ # Save formatted HTML to file+ with open('temp/' + output_file_name, 'w', encoding='utf-8') as f:+ f.write(formatted_html)def save_markdown(markdown_content, output_file_name):- """Save markdown content to a file"""- if not os.path.exists("temp"):- os.makedirs("temp")+ """Save markdown content to a file"""+ if not os.path.exists('temp'):+ os.makedirs('temp')- with open("temp/"+output_file_name, 'w', encoding='utf-8') as f:- f.write(markdown_content)+ with open('temp/' + output_file_name, 'w', encoding='utf-8') as f:+ f.write(markdown_content)def cleanup_html(html_content):- """- Clean up HTML content by processing visible and interactive elements.- Returns both cleaned HTML and main content.- """- if not html_content:- return {"html": "", "main_content": ""}-- soup = BeautifulSoup(html_content, "html.parser")- class_counter = 0-- def is_interactive_element(element):- """Check if element is interactive based on tag or attributes"""- interactive_tags = [- "a", "button", "input", "select", "textarea", "details",- "embed", "label", "menu", "menuitem", "object", "summary"- ]-- interactive_roles = [- "button", "link", "menuitem", "tab", "checkbox", "radio",- "combobox", "listbox", "menu", "menuitem", "option", "slider"- ]-- return (- element.name in interactive_tags or- element.get('role') in interactive_roles or- element.get('tabindex') == '0' or- element.get('onclick') or- element.get('aria-haspopup')- )-- def is_visible(element):- """Check if element would be visible"""- return not (- element.get('aria-hidden') == 'true' or- element.get('hidden') or- element.get('style') and ('display: none' in element.get('style') or- 'visibility: hidden' in element.get('style')) or- element.get('class') and ('hidden' in ' '.join(element.get('class')) or- 'invisible' in ' '.join(element.get('class')))- )-- def is_leaf_element(element):- """Check if element is a leaf node with meaningful content"""- return (- bool(element.string and element.string.strip()) and- not element.find_all(True) and- element.name not in ['script', 'style', 'meta', 'link', 'svg']- )-- def process_element(element):- """Process a single element and its children"""- nonlocal class_counter-- if not isinstance(element, Tag):- return-- # Skip hidden elements- if not is_visible(element):- element.decompose()- return-- # Process interactive elements- if is_interactive_element(element):- if element.get('class'):- element['c'] = str(class_counter)- class_counter += 1- del element['class']-- # Keep only essential attributes- allowed_attrs = ["c", "href", "aria-label", "placeholder", "id", "type", "role"]- attrs = dict(element.attrs)- for attr in attrs:- if attr not in allowed_attrs:- del element[attr]-- # Process leaf elements with content- elif is_leaf_element(element):- if element.get('class'):- element['c'] = str(class_counter)- class_counter += 1- del element['class']-- # Remove unnecessary elements- elif element.name in ['script', 'style', 'meta', 'link', 'svg', 'iframe']:- element.decompose()- return-- # Process children recursively- for child in element.children:- process_element(child)-- # Process the entire document- process_element(soup.body)-- # Extract main content- main_content = ""- main_elem = soup.find('main') or soup.find(id='main')- if main_elem:- main_content = main_elem.get_text(strip=True)-- # Clean up the final HTML- cleaned_html = str(soup)- cleaned_html = " ".join(cleaned_html.split())-- # Remove empty tags- empty_tags_pattern = r"<[^/>][^>]*></[^>]+>"- while re.search(empty_tags_pattern, cleaned_html):- cleaned_html = re.sub(empty_tags_pattern, "", cleaned_html)-- return {- "html": cleaned_html,- "main_content": main_content- }+ """+ Clean up HTML content by processing visible and interactive elements.+ Returns both cleaned HTML and main content.+ """+ if not html_content:+ return {'html': '', 'main_content': ''}++ soup = BeautifulSoup(html_content, 'html.parser')+ class_counter = 0++ def is_interactive_element(element):+ """Check if element is interactive based on tag or attributes"""+ interactive_tags = [+ 'a',+ 'button',+ 'input',+ 'select',+ 'textarea',+ 'details',+ 'embed',+ 'label',+ 'menu',+ 'menuitem',+ 'object',+ 'summary',+ ]++ interactive_roles = [+ 'button',+ 'link',+ 'menuitem',+ 'tab',+ 'checkbox',+ 'radio',+ 'combobox',+ 'listbox',+ 'menu',+ 'menuitem',+ 'option',+ 'slider',+ ]++ return (+ element.name in interactive_tags+ or element.get('role') in interactive_roles+ or element.get('tabindex') == '0'+ or element.get('onclick')+ or element.get('aria-haspopup')+ )++ def is_visible(element):+ """Check if element would be visible"""+ return not (+ element.get('aria-hidden') == 'true'+ or element.get('hidden')+ or element.get('style')+ and (+ 'display: none' in element.get('style')+ or 'visibility: hidden' in element.get('style')+ )+ or element.get('class')+ and (+ 'hidden' in ' '.join(element.get('class'))+ or 'invisible' in ' '.join(element.get('class'))+ )+ )++ def is_leaf_element(element):+ """Check if element is a leaf node with meaningful content"""+ return (+ bool(element.string and element.string.strip())+ and not element.find_all(True)+ and element.name not in ['script', 'style', 'meta', 'link', 'svg']+ )++ def process_element(element):+ """Process a single element and its children"""+ nonlocal class_counter++ if not isinstance(element, Tag):+ return++ # Skip hidden elements+ if not is_visible(element):+ element.decompose()+ return++ # Process interactive elements+ if is_interactive_element(element):+ if element.get('class'):+ element['c'] = str(class_counter)+ class_counter += 1+ del element['class']++ # Keep only essential attributes+ allowed_attrs = [+ 'c',+ 'href',+ 'aria-label',+ 'placeholder',+ 'id',+ 'type',+ 'role',+ ]+ attrs = dict(element.attrs)+ for attr in attrs:+ if attr not in allowed_attrs:+ del element[attr]++ # Process leaf elements with content+ elif is_leaf_element(element):+ if element.get('class'):+ element['c'] = str(class_counter)+ class_counter += 1+ del element['class']++ # Remove unnecessary elements+ elif element.name in ['script', 'style', 'meta', 'link', 'svg', 'iframe']:+ element.decompose()+ return++ # Process children recursively+ for child in element.children:+ process_element(child)++ # Process the entire document+ process_element(soup.body)++ # Extract main content+ main_content = ''+ main_elem = soup.find('main') or soup.find(id='main')+ if main_elem:+ main_content = main_elem.get_text(strip=True)++ # Clean up the final HTML+ cleaned_html = str(soup)+ cleaned_html = ' '.join(cleaned_html.split())++ # Remove empty tags+ empty_tags_pattern = r'<[^/>][^>]*></[^>]+>'+ while re.search(empty_tags_pattern, cleaned_html):+ cleaned_html = re.sub(empty_tags_pattern, '', cleaned_html)++ return {'html': cleaned_html, 'main_content': main_content}diff --git a/src/tests/test_html_cleanup.py b/src/tests/test_html_cleanup.pyindex 8e586bc64..b3ca42578 100644--- a/src/tests/test_html_cleanup.py+++ b/src/tests/test_html_cleanup.py@@ -5,15 +5,15 @@ import osclass TestHTMLCleanup(unittest.TestCase):- def setUp(self):- # Create test directory if it doesn't exist- self.test_dir = "test_files"- if not os.path.exists(self.test_dir):- os.makedirs(self.test_dir)-- def test_cleanup_sample_html(self):- # Sample HTML with various elements to test- test_html = """+ def setUp(self):+ # Create test directory if it doesn't exist+ self.test_dir = 'test_files'+ if not os.path.exists(self.test_dir):+ os.makedirs(self.test_dir)++ def test_cleanup_sample_html(self):+ # Sample HTML with various elements to test+ test_html = """<html><head><script>Some script</script>@@ -36,81 +36,82 @@ class TestHTMLCleanup(unittest.TestCase):</html>"""- result = cleanup_html(test_html)- cleaned_html = result["html"]-- # Parse the cleaned HTML for testing- soup = BeautifulSoup(cleaned_html, 'html.parser')-- # Test that script and style are removed- self.assertEqual(len(soup.find_all('script')), 0)- self.assertEqual(len(soup.find_all('style')), 0)-- # Test that hidden elements are removed- self.assertEqual(len(soup.find_all(attrs={"class": "hidden"})), 0)- self.assertEqual(len(soup.find_all(attrs={"style": "display: none"})), 0)- self.assertEqual(len(soup.find_all(attrs={"aria-hidden": "true"})), 0)-- # Test that interactive elements have 'c' attribute- interactive_elements = soup.find_all(attrs={"c": True})- self.assertGreater(len(interactive_elements), 0)-- # Test specific interactive elements- self.assertIsNotNone(soup.find('button'))- self.assertIsNotNone(soup.find('a'))- self.assertIsNotNone(soup.find('input'))- self.assertIsNotNone(soup.find('select'))-- # Print cleaned HTML for inspection- print("\nCleaned HTML:")- print(cleaned_html)-- def test_cleanup_real_page(self):- # Load a real webpage HTML file- test_file = os.path.join(self.test_dir, "kayak_page.html")-- # First run: download and save the page if it doesn't exist- if not os.path.exists(test_file):- import requests- response = requests.get("https://www.kayak.ch")- with open(test_file, 'w', encoding='utf-8') as f:- f.write(response.text)-- # Read the test file- with open(test_file, 'r', encoding='utf-8') as f:- html_content = f.read()-- # Clean up the HTML- result = cleanup_html(html_content)- cleaned_html = result["html"]-- # Parse the cleaned HTML- soup = BeautifulSoup(cleaned_html, 'html.parser')-- # Test basic cleanup- self.assertEqual(len(soup.find_all('script')), 0)- self.assertEqual(len(soup.find_all('style')), 0)-- # Test interactive elements- interactive_elements = soup.find_all(attrs={"c": True})- self.assertGreater(len(interactive_elements), 0)-- # Print statistics- print("\nReal page cleanup statistics:")- print(f"Total interactive elements found: {len(interactive_elements)}")- print(f"Buttons: {len(soup.find_all('button'))}")- print(f"Links: {len(soup.find_all('a'))}")- print(f"Inputs: {len(soup.find_all('input'))}")- print(f"Selects: {len(soup.find_all('select'))}")-- # Save cleaned HTML for manual inspection- cleaned_file = os.path.join(self.test_dir, "kayak_page_cleaned.html")- with open(cleaned_file, 'w', encoding='utf-8') as f:- f.write(cleaned_html)- print(f"\nCleaned HTML saved to: {cleaned_file}")-- def test_main_content_extraction(self):- test_html = """+ result = cleanup_html(test_html)+ cleaned_html = result['html']++ # Parse the cleaned HTML for testing+ soup = BeautifulSoup(cleaned_html, 'html.parser')++ # Test that script and style are removed+ self.assertEqual(len(soup.find_all('script')), 0)+ self.assertEqual(len(soup.find_all('style')), 0)++ # Test that hidden elements are removed+ self.assertEqual(len(soup.find_all(attrs={'class': 'hidden'})), 0)+ self.assertEqual(len(soup.find_all(attrs={'style': 'display: none'})), 0)+ self.assertEqual(len(soup.find_all(attrs={'aria-hidden': 'true'})), 0)++ # Test that interactive elements have 'c' attribute+ interactive_elements = soup.find_all(attrs={'c': True})+ self.assertGreater(len(interactive_elements), 0)++ # Test specific interactive elements+ self.assertIsNotNone(soup.find('button'))+ self.assertIsNotNone(soup.find('a'))+ self.assertIsNotNone(soup.find('input'))+ self.assertIsNotNone(soup.find('select'))++ # Print cleaned HTML for inspection+ print('\nCleaned HTML:')+ print(cleaned_html)++ def test_cleanup_real_page(self):+ # Load a real webpage HTML file+ test_file = os.path.join(self.test_dir, 'kayak_page.html')++ # First run: download and save the page if it doesn't exist+ if not os.path.exists(test_file):+ import requests++ response = requests.get('https://www.kayak.ch')+ with open(test_file, 'w', encoding='utf-8') as f:+ f.write(response.text)++ # Read the test file+ with open(test_file, 'r', encoding='utf-8') as f:+ html_content = f.read()++ # Clean up the HTML+ result = cleanup_html(html_content)+ cleaned_html = result['html']++ # Parse the cleaned HTML+ soup = BeautifulSoup(cleaned_html, 'html.parser')++ # Test basic cleanup+ self.assertEqual(len(soup.find_all('script')), 0)+ self.assertEqual(len(soup.find_all('style')), 0)++ # Test interactive elements+ interactive_elements = soup.find_all(attrs={'c': True})+ self.assertGreater(len(interactive_elements), 0)++ # Print statistics+ print('\nReal page cleanup statistics:')+ print(f'Total interactive elements found: {len(interactive_elements)}')+ print(f"Buttons: {len(soup.find_all('button'))}")+ print(f"Links: {len(soup.find_all('a'))}")+ print(f"Inputs: {len(soup.find_all('input'))}")+ print(f"Selects: {len(soup.find_all('select'))}")++ # Save cleaned HTML for manual inspection+ cleaned_file = os.path.join(self.test_dir, 'kayak_page_cleaned.html')+ with open(cleaned_file, 'w', encoding='utf-8') as f:+ f.write(cleaned_html)+ print(f'\nCleaned HTML saved to: {cleaned_file}')++ def test_main_content_extraction(self):+ test_html = """<html><body><header>Header content</header>@@ -124,15 +125,15 @@ class TestHTMLCleanup(unittest.TestCase):</html>"""- result = cleanup_html(test_html)- main_content = result["main_content"]+ result = cleanup_html(test_html)+ main_content = result['main_content']- self.assertIn("Main Title", main_content)- self.assertIn("Main content paragraph", main_content)- self.assertIn("Important content", main_content)- self.assertNotIn("Header content", main_content)- self.assertNotIn("Footer content", main_content)+ self.assertIn('Main Title', main_content)+ self.assertIn('Main content paragraph', main_content)+ self.assertIn('Important content', main_content)+ self.assertNotIn('Header content', main_content)+ self.assertNotIn('Footer content', main_content)if __name__ == '__main__':- unittest.main()+ unittest.main()diff --git a/src/tests/test_kayak_search.py b/src/tests/test_kayak_search.pyindex 9fe883445..6f1b4ada3 100644--- a/src/tests/test_kayak_search.py+++ b/src/tests/test_kayak_search.py@@ -8,47 +8,47 @@ from src.agent_interface.planing_agent import PlaningAgentclass TestKayakSearch(unittest.TestCase):- def setUp(self):- self.driver = setup_selenium_driver(headless=False)- self.actions = BrowserActions(self.driver)- self.state_manager = StateManager(self.driver)+ def setUp(self):+ self.driver = setup_selenium_driver(headless=False)+ self.actions = BrowserActions(self.driver)+ self.state_manager = StateManager(self.driver)- def tearDown(self):- self.driver.quit()+ def tearDown(self):+ self.driver.quit()- def test_kayak_flight_search(self):- # Define the task- task = "Go to directly to the url https://www.kayak.ch/ and look there for flights from Zurich to New York for Nov 5th, 2024 for 2 people"+ def test_kayak_flight_search(self):+ # Define the task+ task = 'Go to directly to the url https://www.kayak.ch/ and look there for flights from Zurich to New York for Nov 5th, 2024 for 2 people'- default_actions = self.actions.get_default_actions()- print(f"Default actions: {default_actions}")+ default_actions = self.actions.get_default_actions()+ print(f'Default actions: {default_actions}')- agent = PlaningAgent(task, default_actions)+ agent = PlaningAgent(task, default_actions)- # Main interaction loop- max_steps = 10- for i in range(max_steps):- # Get current state- input("\n\n\nPress Enter to continue...")+ # Main interaction loop+ max_steps = 10+ for i in range(max_steps):+ # Get current state+ input('\n\n\nPress Enter to continue...')- current_state = self.state_manager.get_current_state()- save_formatted_html(current_state["interactable_elements"], f"current_state_{i}.html")- # save_markdown(current_state["main_content"], f"current_state_{i}.md")- # Get next action from agent- text = f"Current state: {current_state}"- print(f"\n{text}\n")+ current_state = self.state_manager.get_current_state()+ save_formatted_html(current_state['interactable_elements'], f'current_state_{i}.html')+ # save_markdown(current_state["main_content"], f"current_state_{i}.md")+ # Get next action from agent+ text = f'Current state: {current_state}'+ print(f'\n{text}\n')- action = agent.chat(text)- print(f"Selected action: {action}")+ action = agent.chat(text)+ print(f'Selected action: {action}')- out = self.actions.execute_action(action)- if out:- print("Task completed")- break+ out = self.actions.execute_action(action)+ if out:+ print('Task completed')+ break- else:- self.fail("Failed to complete flight search task in maximum steps")+ else:+ self.fail('Failed to complete flight search task in maximum steps')if __name__ == '__main__':- unittest.main()+ unittest.main()diff --git a/src/utils/selenium_utils.py b/src/utils/selenium_utils.pyindex b45b46723..b5312a06e 100644--- a/src/utils/selenium_utils.py+++ b/src/utils/selenium_utils.py@@ -8,103 +8,100 @@ from selenium.webdriver.common.by import Bydef setup_selenium_driver(headless: bool = False) -> webdriver.Chrome:- """- Sets up and returns a Selenium WebDriver instance.+ """+ Sets up and returns a Selenium WebDriver instance.- Args:- headless (bool): Whether to run browser in headless mode+ Args:+ headless (bool): Whether to run browser in headless mode- Returns:- webdriver.Chrome: Configured Chrome WebDriver instance- """- # Configure Chrome options- chrome_options = Options()- if headless:- chrome_options.add_argument("--headless")+ Returns:+ webdriver.Chrome: Configured Chrome WebDriver instance+ """+ # Configure Chrome options+ chrome_options = Options()+ if headless:+ chrome_options.add_argument('--headless')- # Disable automation flags- chrome_options.add_argument('--disable-blink-features=AutomationControlled')- chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])- chrome_options.add_experimental_option('useAutomationExtension', False)+ # Disable automation flags+ chrome_options.add_argument('--disable-blink-features=AutomationControlled')+ chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])+ chrome_options.add_experimental_option('useAutomationExtension', False)- # Initialize the Chrome driver- driver = webdriver.Chrome(- service=Service(ChromeDriverManager().install()),- options=chrome_options- )+ # Initialize the Chrome driver+ driver = webdriver.Chrome(+ service=Service(ChromeDriverManager().install()), options=chrome_options+ )- # Add cookie acceptance function- def accept_cookies(driver):- """- More robust cookie acceptance function that tries multiple approaches- """- try:- # Common cookie accept button selectors- cookie_selectors = [- "button[id*='cookie-accept']",- "button[id*='accept-cookie']",- "button[class*='cookie-accept']",- "button[class*='accept-cookie']",- "[aria-label*='accept' i][role='button']",- "[aria-label*='cookie' i][role='button']",- "button:contains('Accept')",- "button:contains('Akzeptieren')",- "button:contains('Zustimmen')",- "button:contains('Alle akzeptieren')",- "#onetrust-accept-btn-handler",- "#accept-all-cookies",- ".accept-cookies",- ".accept-all-cookies"- ]+ # Add cookie acceptance function+ def accept_cookies(driver):+ """+ More robust cookie acceptance function that tries multiple approaches+ """+ try:+ # Common cookie accept button selectors+ cookie_selectors = [+ "button[id*='cookie-accept']",+ "button[id*='accept-cookie']",+ "button[class*='cookie-accept']",+ "button[class*='accept-cookie']",+ "[aria-label*='accept' i][role='button']",+ "[aria-label*='cookie' i][role='button']",+ "button:contains('Accept')",+ "button:contains('Akzeptieren')",+ "button:contains('Zustimmen')",+ "button:contains('Alle akzeptieren')",+ '#onetrust-accept-btn-handler',+ '#accept-all-cookies',+ '.accept-cookies',+ '.accept-all-cookies',+ ]- wait = WebDriverWait(driver, 10)+ wait = WebDriverWait(driver, 10)- # Try each selector- for selector in cookie_selectors:- try:- # Try to find element by CSS selector- cookie_button = wait.until(- EC.element_to_be_clickable((By.CSS_SELECTOR, selector))- )- cookie_button.click()- return True- except:- try:- # Try to find element by XPath containing text- xpath = f"//*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '{selector.lower()}')]"- cookie_button = wait.until(- EC.element_to_be_clickable((By.XPATH, xpath))- )- cookie_button.click()- return True- except:- continue+ # Try each selector+ for selector in cookie_selectors:+ try:+ # Try to find element by CSS selector+ cookie_button = wait.until(+ EC.element_to_be_clickable((By.CSS_SELECTOR, selector))+ )+ cookie_button.click()+ return True+ except:+ try:+ # Try to find element by XPath containing text+ xpath = f"//*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '{selector.lower()}')]"+ cookie_button = wait.until(EC.element_to_be_clickable((By.XPATH, xpath)))+ cookie_button.click()+ return True+ except:+ continue- # Try finding iframe with cookie consent- iframes = driver.find_elements(By.TAG_NAME, "iframe")- for iframe in iframes:- try:- driver.switch_to.frame(iframe)- for selector in cookie_selectors:- try:- cookie_button = wait.until(- EC.element_to_be_clickable((By.CSS_SELECTOR, selector))- )- cookie_button.click()- driver.switch_to.default_content()- return True- except:- continue- driver.switch_to.default_content()- except:- driver.switch_to.default_content()- continue+ # Try finding iframe with cookie consent+ iframes = driver.find_elements(By.TAG_NAME, 'iframe')+ for iframe in iframes:+ try:+ driver.switch_to.frame(iframe)+ for selector in cookie_selectors:+ try:+ cookie_button = wait.until(+ EC.element_to_be_clickable((By.CSS_SELECTOR, selector))+ )+ cookie_button.click()+ driver.switch_to.default_content()+ return True+ except:+ continue+ driver.switch_to.default_content()+ except:+ driver.switch_to.default_content()+ continue- except Exception as e:- print(f"Error accepting cookies: {str(e)}")- return False+ except Exception as e:+ print(f'Error accepting cookies: {str(e)}')+ return False- # Attach the function to the driver instance- driver.accept_cookies = lambda: accept_cookies(driver)+ # Attach the function to the driver instance+ driver.accept_cookies = lambda: accept_cookies(driver)- return driver+ return driver