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
first repo
Gregor Žuničeeb91764d18f
diff --git a/.gitignore b/.gitignorenew file mode 100644index 000000000..d4de66df5--- /dev/null+++ b/.gitignore@@ -0,0 +1,163 @@+# Byte-compiled / optimized / DLL files+__pycache__/+*.py[cod]+*$py.class++# C extensions+*.so++# Distribution / packaging+.Python+build/+develop-eggs/+dist/+downloads/+eggs/+.eggs/+lib/+lib64/+parts/+sdist/+var/+wheels/+share/python-wheels/+*.egg-info/+.installed.cfg+*.egg+MANIFEST++# PyInstaller+# Usually these files are written by a python script from a template+# before PyInstaller builds the exe, so as to inject date/other infos into it.+*.manifest+*.spec++# Installer logs+pip-log.txt+pip-delete-this-directory.txt++# Unit test / coverage reports+htmlcov/+.tox/+.nox/+.coverage+.coverage.*+.cache+nosetests.xml+coverage.xml+*.cover+*.py,cover+.hypothesis/+.pytest_cache/+cover/++# Translations+*.mo+*.pot++# Django stuff:+*.log+local_settings.py+db.sqlite3+db.sqlite3-journal++# Flask stuff:+instance/+.webassets-cache++# Scrapy stuff:+.scrapy++# Sphinx documentation+docs/_build/++# PyBuilder+.pybuilder/+target/++# Jupyter Notebook+.ipynb_checkpoints++# IPython+profile_default/+ipython_config.py++# pyenv+# For a library or package, you might want to ignore these files since the code is+# intended to run in multiple environments; otherwise, check them in:+# .python-version++# pipenv+# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.+# However, in case of collaboration, if having platform-specific dependencies or dependencies+# having no cross-platform support, pipenv may install dependencies that don't work, or not+# install all needed dependencies.+#Pipfile.lock++# poetry+# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.+# This is especially recommended for binary packages to ensure reproducibility, and is more+# commonly ignored for libraries.+# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control+#poetry.lock++# pdm+# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.+#pdm.lock+# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it+# in version control.+# https://pdm.fming.dev/latest/usage/project/#working-with-version-control+.pdm.toml+.pdm-python+.pdm-build/++# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm+__pypackages__/++# Celery stuff+celerybeat-schedule+celerybeat.pid++# SageMath parsed files+*.sage.py++# Environments+.env+.venv+env/+venv/+ENV/+env.bak/+venv.bak/++# Spyder project settings+.spyderproject+.spyproject++# Rope project settings+.ropeproject++# mkdocs documentation+/site++# mypy+.mypy_cache/+.dmypy.json+dmypy.json++# Pyre type checker+.pyre/++# pytype static type analyzer+.pytype/++# Cython debug symbols+cython_debug/++# PyCharm+# JetBrains specific template is maintained in a separate JetBrains.gitignore that can+# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore+# and can be added to the global gitignore or merged into this file. For a more nuclear+# option (not recommended) you can uncomment the following to ignore the entire idea folder.+#.idea/+temp\ No newline at end of filediff --git a/.python-version b/.python-versionnew file mode 100644index 000000000..902b2c90c--- /dev/null+++ b/.python-version@@ -0,0 +1 @@+3.11\ No newline at end of filediff --git a/README.md b/README.mdnew file mode 100644index 000000000..cb2432d4f--- /dev/null+++ b/README.md@@ -0,0 +1,3 @@+# Interfaces for agents++This repository contains the interfaces for agents.diff --git a/agents.ipynb b/agents.ipynbnew file mode 100644index 000000000..16715efc3--- /dev/null+++ b/agents.ipynb@@ -0,0 +1,188 @@+{+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "# Agent prompt\n",+ "\n",+ "```\n",+ "You are web scraping agent. Your task is control the browser where for every step you get the current state and a list of actions you can take.\n",+ "\n",+ "Your task is:\n",+ "Apply for 50 jobs for software engineering in Zurich.\n",+ "\n",+ "Extra context:\n",+ "`\n",+ "Gregor Žunič\n",+ "gregorzunic.com\n",+ "[email protected]\n",+ "github.com/gregpr07\n",+ "linkedin.com/in/gregorzunic\n",+ "EDUCATION\n",+ "ETH Zurich 2022-2026\n",+ "MSc Data Science\n",+ "• First place in Advanced Machine Learning projects\n",+ "University of Ljubljana, Faculty of Mathematics and Physics BSc Physics\n",+ "• Bachelor thesis: GANs in particle physics\n",+ "INDUSTRY\n",+ "2019-2022\n",+ "Spexia.ai 2023-2024\n",+ "Founder\n",+ "• The Easiest Way to Boost Your Organic Traffic\n",+ "Internal Discovery Platform 2023-2023\n",+ "Founder\n",+ "• Find what your company knows with RAG. Instantly.\n",+ "• Didn’t find product market fit\n",+ "Real Fake Photos 2023-2024\n",+ "Founder\n",+ "• Turn your selfies into professional headshots with AI\n",+ "• Built the app from 0 to 70k+ users\n",+ "• Heavy ML to improve stable diffusion\n",+ "Profaile GmbH 2023-2024\n",+ "Founder and CTO\n",+ "• Software and ML Consulting\n",+ "Flare Network 2022-2023\n",+ "Blockchain and Senior Fullstack Developer\n",+ "• Senior frontend and backend developer role.\n",+ "Idoru.capital 2021-2022\n",+ "Tech Lead\n",+ "• Idoru capital is the first crypto asset backed by Real World Assets\n",+ "Strader.io 2021-2021\n",+ "Co-Founder\n",+ "• DeFi/crypto startup for trading strategies\n",+ "Videolectures.NET (JSI Project) 2019-2021\n",+ "Tech Lead\n",+ "• Implemented the new Backend and Website and the Mobile App; apps have 20k users\n",+ "X5GON (JSI Project) 2018-2020\n",+ "ML Researcher & Fullstack developer\n",+ "• EU Horizon2020 project for connecting and analyzing OER resources from multiple repositories;\n",+ "led by Prof. John Shawe-Taylor\n",+ "• Started by collecting data from OER repositories which were analyzed and used to create a state-\n",+ "of-the-art cross-site recommendation system\n",+ "• X5GON Blind Backend and Frontend; sub-project focused on enhancing the learning experience\n",+ "of blind and partially blind people by providing a simplified interface and highly personalized\n",+ "recommendation engine\n",+ "• X5GON Platform and X5GON Blind website; project’s presentation website\n",+ "• X5GON Discovery website; UI for the state-of-the-art cross-site recommendation engine\n",+ "RESEARCH\n",+ "American Slovenian Education Foundation 2021-2023\n",+ "Junior Fellow\n",+ "University of California, Berkeley 07.2021-10.2021\n",+ "Student intern and ASEF fellow under the supervision of Prof. Dawn Song Remote\n",+ "• Cryptocurrency research; Researching EVM cross-chain empirical measurements focused on MEV\n",+ "• Model heuristics for detecting on-chain MEV\n",+ "Jožef Stefan Institute 06.2018-06.2022\n",+ "Student ML Researcher under the supervision of Prof. Dunja Mladenić Ljubljana, Slovenia\n",+ "• Machine Learning research; focused on Natural Language Processing with Transformers\n",+ "• Winner of Innovation IT&ML Hackaton; organized and hosted by Slovenian Post Office\n",+ "• Participated in AI for the Common Good F’AI’R Education Hackathon by British Embassy in Paris\n",+ "• Participated in X5GON hackathon on Open Education and AI; organized by X5gon, hosted at UCL\n",+ "• Reciever of JSI excellence scholarship\n",+ "PUBLICATIONS\n",+ "Žunič Gregor, Novak Erik. Hierarchical classification of educational resources. Data Mining and\n",+ "Data Warehouses - SiKDD, 5 October 2020.\n",+ "OTHER SKILLS\n",+ "KK Ježica 2018-present\n",+ "Semi-Professional Basketball Player Ljubljana, Slovenia\n",+ "• 5-th best scorer in University Basketball League (season 2019/2020)\n",+ "Helios Suns 2015-2018\n",+ "Semi-Professional Basketball Player Domžale, Slovenia\n",+ "General\n",+ "• Language Skills Slovene (mother tongue), English (C1 TOEFL: 107), French (A2), German (A1)\n",+ "• Guitar enthusiast (8 years primary school), Chess (participated in 2 youth world championships)\n",+ "`\n",+ "\n",+ "In every step, please only control the web browser with actions.\n",+ "Actions can also give you back follow up questions about the state of the website if your instructions are ambigous.\n",+ "```"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## State prompt\n",+ "\n",+ "```json\n",+ "{\n",+ " state: {\n",+ " \"current_url\": undefined,\n",+ " },\n",+ " actions: [\n",+ " {\n",+ " \"type\": \"search_google\",\n",+ " \"params\": {\n",+ " \"query\": \"string\"\n",+ " }\n",+ " },\n",+ " {\n",+ " \"type\": \"go_to_url\",\n",+ " \"params\": {\n",+ " \"url\": \"string\"\n",+ " }\n",+ " }\n",+ " ]\n",+ "}\n",+ "```"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "{\n",+ " \"type\": \"search_google\",\n",+ " \"params\": {\n",+ " \"query\": \"software engineering jobs in Zurich\"\n",+ " }\n",+ "}"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "..."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "{\n",+ " state: {\n",+ " \"current_url\": undefined,\n",+ " },\n",+ " actions: [\n",+ " {\n",+ " \"type\": \"search_google\",\n",+ " \"params\": {\n",+ " \"query\": \"string\"\n",+ " }\n",+ " },\n",+ " {\n",+ " \"type\": \"go_to_url\",\n",+ " \"params\": {\n",+ " \"url\": \"string\"\n",+ " }\n",+ " }\n",+ " ]\n",+ "}\n"+ ]+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": ".venv",+ "language": "python",+ "name": "python3"+ },+ "language_info": {+ "name": "python",+ "version": "3.11.4"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 2+}diff --git a/promps.txt b/promps.txtnew file mode 100644index 000000000..7a86b7f3c--- /dev/null+++ b/promps.txt@@ -0,0 +1,12 @@+You are given a website image and corresponding cleaned up HTML.+Your task is to very accurately describe what you see on the website and give me back the functionality and the options of the functionality.++For example, if you see a search bar and there are filter, I want you to give me back "search function" and parameters "param1, "param2", ...+Also, with each param give me the button/element id/c="" that user should press to activate the functionality (for inputs, dropdowns, etc).+(I engineered cost saving method c=""). Reference each button with css selector by c=++Extract as much functionality as possible to a single function, and group functions together, so that it still makes sense. Make 100% certain that each param has functionality connected to it (instruction on what to press).++Return this format+reasoning: ""+function1:\ No newline at end of filediff --git a/pyproject.toml b/pyproject.tomlnew file mode 100644index 000000000..8888fb0e7--- /dev/null+++ b/pyproject.toml@@ -0,0 +1,7 @@+[project]+name = "agent-interface"+version = "0.1.0"+description = "Testing agent interfaces"+readme = "README.md"+requires-python = ">=3.11"+dependencies = []diff --git a/sample.ipynb b/sample.ipynbnew file mode 100644index 000000000..cdfda441a--- /dev/null+++ b/sample.ipynb@@ -0,0 +1,208 @@+{+ "cells": [+ {+ "cell_type": "code",+ "execution_count": 70,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "The autoreload extension is already loaded. To reload it, use:\n",+ " %reload_ext autoreload\n"+ ]+ }+ ],+ "source": [+ "%load_ext autoreload\n",+ "%autoreload 2"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 19,+ "metadata": {},+ "outputs": [],+ "source": [+ "from selenium import webdriver\n",+ "from selenium.webdriver.chrome.service import Service\n",+ "from selenium.webdriver.chrome.options import Options\n",+ "from webdriver_manager.chrome import ChromeDriverManager\n",+ "\n",+ "# Wait for and click the \"Accept all\" button\n",+ "from selenium.webdriver.common.by import By\n",+ "from selenium.webdriver.support.ui import WebDriverWait\n",+ "from selenium.webdriver.support import expected_conditions as EC\n",+ "\n",+ "\n",+ "# Set up Chrome options\n",+ "chrome_options = Options()\n",+ "# chrome_options.add_argument(\"--headless\") # Run in headless mode (no GUI)\n",+ "\n",+ "\n",+ "# Initialize the Chrome driver\n",+ "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('useAutomationExtension', False)\n",+ "\n",+ "\n",+ "# Navigate to Google Flights\n",+ "# 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",+ "\n",+ "driver.get(url)\n",+ "\n",+ "# Get the page HTML\n",+ "\n",+ "# try:\n",+ "# accept_button = WebDriverWait(driver, 1).until(\n",+ "# EC.element_to_be_clickable((By.XPATH, \"//span[text()='Accept all']\"))\n",+ "# )\n",+ "# accept_button.click()\n",+ "# except:\n",+ "# print(\"No accept button found or already accepted\")\n",+ "\n",+ "\n",+ "# Close the browser\n",+ "# driver.quit()"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 22,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Screenshot saved to: temp/screenshot.png\n"+ ]+ }+ ],+ "source": [+ "# Get the image\n",+ "\n",+ "# Get the HTML content\n",+ "html_content = driver.page_source\n",+ "\n",+ "# Take a screenshot and save it\n",+ "screenshot_path = \"temp/screenshot.png\"\n",+ "driver.save_screenshot(screenshot_path)\n",+ "print(f\"Screenshot saved to: {screenshot_path}\")\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": []+ },+ {+ "cell_type": "code",+ "execution_count": 23,+ "metadata": {},+ "outputs": [],+ "source": [+ "# Format and save HTML content to file\n",+ "from bs4 import BeautifulSoup\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)"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 24,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Pure html cost: $0.20 Tokens: 40,469\n",+ "Cleaned html cost: $0.04 Tokens: 7,727\n"+ ]+ }+ ],+ "source": [+ "from tokencost import calculate_prompt_cost, count_string_tokens\n",+ "from src.cleanup.utils import cleanup_html\n",+ "\n",+ "# Clean up html\n",+ "# print(html_content)\n",+ "html_content\n",+ "\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",+ ")\n",+ "\n",+ "cleaned_html = cleanup_html(html_content)\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",+ ")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": []+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": []+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": ".venv",+ "language": "python",+ "name": "python3"+ },+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3",+ "version": "3.11.4"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 2+}diff --git a/src/cleanup/utils.py b/src/cleanup/utils.pynew file mode 100644index 000000000..b8dff73e4--- /dev/null+++ b/src/cleanup/utils.py@@ -0,0 +1,88 @@+import re+from bs4 import BeautifulSoup, Comment, Tag+++def cleanup_html(html_content):+ """+ Clean up html content by removing unnecessary HTML elements and formatting.++ Args:+ html_content (str): Raw HTML content to clean++ Returns:+ str: Cleaned HTML content+ """+ soup = BeautifulSoup(html_content, "html.parser")++ # Remove comments+ for comment in soup.find_all(string=lambda text: isinstance(text, Comment)):+ comment.extract()++ # Remove unwanted tags completely+ unwanted_tags = ["style", "script", "font", "link", "meta"]+ for tag in unwanted_tags:+ for element in soup.find_all(tag):+ element.decompose()++ # Function to check if a tag only contains another single tag+ def is_wrapper_tag(tag):+ # Check if tag has exactly one child that is a tag+ children = list(tag.children)+ tag_children = [child for child in children if isinstance(child, Tag)]++ return (+ len(tag_children) == 1+ and len(children) == 1+ and not tag.get("id") # Preserve tags with ID+ and not tag.get("class") # Preserve tags with class+ and not tag.string # Ensure there's no direct text content+ )++ # Remove nested wrapper tags+ modified = True+ while modified:+ modified = False+ # Look for just divs and spans+ for tag in soup.find_all(["div", "span"]):+ if is_wrapper_tag(tag):+ tag.replace_with(tag.contents[0])+ modified = True++ # Add counter for class enumeration+ class_counter = 0++ # Remove all attributes except allowed ones+ for tag in soup.find_all(True):+ allowed_attrs = [+ "id",+ "name",+ "aria-label",+ "aria-hidden",+ "href",+ "alt",+ # "class",+ # "data-node-index",+ # "data-p",+ # "class",+ ]+ attrs = dict(tag.attrs)+ for attr in attrs:+ if attr == "class":+ # Replace class with enumerated value+ tag["c"] = str(class_counter)+ class_counter += 1+ del tag[attr]+ elif attr not in allowed_attrs:+ del tag[attr]++ # Get the HTML string+ cleaned_html = str(soup)++ # Remove multiple spaces and newlines+ cleaned_html = " ".join(cleaned_html.split())++ # Remove empty tags+ empty_tags_pattern = r"<[^/>][^>]*></[^>]+>"+ cleaned_html = re.sub(empty_tags_pattern, "", cleaned_html)++ return cleaned_html