Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

Refactor and Merge branch 'master' of https://github.com/Significant-Gravitas/Auto-GPT into pr/96

BillSchumacherf2035231e3a4
diff --cc autogpt/commands/web_playwright.py
index 0000000000,0000000000..2b0118d248
new file mode 100644
--- /dev/null
+++ b/autogpt/commands/web_playwright.py
@@@ -1,0 -1,0 +1,76 @@@
++"""Web scraping commands using Playwright"""
++try:
++ from playwright.sync_api import sync_playwright
++except ImportError:
++ print("Playwright not installed. Please install it with 'pip install playwright' to use.")
++from bs4 import BeautifulSoup
++from autogpt.processing.html import extract_hyperlinks, format_hyperlinks
++from typing import List, Union
++
++
++def scrape_text(url: str) -> str:
++ """Scrape text from a webpage
++
++ Args:
++ url (str): The URL to scrape text from
++
++ Returns:
++ str: The scraped text
++ """
++ with sync_playwright() as p:
++ browser = p.chromium.launch()
++ page = browser.new_page()
++
++ try:
++ page.goto(url)
++ html_content = page.content()
++ soup = BeautifulSoup(html_content, "html.parser")
++
++ for script in soup(["script", "style"]):
++ script.extract()
++
++ text = soup.get_text()
++ lines = (line.strip() for line in text.splitlines())
++ chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
++ text = '\n'.join(chunk for chunk in chunks if chunk)
++
++ except Exception as e:
++ text = f"Error: {str(e)}"
++
++ finally:
++ browser.close()
++
++ return text
++
++
++def scrape_links(url: str) -> Union[str, List[str]]:
++ """Scrape links from a webpage
++
++ Args:
++ url (str): The URL to scrape links from
++
++ Returns:
++ Union[str, List[str]]: The scraped links
++ """
++ with sync_playwright() as p:
++ browser = p.chromium.launch()
++ page = browser.new_page()
++
++ try:
++ page.goto(url)
++ html_content = page.content()
++ soup = BeautifulSoup(html_content, "html.parser")
++
++ for script in soup(["script", "style"]):
++ script.extract()
++
++ hyperlinks = extract_hyperlinks(soup, url)
++ formatted_links = format_hyperlinks(hyperlinks)
++
++ except Exception as e:
++ formatted_links = f"Error: {str(e)}"
++
++ finally:
++ browser.close()
++
++ return formatted_links
diff --cc autogpt/commands/web_requests.py
index 0000000000,051cc710fc..a6161ec57d
mode 000000,100644..100644
--- a/autogpt/commands/web_requests.py
+++ b/autogpt/commands/web_requests.py
@@@ -1,0 -1,200 +1,170 @@@
+ """Browse a webpage and summarize it using the LLM model"""
+ from typing import List, Tuple, Union
+ from urllib.parse import urljoin, urlparse
+
+ import requests
+ from requests.compat import urljoin
+ from requests import Response
+ from bs4 import BeautifulSoup
+
+ from autogpt.config import Config
+ from autogpt.memory import get_memory
++from autogpt.processing.html import extract_hyperlinks, format_hyperlinks
+
+ CFG = Config()
+ memory = get_memory(CFG)
+
+ session = requests.Session()
+ session.headers.update({"User-Agent": CFG.user_agent})
+
+
+ def is_valid_url(url: str) -> bool:
+ """Check if the URL is valid
+
+ Args:
+ url (str): The URL to check
+
+ Returns:
+ bool: True if the URL is valid, False otherwise
+ """
+ try:
+ result = urlparse(url)
+ return all([result.scheme, result.netloc])
+ except ValueError:
+ return False
+
+
+ def sanitize_url(url: str) -> str:
+ """Sanitize the URL
+
+ Args:
+ url (str): The URL to sanitize
+
+ Returns:
+ str: The sanitized URL
+ """
+ return urljoin(url, urlparse(url).path)
+
+
+ def check_local_file_access(url: str) -> bool:
+ """Check if the URL is a local file
+
+ Args:
+ url (str): The URL to check
+
+ Returns:
+ bool: True if the URL is a local file, False otherwise
+ """
+ local_prefixes = [
+ "file:///",
+ "file://localhost",
+ "http://localhost",
+ "https://localhost",
+ ]
+ return any(url.startswith(prefix) for prefix in local_prefixes)
+
+
+ def get_response(
+ url: str, timeout: int = 10
+ ) -> Union[Tuple[None, str], Tuple[Response, None]]:
+ """Get the response from a URL
+
+ Args:
+ url (str): The URL to get the response from
+ timeout (int): The timeout for the HTTP request
+
+ Returns:
+ Tuple[None, str] | Tuple[Response, None]: The response and error message
+
+ Raises:
+ ValueError: If the URL is invalid
+ requests.exceptions.RequestException: If the HTTP request fails
+ """
+ try:
+ # Restrict access to local files
+ if check_local_file_access(url):
+ raise ValueError("Access to local files is restricted")
+
+ # Most basic check if the URL is valid:
+ if not url.startswith("http://") and not url.startswith("https://"):
+ raise ValueError("Invalid URL format")
+
+ sanitized_url = sanitize_url(url)
+
+ response = session.get(sanitized_url, timeout=timeout)
+
+ # Check if the response contains an HTTP error
+ if response.status_code >= 400:
+ return None, f"Error: HTTP {str(response.status_code)} error"
+
+ return response, None
+ except ValueError as ve:
+ # Handle invalid URL format
+ return None, f"Error: {str(ve)}"
+
+ except requests.exceptions.RequestException as re:
+ # Handle exceptions related to the HTTP request
+ # (e.g., connection errors, timeouts, etc.)
+ return None, f"Error: {str(re)}"
+
+
+ def scrape_text(url: str) -> str:
+ """Scrape text from a webpage
+
+ Args:
+ url (str): The URL to scrape text from
+
+ Returns:
+ str: The scraped text
+ """
+ response, error_message = get_response(url)
+ if error_message:
+ return error_message
+ if not response:
+ return "Error: Could not get response"
+
+ soup = BeautifulSoup(response.text, "html.parser")
+
+ for script in soup(["script", "style"]):
+ script.extract()
+
+ text = soup.get_text()
+ lines = (line.strip() for line in text.splitlines())
+ chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
+ text = "\n".join(chunk for chunk in chunks if chunk)
+
+ return text
+
+
-def extract_hyperlinks(soup: BeautifulSoup, base_url: str) -> List[Tuple[str, str]]:
- """Extract hyperlinks from a BeautifulSoup object
-
- Args:
- soup (BeautifulSoup): The BeautifulSoup object
- base_url (str): The base URL
-
- Returns:
- List[Tuple[str, str]]: The extracted hyperlinks
- """
- return [
- (link.text, urljoin(base_url, link["href"]))
- for link in soup.find_all("a", href=True)
- ]
-
-
-def format_hyperlinks(hyperlinks: List[Tuple[str, str]]) -> List[str]:
- """Format hyperlinks into a list of strings
-
- Args:
- hyperlinks (List[Tuple[str, str]]): The hyperlinks to format
-
- Returns:
- List[str]: The formatted hyperlinks
- """
- formatted_links = []
- for link_text, link_url in hyperlinks:
- formatted_links.append(f"{link_text} ({link_url})")
- return formatted_links
-
-
+ def scrape_links(url: str) -> Union[str, List[str]]:
+ """Scrape links from a webpage
+
+ Args:
+ url (str): The URL to scrape links from
+
+ Returns:
+ Union[str, List[str]]: The scraped links
+ """
+ response, error_message = get_response(url)
+ if error_message:
+ return error_message
+ if not response:
+ return "Error: Could not get response"
+ soup = BeautifulSoup(response.text, "html.parser")
+
+ for script in soup(["script", "style"]):
+ script.extract()
+
+ hyperlinks = extract_hyperlinks(soup, url)
+
+ return format_hyperlinks(hyperlinks)
+
+
+ def create_message(chunk, question):
+ """Create a message for the user to summarize a chunk of text"""
+ return {
+ "role": "user",
+ "content": f'"""{chunk}""" Using the above text, answer the following'
+ f' question: "{question}" -- if the question cannot be answered using the'
+ " text, summarize the text.",
+ }
diff --cc autogpt/commands/web_selenium.py
index 0000000000,d2ef1a7e08..359803eed3
mode 000000,100644..100644
--- a/autogpt/commands/web_selenium.py
+++ b/autogpt/commands/web_selenium.py
@@@ -1,0 -1,164 +1,141 @@@
+ """Selenium web scraping module."""
+ from selenium import webdriver
++from autogpt.processing.html import extract_hyperlinks, format_hyperlinks
+ import autogpt.processing.text as summary
+ from bs4 import BeautifulSoup
+ from selenium.webdriver.remote.webdriver import WebDriver
+ from selenium.webdriver.common.by import By
+ from selenium.webdriver.support.wait import WebDriverWait
+ from selenium.webdriver.support import expected_conditions as EC
+ from webdriver_manager.chrome import ChromeDriverManager
+ from webdriver_manager.firefox import GeckoDriverManager
+ from selenium.webdriver.chrome.options import Options as ChromeOptions
+ from selenium.webdriver.firefox.options import Options as FirefoxOptions
+ from selenium.webdriver.safari.options import Options as SafariOptions
+ import logging
+ from pathlib import Path
+ from autogpt.config import Config
+ from typing import List, Tuple, Union
+
+ FILE_DIR = Path(__file__).parent.parent
+ CFG = Config()
+
+
+ def browse_website(url: str, question: str) -> Tuple[str, WebDriver]:
+ """Browse a website and return the answer and links to the user
+
+ Args:
+ url (str): The url of the website to browse
+ question (str): The question asked by the user
+
+ Returns:
+ Tuple[str, WebDriver]: The answer and links to the user and the webdriver
+ """
+ driver, text = scrape_text_with_selenium(url)
+ add_header(driver)
+ summary_text = summary.summarize_text(url, text, question, driver)
- links = scrape_links_with_selenium(driver)
++ links = scrape_links_with_selenium(driver, url)
+
+ # Limit links to 5
+ if len(links) > 5:
+ links = links[:5]
+ close_browser(driver)
+ return f"Answer gathered from website: {summary_text} \n \n Links: {links}", driver
+
+
+ def scrape_text_with_selenium(url: str) -> Tuple[WebDriver, str]:
+ """Scrape text from a website using selenium
+
+ Args:
+ url (str): The url of the website to scrape
+
+ Returns:
+ Tuple[WebDriver, str]: The webdriver and the text scraped from the website
+ """
+ logging.getLogger("selenium").setLevel(logging.CRITICAL)
+
+ options_available = {
+ "chrome": ChromeOptions,
+ "safari": SafariOptions,
+ "firefox": FirefoxOptions,
+ }
+
+ options = options_available[CFG.selenium_web_browser]()
+ options.add_argument(
+ "user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.5615.49 Safari/537.36"
+ )
+
+ if CFG.selenium_web_browser == "firefox":
+ driver = webdriver.Firefox(
+ executable_path=GeckoDriverManager().install(), options=options
+ )
+ elif CFG.selenium_web_browser == "safari":
+ # Requires a bit more setup on the users end
+ # See https://developer.apple.com/documentation/webkit/testing_with_webdriver_in_safari
+ driver = webdriver.Safari(options=options)
+ else:
+ driver = webdriver.Chrome(
+ executable_path=ChromeDriverManager().install(), options=options
+ )
+ driver.get(url)
+
+ WebDriverWait(driver, 10).until(
+ EC.presence_of_element_located((By.TAG_NAME, "body"))
+ )
+
+ # Get the HTML content directly from the browser's DOM
+ page_source = driver.execute_script("return document.body.outerHTML;")
+ soup = BeautifulSoup(page_source, "html.parser")
+
+ for script in soup(["script", "style"]):
+ script.extract()
+
+ text = soup.get_text()
+ lines = (line.strip() for line in text.splitlines())
+ chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
+ text = "\n".join(chunk for chunk in chunks if chunk)
+ return driver, text
+
+
-def scrape_links_with_selenium(driver: WebDriver) -> List[str]:
++def scrape_links_with_selenium(driver: WebDriver, url: str) -> List[str]:
+ """Scrape links from a website using selenium
+
+ Args:
+ driver (WebDriver): The webdriver to use to scrape the links
+
+ Returns:
+ List[str]: The links scraped from the website
+ """
+ page_source = driver.page_source
+ soup = BeautifulSoup(page_source, "html.parser")
+
+ for script in soup(["script", "style"]):
+ script.extract()
+
- hyperlinks = extract_hyperlinks(soup)
++ hyperlinks = extract_hyperlinks(soup, url)
+
+ return format_hyperlinks(hyperlinks)
+
+
+ def close_browser(driver: WebDriver) -> None:
+ """Close the browser
+
+ Args:
+ driver (WebDriver): The webdriver to close
+
+ Returns:
+ None
+ """
+ driver.quit()
+
+
-def extract_hyperlinks(soup: BeautifulSoup) -> List[Tuple[str, str]]:
- """Extract hyperlinks from a BeautifulSoup object
-
- Args:
- soup (BeautifulSoup): The BeautifulSoup object to extract the hyperlinks from
-
- Returns:
- List[Tuple[str, str]]: The hyperlinks extracted from the BeautifulSoup object
- """
- return [(link.text, link["href"]) for link in soup.find_all("a", href=True)]
-
-
-def format_hyperlinks(hyperlinks: List[Tuple[str, str]]) -> List[str]:
- """Format hyperlinks to be displayed to the user
-
- Args:
- hyperlinks (List[Tuple[str, str]]): The hyperlinks to format
-
- Returns:
- List[str]: The formatted hyperlinks
- """
- return [f"{link_text} ({link_url})" for link_text, link_url in hyperlinks]
-
-
+ def add_header(driver: WebDriver) -> None:
+ """Add a header to the website
+
+ Args:
+ driver (WebDriver): The webdriver to use to add the header
+
+ Returns:
+ None
+ """
+ driver.execute_script(open(f"{FILE_DIR}/js/overlay.js", "r").read())
diff --cc autogpt/processing/html.py
index 0000000000,0000000000..c43a0b74e8
new file mode 100644
--- /dev/null
+++ b/autogpt/processing/html.py
@@@ -1,0 -1,0 +1,32 @@@
++"""HTML processing functions"""
++from requests.compat import urljoin
++from typing import List, Tuple
++from bs4 import BeautifulSoup
++
++
++def extract_hyperlinks(soup: BeautifulSoup, base_url: str) -> List[Tuple[str, str]]:
++ """Extract hyperlinks from a BeautifulSoup object
++
++ Args:
++ soup (BeautifulSoup): The BeautifulSoup object
++ base_url (str): The base URL
++
++ Returns:
++ List[Tuple[str, str]]: The extracted hyperlinks
++ """
++ return [
++ (link.text, urljoin(base_url, link["href"]))
++ for link in soup.find_all("a", href=True)
++ ]
++
++
++def format_hyperlinks(hyperlinks: List[Tuple[str, str]]) -> List[str]:
++ """Format hyperlinks to be displayed to the user
++
++ Args:
++ hyperlinks (List[Tuple[str, str]]): The hyperlinks to format
++
++ Returns:
++ List[str]: The formatted hyperlinks
++ """
++ return [f"{link_text} ({link_url})" for link_text, link_url in hyperlinks]