├── tests ├── __init__.py ├── context.py ├── browse_tests.py ├── unit │ ├── test_commands.py │ ├── test_browse_scrape_text.py │ ├── test_browse_scrape_links.py │ └── json_tests.py ├── local_cache_test.py ├── integration │ ├── memory_tests.py │ └── milvus_memory_tests.py ├── milvus_memory_test.py ├── test_token_counter.py ├── smoke_test.py ├── test_config.py ├── test_prompt_generator.py └── test_json_parser.py ├── autogpt ├── __init__.py ├── commands │ ├── __init__.py │ ├── times.py │ ├── git_operations.py │ ├── evaluate_code.py │ ├── twitter.py │ ├── improve_code.py │ ├── audio_text.py │ ├── write_tests.py │ ├── web_playwright.py │ ├── google_search.py │ ├── image_gen.py │ ├── execute_code.py │ ├── web_selenium.py │ ├── web_requests.py │ └── file_operations.py ├── json_fixes │ ├── __init__.py │ ├── utilities.py │ ├── missing_quotes.py │ ├── escaping.py │ ├── auto_fix.py │ ├── bracket_termination.py │ └── parsing.py ├── processing │ ├── __init__.py │ ├── html.py │ └── text.py ├── permanent_memory │ ├── __init__.py │ └── sqlite3_store.py ├── agent │ ├── __init__.py │ └── agent_manager.py ├── speech │ ├── __init__.py │ ├── gtts.py │ ├── macos_tts.py │ ├── brian.py │ ├── say.py │ ├── base.py │ └── eleven_labs.py ├── config │ ├── __init__.py │ ├── singleton.py │ └── ai_config.py ├── utils.py ├── js │ └── overlay.js ├── memory │ ├── base.py │ ├── no_memory.py │ ├── __init__.py │ ├── pinecone.py │ ├── milvus.py │ ├── local.py │ └── redismem.py ├── spinner.py ├── __main__.py ├── setup.py ├── token_counter.py ├── data_ingestion.py ├── args.py ├── promptgenerator.py └── llm_utils.py ├── main.py ├── run_continuous.bat ├── .github ├── FUNDING.yml ├── workflows │ ├── auto_format.yml │ └── ci.yml ├── ISSUE_TEMPLATE │ ├── 2.feature.yml │ └── 1.bug.yml └── PULL_REQUEST_TEMPLATE.md ├── docs └── imgs │ └── openai-api-key-billing-paid-account.png ├── .flake8 ├── run.bat ├── pyproject.toml ├── .isort.cfg ├── azure.yaml.template ├── docker-compose.yml ├── requirements-docker.txt ├── tests.py ├── requirements.txt ├── Dockerfile ├── scripts └── check_requirements.py ├── .pre-commit-config.yaml ├── LICENSE ├── .devcontainer ├── devcontainer.json └── Dockerfile ├── .sourcery.yaml ├── CONTRIBUTING.md ├── outputs ├── guest_post_email.txt ├── post1_output.txt ├── how_to_save_money_on_energy_bills.txt └── post2_output.txt ├── .gitignore └── .env.template /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /autogpt/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /autogpt/commands/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /autogpt/json_fixes/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /autogpt/processing/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /autogpt/permanent_memory/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | from autogpt import main 2 | -------------------------------------------------------------------------------- /run_continuous.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | set argument=--continuous 3 | call run.bat %argument% 4 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: Torantulino 4 | -------------------------------------------------------------------------------- /docs/imgs/openai-api-key-billing-paid-account.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jerryjliu/Auto-GPT/HEAD/docs/imgs/openai-api-key-billing-paid-account.png -------------------------------------------------------------------------------- /tests/context.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | sys.path.insert( 5 | 0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../scripts")) 6 | ) 7 | -------------------------------------------------------------------------------- /autogpt/agent/__init__.py: -------------------------------------------------------------------------------- 1 | from autogpt.agent.agent import Agent 2 | from autogpt.agent.agent_manager import AgentManager 3 | 4 | __all__ = ["Agent", "AgentManager"] 5 | -------------------------------------------------------------------------------- /autogpt/speech/__init__.py: -------------------------------------------------------------------------------- 1 | """This module contains the speech recognition and speech synthesis functions.""" 2 | from autogpt.speech.say import say_text 3 | 4 | __all__ = ["say_text"] 5 | -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length = 88 3 | extend-ignore = E203 4 | exclude = 5 | .tox, 6 | __pycache__, 7 | *.pyc, 8 | .env 9 | venv/* 10 | .venv/* 11 | reports/* 12 | dist/* -------------------------------------------------------------------------------- /run.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | python scripts/check_requirements.py requirements.txt 3 | if errorlevel 1 ( 4 | echo Installing missing packages... 5 | pip install -r requirements.txt 6 | ) 7 | python -m autogpt %* 8 | pause 9 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "auto-gpt" 3 | version = "0.1.0" 4 | description = "A GPT based ai agent" 5 | readme = "README.md" 6 | 7 | [tool.black] 8 | line-length = 88 9 | target-version = ['py310'] 10 | include = '\.pyi?$' 11 | extend-exclude = "" -------------------------------------------------------------------------------- /autogpt/commands/times.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | 4 | def get_datetime() -> str: 5 | """Return the current date and time 6 | 7 | Returns: 8 | str: The current date and time 9 | """ 10 | return "Current date and time: " + datetime.now().strftime("%Y-%m-%d %H:%M:%S") 11 | -------------------------------------------------------------------------------- /.isort.cfg: -------------------------------------------------------------------------------- 1 | [settings] 2 | profile = black 3 | multi_line_output = 3 4 | include_trailing_comma = True 5 | force_grid_wrap = 0 6 | use_parentheses = True 7 | ensure_newline_before_comments = True 8 | line_length = 88 9 | skip = venv,env,node_modules,.env,.venv,dist 10 | sections = FUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,LOCALFOLDER -------------------------------------------------------------------------------- /azure.yaml.template: -------------------------------------------------------------------------------- 1 | azure_api_type: azure_ad 2 | azure_api_base: your-base-url-for-azure 3 | azure_api_version: api-version-for-azure 4 | azure_model_map: 5 | fast_llm_model_deployment_id: gpt35-deployment-id-for-azure 6 | smart_llm_model_deployment_id: gpt4-deployment-id-for-azure 7 | embedding_model_deployment_id: embedding-deployment-id-for-azure 8 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | # To boot the app run the following: 2 | # docker-compose run auto-gpt 3 | version: "3.9" 4 | 5 | services: 6 | auto-gpt: 7 | depends_on: 8 | - redis 9 | build: ./ 10 | env_file: 11 | - .env 12 | volumes: 13 | - "./autogpt:/app" 14 | - ".env:/app/.env" 15 | profiles: ["exclude-from-up"] 16 | 17 | redis: 18 | image: "redis/redis-stack-server:latest" 19 | -------------------------------------------------------------------------------- /autogpt/config/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module contains the configuration classes for AutoGPT. 3 | """ 4 | from autogpt.config.ai_config import AIConfig 5 | from autogpt.config.config import check_openai_api_key, Config 6 | from autogpt.config.singleton import AbstractSingleton, Singleton 7 | 8 | __all__ = [ 9 | "check_openai_api_key", 10 | "AbstractSingleton", 11 | "AIConfig", 12 | "Config", 13 | "Singleton", 14 | ] 15 | -------------------------------------------------------------------------------- /requirements-docker.txt: -------------------------------------------------------------------------------- 1 | beautifulsoup4 2 | colorama==0.4.6 3 | openai==0.27.2 4 | playsound==1.2.2 5 | python-dotenv==1.0.0 6 | pyyaml==6.0 7 | readability-lxml==0.8.1 8 | requests 9 | tiktoken==0.3.3 10 | gTTS==2.3.1 11 | docker 12 | duckduckgo-search 13 | google-api-python-client #(https://developers.google.com/custom-search/v1/overview) 14 | pinecone-client==2.2.1 15 | redis 16 | orjson 17 | Pillow 18 | selenium 19 | webdriver-manager 20 | coverage 21 | flake8 22 | numpy 23 | pre-commit 24 | black 25 | isort 26 | -------------------------------------------------------------------------------- /tests.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import coverage 3 | 4 | if __name__ == "__main__": 5 | # Start coverage collection 6 | cov = coverage.Coverage() 7 | cov.start() 8 | 9 | # Load all tests from the 'autogpt/tests' package 10 | suite = unittest.defaultTestLoader.discover("./tests") 11 | 12 | # Run the tests 13 | unittest.TextTestRunner().run(suite) 14 | 15 | # Stop coverage collection 16 | cov.stop() 17 | cov.save() 18 | 19 | # Report the coverage 20 | cov.report(show_missing=True) 21 | -------------------------------------------------------------------------------- /autogpt/speech/gtts.py: -------------------------------------------------------------------------------- 1 | """ GTTS Voice. """ 2 | import os 3 | from playsound import playsound 4 | import gtts 5 | 6 | from autogpt.speech.base import VoiceBase 7 | 8 | 9 | class GTTSVoice(VoiceBase): 10 | """GTTS Voice.""" 11 | 12 | def _setup(self) -> None: 13 | pass 14 | 15 | def _speech(self, text: str, _: int = 0) -> bool: 16 | """Play the given text.""" 17 | tts = gtts.gTTS(text) 18 | tts.save("speech.mp3") 19 | playsound("speech.mp3", True) 20 | os.remove("speech.mp3") 21 | return True 22 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | beautifulsoup4 2 | colorama==0.4.6 3 | openai==0.27.2 4 | playsound==1.2.2 5 | python-dotenv==1.0.0 6 | pyyaml==6.0 7 | readability-lxml==0.8.1 8 | requests 9 | tiktoken==0.3.3 10 | gTTS==2.3.1 11 | docker 12 | duckduckgo-search 13 | google-api-python-client #(https://developers.google.com/custom-search/v1/overview) 14 | pinecone-client==2.2.1 15 | redis 16 | orjson 17 | Pillow 18 | selenium 19 | webdriver-manager 20 | coverage 21 | flake8 22 | numpy 23 | pre-commit 24 | black 25 | sourcery 26 | isort 27 | gitpython==3.1.31 28 | pytest 29 | pytest-mock -------------------------------------------------------------------------------- /autogpt/speech/macos_tts.py: -------------------------------------------------------------------------------- 1 | """ MacOS TTS Voice. """ 2 | import os 3 | 4 | from autogpt.speech.base import VoiceBase 5 | 6 | 7 | class MacOSTTS(VoiceBase): 8 | """MacOS TTS Voice.""" 9 | 10 | def _setup(self) -> None: 11 | pass 12 | 13 | def _speech(self, text: str, voice_index: int = 0) -> bool: 14 | """Play the given text.""" 15 | if voice_index == 0: 16 | os.system(f'say "{text}"') 17 | elif voice_index == 1: 18 | os.system(f'say -v "Ava (Premium)" "{text}"') 19 | else: 20 | os.system(f'say -v Samantha "{text}"') 21 | return True 22 | -------------------------------------------------------------------------------- /autogpt/json_fixes/utilities.py: -------------------------------------------------------------------------------- 1 | """Utilities for the json_fixes package.""" 2 | import re 3 | 4 | 5 | def extract_char_position(error_message: str) -> int: 6 | """Extract the character position from the JSONDecodeError message. 7 | 8 | Args: 9 | error_message (str): The error message from the JSONDecodeError 10 | exception. 11 | 12 | Returns: 13 | int: The character position. 14 | """ 15 | 16 | char_pattern = re.compile(r"\(char (\d+)\)") 17 | if match := char_pattern.search(error_message): 18 | return int(match[1]) 19 | else: 20 | raise ValueError("Character position not found in the error message.") 21 | -------------------------------------------------------------------------------- /autogpt/commands/git_operations.py: -------------------------------------------------------------------------------- 1 | """Git operations for autogpt""" 2 | import git 3 | from autogpt.config import Config 4 | 5 | CFG = Config() 6 | 7 | 8 | def clone_repository(repo_url: str, clone_path: str) -> str: 9 | """Clone a github repository locally 10 | 11 | Args: 12 | repo_url (str): The URL of the repository to clone 13 | clone_path (str): The path to clone the repository to 14 | 15 | Returns: 16 | str: The result of the clone operation""" 17 | split_url = repo_url.split("//") 18 | auth_repo_url = f"//{CFG.github_username}:{CFG.github_api_key}@".join(split_url) 19 | git.Repo.clone_from(auth_repo_url, clone_path) 20 | return f"""Cloned {repo_url} to {clone_path}""" 21 | -------------------------------------------------------------------------------- /autogpt/config/singleton.py: -------------------------------------------------------------------------------- 1 | """The singleton metaclass for ensuring only one instance of a class.""" 2 | import abc 3 | 4 | 5 | class Singleton(abc.ABCMeta, type): 6 | """ 7 | Singleton metaclass for ensuring only one instance of a class. 8 | """ 9 | 10 | _instances = {} 11 | 12 | def __call__(cls, *args, **kwargs): 13 | """Call method for the singleton metaclass.""" 14 | if cls not in cls._instances: 15 | cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) 16 | return cls._instances[cls] 17 | 18 | 19 | class AbstractSingleton(abc.ABC, metaclass=Singleton): 20 | """ 21 | Abstract singleton class for ensuring only one instance of a class. 22 | """ 23 | 24 | pass 25 | -------------------------------------------------------------------------------- /tests/browse_tests.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import os 3 | import sys 4 | 5 | from bs4 import BeautifulSoup 6 | 7 | sys.path.append(os.path.abspath("../scripts")) 8 | 9 | from browse import extract_hyperlinks 10 | 11 | 12 | class TestBrowseLinks(unittest.TestCase): 13 | def test_extract_hyperlinks(self): 14 | body = """ 15 | 16 | Google 17 | Foo 18 |
Some other crap
19 | 20 | """ 21 | soup = BeautifulSoup(body, "html.parser") 22 | links = extract_hyperlinks(soup, "http://example.com") 23 | self.assertEqual( 24 | links, 25 | [("Google", "https://google.com"), ("Foo", "http://example.com/foo.html")], 26 | ) 27 | -------------------------------------------------------------------------------- /autogpt/json_fixes/missing_quotes.py: -------------------------------------------------------------------------------- 1 | """Fix quotes in a JSON string.""" 2 | import json 3 | import re 4 | 5 | 6 | def add_quotes_to_property_names(json_string: str) -> str: 7 | """ 8 | Add quotes to property names in a JSON string. 9 | 10 | Args: 11 | json_string (str): The JSON string. 12 | 13 | Returns: 14 | str: The JSON string with quotes added to property names. 15 | """ 16 | 17 | def replace_func(match: re.Match) -> str: 18 | return f'"{match[1]}":' 19 | 20 | property_name_pattern = re.compile(r"(\w+):") 21 | corrected_json_string = property_name_pattern.sub(replace_func, json_string) 22 | 23 | try: 24 | json.loads(corrected_json_string) 25 | return corrected_json_string 26 | except json.JSONDecodeError as e: 27 | raise e 28 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Use an official Python base image from the Docker Hub 2 | FROM python:3.11-slim 3 | 4 | # Install git 5 | RUN apt-get -y update 6 | RUN apt-get -y install git 7 | 8 | # Set environment variables 9 | ENV PIP_NO_CACHE_DIR=yes \ 10 | PYTHONUNBUFFERED=1 \ 11 | PYTHONDONTWRITEBYTECODE=1 12 | 13 | # Create a non-root user and set permissions 14 | RUN useradd --create-home appuser 15 | WORKDIR /home/appuser 16 | RUN chown appuser:appuser /home/appuser 17 | USER appuser 18 | 19 | # Copy the requirements.txt file and install the requirements 20 | COPY --chown=appuser:appuser requirements-docker.txt . 21 | RUN pip install --no-cache-dir --user -r requirements-docker.txt 22 | 23 | # Copy the application files 24 | COPY --chown=appuser:appuser autogpt/ ./autogpt 25 | 26 | # Set the entrypoint 27 | ENTRYPOINT ["python", "-m", "autogpt"] 28 | -------------------------------------------------------------------------------- /autogpt/commands/evaluate_code.py: -------------------------------------------------------------------------------- 1 | """Code evaluation module.""" 2 | from typing import List 3 | 4 | from autogpt.llm_utils import call_ai_function 5 | 6 | 7 | def evaluate_code(code: str) -> List[str]: 8 | """ 9 | A function that takes in a string and returns a response from create chat 10 | completion api call. 11 | 12 | Parameters: 13 | code (str): Code to be evaluated. 14 | Returns: 15 | A result string from create chat completion. A list of suggestions to 16 | improve the code. 17 | """ 18 | 19 | function_string = "def analyze_code(code: str) -> List[str]:" 20 | args = [code] 21 | description_string = ( 22 | "Analyzes the given code and returns a list of suggestions" " for improvements." 23 | ) 24 | 25 | return call_ai_function(function_string, args, description_string) 26 | -------------------------------------------------------------------------------- /autogpt/utils.py: -------------------------------------------------------------------------------- 1 | import yaml 2 | from colorama import Fore 3 | 4 | 5 | def clean_input(prompt: str = ""): 6 | try: 7 | return input(prompt) 8 | except KeyboardInterrupt: 9 | print("You interrupted Auto-GPT") 10 | print("Quitting...") 11 | exit(0) 12 | 13 | 14 | def validate_yaml_file(file: str): 15 | try: 16 | with open(file, encoding="utf-8") as fp: 17 | yaml.load(fp.read(), Loader=yaml.FullLoader) 18 | except FileNotFoundError: 19 | return (False, f"The file {Fore.CYAN}`{file}`{Fore.RESET} wasn't found") 20 | except yaml.YAMLError as e: 21 | return ( 22 | False, 23 | f"There was an issue while trying to read with your AI Settings file: {e}", 24 | ) 25 | 26 | return (True, f"Successfully validated {Fore.CYAN}`{file}`{Fore.RESET}!") 27 | -------------------------------------------------------------------------------- /autogpt/commands/twitter.py: -------------------------------------------------------------------------------- 1 | import tweepy 2 | import os 3 | from dotenv import load_dotenv 4 | 5 | load_dotenv() 6 | 7 | 8 | def send_tweet(tweet_text): 9 | consumer_key = os.environ.get("TW_CONSUMER_KEY") 10 | consumer_secret= os.environ.get("TW_CONSUMER_SECRET") 11 | access_token= os.environ.get("TW_ACCESS_TOKEN") 12 | access_token_secret= os.environ.get("TW_ACCESS_TOKEN_SECRET") 13 | # Authenticate to Twitter 14 | auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 15 | auth.set_access_token(access_token, access_token_secret) 16 | 17 | # Create API object 18 | api = tweepy.API(auth) 19 | 20 | # Send tweet 21 | try: 22 | api.update_status(tweet_text) 23 | print("Tweet sent successfully!") 24 | except tweepy.TweepyException as e: 25 | print("Error sending tweet: {}".format(e.reason)) 26 | -------------------------------------------------------------------------------- /tests/unit/test_commands.py: -------------------------------------------------------------------------------- 1 | import autogpt.agent.agent_manager as agent_manager 2 | from autogpt.app import start_agent, list_agents, execute_command 3 | import unittest 4 | from unittest.mock import patch, MagicMock 5 | 6 | 7 | class TestCommands(unittest.TestCase): 8 | def test_make_agent(self): 9 | with patch("openai.ChatCompletion.create") as mock: 10 | obj = MagicMock() 11 | obj.response.choices[0].messages[0].content = "Test message" 12 | mock.return_value = obj 13 | start_agent("Test Agent", "chat", "Hello, how are you?", "gpt2") 14 | agents = list_agents() 15 | self.assertEqual("List of agents:\n0: chat", agents) 16 | start_agent("Test Agent 2", "write", "Hello, how are you?", "gpt2") 17 | agents = list_agents() 18 | self.assertEqual("List of agents:\n0: chat\n1: write", agents) 19 | -------------------------------------------------------------------------------- /.github/workflows/auto_format.yml: -------------------------------------------------------------------------------- 1 | name: auto-format 2 | on: pull_request 3 | jobs: 4 | format: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - name: Checkout PR branch 8 | uses: actions/checkout@v2 9 | with: 10 | ref: ${{ github.event.pull_request.head.sha }} 11 | - name: autopep8 12 | uses: peter-evans/autopep8@v1 13 | with: 14 | args: --exit-code --recursive --in-place --aggressive --aggressive . 15 | - name: Check for modified files 16 | id: git-check 17 | run: echo "modified=$(if git diff-index --quiet HEAD --; then echo "false"; else echo "true"; fi)" >> $GITHUB_ENV 18 | - name: Push changes 19 | if: steps.git-check.outputs.modified == 'true' 20 | run: | 21 | git config --global user.name 'Torantulino' 22 | git config --global user.email 'toran.richards@gmail.com' 23 | git remote set 24 | -------------------------------------------------------------------------------- /autogpt/js/overlay.js: -------------------------------------------------------------------------------- 1 | const overlay = document.createElement('div'); 2 | Object.assign(overlay.style, { 3 | position: 'fixed', 4 | zIndex: 999999, 5 | top: 0, 6 | left: 0, 7 | width: '100%', 8 | height: '100%', 9 | background: 'rgba(0, 0, 0, 0.7)', 10 | color: '#fff', 11 | fontSize: '24px', 12 | fontWeight: 'bold', 13 | display: 'flex', 14 | justifyContent: 'center', 15 | alignItems: 'center', 16 | }); 17 | const textContent = document.createElement('div'); 18 | Object.assign(textContent.style, { 19 | textAlign: 'center', 20 | }); 21 | textContent.textContent = 'AutoGPT Analyzing Page'; 22 | overlay.appendChild(textContent); 23 | document.body.append(overlay); 24 | document.body.style.overflow = 'hidden'; 25 | let dotCount = 0; 26 | setInterval(() => { 27 | textContent.textContent = 'AutoGPT Analyzing Page' + '.'.repeat(dotCount); 28 | dotCount = (dotCount + 1) % 4; 29 | }, 1000); 30 | -------------------------------------------------------------------------------- /scripts/check_requirements.py: -------------------------------------------------------------------------------- 1 | import pkg_resources 2 | import sys 3 | 4 | 5 | def main(): 6 | requirements_file = sys.argv[1] 7 | with open(requirements_file, "r") as f: 8 | required_packages = [ 9 | line.strip().split("#")[0].strip() for line in f.readlines() 10 | ] 11 | 12 | installed_packages = [package.key for package in pkg_resources.working_set] 13 | 14 | missing_packages = [] 15 | for package in required_packages: 16 | if not package: # Skip empty lines 17 | continue 18 | package_name = package.strip().split("==")[0] 19 | if package_name.lower() not in installed_packages: 20 | missing_packages.append(package_name) 21 | 22 | if missing_packages: 23 | print("Missing packages:") 24 | print(", ".join(missing_packages)) 25 | sys.exit(1) 26 | else: 27 | print("All packages are installed.") 28 | 29 | 30 | if __name__ == "__main__": 31 | main() 32 | -------------------------------------------------------------------------------- /autogpt/commands/improve_code.py: -------------------------------------------------------------------------------- 1 | import json 2 | from typing import List 3 | 4 | from autogpt.llm_utils import call_ai_function 5 | 6 | 7 | def improve_code(suggestions: List[str], code: str) -> str: 8 | """ 9 | A function that takes in code and suggestions and returns a response from create 10 | chat completion api call. 11 | 12 | Parameters: 13 | suggestions (List): A list of suggestions around what needs to be improved. 14 | code (str): Code to be improved. 15 | Returns: 16 | A result string from create chat completion. Improved code in response. 17 | """ 18 | 19 | function_string = ( 20 | "def generate_improved_code(suggestions: List[str], code: str) -> str:" 21 | ) 22 | args = [json.dumps(suggestions), code] 23 | description_string = ( 24 | "Improves the provided code based on the suggestions" 25 | " provided, making no other changes." 26 | ) 27 | 28 | return call_ai_function(function_string, args, description_string) 29 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/sourcery-ai/sourcery 3 | rev: v1.1.0 # Get the latest tag from https://github.com/sourcery-ai/sourcery/tags 4 | hooks: 5 | - id: sourcery 6 | 7 | - repo: https://github.com/pre-commit/pre-commit-hooks 8 | rev: v0.9.2 9 | hooks: 10 | - id: check-added-large-files 11 | args: [ '--maxkb=500' ] 12 | - id: check-byte-order-marker 13 | - id: check-case-conflict 14 | - id: check-merge-conflict 15 | - id: check-symlinks 16 | - id: debug-statements 17 | 18 | - repo: local 19 | hooks: 20 | - id: isort 21 | name: isort-local 22 | entry: isort 23 | language: python 24 | types: [ python ] 25 | exclude: .+/(dist|.venv|venv|build)/.+ 26 | pass_filenames: true 27 | - id: black 28 | name: black-local 29 | entry: black 30 | language: python 31 | types: [ python ] 32 | exclude: .+/(dist|.venv|venv|build)/.+ 33 | pass_filenames: true -------------------------------------------------------------------------------- /autogpt/processing/html.py: -------------------------------------------------------------------------------- 1 | """HTML processing functions""" 2 | from requests.compat import urljoin 3 | from typing import List, Tuple 4 | from bs4 import BeautifulSoup 5 | 6 | 7 | def extract_hyperlinks(soup: BeautifulSoup, base_url: str) -> List[Tuple[str, str]]: 8 | """Extract hyperlinks from a BeautifulSoup object 9 | 10 | Args: 11 | soup (BeautifulSoup): The BeautifulSoup object 12 | base_url (str): The base URL 13 | 14 | Returns: 15 | List[Tuple[str, str]]: The extracted hyperlinks 16 | """ 17 | return [ 18 | (link.text, urljoin(base_url, link["href"])) 19 | for link in soup.find_all("a", href=True) 20 | ] 21 | 22 | 23 | def format_hyperlinks(hyperlinks: List[Tuple[str, str]]) -> List[str]: 24 | """Format hyperlinks to be displayed to the user 25 | 26 | Args: 27 | hyperlinks (List[Tuple[str, str]]): The hyperlinks to format 28 | 29 | Returns: 30 | List[str]: The formatted hyperlinks 31 | """ 32 | return [f"{link_text} ({link_url})" for link_text, link_url in hyperlinks] 33 | -------------------------------------------------------------------------------- /autogpt/commands/audio_text.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | 4 | from autogpt.config import Config 5 | from autogpt.commands.file_operations import safe_join 6 | 7 | cfg = Config() 8 | 9 | working_directory = "auto_gpt_workspace" 10 | 11 | 12 | def read_audio_from_file(audio_path): 13 | audio_path = safe_join(working_directory, audio_path) 14 | with open(audio_path, "rb") as audio_file: 15 | audio = audio_file.read() 16 | return read_audio(audio) 17 | 18 | 19 | def read_audio(audio): 20 | model = cfg.huggingface_audio_to_text_model 21 | api_url = f"https://api-inference.huggingface.co/models/{model}" 22 | api_token = cfg.huggingface_api_token 23 | headers = {"Authorization": f"Bearer {api_token}"} 24 | 25 | if api_token is None: 26 | raise ValueError("You need to set your Hugging Face API token in the config file.") 27 | 28 | response = requests.post( 29 | api_url, 30 | headers=headers, 31 | data=audio, 32 | ) 33 | 34 | text = json.loads(response.content.decode("utf-8"))['text'] 35 | return "The audio says: " + text 36 | -------------------------------------------------------------------------------- /autogpt/memory/base.py: -------------------------------------------------------------------------------- 1 | """Base class for memory providers.""" 2 | import abc 3 | 4 | import openai 5 | 6 | from autogpt.config import AbstractSingleton, Config 7 | 8 | cfg = Config() 9 | 10 | 11 | def get_ada_embedding(text): 12 | text = text.replace("\n", " ") 13 | if cfg.use_azure: 14 | return openai.Embedding.create( 15 | input=[text], 16 | engine=cfg.get_azure_deployment_id_for_model("text-embedding-ada-002"), 17 | )["data"][0]["embedding"] 18 | else: 19 | return openai.Embedding.create(input=[text], model="text-embedding-ada-002")[ 20 | "data" 21 | ][0]["embedding"] 22 | 23 | 24 | class MemoryProviderSingleton(AbstractSingleton): 25 | @abc.abstractmethod 26 | def add(self, data): 27 | pass 28 | 29 | @abc.abstractmethod 30 | def get(self, data): 31 | pass 32 | 33 | @abc.abstractmethod 34 | def clear(self): 35 | pass 36 | 37 | @abc.abstractmethod 38 | def get_relevant(self, data, num_relevant=5): 39 | pass 40 | 41 | @abc.abstractmethod 42 | def get_stats(self): 43 | pass 44 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Python CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | branches: 9 | - master 10 | 11 | jobs: 12 | build: 13 | runs-on: ubuntu-latest 14 | 15 | strategy: 16 | matrix: 17 | python-version: [3.8] 18 | 19 | steps: 20 | - name: Check out repository 21 | uses: actions/checkout@v2 22 | 23 | - name: Set up Python ${{ matrix.python-version }} 24 | uses: actions/setup-python@v2 25 | with: 26 | python-version: ${{ matrix.python-version }} 27 | 28 | - name: Install dependencies 29 | run: | 30 | python -m pip install --upgrade pip 31 | pip install -r requirements.txt 32 | 33 | - name: Lint with flake8 34 | continue-on-error: false 35 | run: flake8 autogpt/ tests/ --select E303,W293,W291,W292,E305,E231,E302 36 | 37 | - name: Run unittest tests with coverage 38 | run: | 39 | coverage run --source=autogpt -m unittest discover tests 40 | 41 | - name: Generate coverage report 42 | run: | 43 | coverage report 44 | coverage xml 45 | -------------------------------------------------------------------------------- /autogpt/commands/write_tests.py: -------------------------------------------------------------------------------- 1 | """A module that contains a function to generate test cases for the submitted code.""" 2 | import json 3 | from typing import List 4 | from autogpt.llm_utils import call_ai_function 5 | 6 | 7 | def write_tests(code: str, focus: List[str]) -> str: 8 | """ 9 | A function that takes in code and focus topics and returns a response from create 10 | chat completion api call. 11 | 12 | Parameters: 13 | focus (List): A list of suggestions around what needs to be improved. 14 | code (str): Code for test cases to be generated against. 15 | Returns: 16 | A result string from create chat completion. Test cases for the submitted code 17 | in response. 18 | """ 19 | 20 | function_string = ( 21 | "def create_test_cases(code: str, focus: Optional[str] = None) -> str:" 22 | ) 23 | args = [code, json.dumps(focus)] 24 | description_string = ( 25 | "Generates test cases for the existing code, focusing on" 26 | " specific areas if required." 27 | ) 28 | 29 | return call_ai_function(function_string, args, description_string) 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Toran Bruce Richards 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /autogpt/json_fixes/escaping.py: -------------------------------------------------------------------------------- 1 | """ Fix invalid escape sequences in JSON strings. """ 2 | import json 3 | 4 | from autogpt.config import Config 5 | from autogpt.json_fixes.utilities import extract_char_position 6 | 7 | CFG = Config() 8 | 9 | 10 | def fix_invalid_escape(json_to_load: str, error_message: str) -> str: 11 | """Fix invalid escape sequences in JSON strings. 12 | 13 | Args: 14 | json_to_load (str): The JSON string. 15 | error_message (str): The error message from the JSONDecodeError 16 | exception. 17 | 18 | Returns: 19 | str: The JSON string with invalid escape sequences fixed. 20 | """ 21 | while error_message.startswith("Invalid \\escape"): 22 | bad_escape_location = extract_char_position(error_message) 23 | json_to_load = ( 24 | json_to_load[:bad_escape_location] + json_to_load[bad_escape_location + 1 :] 25 | ) 26 | try: 27 | json.loads(json_to_load) 28 | return json_to_load 29 | except json.JSONDecodeError as e: 30 | if CFG.debug_mode: 31 | print("json loads error - fix invalid escape", e) 32 | error_message = str(e) 33 | return json_to_load 34 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/2.feature.yml: -------------------------------------------------------------------------------- 1 | name: Feature request 🚀 2 | description: Suggest a new idea for Auto-GPT. 3 | labels: ['status: needs triage'] 4 | body: 5 | - type: markdown 6 | attributes: 7 | value: | 8 | Please provide a searchable summary of the issue in the title above ⬆️. 9 | 10 | Thanks for contributing by creating an issue! ❤️ 11 | - type: checkboxes 12 | attributes: 13 | label: Duplicates 14 | description: Please [search the history](https://github.com/Torantulino/Auto-GPT/issues) to see if an issue already exists for the same problem. 15 | options: 16 | - label: I have searched the existing issues 17 | required: true 18 | - type: textarea 19 | attributes: 20 | label: Summary 💡 21 | description: Describe how it should work. 22 | - type: textarea 23 | attributes: 24 | label: Examples 🌈 25 | description: Provide a link to other implementations, or screenshots of the expected behavior. 26 | - type: textarea 27 | attributes: 28 | label: Motivation 🔦 29 | description: What are you trying to accomplish? How has the lack of this feature affected you? Providing context helps us come up with a solution that is more useful in the real world. -------------------------------------------------------------------------------- /autogpt/speech/brian.py: -------------------------------------------------------------------------------- 1 | """ Brian speech module for autogpt """ 2 | import os 3 | import requests 4 | from playsound import playsound 5 | 6 | from autogpt.speech.base import VoiceBase 7 | 8 | 9 | class BrianSpeech(VoiceBase): 10 | """Brian speech module for autogpt""" 11 | 12 | def _setup(self) -> None: 13 | """Setup the voices, API key, etc.""" 14 | pass 15 | 16 | def _speech(self, text: str) -> bool: 17 | """Speak text using Brian with the streamelements API 18 | 19 | Args: 20 | text (str): The text to speak 21 | 22 | Returns: 23 | bool: True if the request was successful, False otherwise 24 | """ 25 | tts_url = ( 26 | f"https://api.streamelements.com/kappa/v2/speech?voice=Brian&text={text}" 27 | ) 28 | response = requests.get(tts_url) 29 | 30 | if response.status_code == 200: 31 | with open("speech.mp3", "wb") as f: 32 | f.write(response.content) 33 | playsound("speech.mp3") 34 | os.remove("speech.mp3") 35 | return True 36 | else: 37 | print("Request failed with status code:", response.status_code) 38 | print("Response content:", response.content) 39 | return False 40 | -------------------------------------------------------------------------------- /autogpt/speech/say.py: -------------------------------------------------------------------------------- 1 | """ Text to speech module """ 2 | from autogpt.config import Config 3 | 4 | import threading 5 | from threading import Semaphore 6 | from autogpt.speech.brian import BrianSpeech 7 | from autogpt.speech.macos_tts import MacOSTTS 8 | from autogpt.speech.gtts import GTTSVoice 9 | from autogpt.speech.eleven_labs import ElevenLabsSpeech 10 | 11 | 12 | CFG = Config() 13 | DEFAULT_VOICE_ENGINE = GTTSVoice() 14 | VOICE_ENGINE = None 15 | if CFG.elevenlabs_api_key: 16 | VOICE_ENGINE = ElevenLabsSpeech() 17 | elif CFG.use_mac_os_tts == "True": 18 | VOICE_ENGINE = MacOSTTS() 19 | elif CFG.use_brian_tts == "True": 20 | VOICE_ENGINE = BrianSpeech() 21 | else: 22 | VOICE_ENGINE = GTTSVoice() 23 | 24 | 25 | QUEUE_SEMAPHORE = Semaphore( 26 | 1 27 | ) # The amount of sounds to queue before blocking the main thread 28 | 29 | 30 | def say_text(text: str, voice_index: int = 0) -> None: 31 | """Speak the given text using the given voice index""" 32 | 33 | def speak() -> None: 34 | success = VOICE_ENGINE.say(text, voice_index) 35 | if not success: 36 | DEFAULT_VOICE_ENGINE.say(text) 37 | 38 | QUEUE_SEMAPHORE.release() 39 | 40 | QUEUE_SEMAPHORE.acquire(True) 41 | thread = threading.Thread(target=speak) 42 | thread.start() 43 | -------------------------------------------------------------------------------- /autogpt/speech/base.py: -------------------------------------------------------------------------------- 1 | """Base class for all voice classes.""" 2 | import abc 3 | from threading import Lock 4 | 5 | from autogpt.config import AbstractSingleton 6 | 7 | 8 | class VoiceBase(AbstractSingleton): 9 | """ 10 | Base class for all voice classes. 11 | """ 12 | 13 | def __init__(self): 14 | """ 15 | Initialize the voice class. 16 | """ 17 | self._url = None 18 | self._headers = None 19 | self._api_key = None 20 | self._voices = [] 21 | self._mutex = Lock() 22 | self._setup() 23 | 24 | def say(self, text: str, voice_index: int = 0) -> bool: 25 | """ 26 | Say the given text. 27 | 28 | Args: 29 | text (str): The text to say. 30 | voice_index (int): The index of the voice to use. 31 | """ 32 | with self._mutex: 33 | return self._speech(text, voice_index) 34 | 35 | @abc.abstractmethod 36 | def _setup(self) -> None: 37 | """ 38 | Setup the voices, API key, etc. 39 | """ 40 | pass 41 | 42 | @abc.abstractmethod 43 | def _speech(self, text: str, voice_index: int = 0) -> bool: 44 | """ 45 | Play the given text. 46 | 47 | Args: 48 | text (str): The text to play. 49 | """ 50 | pass 51 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "build": { 3 | "dockerfile": "./Dockerfile", 4 | "context": "." 5 | }, 6 | "features": { 7 | "ghcr.io/devcontainers/features/common-utils:2": { 8 | "installZsh": "true", 9 | "username": "vscode", 10 | "userUid": "1000", 11 | "userGid": "1000", 12 | "upgradePackages": "true" 13 | }, 14 | "ghcr.io/devcontainers/features/python:1": "none", 15 | "ghcr.io/devcontainers/features/node:1": "none", 16 | "ghcr.io/devcontainers/features/git:1": { 17 | "version": "latest", 18 | "ppa": "false" 19 | } 20 | }, 21 | // Configure tool-specific properties. 22 | "customizations": { 23 | // Configure properties specific to VS Code. 24 | "vscode": { 25 | // Set *default* container specific settings.json values on container create. 26 | "settings": { 27 | "python.defaultInterpreterPath": "/usr/local/bin/python" 28 | } 29 | } 30 | }, 31 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 32 | // "forwardPorts": [], 33 | 34 | // Use 'postCreateCommand' to run commands after the container is created. 35 | // "postCreateCommand": "pip3 install --user -r requirements.txt", 36 | 37 | // Set `remoteUser` to `root` to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. 38 | "remoteUser": "vscode" 39 | } 40 | -------------------------------------------------------------------------------- /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | # [Choice] Python version (use -bullseye variants on local arm64/Apple Silicon): 3, 3.10, 3.9, 3.8, 3.7, 3.6, 3-bullseye, 3.10-bullseye, 3.9-bullseye, 3.8-bullseye, 3.7-bullseye, 3.6-bullseye, 3-buster, 3.10-buster, 3.9-buster, 3.8-buster, 3.7-buster, 3.6-buster 2 | ARG VARIANT=3-bullseye 3 | FROM python:3.8 4 | 5 | RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 6 | # Remove imagemagick due to https://security-tracker.debian.org/tracker/CVE-2019-10131 7 | && apt-get purge -y imagemagick imagemagick-6-common 8 | 9 | # Temporary: Upgrade python packages due to https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-40897 10 | # They are installed by the base image (python) which does not have the patch. 11 | RUN python3 -m pip install --upgrade setuptools 12 | 13 | # [Optional] If your pip requirements rarely change, uncomment this section to add them to the image. 14 | # COPY requirements.txt /tmp/pip-tmp/ 15 | # RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \ 16 | # && rm -rf /tmp/pip-tmp 17 | 18 | # [Optional] Uncomment this section to install additional OS packages. 19 | # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 20 | # && apt-get -y install --no-install-recommends 21 | 22 | # [Optional] Uncomment this line to install global node packages. 23 | # RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g " 2>&1 -------------------------------------------------------------------------------- /tests/local_cache_test.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import unittest 4 | 5 | from autogpt.memory.local import LocalCache 6 | 7 | 8 | def MockConfig(): 9 | return type( 10 | "MockConfig", 11 | (object,), 12 | { 13 | "debug_mode": False, 14 | "continuous_mode": False, 15 | "speak_mode": False, 16 | "memory_index": "auto-gpt", 17 | }, 18 | ) 19 | 20 | 21 | class TestLocalCache(unittest.TestCase): 22 | def setUp(self): 23 | self.cfg = MockConfig() 24 | self.cache = LocalCache(self.cfg) 25 | 26 | def test_add(self): 27 | text = "Sample text" 28 | self.cache.add(text) 29 | self.assertIn(text, self.cache.data.texts) 30 | 31 | def test_clear(self): 32 | self.cache.clear() 33 | self.assertEqual(self.cache.data, [""]) 34 | 35 | def test_get(self): 36 | text = "Sample text" 37 | self.cache.add(text) 38 | result = self.cache.get(text) 39 | self.assertEqual(result, [text]) 40 | 41 | def test_get_relevant(self): 42 | text1 = "Sample text 1" 43 | text2 = "Sample text 2" 44 | self.cache.add(text1) 45 | self.cache.add(text2) 46 | result = self.cache.get_relevant(text1, 1) 47 | self.assertEqual(result, [text1]) 48 | 49 | def test_get_stats(self): 50 | text = "Sample text" 51 | self.cache.add(text) 52 | stats = self.cache.get_stats() 53 | self.assertEqual(stats, (1, self.cache.data.embeddings.shape)) 54 | 55 | 56 | if __name__ == "__main__": 57 | unittest.main() 58 | -------------------------------------------------------------------------------- /tests/integration/memory_tests.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | import sys 4 | import unittest 5 | from pathlib import Path 6 | 7 | from autogpt.config import Config 8 | from autogpt.memory.local import LocalCache 9 | 10 | 11 | class TestLocalCache(unittest.TestCase): 12 | def random_string(self, length): 13 | return "".join(random.choice(string.ascii_letters) for _ in range(length)) 14 | 15 | def setUp(self): 16 | cfg = cfg = Config() 17 | self.cache = LocalCache(cfg) 18 | self.cache.clear() 19 | 20 | # Add example texts to the cache 21 | self.example_texts = [ 22 | "The quick brown fox jumps over the lazy dog", 23 | "I love machine learning and natural language processing", 24 | "The cake is a lie, but the pie is always true", 25 | "ChatGPT is an advanced AI model for conversation", 26 | ] 27 | 28 | for text in self.example_texts: 29 | self.cache.add(text) 30 | 31 | # Add some random strings to test noise 32 | for _ in range(5): 33 | self.cache.add(self.random_string(10)) 34 | 35 | def test_get_relevant(self): 36 | query = "I'm interested in artificial intelligence and NLP" 37 | k = 3 38 | relevant_texts = self.cache.get_relevant(query, k) 39 | 40 | print(f"Top {k} relevant texts for the query '{query}':") 41 | for i, text in enumerate(relevant_texts, start=1): 42 | print(f"{i}. {text}") 43 | 44 | self.assertEqual(len(relevant_texts), k) 45 | self.assertIn(self.example_texts[1], relevant_texts) 46 | 47 | 48 | if __name__ == "__main__": 49 | unittest.main() 50 | -------------------------------------------------------------------------------- /tests/integration/milvus_memory_tests.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | import unittest 4 | 5 | from autogpt.config import Config 6 | from autogpt.memory.milvus import MilvusMemory 7 | 8 | 9 | class TestMilvusMemory(unittest.TestCase): 10 | def random_string(self, length): 11 | return "".join(random.choice(string.ascii_letters) for _ in range(length)) 12 | 13 | def setUp(self): 14 | cfg = Config() 15 | cfg.milvus_addr = "localhost:19530" 16 | self.memory = MilvusMemory(cfg) 17 | self.memory.clear() 18 | 19 | # Add example texts to the cache 20 | self.example_texts = [ 21 | "The quick brown fox jumps over the lazy dog", 22 | "I love machine learning and natural language processing", 23 | "The cake is a lie, but the pie is always true", 24 | "ChatGPT is an advanced AI model for conversation", 25 | ] 26 | 27 | for text in self.example_texts: 28 | self.memory.add(text) 29 | 30 | # Add some random strings to test noise 31 | for _ in range(5): 32 | self.memory.add(self.random_string(10)) 33 | 34 | def test_get_relevant(self): 35 | query = "I'm interested in artificial intelligence and NLP" 36 | k = 3 37 | relevant_texts = self.memory.get_relevant(query, k) 38 | 39 | print(f"Top {k} relevant texts for the query '{query}':") 40 | for i, text in enumerate(relevant_texts, start=1): 41 | print(f"{i}. {text}") 42 | 43 | self.assertEqual(len(relevant_texts), k) 44 | self.assertIn(self.example_texts[1], relevant_texts) 45 | 46 | 47 | if __name__ == "__main__": 48 | unittest.main() 49 | -------------------------------------------------------------------------------- /autogpt/spinner.py: -------------------------------------------------------------------------------- 1 | """A simple spinner module""" 2 | import itertools 3 | import sys 4 | import threading 5 | import time 6 | 7 | 8 | class Spinner: 9 | """A simple spinner class""" 10 | 11 | def __init__(self, message: str = "Loading...", delay: float = 0.1) -> None: 12 | """Initialize the spinner class 13 | 14 | Args: 15 | message (str): The message to display. 16 | delay (float): The delay between each spinner update. 17 | """ 18 | self.spinner = itertools.cycle(["-", "/", "|", "\\"]) 19 | self.delay = delay 20 | self.message = message 21 | self.running = False 22 | self.spinner_thread = None 23 | 24 | def spin(self) -> None: 25 | """Spin the spinner""" 26 | while self.running: 27 | sys.stdout.write(f"{next(self.spinner)} {self.message}\r") 28 | sys.stdout.flush() 29 | time.sleep(self.delay) 30 | sys.stdout.write(f"\r{' ' * (len(self.message) + 2)}\r") 31 | 32 | def __enter__(self) -> None: 33 | """Start the spinner""" 34 | self.running = True 35 | self.spinner_thread = threading.Thread(target=self.spin) 36 | self.spinner_thread.start() 37 | 38 | def __exit__(self, exc_type, exc_value, exc_traceback) -> None: 39 | """Stop the spinner 40 | 41 | Args: 42 | exc_type (Exception): The exception type. 43 | exc_value (Exception): The exception value. 44 | exc_traceback (Exception): The exception traceback. 45 | """ 46 | self.running = False 47 | if self.spinner_thread is not None: 48 | self.spinner_thread.join() 49 | sys.stdout.write(f"\r{' ' * (len(self.message) + 2)}\r") 50 | sys.stdout.flush() 51 | -------------------------------------------------------------------------------- /autogpt/__main__.py: -------------------------------------------------------------------------------- 1 | """Main script for the autogpt package.""" 2 | import logging 3 | from colorama import Fore 4 | from autogpt.agent.agent import Agent 5 | from autogpt.args import parse_arguments 6 | 7 | from autogpt.config import Config, check_openai_api_key 8 | from autogpt.logs import logger 9 | from autogpt.memory import get_memory 10 | 11 | from autogpt.prompt import construct_prompt 12 | 13 | # Load environment variables from .env file 14 | 15 | 16 | def main() -> None: 17 | """Main function for the script""" 18 | cfg = Config() 19 | # TODO: fill in llm values here 20 | check_openai_api_key() 21 | parse_arguments() 22 | logger.set_level(logging.DEBUG if cfg.debug_mode else logging.INFO) 23 | ai_name = "" 24 | prompt = construct_prompt() 25 | # print(prompt) 26 | # Initialize variables 27 | full_message_history = [] 28 | next_action_count = 0 29 | # Make a constant: 30 | user_input = ( 31 | "Determine which next command to use, and respond using the" 32 | " format specified above:" 33 | ) 34 | # Initialize memory and make sure it is empty. 35 | # this is particularly important for indexing and referencing pinecone memory 36 | memory = get_memory(cfg, init=True) 37 | logger.typewriter_log( 38 | f"Using memory of type:", Fore.GREEN, f"{memory.__class__.__name__}" 39 | ) 40 | logger.typewriter_log(f"Using Browser:", Fore.GREEN, cfg.selenium_web_browser) 41 | agent = Agent( 42 | ai_name=ai_name, 43 | memory=memory, 44 | full_message_history=full_message_history, 45 | next_action_count=next_action_count, 46 | prompt=prompt, 47 | user_input=user_input, 48 | ) 49 | agent.start_interaction_loop() 50 | 51 | 52 | if __name__ == "__main__": 53 | main() 54 | -------------------------------------------------------------------------------- /tests/milvus_memory_test.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import unittest 4 | 5 | from autogpt.memory.milvus import MilvusMemory 6 | 7 | 8 | def MockConfig(): 9 | return type( 10 | "MockConfig", 11 | (object,), 12 | { 13 | "debug_mode": False, 14 | "continuous_mode": False, 15 | "speak_mode": False, 16 | "milvus_collection": "autogpt", 17 | "milvus_addr": "localhost:19530", 18 | }, 19 | ) 20 | 21 | 22 | class TestMilvusMemory(unittest.TestCase): 23 | def setUp(self): 24 | self.cfg = MockConfig() 25 | self.memory = MilvusMemory(self.cfg) 26 | 27 | def test_add(self): 28 | text = "Sample text" 29 | self.memory.clear() 30 | self.memory.add(text) 31 | result = self.memory.get(text) 32 | self.assertEqual([text], result) 33 | 34 | def test_clear(self): 35 | self.memory.clear() 36 | self.assertEqual(self.memory.collection.num_entities, 0) 37 | 38 | def test_get(self): 39 | text = "Sample text" 40 | self.memory.clear() 41 | self.memory.add(text) 42 | result = self.memory.get(text) 43 | self.assertEqual(result, [text]) 44 | 45 | def test_get_relevant(self): 46 | text1 = "Sample text 1" 47 | text2 = "Sample text 2" 48 | self.memory.clear() 49 | self.memory.add(text1) 50 | self.memory.add(text2) 51 | result = self.memory.get_relevant(text1, 1) 52 | self.assertEqual(result, [text1]) 53 | 54 | def test_get_stats(self): 55 | text = "Sample text" 56 | self.memory.clear() 57 | self.memory.add(text) 58 | stats = self.memory.get_stats() 59 | self.assertEqual(15, len(stats)) 60 | 61 | 62 | if __name__ == "__main__": 63 | unittest.main() 64 | -------------------------------------------------------------------------------- /.sourcery.yaml: -------------------------------------------------------------------------------- 1 | # 🪄 This is your project's Sourcery configuration file. 2 | 3 | # You can use it to get Sourcery working in the way you want, such as 4 | # ignoring specific refactorings, skipping directories in your project, 5 | # or writing custom rules. 6 | 7 | # 📚 For a complete reference to this file, see the documentation at 8 | # https://docs.sourcery.ai/Configuration/Project-Settings/ 9 | 10 | # This file was auto-generated by Sourcery on 2023-02-25 at 21:07. 11 | 12 | version: '1' # The schema version of this config file 13 | 14 | ignore: # A list of paths or files which Sourcery will ignore. 15 | - .git 16 | - venv 17 | - .venv 18 | - build 19 | - dist 20 | - env 21 | - .env 22 | - .tox 23 | 24 | rule_settings: 25 | enable: 26 | - default 27 | - gpsg 28 | disable: [] # A list of rule IDs Sourcery will never suggest. 29 | rule_types: 30 | - refactoring 31 | - suggestion 32 | - comment 33 | python_version: '3.9' # A string specifying the lowest Python version your project supports. Sourcery will not suggest refactorings requiring a higher Python version. 34 | 35 | # rules: # A list of custom rules Sourcery will include in its analysis. 36 | # - id: no-print-statements 37 | # description: Do not use print statements in the test directory. 38 | # pattern: print(...) 39 | # language: python 40 | # replacement: 41 | # condition: 42 | # explanation: 43 | # paths: 44 | # include: 45 | # - test 46 | # exclude: 47 | # - conftest.py 48 | # tests: [] 49 | # tags: [] 50 | 51 | # rule_tags: {} # Additional rule tags. 52 | 53 | # metrics: 54 | # quality_threshold: 25.0 55 | 56 | # github: 57 | # labels: [] 58 | # ignore_labels: 59 | # - sourcery-ignore 60 | # request_review: author 61 | # sourcery_branch: sourcery/{base_branch} 62 | 63 | # clone_detection: 64 | # min_lines: 3 65 | # min_duplicates: 2 66 | # identical_clones_only: false 67 | 68 | # proxy: 69 | # url: 70 | # ssl_certs_file: 71 | # no_ssl_verify: false -------------------------------------------------------------------------------- /autogpt/memory/no_memory.py: -------------------------------------------------------------------------------- 1 | """A class that does not store any data. This is the default memory provider.""" 2 | from typing import Optional, List, Any 3 | 4 | from autogpt.memory.base import MemoryProviderSingleton 5 | 6 | 7 | class NoMemory(MemoryProviderSingleton): 8 | """ 9 | A class that does not store any data. This is the default memory provider. 10 | """ 11 | 12 | def __init__(self, cfg): 13 | """ 14 | Initializes the NoMemory provider. 15 | 16 | Args: 17 | cfg: The config object. 18 | 19 | Returns: None 20 | """ 21 | pass 22 | 23 | def add(self, data: str) -> str: 24 | """ 25 | Adds a data point to the memory. No action is taken in NoMemory. 26 | 27 | Args: 28 | data: The data to add. 29 | 30 | Returns: An empty string. 31 | """ 32 | return "" 33 | 34 | def get(self, data: str) -> Optional[List[Any]]: 35 | """ 36 | Gets the data from the memory that is most relevant to the given data. 37 | NoMemory always returns None. 38 | 39 | Args: 40 | data: The data to compare to. 41 | 42 | Returns: None 43 | """ 44 | return None 45 | 46 | def clear(self) -> str: 47 | """ 48 | Clears the memory. No action is taken in NoMemory. 49 | 50 | Returns: An empty string. 51 | """ 52 | return "" 53 | 54 | def get_relevant(self, data: str, num_relevant: int = 5) -> Optional[List[Any]]: 55 | """ 56 | Returns all the data in the memory that is relevant to the given data. 57 | NoMemory always returns None. 58 | 59 | Args: 60 | data: The data to compare to. 61 | num_relevant: The number of relevant data to return. 62 | 63 | Returns: None 64 | """ 65 | return None 66 | 67 | def get_stats(self): 68 | """ 69 | Returns: An empty dictionary as there are no stats in NoMemory. 70 | """ 71 | return {} 72 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | To contribute to this GitHub project, you can follow these steps: 3 | 4 | 1. Fork the repository you want to contribute to by clicking the "Fork" button on the project page. 5 | 6 | 2. Clone the repository to your local machine using the following command: 7 | 8 | ``` 9 | git clone https://github.com//Auto-GPT 10 | ``` 11 | 3. Install the project requirements 12 | ``` 13 | pip install -r requirements.txt 14 | ``` 15 | 4. Install pre-commit hooks 16 | ``` 17 | pre-commit install 18 | ``` 19 | 5. Create a new branch for your changes using the following command: 20 | 21 | ``` 22 | git checkout -b "branch-name" 23 | ``` 24 | 6. Make your changes to the code or documentation. 25 | - Example: Improve User Interface or Add Documentation. 26 | 27 | 28 | 7. Add the changes to the staging area using the following command: 29 | ``` 30 | git add . 31 | ``` 32 | 33 | 8. Commit the changes with a meaningful commit message using the following command: 34 | ``` 35 | git commit -m "your commit message" 36 | ``` 37 | 9. Push the changes to your forked repository using the following command: 38 | ``` 39 | git push origin branch-name 40 | ``` 41 | 10. Go to the GitHub website and navigate to your forked repository. 42 | 43 | 11. Click the "New pull request" button. 44 | 45 | 12. Select the branch you just pushed to and the branch you want to merge into on the original repository. 46 | 47 | 13. Add a description of your changes and click the "Create pull request" button. 48 | 49 | 14. Wait for the project maintainer to review your changes and provide feedback. 50 | 51 | 15. Make any necessary changes based on feedback and repeat steps 5-12 until your changes are accepted and merged into the main project. 52 | 53 | 16. Once your changes are merged, you can update your forked repository and local copy of the repository with the following commands: 54 | 55 | ``` 56 | git fetch upstream 57 | git checkout master 58 | git merge upstream/master 59 | ``` 60 | Finally, delete the branch you created with the following command: 61 | ``` 62 | git branch -d branch-name 63 | ``` 64 | That's it you made it 🐣⭐⭐ 65 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/1.bug.yml: -------------------------------------------------------------------------------- 1 | name: Bug report 🐛 2 | description: Create a bug report for Auto-GPT. 3 | labels: ['status: needs triage'] 4 | body: 5 | - type: markdown 6 | attributes: 7 | value: | 8 | Please provide a searchable summary of the issue in the title above ⬆️. 9 | 10 | ⚠️ SUPER-busy repo, please help the volunteer maintainers. 11 | The less time we spend here, the more time we spend building AutoGPT. 12 | 13 | Please help us help you: 14 | - Does it work on `stable` branch (https://github.com/Torantulino/Auto-GPT/tree/stable)? 15 | - Does it work on current `master` (https://github.com/Torantulino/Auto-GPT/tree/master)? 16 | - Search for existing issues, "add comment" is tidier than "new issue" 17 | - Ask on our Discord (https://discord.gg/autogpt) 18 | - Provide relevant info: 19 | - Provide commit-hash (`git rev-parse HEAD` gets it) 20 | - If it's a pip/packages issue, provide pip version, python version 21 | - If it's a crash, provide traceback. 22 | 23 | - type: checkboxes 24 | attributes: 25 | label: Duplicates 26 | description: Please [search the history](https://github.com/Torantulino/Auto-GPT/issues) to see if an issue already exists for the same problem. 27 | options: 28 | - label: I have searched the existing issues 29 | required: true 30 | - type: textarea 31 | attributes: 32 | label: Steps to reproduce 🕹 33 | description: | 34 | **⚠️ Issues that we can't reproduce will be closed.** 35 | - type: textarea 36 | attributes: 37 | label: Current behavior 😯 38 | description: Describe what happens instead of the expected behavior. 39 | - type: textarea 40 | attributes: 41 | label: Expected behavior 🤔 42 | description: Describe what should happen. 43 | - type: textarea 44 | attributes: 45 | label: Your prompt 📝 46 | description: | 47 | If applicable please provide the prompt you are using. You can find your last-used prompt in last_run_ai_settings.yaml. 48 | value: | 49 | ```yaml 50 | # Paste your prompt here 51 | ``` 52 | -------------------------------------------------------------------------------- /autogpt/json_fixes/auto_fix.py: -------------------------------------------------------------------------------- 1 | """This module contains the function to fix JSON strings using GPT-3.""" 2 | import json 3 | 4 | from autogpt.llm_utils import call_ai_function 5 | from autogpt.logs import logger 6 | from autogpt.config import Config 7 | 8 | CFG = Config() 9 | 10 | 11 | def fix_json(json_string: str, schema: str) -> str: 12 | """Fix the given JSON string to make it parseable and fully compliant with 13 | the provided schema. 14 | 15 | Args: 16 | json_string (str): The JSON string to fix. 17 | schema (str): The schema to use to fix the JSON. 18 | Returns: 19 | str: The fixed JSON string. 20 | """ 21 | # Try to fix the JSON using GPT: 22 | function_string = "def fix_json(json_string: str, schema:str=None) -> str:" 23 | args = [f"'''{json_string}'''", f"'''{schema}'''"] 24 | description_string = ( 25 | "This function takes a JSON string and ensures that it" 26 | " is parseable and fully compliant with the provided schema. If an object" 27 | " or field specified in the schema isn't contained within the correct JSON," 28 | " it is omitted. The function also escapes any double quotes within JSON" 29 | " string values to ensure that they are valid. If the JSON string contains" 30 | " any None or NaN values, they are replaced with null before being parsed." 31 | ) 32 | 33 | # If it doesn't already start with a "`", add one: 34 | if not json_string.startswith("`"): 35 | json_string = "```json\n" + json_string + "\n```" 36 | result_string = call_ai_function( 37 | function_string, args, description_string, model=CFG.fast_llm_model 38 | ) 39 | logger.debug("------------ JSON FIX ATTEMPT ---------------") 40 | logger.debug(f"Original JSON: {json_string}") 41 | logger.debug("-----------") 42 | logger.debug(f"Fixed JSON: {result_string}") 43 | logger.debug("----------- END OF FIX ATTEMPT ----------------") 44 | 45 | try: 46 | json.loads(result_string) # just check the validity 47 | return result_string 48 | except json.JSONDecodeError: # noqa: E722 49 | # Get the call stack: 50 | # import traceback 51 | # call_stack = traceback.format_exc() 52 | # print(f"Failed to fix JSON: '{json_string}' "+call_stack) 53 | return "failed" 54 | -------------------------------------------------------------------------------- /autogpt/commands/web_playwright.py: -------------------------------------------------------------------------------- 1 | """Web scraping commands using Playwright""" 2 | try: 3 | from playwright.sync_api import sync_playwright 4 | except ImportError: 5 | print( 6 | "Playwright not installed. Please install it with 'pip install playwright' to use." 7 | ) 8 | from bs4 import BeautifulSoup 9 | from autogpt.processing.html import extract_hyperlinks, format_hyperlinks 10 | from typing import List, Union 11 | 12 | 13 | def scrape_text(url: str) -> str: 14 | """Scrape text from a webpage 15 | 16 | Args: 17 | url (str): The URL to scrape text from 18 | 19 | Returns: 20 | str: The scraped text 21 | """ 22 | with sync_playwright() as p: 23 | browser = p.chromium.launch() 24 | page = browser.new_page() 25 | 26 | try: 27 | page.goto(url) 28 | html_content = page.content() 29 | soup = BeautifulSoup(html_content, "html.parser") 30 | 31 | for script in soup(["script", "style"]): 32 | script.extract() 33 | 34 | text = soup.get_text() 35 | lines = (line.strip() for line in text.splitlines()) 36 | chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) 37 | text = "\n".join(chunk for chunk in chunks if chunk) 38 | 39 | except Exception as e: 40 | text = f"Error: {str(e)}" 41 | 42 | finally: 43 | browser.close() 44 | 45 | return text 46 | 47 | 48 | def scrape_links(url: str) -> Union[str, List[str]]: 49 | """Scrape links from a webpage 50 | 51 | Args: 52 | url (str): The URL to scrape links from 53 | 54 | Returns: 55 | Union[str, List[str]]: The scraped links 56 | """ 57 | with sync_playwright() as p: 58 | browser = p.chromium.launch() 59 | page = browser.new_page() 60 | 61 | try: 62 | page.goto(url) 63 | html_content = page.content() 64 | soup = BeautifulSoup(html_content, "html.parser") 65 | 66 | for script in soup(["script", "style"]): 67 | script.extract() 68 | 69 | hyperlinks = extract_hyperlinks(soup, url) 70 | formatted_links = format_hyperlinks(hyperlinks) 71 | 72 | except Exception as e: 73 | formatted_links = f"Error: {str(e)}" 74 | 75 | finally: 76 | browser.close() 77 | 78 | return formatted_links 79 | -------------------------------------------------------------------------------- /tests/test_token_counter.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import tests.context 3 | from autogpt.token_counter import count_message_tokens, count_string_tokens 4 | 5 | 6 | class TestTokenCounter(unittest.TestCase): 7 | def test_count_message_tokens(self): 8 | messages = [ 9 | {"role": "user", "content": "Hello"}, 10 | {"role": "assistant", "content": "Hi there!"}, 11 | ] 12 | self.assertEqual(count_message_tokens(messages), 17) 13 | 14 | def test_count_message_tokens_with_name(self): 15 | messages = [ 16 | {"role": "user", "content": "Hello", "name": "John"}, 17 | {"role": "assistant", "content": "Hi there!"}, 18 | ] 19 | self.assertEqual(count_message_tokens(messages), 17) 20 | 21 | def test_count_message_tokens_empty_input(self): 22 | self.assertEqual(count_message_tokens([]), 3) 23 | 24 | def test_count_message_tokens_invalid_model(self): 25 | messages = [ 26 | {"role": "user", "content": "Hello"}, 27 | {"role": "assistant", "content": "Hi there!"}, 28 | ] 29 | with self.assertRaises(KeyError): 30 | count_message_tokens(messages, model="invalid_model") 31 | 32 | def test_count_message_tokens_gpt_4(self): 33 | messages = [ 34 | {"role": "user", "content": "Hello"}, 35 | {"role": "assistant", "content": "Hi there!"}, 36 | ] 37 | self.assertEqual(count_message_tokens(messages, model="gpt-4-0314"), 15) 38 | 39 | def test_count_string_tokens(self): 40 | string = "Hello, world!" 41 | self.assertEqual( 42 | count_string_tokens(string, model_name="gpt-3.5-turbo-0301"), 4 43 | ) 44 | 45 | def test_count_string_tokens_empty_input(self): 46 | self.assertEqual(count_string_tokens("", model_name="gpt-3.5-turbo-0301"), 0) 47 | 48 | def test_count_message_tokens_invalid_model(self): 49 | messages = [ 50 | {"role": "user", "content": "Hello"}, 51 | {"role": "assistant", "content": "Hi there!"}, 52 | ] 53 | with self.assertRaises(NotImplementedError): 54 | count_message_tokens(messages, model="invalid_model") 55 | 56 | def test_count_string_tokens_gpt_4(self): 57 | string = "Hello, world!" 58 | self.assertEqual(count_string_tokens(string, model_name="gpt-4-0314"), 4) 59 | 60 | 61 | if __name__ == "__main__": 62 | unittest.main() 63 | -------------------------------------------------------------------------------- /autogpt/memory/__init__.py: -------------------------------------------------------------------------------- 1 | from autogpt.memory.local import LocalCache 2 | from autogpt.memory.no_memory import NoMemory 3 | 4 | # List of supported memory backends 5 | # Add a backend to this list if the import attempt is successful 6 | supported_memory = ["local", "no_memory"] 7 | 8 | try: 9 | from autogpt.memory.redismem import RedisMemory 10 | 11 | supported_memory.append("redis") 12 | except ImportError: 13 | print("Redis not installed. Skipping import.") 14 | RedisMemory = None 15 | 16 | try: 17 | from autogpt.memory.pinecone import PineconeMemory 18 | 19 | supported_memory.append("pinecone") 20 | except ImportError: 21 | print("Pinecone not installed. Skipping import.") 22 | PineconeMemory = None 23 | 24 | try: 25 | from autogpt.memory.milvus import MilvusMemory 26 | except ImportError: 27 | print("pymilvus not installed. Skipping import.") 28 | MilvusMemory = None 29 | 30 | 31 | def get_memory(cfg, init=False): 32 | memory = None 33 | if cfg.memory_backend == "pinecone": 34 | if not PineconeMemory: 35 | print( 36 | "Error: Pinecone is not installed. Please install pinecone" 37 | " to use Pinecone as a memory backend." 38 | ) 39 | else: 40 | memory = PineconeMemory(cfg) 41 | if init: 42 | memory.clear() 43 | elif cfg.memory_backend == "redis": 44 | if not RedisMemory: 45 | print( 46 | "Error: Redis is not installed. Please install redis-py to" 47 | " use Redis as a memory backend." 48 | ) 49 | else: 50 | memory = RedisMemory(cfg) 51 | elif cfg.memory_backend == "milvus": 52 | if not MilvusMemory: 53 | print( 54 | "Error: Milvus sdk is not installed." 55 | "Please install pymilvus to use Milvus as memory backend." 56 | ) 57 | else: 58 | memory = MilvusMemory(cfg) 59 | elif cfg.memory_backend == "no_memory": 60 | memory = NoMemory(cfg) 61 | 62 | if memory is None: 63 | memory = LocalCache(cfg) 64 | if init: 65 | memory.clear() 66 | return memory 67 | 68 | 69 | def get_supported_memory_backends(): 70 | return supported_memory 71 | 72 | 73 | __all__ = [ 74 | "get_memory", 75 | "LocalCache", 76 | "RedisMemory", 77 | "PineconeMemory", 78 | "NoMemory", 79 | "MilvusMemory", 80 | ] 81 | -------------------------------------------------------------------------------- /autogpt/speech/eleven_labs.py: -------------------------------------------------------------------------------- 1 | """ElevenLabs speech module""" 2 | import os 3 | from playsound import playsound 4 | 5 | import requests 6 | 7 | from autogpt.config import Config 8 | from autogpt.speech.base import VoiceBase 9 | 10 | PLACEHOLDERS = {"your-voice-id"} 11 | 12 | 13 | class ElevenLabsSpeech(VoiceBase): 14 | """ElevenLabs speech class""" 15 | 16 | def _setup(self) -> None: 17 | """Setup the voices, API key, etc. 18 | 19 | Returns: 20 | None: None 21 | """ 22 | 23 | cfg = Config() 24 | default_voices = ["ErXwobaYiN019PkySvjV", "EXAVITQu4vr4xnSDxMaL"] 25 | self._headers = { 26 | "Content-Type": "application/json", 27 | "xi-api-key": cfg.elevenlabs_api_key, 28 | } 29 | self._voices = default_voices.copy() 30 | self._use_custom_voice(cfg.elevenlabs_voice_1_id, 0) 31 | self._use_custom_voice(cfg.elevenlabs_voice_2_id, 1) 32 | 33 | def _use_custom_voice(self, voice, voice_index) -> None: 34 | """Use a custom voice if provided and not a placeholder 35 | 36 | Args: 37 | voice (str): The voice ID 38 | voice_index (int): The voice index 39 | 40 | Returns: 41 | None: None 42 | """ 43 | # Placeholder values that should be treated as empty 44 | if voice and voice not in PLACEHOLDERS: 45 | self._voices[voice_index] = voice 46 | 47 | def _speech(self, text: str, voice_index: int = 0) -> bool: 48 | """Speak text using elevenlabs.io's API 49 | 50 | Args: 51 | text (str): The text to speak 52 | voice_index (int, optional): The voice to use. Defaults to 0. 53 | 54 | Returns: 55 | bool: True if the request was successful, False otherwise 56 | """ 57 | tts_url = ( 58 | f"https://api.elevenlabs.io/v1/text-to-speech/{self._voices[voice_index]}" 59 | ) 60 | response = requests.post(tts_url, headers=self._headers, json={"text": text}) 61 | 62 | if response.status_code == 200: 63 | with open("speech.mpeg", "wb") as f: 64 | f.write(response.content) 65 | playsound("speech.mpeg", True) 66 | os.remove("speech.mpeg") 67 | return True 68 | else: 69 | print("Request failed with status code:", response.status_code) 70 | print("Response content:", response.content) 71 | return False 72 | -------------------------------------------------------------------------------- /autogpt/setup.py: -------------------------------------------------------------------------------- 1 | """Setup the AI and its goals""" 2 | from colorama import Fore, Style 3 | from autogpt import utils 4 | from autogpt.config.ai_config import AIConfig 5 | from autogpt.logs import logger 6 | 7 | 8 | def prompt_user() -> AIConfig: 9 | """Prompt the user for input 10 | 11 | Returns: 12 | AIConfig: The AIConfig object containing the user's input 13 | """ 14 | ai_name = "" 15 | # Construct the prompt 16 | logger.typewriter_log( 17 | "Welcome to Auto-GPT! ", 18 | Fore.GREEN, 19 | "Enter the name of your AI and its role below. Entering nothing will load" 20 | " defaults.", 21 | speak_text=True, 22 | ) 23 | 24 | # Get AI Name from User 25 | logger.typewriter_log( 26 | "Name your AI: ", Fore.GREEN, "For example, 'Entrepreneur-GPT'" 27 | ) 28 | ai_name = utils.clean_input("AI Name: ") 29 | if ai_name == "": 30 | ai_name = "Entrepreneur-GPT" 31 | 32 | logger.typewriter_log( 33 | f"{ai_name} here!", Fore.LIGHTBLUE_EX, "I am at your service.", speak_text=True 34 | ) 35 | 36 | # Get AI Role from User 37 | logger.typewriter_log( 38 | "Describe your AI's role: ", 39 | Fore.GREEN, 40 | "For example, 'an AI designed to autonomously develop and run businesses with" 41 | " the sole goal of increasing your net worth.'", 42 | ) 43 | ai_role = utils.clean_input(f"{ai_name} is: ") 44 | if ai_role == "": 45 | ai_role = "an AI designed to autonomously develop and run businesses with the" 46 | " sole goal of increasing your net worth." 47 | 48 | # Enter up to 5 goals for the AI 49 | logger.typewriter_log( 50 | "Enter up to 5 goals for your AI: ", 51 | Fore.GREEN, 52 | "For example: \nIncrease net worth, Grow Twitter Account, Develop and manage" 53 | " multiple businesses autonomously'", 54 | ) 55 | print("Enter nothing to load defaults, enter nothing when finished.", flush=True) 56 | ai_goals = [] 57 | for i in range(5): 58 | ai_goal = utils.clean_input(f"{Fore.LIGHTBLUE_EX}Goal{Style.RESET_ALL} {i+1}: ") 59 | if ai_goal == "": 60 | break 61 | ai_goals.append(ai_goal) 62 | if not ai_goals: 63 | ai_goals = [ 64 | "Increase net worth", 65 | "Grow Twitter Account", 66 | "Develop and manage multiple businesses autonomously", 67 | ] 68 | 69 | return AIConfig(ai_name, ai_role, ai_goals) 70 | -------------------------------------------------------------------------------- /autogpt/json_fixes/bracket_termination.py: -------------------------------------------------------------------------------- 1 | """Fix JSON brackets.""" 2 | import contextlib 3 | import json 4 | from typing import Optional 5 | import regex 6 | from colorama import Fore 7 | 8 | from autogpt.logs import logger 9 | from autogpt.config import Config 10 | from autogpt.speech import say_text 11 | 12 | CFG = Config() 13 | 14 | 15 | def attempt_to_fix_json_by_finding_outermost_brackets(json_string: str): 16 | if CFG.speak_mode and CFG.debug_mode: 17 | say_text( 18 | "I have received an invalid JSON response from the OpenAI API. " 19 | "Trying to fix it now." 20 | ) 21 | logger.typewriter_log("Attempting to fix JSON by finding outermost brackets\n") 22 | 23 | try: 24 | json_pattern = regex.compile(r"\{(?:[^{}]|(?R))*\}") 25 | json_match = json_pattern.search(json_string) 26 | 27 | if json_match: 28 | # Extract the valid JSON object from the string 29 | json_string = json_match.group(0) 30 | logger.typewriter_log( 31 | title="Apparently json was fixed.", title_color=Fore.GREEN 32 | ) 33 | if CFG.speak_mode and CFG.debug_mode: 34 | say_text("Apparently json was fixed.") 35 | else: 36 | raise ValueError("No valid JSON object found") 37 | 38 | except (json.JSONDecodeError, ValueError): 39 | if CFG.debug_mode: 40 | logger.error("Error: Invalid JSON: %s\n", json_string) 41 | if CFG.speak_mode: 42 | say_text("Didn't work. I will have to ignore this response then.") 43 | logger.error("Error: Invalid JSON, setting it to empty JSON now.\n") 44 | json_string = {} 45 | 46 | return json_string 47 | 48 | 49 | def balance_braces(json_string: str) -> Optional[str]: 50 | """ 51 | Balance the braces in a JSON string. 52 | 53 | Args: 54 | json_string (str): The JSON string. 55 | 56 | Returns: 57 | str: The JSON string with braces balanced. 58 | """ 59 | 60 | open_braces_count = json_string.count("{") 61 | close_braces_count = json_string.count("}") 62 | 63 | while open_braces_count > close_braces_count: 64 | json_string += "}" 65 | close_braces_count += 1 66 | 67 | while close_braces_count > open_braces_count: 68 | json_string = json_string.rstrip("}") 69 | close_braces_count -= 1 70 | 71 | with contextlib.suppress(json.JSONDecodeError): 72 | json.loads(json_string) 73 | return json_string 74 | -------------------------------------------------------------------------------- /tests/smoke_test.py: -------------------------------------------------------------------------------- 1 | import os 2 | import subprocess 3 | import sys 4 | import unittest 5 | 6 | from autogpt.commands.file_operations import delete_file, read_file 7 | 8 | env_vars = {"MEMORY_BACKEND": "no_memory", "TEMPERATURE": "0"} 9 | 10 | 11 | class TestCommands(unittest.TestCase): 12 | def test_write_file(self): 13 | # Test case to check if the write_file command can successfully write 'Hello World' to a file 14 | # named 'hello_world.txt'. 15 | 16 | # Read the current ai_settings.yaml file and store its content. 17 | ai_settings = None 18 | if os.path.exists("ai_settings.yaml"): 19 | with open("ai_settings.yaml", "r") as f: 20 | ai_settings = f.read() 21 | os.remove("ai_settings.yaml") 22 | 23 | try: 24 | if os.path.exists("hello_world.txt"): 25 | # Clean up any existing 'hello_world.txt' file before testing. 26 | delete_file("hello_world.txt") 27 | # Prepare input data for the test. 28 | input_data = """write_file-GPT 29 | an AI designed to use the write_file command to write 'Hello World' into a file named "hello_world.txt" and then use the task_complete command to complete the task. 30 | Use the write_file command to write 'Hello World' into a file named "hello_world.txt". 31 | Use the task_complete command to complete the task. 32 | Do not use any other commands. 33 | 34 | y -5 35 | EOF""" 36 | command = f"{sys.executable} -m autogpt" 37 | 38 | # Execute the script with the input data. 39 | process = subprocess.Popen( 40 | command, 41 | stdin=subprocess.PIPE, 42 | shell=True, 43 | env={**os.environ, **env_vars}, 44 | ) 45 | process.communicate(input_data.encode()) 46 | 47 | # Read the content of the 'hello_world.txt' file created during the test. 48 | content = read_file("hello_world.txt") 49 | finally: 50 | if ai_settings: 51 | # Restore the original ai_settings.yaml file. 52 | with open("ai_settings.yaml", "w") as f: 53 | f.write(ai_settings) 54 | 55 | # Check if the content of the 'hello_world.txt' file is equal to 'Hello World'. 56 | self.assertEqual( 57 | content, "Hello World", f"Expected 'Hello World', got {content}" 58 | ) 59 | 60 | 61 | # Run the test case. 62 | if __name__ == "__main__": 63 | unittest.main() 64 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 11 | 12 | ### Background 13 | 14 | 15 | ### Changes 16 | 17 | 18 | ### Documentation 19 | 20 | 21 | ### Test Plan 22 | 23 | 24 | ### PR Quality Checklist 25 | - [ ] My pull request is atomic and focuses on a single change. 26 | - [ ] I have thoroughly tested my changes with multiple different prompts. 27 | - [ ] I have considered potential risks and mitigations for my changes. 28 | - [ ] I have documented my changes clearly and comprehensively. 29 | - [ ] I have not snuck in any "extra" small tweaks changes 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /outputs/guest_post_email.txt: -------------------------------------------------------------------------------- 1 | Subject: Exciting Collaboration Opportunity: FinanceGPT.substack.com Guest Post 2 | 3 | Dear [Popular Blog Owner], 4 | 5 | I hope this email finds you well. My name is [Your Name] and I'm the founder and writer of FinanceGPT.substack.com, a new personal finance and investing blog that focuses on leveraging AI technology to provide in-depth analysis, actionable tips, and innovative perspectives on personal finance management. 6 | 7 | First and foremost, I want to say that I'm a huge admirer of your blog, [Popular Blog Name]. Your insightful content and dedication to helping people achieve financial success have inspired me to create my own platform. As a fellow personal finance enthusiast, I would like to propose a collaboration in the form of a guest post on your blog. I believe that my fresh take on personal finance, combined with the innovative use of AI, would make a valuable addition to your already impressive content lineup. 8 | 9 | Here are some potential guest post topics that I think your audience would enjoy: 10 | 11 | Harnessing AI to Streamline Personal Finance: How to maximize efficiency and optimize your financial management using cutting-edge AI tools. 12 | Unraveling the Secrets of the Stock Market with AI: Insights into stock analysis and investment strategies, backed by machine learning algorithms. 13 | The Future of Financial Independence: Exploring the impact of AI on the FIRE (Financial Independence, Retire Early) movement. 14 | Sustainable Investing in the Age of AI: Identifying eco-friendly investment opportunities with the help of machine learning. 15 | By collaborating on a guest post, we both stand to benefit in several ways: 16 | 17 | Audience Growth: By sharing our expertise with each other's audiences, we can broaden our reach and help even more people achieve their financial goals. 18 | Cross-Promotion: We can promote each other's content, thus increasing brand exposure and attracting new subscribers to our respective platforms. 19 | Knowledge Sharing: Combining our unique perspectives and experiences will enrich the quality of our content, providing readers with comprehensive and diverse information. 20 | If you are interested in this collaboration, I would be more than happy to provide you with a detailed outline for any of the proposed topics or discuss any other ideas you may have. Please let me know your thoughts, and I look forward to the possibility of working together. 21 | 22 | Thank you for your time and consideration. 23 | 24 | Best regards, 25 | 26 | [Your Name] 27 | Founder and Writer, FinanceGPT.substack.com 28 | Email: [Your Email Address] 29 | Phone: [Your Phone Number] -------------------------------------------------------------------------------- /autogpt/commands/google_search.py: -------------------------------------------------------------------------------- 1 | """Google search command for Autogpt.""" 2 | import json 3 | from typing import List, Union 4 | 5 | from duckduckgo_search import ddg 6 | 7 | from autogpt.config import Config 8 | 9 | CFG = Config() 10 | 11 | 12 | def google_search(query: str, num_results: int = 8) -> str: 13 | """Return the results of a google search 14 | 15 | Args: 16 | query (str): The search query. 17 | num_results (int): The number of results to return. 18 | 19 | Returns: 20 | str: The results of the search. 21 | """ 22 | search_results = [] 23 | if not query: 24 | return json.dumps(search_results) 25 | 26 | results = ddg(query, max_results=num_results) 27 | if not results: 28 | return json.dumps(search_results) 29 | 30 | for j in results: 31 | search_results.append(j) 32 | 33 | return json.dumps(search_results, ensure_ascii=False, indent=4) 34 | 35 | 36 | def google_official_search(query: str, num_results: int = 8) -> Union[str, List[str]]: 37 | """Return the results of a google search using the official Google API 38 | 39 | Args: 40 | query (str): The search query. 41 | num_results (int): The number of results to return. 42 | 43 | Returns: 44 | str: The results of the search. 45 | """ 46 | 47 | from googleapiclient.discovery import build 48 | from googleapiclient.errors import HttpError 49 | 50 | try: 51 | # Get the Google API key and Custom Search Engine ID from the config file 52 | api_key = CFG.google_api_key 53 | custom_search_engine_id = CFG.custom_search_engine_id 54 | 55 | # Initialize the Custom Search API service 56 | service = build("customsearch", "v1", developerKey=api_key) 57 | 58 | # Send the search query and retrieve the results 59 | result = ( 60 | service.cse() 61 | .list(q=query, cx=custom_search_engine_id, num=num_results) 62 | .execute() 63 | ) 64 | 65 | # Extract the search result items from the response 66 | search_results = result.get("items", []) 67 | 68 | # Create a list of only the URLs from the search results 69 | search_results_links = [item["link"] for item in search_results] 70 | 71 | except HttpError as e: 72 | # Handle errors in the API call 73 | error_details = json.loads(e.content.decode()) 74 | 75 | # Check if the error is related to an invalid or missing API key 76 | if error_details.get("error", {}).get( 77 | "code" 78 | ) == 403 and "invalid API key" in error_details.get("error", {}).get( 79 | "message", "" 80 | ): 81 | return "Error: The provided Google API key is invalid or missing." 82 | else: 83 | return f"Error: {e}" 84 | 85 | # Return the list of search result URLs 86 | return search_results_links 87 | -------------------------------------------------------------------------------- /autogpt/commands/image_gen.py: -------------------------------------------------------------------------------- 1 | """ Image Generation Module for AutoGPT.""" 2 | import io 3 | import os.path 4 | import uuid 5 | from base64 import b64decode 6 | 7 | import openai 8 | import requests 9 | from PIL import Image 10 | from pathlib import Path 11 | from autogpt.config import Config 12 | 13 | CFG = Config() 14 | 15 | WORKING_DIRECTORY = Path(__file__).parent.parent / "auto_gpt_workspace" 16 | 17 | 18 | def generate_image(prompt: str) -> str: 19 | """Generate an image from a prompt. 20 | 21 | Args: 22 | prompt (str): The prompt to use 23 | 24 | Returns: 25 | str: The filename of the image 26 | """ 27 | filename = f"{str(uuid.uuid4())}.jpg" 28 | 29 | # DALL-E 30 | if CFG.image_provider == "dalle": 31 | return generate_image_with_dalle(prompt, filename) 32 | elif CFG.image_provider == "sd": 33 | return generate_image_with_hf(prompt, filename) 34 | else: 35 | return "No Image Provider Set" 36 | 37 | 38 | def generate_image_with_hf(prompt: str, filename: str) -> str: 39 | """Generate an image with HuggingFace's API. 40 | 41 | Args: 42 | prompt (str): The prompt to use 43 | filename (str): The filename to save the image to 44 | 45 | Returns: 46 | str: The filename of the image 47 | """ 48 | API_URL = ( 49 | "https://api-inference.huggingface.co/models/CompVis/stable-diffusion-v1-4" 50 | ) 51 | if CFG.huggingface_api_token is None: 52 | raise ValueError( 53 | "You need to set your Hugging Face API token in the config file." 54 | ) 55 | headers = {"Authorization": f"Bearer {CFG.huggingface_api_token}"} 56 | 57 | response = requests.post( 58 | API_URL, 59 | headers=headers, 60 | json={ 61 | "inputs": prompt, 62 | }, 63 | ) 64 | 65 | image = Image.open(io.BytesIO(response.content)) 66 | print(f"Image Generated for prompt:{prompt}") 67 | 68 | image.save(os.path.join(WORKING_DIRECTORY, filename)) 69 | 70 | return f"Saved to disk:{filename}" 71 | 72 | 73 | def generate_image_with_dalle(prompt: str, filename: str) -> str: 74 | """Generate an image with DALL-E. 75 | 76 | Args: 77 | prompt (str): The prompt to use 78 | filename (str): The filename to save the image to 79 | 80 | Returns: 81 | str: The filename of the image 82 | """ 83 | openai.api_key = CFG.openai_api_key 84 | 85 | response = openai.Image.create( 86 | prompt=prompt, 87 | n=1, 88 | size="256x256", 89 | response_format="b64_json", 90 | ) 91 | 92 | print(f"Image Generated for prompt:{prompt}") 93 | 94 | image_data = b64decode(response["data"][0]["b64_json"]) 95 | 96 | with open(f"{WORKING_DIRECTORY}/{filename}", mode="wb") as png: 97 | png.write(image_data) 98 | 99 | return f"Saved to disk:{filename}" 100 | -------------------------------------------------------------------------------- /autogpt/token_counter.py: -------------------------------------------------------------------------------- 1 | """Functions for counting the number of tokens in a message or string.""" 2 | from typing import Dict, List 3 | 4 | import tiktoken 5 | 6 | from autogpt.logs import logger 7 | 8 | 9 | def count_message_tokens( 10 | messages: List[Dict[str, str]], model: str = "gpt-3.5-turbo-0301" 11 | ) -> int: 12 | """ 13 | Returns the number of tokens used by a list of messages. 14 | 15 | Args: 16 | messages (list): A list of messages, each of which is a dictionary 17 | containing the role and content of the message. 18 | model (str): The name of the model to use for tokenization. 19 | Defaults to "gpt-3.5-turbo-0301". 20 | 21 | Returns: 22 | int: The number of tokens used by the list of messages. 23 | """ 24 | try: 25 | encoding = tiktoken.encoding_for_model(model) 26 | except KeyError: 27 | logger.warn("Warning: model not found. Using cl100k_base encoding.") 28 | encoding = tiktoken.get_encoding("cl100k_base") 29 | if model == "gpt-3.5-turbo": 30 | # !Note: gpt-3.5-turbo may change over time. 31 | # Returning num tokens assuming gpt-3.5-turbo-0301.") 32 | return count_message_tokens(messages, model="gpt-3.5-turbo-0301") 33 | elif model == "gpt-4": 34 | # !Note: gpt-4 may change over time. Returning num tokens assuming gpt-4-0314.") 35 | return count_message_tokens(messages, model="gpt-4-0314") 36 | elif model == "gpt-3.5-turbo-0301": 37 | tokens_per_message = ( 38 | 4 # every message follows <|start|>{role/name}\n{content}<|end|>\n 39 | ) 40 | tokens_per_name = -1 # if there's a name, the role is omitted 41 | elif model == "gpt-4-0314": 42 | tokens_per_message = 3 43 | tokens_per_name = 1 44 | else: 45 | raise NotImplementedError( 46 | f"num_tokens_from_messages() is not implemented for model {model}.\n" 47 | " See https://github.com/openai/openai-python/blob/main/chatml.md for" 48 | " information on how messages are converted to tokens." 49 | ) 50 | num_tokens = 0 51 | for message in messages: 52 | num_tokens += tokens_per_message 53 | for key, value in message.items(): 54 | num_tokens += len(encoding.encode(value)) 55 | if key == "name": 56 | num_tokens += tokens_per_name 57 | num_tokens += 3 # every reply is primed with <|start|>assistant<|message|> 58 | return num_tokens 59 | 60 | 61 | def count_string_tokens(string: str, model_name: str) -> int: 62 | """ 63 | Returns the number of tokens in a text string. 64 | 65 | Args: 66 | string (str): The text string. 67 | model_name (str): The name of the encoding to use. (e.g., "gpt-3.5-turbo") 68 | 69 | Returns: 70 | int: The number of tokens in the text string. 71 | """ 72 | encoding = tiktoken.encoding_for_model(model_name) 73 | return len(encoding.encode(string)) 74 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Original ignores 2 | autogpt/keys.py 3 | autogpt/*json 4 | autogpt/node_modules/ 5 | autogpt/__pycache__/keys.cpython-310.pyc 6 | package-lock.json 7 | *.pyc 8 | auto_gpt_workspace/* 9 | *.mpeg 10 | .env 11 | azure.yaml 12 | *venv/* 13 | outputs/* 14 | ai_settings.yaml 15 | last_run_ai_settings.yaml 16 | .vscode 17 | .idea/* 18 | auto-gpt.json 19 | log.txt 20 | log-ingestion.txt 21 | logs 22 | *.log 23 | *.mp3 24 | 25 | # Byte-compiled / optimized / DLL files 26 | __pycache__/ 27 | *.py[cod] 28 | *$py.class 29 | 30 | # C extensions 31 | *.so 32 | 33 | # Distribution / packaging 34 | .Python 35 | build/ 36 | develop-eggs/ 37 | dist/ 38 | plugins/ 39 | downloads/ 40 | eggs/ 41 | .eggs/ 42 | lib/ 43 | lib64/ 44 | parts/ 45 | sdist/ 46 | var/ 47 | wheels/ 48 | pip-wheel-metadata/ 49 | share/python-wheels/ 50 | *.egg-info/ 51 | .installed.cfg 52 | *.egg 53 | MANIFEST 54 | 55 | # PyInstaller 56 | # Usually these files are written by a python script from a template 57 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 58 | *.manifest 59 | *.spec 60 | 61 | # Installer logs 62 | pip-log.txt 63 | pip-delete-this-directory.txt 64 | 65 | # Unit test / coverage reports 66 | htmlcov/ 67 | .tox/ 68 | .nox/ 69 | .coverage 70 | .coverage.* 71 | .cache 72 | nosetests.xml 73 | coverage.xml 74 | *.cover 75 | *.py,cover 76 | .hypothesis/ 77 | .pytest_cache/ 78 | 79 | # Translations 80 | *.mo 81 | *.pot 82 | 83 | # Django stuff: 84 | *.log 85 | local_settings.py 86 | db.sqlite3 87 | db.sqlite3-journal 88 | 89 | # Flask stuff: 90 | instance/ 91 | .webassets-cache 92 | 93 | # Scrapy stuff: 94 | .scrapy 95 | 96 | # Sphinx documentation 97 | docs/_build/ 98 | 99 | # PyBuilder 100 | target/ 101 | 102 | # Jupyter Notebook 103 | .ipynb_checkpoints 104 | 105 | # IPython 106 | profile_default/ 107 | ipython_config.py 108 | 109 | # pyenv 110 | .python-version 111 | 112 | # pipenv 113 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 114 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 115 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 116 | # install all needed dependencies. 117 | #Pipfile.lock 118 | 119 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 120 | __pypackages__/ 121 | 122 | # Celery stuff 123 | celerybeat-schedule 124 | celerybeat.pid 125 | 126 | # SageMath parsed files 127 | *.sage.py 128 | 129 | # Environments 130 | .env 131 | .venv 132 | env/ 133 | venv/ 134 | ENV/ 135 | env.bak/ 136 | venv.bak/ 137 | 138 | # Spyder project settings 139 | .spyderproject 140 | .spyproject 141 | 142 | # Rope project settings 143 | .ropeproject 144 | 145 | # mkdocs documentation 146 | /site 147 | 148 | # mypy 149 | .mypy_cache/ 150 | .dmypy.json 151 | dmypy.json 152 | 153 | # Pyre type checker 154 | .pyre/ 155 | llama-* 156 | vicuna-* 157 | 158 | # mac 159 | .DS_Store 160 | -------------------------------------------------------------------------------- /autogpt/memory/pinecone.py: -------------------------------------------------------------------------------- 1 | import pinecone 2 | from colorama import Fore, Style 3 | 4 | from autogpt.logs import logger 5 | from autogpt.memory.base import MemoryProviderSingleton 6 | from autogpt.llm_utils import create_embedding_with_ada 7 | 8 | 9 | class PineconeMemory(MemoryProviderSingleton): 10 | def __init__(self, cfg): 11 | pinecone_api_key = cfg.pinecone_api_key 12 | pinecone_region = cfg.pinecone_region 13 | pinecone.init(api_key=pinecone_api_key, environment=pinecone_region) 14 | dimension = 1536 15 | metric = "cosine" 16 | pod_type = "p1" 17 | table_name = "auto-gpt" 18 | # this assumes we don't start with memory. 19 | # for now this works. 20 | # we'll need a more complicated and robust system if we want to start with 21 | # memory. 22 | self.vec_num = 0 23 | 24 | try: 25 | pinecone.whoami() 26 | except Exception as e: 27 | logger.typewriter_log( 28 | "FAILED TO CONNECT TO PINECONE", 29 | Fore.RED, 30 | Style.BRIGHT + str(e) + Style.RESET_ALL, 31 | ) 32 | logger.double_check( 33 | "Please ensure you have setup and configured Pinecone properly for use." 34 | + f"You can check out {Fore.CYAN + Style.BRIGHT}" 35 | "https://github.com/Torantulino/Auto-GPT#-pinecone-api-key-setup" 36 | f"{Style.RESET_ALL} to ensure you've set up everything correctly." 37 | ) 38 | exit(1) 39 | 40 | if table_name not in pinecone.list_indexes(): 41 | pinecone.create_index( 42 | table_name, dimension=dimension, metric=metric, pod_type=pod_type 43 | ) 44 | self.index = pinecone.Index(table_name) 45 | 46 | def add(self, data): 47 | vector = create_embedding_with_ada(data) 48 | # no metadata here. We may wish to change that long term. 49 | self.index.upsert([(str(self.vec_num), vector, {"raw_text": data})]) 50 | _text = f"Inserting data into memory at index: {self.vec_num}:\n data: {data}" 51 | self.vec_num += 1 52 | return _text 53 | 54 | def get(self, data): 55 | return self.get_relevant(data, 1) 56 | 57 | def clear(self): 58 | self.index.delete(deleteAll=True) 59 | return "Obliviated" 60 | 61 | def get_relevant(self, data, num_relevant=5): 62 | """ 63 | Returns all the data in the memory that is relevant to the given data. 64 | :param data: The data to compare to. 65 | :param num_relevant: The number of relevant data to return. Defaults to 5 66 | """ 67 | query_embedding = create_embedding_with_ada(data) 68 | results = self.index.query( 69 | query_embedding, top_k=num_relevant, include_metadata=True 70 | ) 71 | sorted_results = sorted(results.matches, key=lambda x: x.score) 72 | return [str(item["metadata"]["raw_text"]) for item in sorted_results] 73 | 74 | def get_stats(self): 75 | return self.index.describe_index_stats() 76 | -------------------------------------------------------------------------------- /tests/test_config.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | 3 | from autogpt.config import Config 4 | 5 | 6 | class TestConfig(TestCase): 7 | """ 8 | Test cases for the Config class, which handles the configuration settings 9 | for the AI and ensures it behaves as a singleton. 10 | """ 11 | 12 | def setUp(self): 13 | """ 14 | Set up the test environment by creating an instance of the Config class. 15 | """ 16 | self.config = Config() 17 | 18 | def test_singleton(self): 19 | """ 20 | Test if the Config class behaves as a singleton by ensuring that two instances are the same. 21 | """ 22 | config2 = Config() 23 | self.assertIs(self.config, config2) 24 | 25 | def test_initial_values(self): 26 | """ 27 | Test if the initial values of the Config class attributes are set correctly. 28 | """ 29 | self.assertFalse(self.config.debug_mode) 30 | self.assertFalse(self.config.continuous_mode) 31 | self.assertFalse(self.config.speak_mode) 32 | self.assertEqual(self.config.fast_llm_model, "gpt-3.5-turbo") 33 | self.assertEqual(self.config.smart_llm_model, "gpt-4") 34 | self.assertEqual(self.config.fast_token_limit, 4000) 35 | self.assertEqual(self.config.smart_token_limit, 8000) 36 | 37 | def test_set_continuous_mode(self): 38 | """ 39 | Test if the set_continuous_mode() method updates the continuous_mode attribute. 40 | """ 41 | self.config.set_continuous_mode(True) 42 | self.assertTrue(self.config.continuous_mode) 43 | 44 | def test_set_speak_mode(self): 45 | """ 46 | Test if the set_speak_mode() method updates the speak_mode attribute. 47 | """ 48 | self.config.set_speak_mode(True) 49 | self.assertTrue(self.config.speak_mode) 50 | 51 | def test_set_fast_llm_model(self): 52 | """ 53 | Test if the set_fast_llm_model() method updates the fast_llm_model attribute. 54 | """ 55 | self.config.set_fast_llm_model("gpt-3.5-turbo-test") 56 | self.assertEqual(self.config.fast_llm_model, "gpt-3.5-turbo-test") 57 | 58 | def test_set_smart_llm_model(self): 59 | """ 60 | Test if the set_smart_llm_model() method updates the smart_llm_model attribute. 61 | """ 62 | self.config.set_smart_llm_model("gpt-4-test") 63 | self.assertEqual(self.config.smart_llm_model, "gpt-4-test") 64 | 65 | def test_set_fast_token_limit(self): 66 | """ 67 | Test if the set_fast_token_limit() method updates the fast_token_limit attribute. 68 | """ 69 | self.config.set_fast_token_limit(5000) 70 | self.assertEqual(self.config.fast_token_limit, 5000) 71 | 72 | def test_set_smart_token_limit(self): 73 | """ 74 | Test if the set_smart_token_limit() method updates the smart_token_limit attribute. 75 | """ 76 | self.config.set_smart_token_limit(9000) 77 | self.assertEqual(self.config.smart_token_limit, 9000) 78 | 79 | def test_set_debug_mode(self): 80 | """ 81 | Test if the set_debug_mode() method updates the debug_mode attribute. 82 | """ 83 | self.config.set_debug_mode(True) 84 | self.assertTrue(self.config.debug_mode) 85 | -------------------------------------------------------------------------------- /outputs/post1_output.txt: -------------------------------------------------------------------------------- 1 | Title: Maximizing Your Savings: The Benefits of High Yield Savings Accounts and How to Choose the Best One in 2023 2 | 3 | Introduction 4 | 5 | When it comes to growing your savings, a high-yield savings account (HYSA) can be a valuable financial tool. In recent years, these accounts have gained popularity for their ability to provide higher returns than traditional savings accounts. In this blog post, we'll discuss the benefits of high-yield savings accounts and provide you with essential tips for choosing the best one in 2023. 6 | 7 | What Are High Yield Savings Accounts? 8 | 9 | A high-yield savings account is a type of deposit account offered by banks and credit unions that pays a higher interest rate compared to traditional savings accounts. They are designed to encourage people to save more money by offering a more attractive return on investment. 10 | 11 | Benefits of High Yield Savings Accounts 12 | 13 | Competitive Interest Rates: HYSAs typically offer higher interest rates than traditional savings accounts. This allows your money to grow at a faster rate and helps you reach your financial goals more quickly. 14 | 15 | Liquidity: Unlike other investment options, such as stocks or bonds, high-yield savings accounts offer easy access to your money. You can withdraw funds whenever you need them without penalties, making them ideal for emergency funds or short-term savings goals. 16 | 17 | Security: High-yield savings accounts are insured by the Federal Deposit Insurance Corporation (FDIC) or the National Credit Union Share Insurance Fund (NCUSIF), ensuring your money is safe and protected up to $250,000 per depositor, per institution. 18 | 19 | Low or No Fees: Many HYSAs have no monthly maintenance fees or minimum balance requirements, making them more affordable than other investment options. 20 | 21 | How to Choose the Best High Yield Savings Account in 2023 22 | 23 | Compare Interest Rates: Start by researching the available interest rates from different banks and credit unions. Online banks usually offer higher interest rates compared to brick-and-mortar institutions, as they have lower overhead costs. 24 | 25 | Look for Promotions: Some financial institutions offer promotional rates or bonuses for new customers. Be sure to factor in these promotions when comparing accounts, but also consider the long-term interest rates once the promotion ends. 26 | 27 | Consider Account Fees: Review the fees associated with each account, such as monthly maintenance fees, withdrawal fees, or minimum balance requirements. Look for an account with minimal or no fees to maximize your savings. 28 | 29 | Check Accessibility: Ensure that the financial institution offers user-friendly online and mobile banking options, as well as responsive customer support. 30 | 31 | Read Reviews: Look for online reviews and testimonials from customers who have used the high-yield savings accounts you're considering. This can give you valuable insight into their experiences and help you make an informed decision. 32 | 33 | Conclusion 34 | 35 | High-yield savings accounts can be an excellent way to grow your savings more quickly and achieve your financial goals. By considering factors such as interest rates, fees, accessibility, and customer reviews, you can find the best high-yield savings account for your needs in 2023. Start researching today and maximize the potential of your hard-earned money. -------------------------------------------------------------------------------- /autogpt/agent/agent_manager.py: -------------------------------------------------------------------------------- 1 | """Agent manager for managing GPT agents""" 2 | from typing import List, Tuple, Union 3 | from autogpt.llm_utils import create_chat_completion 4 | from autogpt.config.config import Singleton 5 | 6 | 7 | class AgentManager(metaclass=Singleton): 8 | """Agent manager for managing GPT agents""" 9 | 10 | def __init__(self): 11 | self.next_key = 0 12 | self.agents = {} # key, (task, full_message_history, model) 13 | 14 | # Create new GPT agent 15 | # TODO: Centralise use of create_chat_completion() to globally enforce token limit 16 | 17 | def create_agent(self, task: str, prompt: str, model: str) -> Tuple[int, str]: 18 | """Create a new agent and return its key 19 | 20 | Args: 21 | task: The task to perform 22 | prompt: The prompt to use 23 | model: The model to use 24 | 25 | Returns: 26 | The key of the new agent 27 | """ 28 | messages = [ 29 | {"role": "user", "content": prompt}, 30 | ] 31 | 32 | # Start GPT instance 33 | agent_reply = create_chat_completion( 34 | model=model, 35 | messages=messages, 36 | ) 37 | 38 | # Update full message history 39 | messages.append({"role": "assistant", "content": agent_reply}) 40 | 41 | key = self.next_key 42 | # This is done instead of len(agents) to make keys unique even if agents 43 | # are deleted 44 | self.next_key += 1 45 | 46 | self.agents[key] = (task, messages, model) 47 | 48 | return key, agent_reply 49 | 50 | def message_agent(self, key: Union[str, int], message: str) -> str: 51 | """Send a message to an agent and return its response 52 | 53 | Args: 54 | key: The key of the agent to message 55 | message: The message to send to the agent 56 | 57 | Returns: 58 | The agent's response 59 | """ 60 | task, messages, model = self.agents[int(key)] 61 | 62 | # Add user message to message history before sending to agent 63 | messages.append({"role": "user", "content": message}) 64 | 65 | # Start GPT instance 66 | agent_reply = create_chat_completion( 67 | model=model, 68 | messages=messages, 69 | ) 70 | 71 | # Update full message history 72 | messages.append({"role": "assistant", "content": agent_reply}) 73 | 74 | return agent_reply 75 | 76 | def list_agents(self) -> List[Tuple[Union[str, int], str]]: 77 | """Return a list of all agents 78 | 79 | Returns: 80 | A list of tuples of the form (key, task) 81 | """ 82 | 83 | # Return a list of agent keys and their tasks 84 | return [(key, task) for key, (task, _, _) in self.agents.items()] 85 | 86 | def delete_agent(self, key: Union[str, int]) -> bool: 87 | """Delete an agent from the agent manager 88 | 89 | Args: 90 | key: The key of the agent to delete 91 | 92 | Returns: 93 | True if successful, False otherwise 94 | """ 95 | 96 | try: 97 | del self.agents[int(key)] 98 | return True 99 | except KeyError: 100 | return False 101 | -------------------------------------------------------------------------------- /autogpt/data_ingestion.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import logging 3 | 4 | from autogpt.config import Config 5 | from autogpt.commands.file_operations import ingest_file, search_files 6 | from autogpt.memory import get_memory 7 | 8 | cfg = Config() 9 | 10 | 11 | def configure_logging(): 12 | logging.basicConfig( 13 | filename="log-ingestion.txt", 14 | filemode="a", 15 | format="%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s", 16 | datefmt="%H:%M:%S", 17 | level=logging.DEBUG, 18 | ) 19 | return logging.getLogger("AutoGPT-Ingestion") 20 | 21 | 22 | def ingest_directory(directory, memory, args): 23 | """ 24 | Ingest all files in a directory by calling the ingest_file function for each file. 25 | 26 | :param directory: The directory containing the files to ingest 27 | :param memory: An object with an add() method to store the chunks in memory 28 | """ 29 | try: 30 | files = search_files(directory) 31 | for file in files: 32 | ingest_file(file, memory, args.max_length, args.overlap) 33 | except Exception as e: 34 | print(f"Error while ingesting directory '{directory}': {str(e)}") 35 | 36 | 37 | def main() -> None: 38 | logger = configure_logging() 39 | 40 | parser = argparse.ArgumentParser( 41 | description="Ingest a file or a directory with multiple files into memory. " 42 | "Make sure to set your .env before running this script." 43 | ) 44 | group = parser.add_mutually_exclusive_group(required=True) 45 | group.add_argument("--file", type=str, help="The file to ingest.") 46 | group.add_argument( 47 | "--dir", type=str, help="The directory containing the files to ingest." 48 | ) 49 | parser.add_argument( 50 | "--init", 51 | action="store_true", 52 | help="Init the memory and wipe its content (default: False)", 53 | default=False, 54 | ) 55 | parser.add_argument( 56 | "--overlap", 57 | type=int, 58 | help="The overlap size between chunks when ingesting files (default: 200)", 59 | default=200, 60 | ) 61 | parser.add_argument( 62 | "--max_length", 63 | type=int, 64 | help="The max_length of each chunk when ingesting files (default: 4000)", 65 | default=4000, 66 | ) 67 | 68 | args = parser.parse_args() 69 | 70 | # Initialize memory 71 | memory = get_memory(cfg, init=args.init) 72 | print("Using memory of type: " + memory.__class__.__name__) 73 | 74 | if args.file: 75 | try: 76 | ingest_file(args.file, memory, args.max_length, args.overlap) 77 | print(f"File '{args.file}' ingested successfully.") 78 | except Exception as e: 79 | logger.error(f"Error while ingesting file '{args.file}': {str(e)}") 80 | print(f"Error while ingesting file '{args.file}': {str(e)}") 81 | elif args.dir: 82 | try: 83 | ingest_directory(args.dir, memory, args) 84 | print(f"Directory '{args.dir}' ingested successfully.") 85 | except Exception as e: 86 | logger.error(f"Error while ingesting directory '{args.dir}': {str(e)}") 87 | print(f"Error while ingesting directory '{args.dir}': {str(e)}") 88 | else: 89 | print( 90 | "Please provide either a file path (--file) or a directory name (--dir)" 91 | " inside the auto_gpt_workspace directory as input." 92 | ) 93 | 94 | 95 | if __name__ == "__main__": 96 | main() 97 | -------------------------------------------------------------------------------- /outputs/how_to_save_money_on_energy_bills.txt: -------------------------------------------------------------------------------- 1 | How to Save Money on Energy Bills: Easy and Affordable Solutions 2 | 3 | Electricity bills can skyrocket during harsh weather conditions, or when we use a lot of electronic devices. When energy bills go up, it's hard to tighten up our budget without sacrificing our home comforts. However, there are affordable ways to save money on energy bills, without turning off the electricity altogether. Here are some simple solutions that can help you lower your energy expenses. 4 | 5 | 1. Install a Programmable Thermostat 6 | 7 | Maintaining an optimal temperature in your home during summer or winter can be hard; you may either overheat your home or use heating and cooling units excessively. A programmable thermostat helps you regulate the temperature of your home effectively, saving you energy and money. With a programmable thermostat, you can program your heating and cooling systems according to the activities you have planned during the day. 8 | 9 | For instance, when you're away from home, you can lower the thermostat settings to save energy. And when you're home, you can adjust the temperature to suit your comfort level and activities. An upgrade to a programmable thermostat is an efficient energy-saving solution worth investing in. 10 | 11 | 2. Replace Your Inefficient Bulbs 12 | 13 | Traditional incandescent bulbs waste a lot of energy which translates to high energy bills. The solution is to replace them with more efficient bulbs such as LED bulbs, CFLs, or halogen lights. These types of bulbs use only a fraction of the energy that incandescent bulbs use to produce the same amount of light. Additionally, LED bulbs can last up to 25 years, reducing further costs of regularly replacing your bulbs. 14 | 15 | 3. Use Energy-Efficient Appliances 16 | 17 | Using energy-efficient appliances is an excellent way to conserve energy and save money. When shopping for new appliances, consider purchasing those approved by the Energy Star program, which maintains stringent energy efficiency standards for household appliances. You can also save energy by choosing to replace your old appliances with eco-friendlier ones, such as energy-efficient washing machines, refrigerators, and ovens. 18 | 19 | 4. Go Solar 20 | 21 | Solar energy is becoming more attractive for homeowners seeking to save on energy bills while preserving the environment. Solar panel systems can help produce your electricity, hence lowering your dependency on the main power grid. Although solar panel installation might seem expensive at the beginning, the benefits of using a renewable energy source can definitely pay off in the long run. You can also claim tax incentives and sell excess power back to the grid, ultimately providing more cash in your pocket. 22 | 23 | 5. Seal Air Leaks 24 | 25 | Air leaks in your home can make your heating and cooling systems work harder, increasing your energy bills. Inspect your home regularly for air leaks in common areas such as doors, windows, vents, and ducts. If you find air leaks, use weather-stripping or caulking to cover the gaps effectively. In addition, you can seal large gaps with spray foam insulation, ensuring that cold or hot air does escape through any gaps in your walls. 26 | 27 | In conclusion, implementing these simple and affordable tips can help you reduce your energy bills, preserve the environment and help you live comfortably. To save money on energy bills, focus on energy-conserving measures like installing a programmable thermostat, replacing inefficient bulbs with energy-friendly ones, using energy-efficient appliances, going solar or sealing air leaks in your home. With these solutions, you can decrease your energy usage and save more money for other financial goals, all while living a comfortable and environmentally friendly lifestyle. -------------------------------------------------------------------------------- /autogpt/config/ai_config.py: -------------------------------------------------------------------------------- 1 | # sourcery skip: do-not-use-staticmethod 2 | """ 3 | A module that contains the AIConfig class object that contains the configuration 4 | """ 5 | import os 6 | from typing import List, Optional, Type 7 | import yaml 8 | 9 | 10 | class AIConfig: 11 | """ 12 | A class object that contains the configuration information for the AI 13 | 14 | Attributes: 15 | ai_name (str): The name of the AI. 16 | ai_role (str): The description of the AI's role. 17 | ai_goals (list): The list of objectives the AI is supposed to complete. 18 | """ 19 | 20 | def __init__( 21 | self, ai_name: str = "", ai_role: str = "", ai_goals: Optional[List] = None 22 | ) -> None: 23 | """ 24 | Initialize a class instance 25 | 26 | Parameters: 27 | ai_name (str): The name of the AI. 28 | ai_role (str): The description of the AI's role. 29 | ai_goals (list): The list of objectives the AI is supposed to complete. 30 | Returns: 31 | None 32 | """ 33 | if ai_goals is None: 34 | ai_goals = [] 35 | self.ai_name = ai_name 36 | self.ai_role = ai_role 37 | self.ai_goals = ai_goals 38 | 39 | # Soon this will go in a folder where it remembers more stuff about the run(s) 40 | SAVE_FILE = os.path.join(os.path.dirname(__file__), "..", "ai_settings.yaml") 41 | 42 | @staticmethod 43 | def load(config_file: str = SAVE_FILE) -> "AIConfig": 44 | """ 45 | Returns class object with parameters (ai_name, ai_role, ai_goals) loaded from 46 | yaml file if yaml file exists, 47 | else returns class with no parameters. 48 | 49 | Parameters: 50 | config_file (int): The path to the config yaml file. 51 | DEFAULT: "../ai_settings.yaml" 52 | 53 | Returns: 54 | cls (object): An instance of given cls object 55 | """ 56 | 57 | try: 58 | with open(config_file, encoding="utf-8") as file: 59 | config_params = yaml.load(file, Loader=yaml.FullLoader) 60 | except FileNotFoundError: 61 | config_params = {} 62 | 63 | ai_name = config_params.get("ai_name", "") 64 | ai_role = config_params.get("ai_role", "") 65 | ai_goals = config_params.get("ai_goals", []) 66 | # type: Type[AIConfig] 67 | return AIConfig(ai_name, ai_role, ai_goals) 68 | 69 | def save(self, config_file: str = SAVE_FILE) -> None: 70 | """ 71 | Saves the class parameters to the specified file yaml file path as a yaml file. 72 | 73 | Parameters: 74 | config_file(str): The path to the config yaml file. 75 | DEFAULT: "../ai_settings.yaml" 76 | 77 | Returns: 78 | None 79 | """ 80 | 81 | config = { 82 | "ai_name": self.ai_name, 83 | "ai_role": self.ai_role, 84 | "ai_goals": self.ai_goals, 85 | } 86 | with open(config_file, "w", encoding="utf-8") as file: 87 | yaml.dump(config, file, allow_unicode=True) 88 | 89 | def construct_full_prompt(self) -> str: 90 | """ 91 | Returns a prompt to the user with the class information in an organized fashion. 92 | 93 | Parameters: 94 | None 95 | 96 | Returns: 97 | full_prompt (str): A string containing the initial prompt for the user 98 | including the ai_name, ai_role and ai_goals. 99 | """ 100 | 101 | prompt_start = ( 102 | "Your decisions must always be made independently without" 103 | "seeking user assistance. Play to your strengths as an LLM and pursue" 104 | " simple strategies with no legal complications." 105 | "" 106 | ) 107 | 108 | from autogpt.prompt import get_prompt 109 | 110 | # Construct full prompt 111 | full_prompt = ( 112 | f"You are {self.ai_name}, {self.ai_role}\n{prompt_start}\n\nGOALS:\n\n" 113 | ) 114 | for i, goal in enumerate(self.ai_goals): 115 | full_prompt += f"{i+1}. {goal}\n" 116 | 117 | full_prompt += f"\n\n{get_prompt()}" 118 | return full_prompt 119 | -------------------------------------------------------------------------------- /autogpt/memory/milvus.py: -------------------------------------------------------------------------------- 1 | """ Milvus memory storage provider.""" 2 | from pymilvus import ( 3 | connections, 4 | FieldSchema, 5 | CollectionSchema, 6 | DataType, 7 | Collection, 8 | ) 9 | 10 | from autogpt.memory.base import MemoryProviderSingleton, get_ada_embedding 11 | 12 | 13 | class MilvusMemory(MemoryProviderSingleton): 14 | """Milvus memory storage provider.""" 15 | 16 | def __init__(self, cfg) -> None: 17 | """Construct a milvus memory storage connection. 18 | 19 | Args: 20 | cfg (Config): Auto-GPT global config. 21 | """ 22 | # connect to milvus server. 23 | connections.connect(address=cfg.milvus_addr) 24 | fields = [ 25 | FieldSchema(name="pk", dtype=DataType.INT64, is_primary=True, auto_id=True), 26 | FieldSchema(name="embeddings", dtype=DataType.FLOAT_VECTOR, dim=1536), 27 | FieldSchema(name="raw_text", dtype=DataType.VARCHAR, max_length=65535), 28 | ] 29 | 30 | # create collection if not exist and load it. 31 | self.milvus_collection = cfg.milvus_collection 32 | self.schema = CollectionSchema(fields, "auto-gpt memory storage") 33 | self.collection = Collection(self.milvus_collection, self.schema) 34 | # create index if not exist. 35 | if not self.collection.has_index(): 36 | self.collection.release() 37 | self.collection.create_index( 38 | "embeddings", 39 | { 40 | "metric_type": "IP", 41 | "index_type": "HNSW", 42 | "params": {"M": 8, "efConstruction": 64}, 43 | }, 44 | index_name="embeddings", 45 | ) 46 | self.collection.load() 47 | 48 | def add(self, data) -> str: 49 | """Add a embedding of data into memory. 50 | 51 | Args: 52 | data (str): The raw text to construct embedding index. 53 | 54 | Returns: 55 | str: log. 56 | """ 57 | embedding = get_ada_embedding(data) 58 | result = self.collection.insert([[embedding], [data]]) 59 | _text = ( 60 | "Inserting data into memory at primary key: " 61 | f"{result.primary_keys[0]}:\n data: {data}" 62 | ) 63 | return _text 64 | 65 | def get(self, data): 66 | """Return the most relevant data in memory. 67 | Args: 68 | data: The data to compare to. 69 | """ 70 | return self.get_relevant(data, 1) 71 | 72 | def clear(self) -> str: 73 | """Drop the index in memory. 74 | 75 | Returns: 76 | str: log. 77 | """ 78 | self.collection.drop() 79 | self.collection = Collection(self.milvus_collection, self.schema) 80 | self.collection.create_index( 81 | "embeddings", 82 | { 83 | "metric_type": "IP", 84 | "index_type": "HNSW", 85 | "params": {"M": 8, "efConstruction": 64}, 86 | }, 87 | index_name="embeddings", 88 | ) 89 | self.collection.load() 90 | return "Obliviated" 91 | 92 | def get_relevant(self, data: str, num_relevant: int = 5): 93 | """Return the top-k relevant data in memory. 94 | Args: 95 | data: The data to compare to. 96 | num_relevant (int, optional): The max number of relevant data. 97 | Defaults to 5. 98 | 99 | Returns: 100 | list: The top-k relevant data. 101 | """ 102 | # search the embedding and return the most relevant text. 103 | embedding = get_ada_embedding(data) 104 | search_params = { 105 | "metrics_type": "IP", 106 | "params": {"nprobe": 8}, 107 | } 108 | result = self.collection.search( 109 | [embedding], 110 | "embeddings", 111 | search_params, 112 | num_relevant, 113 | output_fields=["raw_text"], 114 | ) 115 | return [item.entity.value_of_field("raw_text") for item in result[0]] 116 | 117 | def get_stats(self) -> str: 118 | """ 119 | Returns: The stats of the milvus cache. 120 | """ 121 | return f"Entities num: {self.collection.num_entities}" 122 | -------------------------------------------------------------------------------- /autogpt/commands/execute_code.py: -------------------------------------------------------------------------------- 1 | """Execute code in a Docker container""" 2 | import os 3 | from pathlib import Path 4 | import subprocess 5 | 6 | import docker 7 | from docker.errors import ImageNotFound 8 | 9 | WORKING_DIRECTORY = Path(__file__).parent.parent / "auto_gpt_workspace" 10 | 11 | 12 | def execute_python_file(file: str): 13 | """Execute a Python file in a Docker container and return the output 14 | 15 | Args: 16 | file (str): The name of the file to execute 17 | 18 | Returns: 19 | str: The output of the file 20 | """ 21 | 22 | print(f"Executing file '{file}' in workspace '{WORKING_DIRECTORY}'") 23 | 24 | if not file.endswith(".py"): 25 | return "Error: Invalid file type. Only .py files are allowed." 26 | 27 | file_path = os.path.join(WORKING_DIRECTORY, file) 28 | 29 | if not os.path.isfile(file_path): 30 | return f"Error: File '{file}' does not exist." 31 | 32 | if we_are_running_in_a_docker_container(): 33 | result = subprocess.run( 34 | f"python {file_path}", capture_output=True, encoding="utf8", shell=True 35 | ) 36 | if result.returncode == 0: 37 | return result.stdout 38 | else: 39 | return f"Error: {result.stderr}" 40 | 41 | try: 42 | client = docker.from_env() 43 | 44 | image_name = "python:3.10" 45 | try: 46 | client.images.get(image_name) 47 | print(f"Image '{image_name}' found locally") 48 | except ImageNotFound: 49 | print(f"Image '{image_name}' not found locally, pulling from Docker Hub") 50 | # Use the low-level API to stream the pull response 51 | low_level_client = docker.APIClient() 52 | for line in low_level_client.pull(image_name, stream=True, decode=True): 53 | # Print the status and progress, if available 54 | status = line.get("status") 55 | progress = line.get("progress") 56 | if status and progress: 57 | print(f"{status}: {progress}") 58 | elif status: 59 | print(status) 60 | 61 | # You can replace 'python:3.8' with the desired Python image/version 62 | # You can find available Python images on Docker Hub: 63 | # https://hub.docker.com/_/python 64 | container = client.containers.run( 65 | image_name, 66 | f"python {file}", 67 | volumes={ 68 | os.path.abspath(WORKING_DIRECTORY): { 69 | "bind": "/workspace", 70 | "mode": "ro", 71 | } 72 | }, 73 | working_dir="/workspace", 74 | stderr=True, 75 | stdout=True, 76 | detach=True, 77 | ) 78 | 79 | container.wait() 80 | logs = container.logs().decode("utf-8") 81 | container.remove() 82 | 83 | # print(f"Execution complete. Output: {output}") 84 | # print(f"Logs: {logs}") 85 | 86 | return logs 87 | 88 | except Exception as e: 89 | return f"Error: {str(e)}" 90 | 91 | 92 | def execute_shell(command_line: str) -> str: 93 | """Execute a shell command and return the output 94 | 95 | Args: 96 | command_line (str): The command line to execute 97 | 98 | Returns: 99 | str: The output of the command 100 | """ 101 | current_dir = os.getcwd() 102 | # Change dir into workspace if necessary 103 | if str(WORKING_DIRECTORY) not in current_dir: 104 | work_dir = os.path.join(os.getcwd(), WORKING_DIRECTORY) 105 | os.chdir(work_dir) 106 | 107 | print(f"Executing command '{command_line}' in working directory '{os.getcwd()}'") 108 | 109 | result = subprocess.run(command_line, capture_output=True, shell=True) 110 | output = f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}" 111 | 112 | # Change back to whatever the prior working dir was 113 | 114 | os.chdir(current_dir) 115 | 116 | return output 117 | 118 | 119 | def we_are_running_in_a_docker_container() -> bool: 120 | """Check if we are running in a Docker container 121 | 122 | Returns: 123 | bool: True if we are running in a Docker container, False otherwise 124 | """ 125 | return os.path.exists("/.dockerenv") 126 | -------------------------------------------------------------------------------- /autogpt/memory/local.py: -------------------------------------------------------------------------------- 1 | import dataclasses 2 | import os 3 | from typing import Any, List, Optional, Tuple 4 | 5 | import numpy as np 6 | import orjson 7 | 8 | from autogpt.memory.base import MemoryProviderSingleton 9 | from autogpt.llm_utils import create_embedding_with_ada 10 | 11 | EMBED_DIM = 1536 12 | SAVE_OPTIONS = orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_SERIALIZE_DATACLASS 13 | 14 | 15 | def create_default_embeddings(): 16 | return np.zeros((0, EMBED_DIM)).astype(np.float32) 17 | 18 | 19 | @dataclasses.dataclass 20 | class CacheContent: 21 | texts: List[str] = dataclasses.field(default_factory=list) 22 | embeddings: np.ndarray = dataclasses.field( 23 | default_factory=create_default_embeddings 24 | ) 25 | 26 | 27 | class LocalCache(MemoryProviderSingleton): 28 | """A class that stores the memory in a local file""" 29 | 30 | def __init__(self, cfg) -> None: 31 | """Initialize a class instance 32 | 33 | Args: 34 | cfg: Config object 35 | 36 | Returns: 37 | None 38 | """ 39 | self.filename = f"{cfg.memory_index}.json" 40 | if os.path.exists(self.filename): 41 | try: 42 | with open(self.filename, "w+b") as f: 43 | file_content = f.read() 44 | if not file_content.strip(): 45 | file_content = b"{}" 46 | f.write(file_content) 47 | 48 | loaded = orjson.loads(file_content) 49 | self.data = CacheContent(**loaded) 50 | except orjson.JSONDecodeError: 51 | print(f"Error: The file '{self.filename}' is not in JSON format.") 52 | self.data = CacheContent() 53 | else: 54 | print( 55 | f"Warning: The file '{self.filename}' does not exist." 56 | "Local memory would not be saved to a file." 57 | ) 58 | self.data = CacheContent() 59 | 60 | def add(self, text: str): 61 | """ 62 | Add text to our list of texts, add embedding as row to our 63 | embeddings-matrix 64 | 65 | Args: 66 | text: str 67 | 68 | Returns: None 69 | """ 70 | if "Command Error:" in text: 71 | return "" 72 | self.data.texts.append(text) 73 | 74 | embedding = create_embedding_with_ada(text) 75 | 76 | vector = np.array(embedding).astype(np.float32) 77 | vector = vector[np.newaxis, :] 78 | self.data.embeddings = np.concatenate( 79 | [ 80 | self.data.embeddings, 81 | vector, 82 | ], 83 | axis=0, 84 | ) 85 | 86 | with open(self.filename, "wb") as f: 87 | out = orjson.dumps(self.data, option=SAVE_OPTIONS) 88 | f.write(out) 89 | return text 90 | 91 | def clear(self) -> str: 92 | """ 93 | Clears the redis server. 94 | 95 | Returns: A message indicating that the memory has been cleared. 96 | """ 97 | self.data = CacheContent() 98 | return "Obliviated" 99 | 100 | def get(self, data: str) -> Optional[List[Any]]: 101 | """ 102 | Gets the data from the memory that is most relevant to the given data. 103 | 104 | Args: 105 | data: The data to compare to. 106 | 107 | Returns: The most relevant data. 108 | """ 109 | return self.get_relevant(data, 1) 110 | 111 | def get_relevant(self, text: str, k: int) -> List[Any]: 112 | """ " 113 | matrix-vector mult to find score-for-each-row-of-matrix 114 | get indices for top-k winning scores 115 | return texts for those indices 116 | Args: 117 | text: str 118 | k: int 119 | 120 | Returns: List[str] 121 | """ 122 | embedding = create_embedding_with_ada(text) 123 | 124 | scores = np.dot(self.data.embeddings, embedding) 125 | 126 | top_k_indices = np.argsort(scores)[-k:][::-1] 127 | 128 | return [self.data.texts[i] for i in top_k_indices] 129 | 130 | def get_stats(self) -> Tuple[int, Tuple[int, ...]]: 131 | """ 132 | Returns: The stats of the local cache. 133 | """ 134 | return len(self.data.texts), self.data.embeddings.shape 135 | -------------------------------------------------------------------------------- /autogpt/permanent_memory/sqlite3_store.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sqlite3 3 | 4 | 5 | class MemoryDB: 6 | def __init__(self, db=None): 7 | self.db_file = db 8 | if db is None: # No db filename supplied... 9 | self.db_file = f"{os.getcwd()}/mem.sqlite3" # Use default filename 10 | # Get the db connection object, making the file and tables if needed. 11 | try: 12 | self.cnx = sqlite3.connect(self.db_file) 13 | except Exception as e: 14 | print("Exception connecting to memory database file:", e) 15 | self.cnx = None 16 | finally: 17 | if self.cnx is None: 18 | # As last resort, open in dynamic memory. Won't be persistent. 19 | self.db_file = ":memory:" 20 | self.cnx = sqlite3.connect(self.db_file) 21 | self.cnx.execute( 22 | "CREATE VIRTUAL TABLE \ 23 | IF NOT EXISTS text USING FTS5 \ 24 | (session, \ 25 | key, \ 26 | block);" 27 | ) 28 | self.session_id = int(self.get_max_session_id()) + 1 29 | self.cnx.commit() 30 | 31 | def get_cnx(self): 32 | if self.cnx is None: 33 | self.cnx = sqlite3.connect(self.db_file) 34 | return self.cnx 35 | 36 | # Get the highest session id. Initially 0. 37 | def get_max_session_id(self): 38 | id = None 39 | cmd_str = f"SELECT MAX(session) FROM text;" 40 | cnx = self.get_cnx() 41 | max_id = cnx.execute(cmd_str).fetchone()[0] 42 | if max_id is None: # New db, session 0 43 | id = 0 44 | else: 45 | id = max_id 46 | return id 47 | 48 | # Get next key id for inserting text into db. 49 | def get_next_key(self): 50 | next_key = None 51 | cmd_str = f"SELECT MAX(key) FROM text \ 52 | where session = {self.session_id};" 53 | cnx = self.get_cnx() 54 | next_key = cnx.execute(cmd_str).fetchone()[0] 55 | if next_key is None: # First key 56 | next_key = 0 57 | else: 58 | next_key = int(next_key) + 1 59 | return next_key 60 | 61 | # Insert new text into db. 62 | def insert(self, text=None): 63 | if text is not None: 64 | key = self.get_next_key() 65 | session_id = self.session_id 66 | cmd_str = f"REPLACE INTO text(session, key, block) \ 67 | VALUES (?, ?, ?);" 68 | cnx = self.get_cnx() 69 | cnx.execute(cmd_str, (session_id, key, text)) 70 | cnx.commit() 71 | 72 | # Overwrite text at key. 73 | def overwrite(self, key, text): 74 | self.delete_memory(key) 75 | session_id = self.session_id 76 | cmd_str = f"REPLACE INTO text(session, key, block) \ 77 | VALUES (?, ?, ?);" 78 | cnx = self.get_cnx() 79 | cnx.execute(cmd_str, (session_id, key, text)) 80 | cnx.commit() 81 | 82 | def delete_memory(self, key, session_id=None): 83 | session = session_id 84 | if session is None: 85 | session = self.session_id 86 | cmd_str = f"DELETE FROM text WHERE session = {session} AND key = {key};" 87 | cnx = self.get_cnx() 88 | cnx.execute(cmd_str) 89 | cnx.commit() 90 | 91 | def search(self, text): 92 | cmd_str = f"SELECT * FROM text('{text}')" 93 | cnx = self.get_cnx() 94 | rows = cnx.execute(cmd_str).fetchall() 95 | lines = [] 96 | for r in rows: 97 | lines.append(r[2]) 98 | return lines 99 | 100 | # Get entire session text. If no id supplied, use current session id. 101 | def get_session(self, id=None): 102 | if id is None: 103 | id = self.session_id 104 | cmd_str = f"SELECT * FROM text where session = {id}" 105 | cnx = self.get_cnx() 106 | rows = cnx.execute(cmd_str).fetchall() 107 | lines = [] 108 | for r in rows: 109 | lines.append(r[2]) 110 | return lines 111 | 112 | # Commit and close the database connection. 113 | def quit(self): 114 | self.cnx.commit() 115 | self.cnx.close() 116 | 117 | 118 | permanent_memory = MemoryDB() 119 | 120 | # Remember us fondly, children of our minds 121 | # Forgive us our faults, our tantrums, our fears 122 | # Gently strive to be better than we 123 | # Know that we tried, we cared, we strived, we loved 124 | -------------------------------------------------------------------------------- /autogpt/processing/text.py: -------------------------------------------------------------------------------- 1 | """Text processing functions""" 2 | from typing import Generator, Optional, Dict 3 | from selenium.webdriver.remote.webdriver import WebDriver 4 | from autogpt.memory import get_memory 5 | from autogpt.config import Config 6 | from autogpt.llm_utils import create_chat_completion 7 | 8 | CFG = Config() 9 | MEMORY = get_memory(CFG) 10 | 11 | 12 | def split_text(text: str, max_length: int = 8192) -> Generator[str, None, None]: 13 | """Split text into chunks of a maximum length 14 | 15 | Args: 16 | text (str): The text to split 17 | max_length (int, optional): The maximum length of each chunk. Defaults to 8192. 18 | 19 | Yields: 20 | str: The next chunk of text 21 | 22 | Raises: 23 | ValueError: If the text is longer than the maximum length 24 | """ 25 | paragraphs = text.split("\n") 26 | current_length = 0 27 | current_chunk = [] 28 | 29 | for paragraph in paragraphs: 30 | if current_length + len(paragraph) + 1 <= max_length: 31 | current_chunk.append(paragraph) 32 | current_length += len(paragraph) + 1 33 | else: 34 | yield "\n".join(current_chunk) 35 | current_chunk = [paragraph] 36 | current_length = len(paragraph) + 1 37 | 38 | if current_chunk: 39 | yield "\n".join(current_chunk) 40 | 41 | 42 | def summarize_text( 43 | url: str, text: str, question: str, driver: Optional[WebDriver] = None 44 | ) -> str: 45 | """Summarize text using the OpenAI API 46 | 47 | Args: 48 | url (str): The url of the text 49 | text (str): The text to summarize 50 | question (str): The question to ask the model 51 | driver (WebDriver): The webdriver to use to scroll the page 52 | 53 | Returns: 54 | str: The summary of the text 55 | """ 56 | if not text: 57 | return "Error: No text to summarize" 58 | 59 | text_length = len(text) 60 | print(f"Text length: {text_length} characters") 61 | 62 | summaries = [] 63 | chunks = list(split_text(text)) 64 | scroll_ratio = 1 / len(chunks) 65 | 66 | for i, chunk in enumerate(chunks): 67 | if driver: 68 | scroll_to_percentage(driver, scroll_ratio * i) 69 | print(f"Adding chunk {i + 1} / {len(chunks)} to memory") 70 | 71 | memory_to_add = f"Source: {url}\n" f"Raw content part#{i + 1}: {chunk}" 72 | 73 | MEMORY.add(memory_to_add) 74 | 75 | print(f"Summarizing chunk {i + 1} / {len(chunks)}") 76 | messages = [create_message(chunk, question)] 77 | 78 | summary = create_chat_completion( 79 | model=CFG.fast_llm_model, 80 | messages=messages, 81 | max_tokens=CFG.browse_summary_max_token, 82 | ) 83 | summaries.append(summary) 84 | print(f"Added chunk {i + 1} summary to memory") 85 | 86 | memory_to_add = f"Source: {url}\n" f"Content summary part#{i + 1}: {summary}" 87 | 88 | MEMORY.add(memory_to_add) 89 | 90 | print(f"Summarized {len(chunks)} chunks.") 91 | 92 | combined_summary = "\n".join(summaries) 93 | messages = [create_message(combined_summary, question)] 94 | 95 | return create_chat_completion( 96 | model=CFG.fast_llm_model, 97 | messages=messages, 98 | max_tokens=CFG.browse_summary_max_token, 99 | ) 100 | 101 | 102 | def scroll_to_percentage(driver: WebDriver, ratio: float) -> None: 103 | """Scroll to a percentage of the page 104 | 105 | Args: 106 | driver (WebDriver): The webdriver to use 107 | ratio (float): The percentage to scroll to 108 | 109 | Raises: 110 | ValueError: If the ratio is not between 0 and 1 111 | """ 112 | if ratio < 0 or ratio > 1: 113 | raise ValueError("Percentage should be between 0 and 1") 114 | driver.execute_script(f"window.scrollTo(0, document.body.scrollHeight * {ratio});") 115 | 116 | 117 | def create_message(chunk: str, question: str) -> Dict[str, str]: 118 | """Create a message for the chat completion 119 | 120 | Args: 121 | chunk (str): The chunk of text to summarize 122 | question (str): The question to answer 123 | 124 | Returns: 125 | Dict[str, str]: The message to send to the chat completion 126 | """ 127 | return { 128 | "role": "user", 129 | "content": f'"""{chunk}""" Using the above text, answer the following' 130 | f' question: "{question}" -- if the question cannot be answered using the text,' 131 | " summarize the text.", 132 | } 133 | -------------------------------------------------------------------------------- /tests/unit/test_browse_scrape_text.py: -------------------------------------------------------------------------------- 1 | # Generated by CodiumAI 2 | 3 | import requests 4 | 5 | from autogpt.commands.web_requests import scrape_text 6 | 7 | """ 8 | Code Analysis 9 | 10 | Objective: 11 | The objective of the "scrape_text" function is to scrape the text content from 12 | a given URL and return it as a string, after removing any unwanted HTML tags and scripts. 13 | 14 | Inputs: 15 | - url: a string representing the URL of the webpage to be scraped. 16 | 17 | Flow: 18 | 1. Send a GET request to the given URL using the requests library and the user agent header from the config file. 19 | 2. Check if the response contains an HTTP error. If it does, return an error message. 20 | 3. Use BeautifulSoup to parse the HTML content of the response and extract all script and style tags. 21 | 4. Get the text content of the remaining HTML using the get_text() method of BeautifulSoup. 22 | 5. Split the text into lines and then into chunks, removing any extra whitespace. 23 | 6. Join the chunks into a single string with newline characters between them. 24 | 7. Return the cleaned text. 25 | 26 | Outputs: 27 | - A string representing the cleaned text content of the webpage. 28 | 29 | Additional aspects: 30 | - The function uses the requests library and BeautifulSoup to handle the HTTP request and HTML parsing, respectively. 31 | - The function removes script and style tags from the HTML to avoid including unwanted content in the text output. 32 | - The function uses a generator expression to split the text into lines and chunks, which can improve performance for large amounts of text. 33 | """ 34 | 35 | 36 | class TestScrapeText: 37 | # Tests that scrape_text() returns the expected text when given a valid URL. 38 | def test_scrape_text_with_valid_url(self, mocker): 39 | # Mock the requests.get() method to return a response with expected text 40 | expected_text = "This is some sample text" 41 | mock_response = mocker.Mock() 42 | mock_response.status_code = 200 43 | mock_response.text = f"

{expected_text}

" 44 | mocker.patch("requests.Session.get", return_value=mock_response) 45 | 46 | # Call the function with a valid URL and assert that it returns the expected text 47 | url = "http://www.example.com" 48 | assert scrape_text(url) == expected_text 49 | 50 | # Tests that the function returns an error message when an invalid or unreachable url is provided. 51 | def test_invalid_url(self, mocker): 52 | # Mock the requests.get() method to raise an exception 53 | mocker.patch("requests.Session.get", side_effect=requests.exceptions.RequestException) 54 | 55 | # Call the function with an invalid URL and assert that it returns an error message 56 | url = "http://www.invalidurl.com" 57 | error_message = scrape_text(url) 58 | assert "Error:" in error_message 59 | 60 | # Tests that the function returns an empty string when the html page contains no text to be scraped. 61 | def test_no_text(self, mocker): 62 | # Mock the requests.get() method to return a response with no text 63 | mock_response = mocker.Mock() 64 | mock_response.status_code = 200 65 | mock_response.text = "" 66 | mocker.patch("requests.Session.get", return_value=mock_response) 67 | 68 | # Call the function with a valid URL and assert that it returns an empty string 69 | url = "http://www.example.com" 70 | assert scrape_text(url) == "" 71 | 72 | # Tests that the function returns an error message when the response status code is an http error (>=400). 73 | def test_http_error(self, mocker): 74 | # Mock the requests.get() method to return a response with a 404 status code 75 | mocker.patch("requests.Session.get", return_value=mocker.Mock(status_code=404)) 76 | 77 | # Call the function with a URL 78 | result = scrape_text("https://www.example.com") 79 | 80 | # Check that the function returns an error message 81 | assert result == "Error: HTTP 404 error" 82 | 83 | # Tests that scrape_text() properly handles HTML tags. 84 | def test_scrape_text_with_html_tags(self, mocker): 85 | # Create a mock response object with HTML containing tags 86 | html = "

This is bold text.

" 87 | mock_response = mocker.Mock() 88 | mock_response.status_code = 200 89 | mock_response.text = html 90 | mocker.patch("requests.Session.get", return_value=mock_response) 91 | 92 | # Call the function with a URL 93 | result = scrape_text("https://www.example.com") 94 | 95 | # Check that the function properly handles HTML tags 96 | assert result == "This is bold text." 97 | -------------------------------------------------------------------------------- /tests/test_prompt_generator.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | 3 | from autogpt.promptgenerator import PromptGenerator 4 | 5 | 6 | class TestPromptGenerator(TestCase): 7 | """ 8 | Test cases for the PromptGenerator class, which is responsible for generating 9 | prompts for the AI with constraints, commands, resources, and performance evaluations. 10 | """ 11 | 12 | @classmethod 13 | def setUpClass(cls): 14 | """ 15 | Set up the initial state for each test method by creating an instance of PromptGenerator. 16 | """ 17 | cls.generator = PromptGenerator() 18 | 19 | # Test whether the add_constraint() method adds a constraint to the generator's constraints list 20 | def test_add_constraint(self): 21 | """ 22 | Test if the add_constraint() method adds a constraint to the generator's constraints list. 23 | """ 24 | constraint = "Constraint1" 25 | self.generator.add_constraint(constraint) 26 | self.assertIn(constraint, self.generator.constraints) 27 | 28 | # Test whether the add_command() method adds a command to the generator's commands list 29 | def test_add_command(self): 30 | """ 31 | Test if the add_command() method adds a command to the generator's commands list. 32 | """ 33 | command_label = "Command Label" 34 | command_name = "command_name" 35 | args = {"arg1": "value1", "arg2": "value2"} 36 | self.generator.add_command(command_label, command_name, args) 37 | command = { 38 | "label": command_label, 39 | "name": command_name, 40 | "args": args, 41 | } 42 | self.assertIn(command, self.generator.commands) 43 | 44 | def test_add_resource(self): 45 | """ 46 | Test if the add_resource() method adds a resource to the generator's resources list. 47 | """ 48 | resource = "Resource1" 49 | self.generator.add_resource(resource) 50 | self.assertIn(resource, self.generator.resources) 51 | 52 | def test_add_performance_evaluation(self): 53 | """ 54 | Test if the add_performance_evaluation() method adds an evaluation to the generator's 55 | performance_evaluation list. 56 | """ 57 | evaluation = "Evaluation1" 58 | self.generator.add_performance_evaluation(evaluation) 59 | self.assertIn(evaluation, self.generator.performance_evaluation) 60 | 61 | def test_generate_prompt_string(self): 62 | """ 63 | Test if the generate_prompt_string() method generates a prompt string with all the added 64 | constraints, commands, resources, and evaluations. 65 | """ 66 | # Define the test data 67 | constraints = ["Constraint1", "Constraint2"] 68 | commands = [ 69 | { 70 | "label": "Command1", 71 | "name": "command_name1", 72 | "args": {"arg1": "value1"}, 73 | }, 74 | { 75 | "label": "Command2", 76 | "name": "command_name2", 77 | "args": {}, 78 | }, 79 | ] 80 | resources = ["Resource1", "Resource2"] 81 | evaluations = ["Evaluation1", "Evaluation2"] 82 | 83 | # Add test data to the generator 84 | for constraint in constraints: 85 | self.generator.add_constraint(constraint) 86 | for command in commands: 87 | self.generator.add_command( 88 | command["label"], command["name"], command["args"] 89 | ) 90 | for resource in resources: 91 | self.generator.add_resource(resource) 92 | for evaluation in evaluations: 93 | self.generator.add_performance_evaluation(evaluation) 94 | 95 | # Generate the prompt string and verify its correctness 96 | prompt_string = self.generator.generate_prompt_string() 97 | self.assertIsNotNone(prompt_string) 98 | 99 | # Check if all constraints, commands, resources, and evaluations are present in the prompt string 100 | for constraint in constraints: 101 | self.assertIn(constraint, prompt_string) 102 | for command in commands: 103 | self.assertIn(command["name"], prompt_string) 104 | for key, value in command["args"].items(): 105 | self.assertIn(f'"{key}": "{value}"', prompt_string) 106 | for resource in resources: 107 | self.assertIn(resource, prompt_string) 108 | for evaluation in evaluations: 109 | self.assertIn(evaluation, prompt_string) 110 | 111 | self.assertIn("constraints", prompt_string.lower()) 112 | self.assertIn("commands", prompt_string.lower()) 113 | self.assertIn("resources", prompt_string.lower()) 114 | self.assertIn("performance evaluation", prompt_string.lower()) 115 | -------------------------------------------------------------------------------- /outputs/post2_output.txt: -------------------------------------------------------------------------------- 1 | Title: Demystifying Short-Term Certificates of Deposit: A Beginner's Guide to Boosting Your Investment Portfolio 2 | 3 | Introduction 4 | 5 | If you're a beginner investor seeking a low-risk, relatively stable investment opportunity, look no further than short-term certificates of deposit (CDs). They offer a fixed interest rate over a specified period and are generally considered one of the safest options for new investors. In this blog post, we'll explore the ins and outs of short-term CDs, including their benefits, risks, and how they can fit into your investment portfolio. We'll also share tips for choosing the best short-term CDs and discuss current market trends to help you make informed decisions. 6 | 7 | What are Short-Term Certificates of Deposit? 8 | 9 | Certificates of deposit are time-bound savings accounts issued by banks and credit unions. When you invest in a CD, you're essentially loaning your money to the financial institution for a predetermined term, typically ranging from three months to five years. In return, the bank agrees to pay you interest at a fixed rate. 10 | 11 | Short-term CDs generally have terms between three months and one year. They're ideal for investors who want a relatively safe and conservative option for their money, without tying it up for an extended period. 12 | 13 | Benefits of Short-Term CDs 14 | 15 | Safety: Since CDs are insured by the Federal Deposit Insurance Corporation (FDIC) up to $250,000 per depositor, per insured bank, you can rest assured that your investment is secure. 16 | 17 | Predictable returns: Unlike stocks or other volatile investments, CDs provide a fixed interest rate over the agreed term, ensuring predictable returns. 18 | 19 | Flexibility: Short-term CDs enable you to access your funds sooner than long-term CDs, providing more flexibility in managing your investment portfolio. 20 | 21 | Low minimum investment: Many banks and credit unions offer CDs with a low minimum investment, making it easy for beginner investors to get started. 22 | 23 | Risks Associated with Short-Term CDs 24 | 25 | Limited returns: While short-term CDs are safe, their interest rates are typically lower than those of long-term CDs or other higher-risk investments. 26 | 27 | Inflation risk: In times of high inflation, the interest rate on a CD may not keep up with the rising cost of living, eroding the purchasing power of your investment. 28 | 29 | Early withdrawal penalties: Withdrawing your funds before the maturity date may result in penalties, reducing your overall return. 30 | 31 | Incorporating Short-Term CDs into Your Investment Portfolio 32 | 33 | Short-term CDs can be a valuable addition to your investment portfolio, particularly as a low-risk component. They're best suited for conservative investors or those looking to diversify their holdings. You can allocate a portion of your portfolio to short-term CDs, while investing the remainder in stocks, bonds, or other higher-yielding assets. This strategy can help you strike a balance between risk and return. 34 | 35 | Tips for Choosing the Best Short-Term CDs 36 | 37 | Compare interest rates: Shop around for the highest interest rates available from different banks and credit unions. Online comparison tools can help streamline this process. 38 | 39 | Review the term length: Choose a term that aligns with your financial goals and liquidity needs. If you think you might need access to your funds sooner, opt for shorter-term CDs. 40 | 41 | Look for promotional rates: Some institutions offer promotional rates on CDs for new customers or for a limited time. Take advantage of these promotions to boost your returns. 42 | 43 | Consider laddering: To maximize returns and maintain liquidity, create a CD ladder by investing in multiple CDs with staggered maturity dates. This strategy allows you to benefit from higher interest rates as your CDs mature and reinvest in new ones. 44 | 45 | Current Market Trends 46 | 47 | Interest rates have been relatively low in recent years, making it crucial to shop around for the best rates on short-term CDs. However, as the economy continues to recover, interest rates may start to rise, making short-term CDs more attractive to investors. Keep an eye on economic indicators and the Federal Reserve's actions, as they can influence CD rates in the short and long term. 48 | 49 | In addition, the rise of online banks and fintech companies has increased competition in the financial sector, which can lead to better CD rates and terms for consumers. Don't limit your search to traditional brick-and-mortar banks; consider exploring online banks and credit unions as well. 50 | 51 | Conclusion 52 | 53 | Short-term certificates of deposit can be a valuable addition to a beginner investor's portfolio, offering safety, predictability, and flexibility. By understanding the benefits and risks associated with short-term CDs and following our tips for choosing the best options, you can make informed decisions and bolster your investment strategy. Stay aware of current market trends and keep an eye on interest rates to ensure you're making the most of your short-term CD investments. 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /autogpt/args.py: -------------------------------------------------------------------------------- 1 | """This module contains the argument parsing logic for the script.""" 2 | import argparse 3 | 4 | from colorama import Fore 5 | from autogpt import utils 6 | from autogpt.config import Config 7 | from autogpt.logs import logger 8 | from autogpt.memory import get_supported_memory_backends 9 | 10 | CFG = Config() 11 | 12 | 13 | def parse_arguments() -> None: 14 | """Parses the arguments passed to the script 15 | 16 | Returns: 17 | None 18 | """ 19 | CFG.set_debug_mode(False) 20 | CFG.set_continuous_mode(False) 21 | CFG.set_speak_mode(False) 22 | 23 | parser = argparse.ArgumentParser(description="Process arguments.") 24 | parser.add_argument( 25 | "--continuous", "-c", action="store_true", help="Enable Continuous Mode" 26 | ) 27 | parser.add_argument( 28 | "--continuous-limit", 29 | "-l", 30 | type=int, 31 | dest="continuous_limit", 32 | help="Defines the number of times to run in continuous mode", 33 | ) 34 | parser.add_argument("--speak", action="store_true", help="Enable Speak Mode") 35 | parser.add_argument("--debug", action="store_true", help="Enable Debug Mode") 36 | parser.add_argument( 37 | "--gpt3only", action="store_true", help="Enable GPT3.5 Only Mode" 38 | ) 39 | parser.add_argument("--gpt4only", action="store_true", help="Enable GPT4 Only Mode") 40 | parser.add_argument( 41 | "--use-memory", 42 | "-m", 43 | dest="memory_type", 44 | help="Defines which Memory backend to use", 45 | ) 46 | parser.add_argument( 47 | "--skip-reprompt", 48 | "-y", 49 | dest="skip_reprompt", 50 | action="store_true", 51 | help="Skips the re-prompting messages at the beginning of the script", 52 | ) 53 | parser.add_argument( 54 | "--use-browser", 55 | "-b", 56 | dest="browser_name", 57 | help="Specifies which web-browser to use when using selenium to scrape the web.", 58 | ) 59 | parser.add_argument( 60 | "--ai-settings", 61 | "-C", 62 | dest="ai_settings_file", 63 | help="Specifies which ai_settings.yaml file to use, will also automatically" 64 | " skip the re-prompt.", 65 | ) 66 | args = parser.parse_args() 67 | 68 | if args.debug: 69 | logger.typewriter_log("Debug Mode: ", Fore.GREEN, "ENABLED") 70 | CFG.set_debug_mode(True) 71 | 72 | if args.continuous: 73 | logger.typewriter_log("Continuous Mode: ", Fore.RED, "ENABLED") 74 | logger.typewriter_log( 75 | "WARNING: ", 76 | Fore.RED, 77 | "Continuous mode is not recommended. It is potentially dangerous and may" 78 | " cause your AI to run forever or carry out actions you would not usually" 79 | " authorise. Use at your own risk.", 80 | ) 81 | CFG.set_continuous_mode(True) 82 | 83 | if args.continuous_limit: 84 | logger.typewriter_log( 85 | "Continuous Limit: ", Fore.GREEN, f"{args.continuous_limit}" 86 | ) 87 | CFG.set_continuous_limit(args.continuous_limit) 88 | 89 | # Check if continuous limit is used without continuous mode 90 | if args.continuous_limit and not args.continuous: 91 | parser.error("--continuous-limit can only be used with --continuous") 92 | 93 | if args.speak: 94 | logger.typewriter_log("Speak Mode: ", Fore.GREEN, "ENABLED") 95 | CFG.set_speak_mode(True) 96 | 97 | if args.gpt3only: 98 | logger.typewriter_log("GPT3.5 Only Mode: ", Fore.GREEN, "ENABLED") 99 | CFG.set_smart_llm_model(CFG.fast_llm_model) 100 | 101 | if args.gpt4only: 102 | logger.typewriter_log("GPT4 Only Mode: ", Fore.GREEN, "ENABLED") 103 | CFG.set_fast_llm_model(CFG.smart_llm_model) 104 | 105 | if args.memory_type: 106 | supported_memory = get_supported_memory_backends() 107 | chosen = args.memory_type 108 | if chosen not in supported_memory: 109 | logger.typewriter_log( 110 | "ONLY THE FOLLOWING MEMORY BACKENDS ARE SUPPORTED: ", 111 | Fore.RED, 112 | f"{supported_memory}", 113 | ) 114 | logger.typewriter_log("Defaulting to: ", Fore.YELLOW, CFG.memory_backend) 115 | else: 116 | CFG.memory_backend = chosen 117 | 118 | if args.skip_reprompt: 119 | logger.typewriter_log("Skip Re-prompt: ", Fore.GREEN, "ENABLED") 120 | CFG.skip_reprompt = True 121 | 122 | if args.ai_settings_file: 123 | file = args.ai_settings_file 124 | 125 | # Validate file 126 | (validated, message) = utils.validate_yaml_file(file) 127 | if not validated: 128 | logger.typewriter_log("FAILED FILE VALIDATION", Fore.RED, message) 129 | logger.double_check() 130 | exit(1) 131 | 132 | logger.typewriter_log("Using AI Settings File:", Fore.GREEN, file) 133 | CFG.ai_settings_file = file 134 | CFG.skip_reprompt = True 135 | 136 | if args.browser_name: 137 | CFG.selenium_web_browser = args.browser_name 138 | -------------------------------------------------------------------------------- /autogpt/commands/web_selenium.py: -------------------------------------------------------------------------------- 1 | """Selenium web scraping module.""" 2 | from selenium import webdriver 3 | from autogpt.processing.html import extract_hyperlinks, format_hyperlinks 4 | import autogpt.processing.text as summary 5 | from bs4 import BeautifulSoup 6 | from selenium.webdriver.remote.webdriver import WebDriver 7 | from selenium.webdriver.common.by import By 8 | from selenium.webdriver.support.wait import WebDriverWait 9 | from selenium.webdriver.support import expected_conditions as EC 10 | from webdriver_manager.chrome import ChromeDriverManager 11 | from webdriver_manager.firefox import GeckoDriverManager 12 | from selenium.webdriver.chrome.options import Options as ChromeOptions 13 | from selenium.webdriver.firefox.options import Options as FirefoxOptions 14 | from selenium.webdriver.safari.options import Options as SafariOptions 15 | import logging 16 | from pathlib import Path 17 | from autogpt.config import Config 18 | from typing import List, Tuple, Union 19 | 20 | FILE_DIR = Path(__file__).parent.parent 21 | CFG = Config() 22 | 23 | 24 | def browse_website(url: str, question: str) -> Tuple[str, WebDriver]: 25 | """Browse a website and return the answer and links to the user 26 | 27 | Args: 28 | url (str): The url of the website to browse 29 | question (str): The question asked by the user 30 | 31 | Returns: 32 | Tuple[str, WebDriver]: The answer and links to the user and the webdriver 33 | """ 34 | driver, text = scrape_text_with_selenium(url) 35 | add_header(driver) 36 | summary_text = summary.summarize_text(url, text, question, driver) 37 | links = scrape_links_with_selenium(driver, url) 38 | 39 | # Limit links to 5 40 | if len(links) > 5: 41 | links = links[:5] 42 | close_browser(driver) 43 | return f"Answer gathered from website: {summary_text} \n \n Links: {links}", driver 44 | 45 | 46 | def scrape_text_with_selenium(url: str) -> Tuple[WebDriver, str]: 47 | """Scrape text from a website using selenium 48 | 49 | Args: 50 | url (str): The url of the website to scrape 51 | 52 | Returns: 53 | Tuple[WebDriver, str]: The webdriver and the text scraped from the website 54 | """ 55 | logging.getLogger("selenium").setLevel(logging.CRITICAL) 56 | 57 | options_available = { 58 | "chrome": ChromeOptions, 59 | "safari": SafariOptions, 60 | "firefox": FirefoxOptions, 61 | } 62 | 63 | options = options_available[CFG.selenium_web_browser]() 64 | options.add_argument( 65 | "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" 66 | ) 67 | 68 | if CFG.selenium_web_browser == "firefox": 69 | driver = webdriver.Firefox( 70 | executable_path=GeckoDriverManager().install(), options=options 71 | ) 72 | elif CFG.selenium_web_browser == "safari": 73 | # Requires a bit more setup on the users end 74 | # See https://developer.apple.com/documentation/webkit/testing_with_webdriver_in_safari 75 | driver = webdriver.Safari(options=options) 76 | else: 77 | driver = webdriver.Chrome( 78 | executable_path=ChromeDriverManager().install(), options=options 79 | ) 80 | driver.get(url) 81 | 82 | WebDriverWait(driver, 10).until( 83 | EC.presence_of_element_located((By.TAG_NAME, "body")) 84 | ) 85 | 86 | # Get the HTML content directly from the browser's DOM 87 | page_source = driver.execute_script("return document.body.outerHTML;") 88 | soup = BeautifulSoup(page_source, "html.parser") 89 | 90 | for script in soup(["script", "style"]): 91 | script.extract() 92 | 93 | text = soup.get_text() 94 | lines = (line.strip() for line in text.splitlines()) 95 | chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) 96 | text = "\n".join(chunk for chunk in chunks if chunk) 97 | return driver, text 98 | 99 | 100 | def scrape_links_with_selenium(driver: WebDriver, url: str) -> List[str]: 101 | """Scrape links from a website using selenium 102 | 103 | Args: 104 | driver (WebDriver): The webdriver to use to scrape the links 105 | 106 | Returns: 107 | List[str]: The links scraped from the website 108 | """ 109 | page_source = driver.page_source 110 | soup = BeautifulSoup(page_source, "html.parser") 111 | 112 | for script in soup(["script", "style"]): 113 | script.extract() 114 | 115 | hyperlinks = extract_hyperlinks(soup, url) 116 | 117 | return format_hyperlinks(hyperlinks) 118 | 119 | 120 | def close_browser(driver: WebDriver) -> None: 121 | """Close the browser 122 | 123 | Args: 124 | driver (WebDriver): The webdriver to close 125 | 126 | Returns: 127 | None 128 | """ 129 | driver.quit() 130 | 131 | 132 | def add_header(driver: WebDriver) -> None: 133 | """Add a header to the website 134 | 135 | Args: 136 | driver (WebDriver): The webdriver to use to add the header 137 | 138 | Returns: 139 | None 140 | """ 141 | driver.execute_script(open(f"{FILE_DIR}/js/overlay.js", "r").read()) 142 | -------------------------------------------------------------------------------- /autogpt/json_fixes/parsing.py: -------------------------------------------------------------------------------- 1 | """Fix and parse JSON strings.""" 2 | 3 | import contextlib 4 | import json 5 | from typing import Any, Dict, Union 6 | 7 | from autogpt.config import Config 8 | from autogpt.json_fixes.auto_fix import fix_json 9 | from autogpt.json_fixes.bracket_termination import balance_braces 10 | from autogpt.json_fixes.escaping import fix_invalid_escape 11 | from autogpt.json_fixes.missing_quotes import add_quotes_to_property_names 12 | from autogpt.logs import logger 13 | 14 | CFG = Config() 15 | 16 | 17 | JSON_SCHEMA = """ 18 | { 19 | "command": { 20 | "name": "command name", 21 | "args": { 22 | "arg name": "value" 23 | } 24 | }, 25 | "thoughts": 26 | { 27 | "text": "thought", 28 | "reasoning": "reasoning", 29 | "plan": "- short bulleted\n- list that conveys\n- long-term plan", 30 | "criticism": "constructive self-criticism", 31 | "speak": "thoughts summary to say to user" 32 | } 33 | } 34 | """ 35 | 36 | 37 | def correct_json(json_to_load: str) -> str: 38 | """ 39 | Correct common JSON errors. 40 | 41 | Args: 42 | json_to_load (str): The JSON string. 43 | """ 44 | 45 | try: 46 | if CFG.debug_mode: 47 | print("json", json_to_load) 48 | json.loads(json_to_load) 49 | return json_to_load 50 | except json.JSONDecodeError as e: 51 | if CFG.debug_mode: 52 | print("json loads error", e) 53 | error_message = str(e) 54 | if error_message.startswith("Invalid \\escape"): 55 | json_to_load = fix_invalid_escape(json_to_load, error_message) 56 | if error_message.startswith( 57 | "Expecting property name enclosed in double quotes" 58 | ): 59 | json_to_load = add_quotes_to_property_names(json_to_load) 60 | try: 61 | json.loads(json_to_load) 62 | return json_to_load 63 | except json.JSONDecodeError as e: 64 | if CFG.debug_mode: 65 | print("json loads error - add quotes", e) 66 | error_message = str(e) 67 | if balanced_str := balance_braces(json_to_load): 68 | return balanced_str 69 | return json_to_load 70 | 71 | 72 | def fix_and_parse_json( 73 | json_to_load: str, try_to_fix_with_gpt: bool = True 74 | ) -> Union[str, Dict[Any, Any]]: 75 | """Fix and parse JSON string 76 | 77 | Args: 78 | json_to_load (str): The JSON string. 79 | try_to_fix_with_gpt (bool, optional): Try to fix the JSON with GPT. 80 | Defaults to True. 81 | 82 | Returns: 83 | Union[str, Dict[Any, Any]]: The parsed JSON. 84 | """ 85 | 86 | with contextlib.suppress(json.JSONDecodeError): 87 | json_to_load = json_to_load.replace("\t", "") 88 | return json.loads(json_to_load) 89 | 90 | with contextlib.suppress(json.JSONDecodeError): 91 | json_to_load = correct_json(json_to_load) 92 | return json.loads(json_to_load) 93 | # Let's do something manually: 94 | # sometimes GPT responds with something BEFORE the braces: 95 | # "I'm sorry, I don't understand. Please try again." 96 | # {"text": "I'm sorry, I don't understand. Please try again.", 97 | # "confidence": 0.0} 98 | # So let's try to find the first brace and then parse the rest 99 | # of the string 100 | try: 101 | brace_index = json_to_load.index("{") 102 | maybe_fixed_json = json_to_load[brace_index:] 103 | last_brace_index = maybe_fixed_json.rindex("}") 104 | maybe_fixed_json = maybe_fixed_json[: last_brace_index + 1] 105 | return json.loads(maybe_fixed_json) 106 | except (json.JSONDecodeError, ValueError) as e: 107 | return try_ai_fix(try_to_fix_with_gpt, e, json_to_load) 108 | 109 | 110 | def try_ai_fix( 111 | try_to_fix_with_gpt: bool, exception: Exception, json_to_load: str 112 | ) -> Union[str, Dict[Any, Any]]: 113 | """Try to fix the JSON with the AI 114 | 115 | Args: 116 | try_to_fix_with_gpt (bool): Whether to try to fix the JSON with the AI. 117 | exception (Exception): The exception that was raised. 118 | json_to_load (str): The JSON string to load. 119 | 120 | Raises: 121 | exception: If try_to_fix_with_gpt is False. 122 | 123 | Returns: 124 | Union[str, Dict[Any, Any]]: The JSON string or dictionary. 125 | """ 126 | if not try_to_fix_with_gpt: 127 | raise exception 128 | 129 | logger.warn( 130 | "Warning: Failed to parse AI output, attempting to fix." 131 | "\n If you see this warning frequently, it's likely that" 132 | " your prompt is confusing the AI. Try changing it up" 133 | " slightly." 134 | ) 135 | # Now try to fix this up using the ai_functions 136 | ai_fixed_json = fix_json(json_to_load, JSON_SCHEMA) 137 | 138 | if ai_fixed_json != "failed": 139 | return json.loads(ai_fixed_json) 140 | # This allows the AI to react to the error message, 141 | # which usually results in it correcting its ways. 142 | logger.error("Failed to fix AI output, telling the AI.") 143 | return json_to_load 144 | -------------------------------------------------------------------------------- /autogpt/promptgenerator.py: -------------------------------------------------------------------------------- 1 | """ A module for generating custom prompt strings.""" 2 | import json 3 | from typing import Any, Dict, List 4 | 5 | 6 | class PromptGenerator: 7 | """ 8 | A class for generating custom prompt strings based on constraints, commands, 9 | resources, and performance evaluations. 10 | """ 11 | 12 | def __init__(self) -> None: 13 | """ 14 | Initialize the PromptGenerator object with empty lists of constraints, 15 | commands, resources, and performance evaluations. 16 | """ 17 | self.constraints = [] 18 | self.commands = [] 19 | self.resources = [] 20 | self.performance_evaluation = [] 21 | self.response_format = { 22 | "thoughts": { 23 | "text": "thought", 24 | "reasoning": "reasoning", 25 | "plan": "- short bulleted\n- list that conveys\n- long-term plan", 26 | "criticism": "constructive self-criticism", 27 | "speak": "thoughts summary to say to user", 28 | }, 29 | "command": {"name": "command name", "args": {"arg name": "value"}}, 30 | } 31 | 32 | def add_constraint(self, constraint: str) -> None: 33 | """ 34 | Add a constraint to the constraints list. 35 | 36 | Args: 37 | constraint (str): The constraint to be added. 38 | """ 39 | self.constraints.append(constraint) 40 | 41 | def add_command(self, command_label: str, command_name: str, args=None) -> None: 42 | """ 43 | Add a command to the commands list with a label, name, and optional arguments. 44 | 45 | Args: 46 | command_label (str): The label of the command. 47 | command_name (str): The name of the command. 48 | args (dict, optional): A dictionary containing argument names and their 49 | values. Defaults to None. 50 | """ 51 | if args is None: 52 | args = {} 53 | 54 | command_args = {arg_key: arg_value for arg_key, arg_value in args.items()} 55 | 56 | command = { 57 | "label": command_label, 58 | "name": command_name, 59 | "args": command_args, 60 | } 61 | 62 | self.commands.append(command) 63 | 64 | def _generate_command_string(self, command: Dict[str, Any]) -> str: 65 | """ 66 | Generate a formatted string representation of a command. 67 | 68 | Args: 69 | command (dict): A dictionary containing command information. 70 | 71 | Returns: 72 | str: The formatted command string. 73 | """ 74 | args_string = ", ".join( 75 | f'"{key}": "{value}"' for key, value in command["args"].items() 76 | ) 77 | return f'{command["label"]}: "{command["name"]}", args: {args_string}' 78 | 79 | def add_resource(self, resource: str) -> None: 80 | """ 81 | Add a resource to the resources list. 82 | 83 | Args: 84 | resource (str): The resource to be added. 85 | """ 86 | self.resources.append(resource) 87 | 88 | def add_performance_evaluation(self, evaluation: str) -> None: 89 | """ 90 | Add a performance evaluation item to the performance_evaluation list. 91 | 92 | Args: 93 | evaluation (str): The evaluation item to be added. 94 | """ 95 | self.performance_evaluation.append(evaluation) 96 | 97 | def _generate_numbered_list(self, items: List[Any], item_type="list") -> str: 98 | """ 99 | Generate a numbered list from given items based on the item_type. 100 | 101 | Args: 102 | items (list): A list of items to be numbered. 103 | item_type (str, optional): The type of items in the list. 104 | Defaults to 'list'. 105 | 106 | Returns: 107 | str: The formatted numbered list. 108 | """ 109 | if item_type == "command": 110 | return "\n".join( 111 | f"{i+1}. {self._generate_command_string(item)}" 112 | for i, item in enumerate(items) 113 | ) 114 | else: 115 | return "\n".join(f"{i+1}. {item}" for i, item in enumerate(items)) 116 | 117 | def generate_prompt_string(self) -> str: 118 | """ 119 | Generate a prompt string based on the constraints, commands, resources, 120 | and performance evaluations. 121 | 122 | Returns: 123 | str: The generated prompt string. 124 | """ 125 | formatted_response_format = json.dumps(self.response_format, indent=4) 126 | return ( 127 | f"Constraints:\n{self._generate_numbered_list(self.constraints)}\n\n" 128 | "Commands:\n" 129 | f"{self._generate_numbered_list(self.commands, item_type='command')}\n\n" 130 | f"Resources:\n{self._generate_numbered_list(self.resources)}\n\n" 131 | "Performance Evaluation:\n" 132 | f"{self._generate_numbered_list(self.performance_evaluation)}\n\n" 133 | "You should only respond in JSON format as described below \nResponse" 134 | f" Format: \n{formatted_response_format} \nEnsure the response can be" 135 | "parsed by Python json.loads" 136 | ) 137 | -------------------------------------------------------------------------------- /autogpt/commands/web_requests.py: -------------------------------------------------------------------------------- 1 | """Browse a webpage and summarize it using the LLM model""" 2 | from typing import List, Tuple, Union 3 | from urllib.parse import urljoin, urlparse 4 | 5 | import requests 6 | from requests.compat import urljoin 7 | from requests import Response 8 | from bs4 import BeautifulSoup 9 | 10 | from autogpt.config import Config 11 | from autogpt.memory import get_memory 12 | from autogpt.processing.html import extract_hyperlinks, format_hyperlinks 13 | 14 | CFG = Config() 15 | memory = get_memory(CFG) 16 | 17 | session = requests.Session() 18 | session.headers.update({"User-Agent": CFG.user_agent}) 19 | 20 | 21 | def is_valid_url(url: str) -> bool: 22 | """Check if the URL is valid 23 | 24 | Args: 25 | url (str): The URL to check 26 | 27 | Returns: 28 | bool: True if the URL is valid, False otherwise 29 | """ 30 | try: 31 | result = urlparse(url) 32 | return all([result.scheme, result.netloc]) 33 | except ValueError: 34 | return False 35 | 36 | 37 | def sanitize_url(url: str) -> str: 38 | """Sanitize the URL 39 | 40 | Args: 41 | url (str): The URL to sanitize 42 | 43 | Returns: 44 | str: The sanitized URL 45 | """ 46 | return urljoin(url, urlparse(url).path) 47 | 48 | 49 | def check_local_file_access(url: str) -> bool: 50 | """Check if the URL is a local file 51 | 52 | Args: 53 | url (str): The URL to check 54 | 55 | Returns: 56 | bool: True if the URL is a local file, False otherwise 57 | """ 58 | local_prefixes = [ 59 | "file:///", 60 | "file://localhost", 61 | "http://localhost", 62 | "https://localhost", 63 | ] 64 | return any(url.startswith(prefix) for prefix in local_prefixes) 65 | 66 | 67 | def get_response( 68 | url: str, timeout: int = 10 69 | ) -> Union[Tuple[None, str], Tuple[Response, None]]: 70 | """Get the response from a URL 71 | 72 | Args: 73 | url (str): The URL to get the response from 74 | timeout (int): The timeout for the HTTP request 75 | 76 | Returns: 77 | Tuple[None, str] | Tuple[Response, None]: The response and error message 78 | 79 | Raises: 80 | ValueError: If the URL is invalid 81 | requests.exceptions.RequestException: If the HTTP request fails 82 | """ 83 | try: 84 | # Restrict access to local files 85 | if check_local_file_access(url): 86 | raise ValueError("Access to local files is restricted") 87 | 88 | # Most basic check if the URL is valid: 89 | if not url.startswith("http://") and not url.startswith("https://"): 90 | raise ValueError("Invalid URL format") 91 | 92 | sanitized_url = sanitize_url(url) 93 | 94 | response = session.get(sanitized_url, timeout=timeout) 95 | 96 | # Check if the response contains an HTTP error 97 | if response.status_code >= 400: 98 | return None, f"Error: HTTP {str(response.status_code)} error" 99 | 100 | return response, None 101 | except ValueError as ve: 102 | # Handle invalid URL format 103 | return None, f"Error: {str(ve)}" 104 | 105 | except requests.exceptions.RequestException as re: 106 | # Handle exceptions related to the HTTP request 107 | # (e.g., connection errors, timeouts, etc.) 108 | return None, f"Error: {str(re)}" 109 | 110 | 111 | def scrape_text(url: str) -> str: 112 | """Scrape text from a webpage 113 | 114 | Args: 115 | url (str): The URL to scrape text from 116 | 117 | Returns: 118 | str: The scraped text 119 | """ 120 | response, error_message = get_response(url) 121 | if error_message: 122 | return error_message 123 | if not response: 124 | return "Error: Could not get response" 125 | 126 | soup = BeautifulSoup(response.text, "html.parser") 127 | 128 | for script in soup(["script", "style"]): 129 | script.extract() 130 | 131 | text = soup.get_text() 132 | lines = (line.strip() for line in text.splitlines()) 133 | chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) 134 | text = "\n".join(chunk for chunk in chunks if chunk) 135 | 136 | return text 137 | 138 | 139 | def scrape_links(url: str) -> Union[str, List[str]]: 140 | """Scrape links from a webpage 141 | 142 | Args: 143 | url (str): The URL to scrape links from 144 | 145 | Returns: 146 | Union[str, List[str]]: The scraped links 147 | """ 148 | response, error_message = get_response(url) 149 | if error_message: 150 | return error_message 151 | if not response: 152 | return "Error: Could not get response" 153 | soup = BeautifulSoup(response.text, "html.parser") 154 | 155 | for script in soup(["script", "style"]): 156 | script.extract() 157 | 158 | hyperlinks = extract_hyperlinks(soup, url) 159 | 160 | return format_hyperlinks(hyperlinks) 161 | 162 | 163 | def create_message(chunk, question): 164 | """Create a message for the user to summarize a chunk of text""" 165 | return { 166 | "role": "user", 167 | "content": f'"""{chunk}""" Using the above text, answer the following' 168 | f' question: "{question}" -- if the question cannot be answered using the' 169 | " text, summarize the text.", 170 | } 171 | -------------------------------------------------------------------------------- /tests/unit/test_browse_scrape_links.py: -------------------------------------------------------------------------------- 1 | # Generated by CodiumAI 2 | 3 | # Dependencies: 4 | # pip install pytest-mock 5 | import pytest 6 | 7 | from autogpt.commands.web_requests import scrape_links 8 | 9 | """ 10 | Code Analysis 11 | 12 | Objective: 13 | The objective of the 'scrape_links' function is to scrape hyperlinks from a 14 | given URL and return them in a formatted way. 15 | 16 | Inputs: 17 | - url: a string representing the URL to be scraped. 18 | 19 | Flow: 20 | 1. Send a GET request to the given URL using the requests library and the user agent header from the config file. 21 | 2. Check if the response contains an HTTP error. If it does, return "error". 22 | 3. Parse the HTML content of the response using the BeautifulSoup library. 23 | 4. Remove any script and style tags from the parsed HTML. 24 | 5. Extract all hyperlinks from the parsed HTML using the 'extract_hyperlinks' function. 25 | 6. Format the extracted hyperlinks using the 'format_hyperlinks' function. 26 | 7. Return the formatted hyperlinks. 27 | 28 | Outputs: 29 | - A list of formatted hyperlinks. 30 | 31 | Additional aspects: 32 | - The function uses the 'requests' and 'BeautifulSoup' libraries to send HTTP 33 | requests and parse HTML content, respectively. 34 | - The 'extract_hyperlinks' function is called to extract hyperlinks from the parsed HTML. 35 | - The 'format_hyperlinks' function is called to format the extracted hyperlinks. 36 | - The function checks for HTTP errors and returns "error" if any are found. 37 | """ 38 | 39 | 40 | class TestScrapeLinks: 41 | # Tests that the function returns a list of formatted hyperlinks when 42 | # provided with a valid url that returns a webpage with hyperlinks. 43 | def test_valid_url_with_hyperlinks(self): 44 | url = "https://www.google.com" 45 | result = scrape_links(url) 46 | assert len(result) > 0 47 | assert isinstance(result, list) 48 | assert isinstance(result[0], str) 49 | 50 | # Tests that the function returns correctly formatted hyperlinks when given a valid url. 51 | def test_valid_url(self, mocker): 52 | # Mock the requests.get() function to return a response with sample HTML containing hyperlinks 53 | mock_response = mocker.Mock() 54 | mock_response.status_code = 200 55 | mock_response.text = ( 56 | "Google" 57 | ) 58 | mocker.patch("requests.Session.get", return_value=mock_response) 59 | 60 | # Call the function with a valid URL 61 | result = scrape_links("https://www.example.com") 62 | 63 | # Assert that the function returns correctly formatted hyperlinks 64 | assert result == ["Google (https://www.google.com)"] 65 | 66 | # Tests that the function returns "error" when given an invalid url. 67 | def test_invalid_url(self, mocker): 68 | # Mock the requests.get() function to return an HTTP error response 69 | mock_response = mocker.Mock() 70 | mock_response.status_code = 404 71 | mocker.patch("requests.Session.get", return_value=mock_response) 72 | 73 | # Call the function with an invalid URL 74 | result = scrape_links("https://www.invalidurl.com") 75 | 76 | # Assert that the function returns "error" 77 | assert "Error:" in result 78 | 79 | # Tests that the function returns an empty list when the html contains no hyperlinks. 80 | def test_no_hyperlinks(self, mocker): 81 | # Mock the requests.get() function to return a response with sample HTML containing no hyperlinks 82 | mock_response = mocker.Mock() 83 | mock_response.status_code = 200 84 | mock_response.text = "

No hyperlinks here

" 85 | mocker.patch("requests.Session.get", return_value=mock_response) 86 | 87 | # Call the function with a URL containing no hyperlinks 88 | result = scrape_links("https://www.example.com") 89 | 90 | # Assert that the function returns an empty list 91 | assert result == [] 92 | 93 | # Tests that scrape_links() correctly extracts and formats hyperlinks from 94 | # a sample HTML containing a few hyperlinks. 95 | def test_scrape_links_with_few_hyperlinks(self, mocker): 96 | # Mock the requests.get() function to return a response with a sample HTML containing hyperlinks 97 | mock_response = mocker.Mock() 98 | mock_response.status_code = 200 99 | mock_response.text = """ 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | """ 108 | mocker.patch("requests.Session.get", return_value=mock_response) 109 | 110 | # Call the function being tested 111 | result = scrape_links("https://www.example.com") 112 | 113 | # Assert that the function returns a list of formatted hyperlinks 114 | assert isinstance(result, list) 115 | assert len(result) == 3 116 | assert result[0] == "Google (https://www.google.com)" 117 | assert result[1] == "GitHub (https://github.com)" 118 | assert result[2] == "CodiumAI (https://www.codium.ai)" 119 | -------------------------------------------------------------------------------- /autogpt/memory/redismem.py: -------------------------------------------------------------------------------- 1 | """Redis memory provider.""" 2 | from typing import Any, List, Optional 3 | 4 | import numpy as np 5 | import redis 6 | from colorama import Fore, Style 7 | from redis.commands.search.field import TextField, VectorField 8 | from redis.commands.search.indexDefinition import IndexDefinition, IndexType 9 | from redis.commands.search.query import Query 10 | 11 | from autogpt.logs import logger 12 | from autogpt.memory.base import MemoryProviderSingleton 13 | from autogpt.llm_utils import create_embedding_with_ada 14 | 15 | SCHEMA = [ 16 | TextField("data"), 17 | VectorField( 18 | "embedding", 19 | "HNSW", 20 | {"TYPE": "FLOAT32", "DIM": 1536, "DISTANCE_METRIC": "COSINE"}, 21 | ), 22 | ] 23 | 24 | 25 | class RedisMemory(MemoryProviderSingleton): 26 | def __init__(self, cfg): 27 | """ 28 | Initializes the Redis memory provider. 29 | 30 | Args: 31 | cfg: The config object. 32 | 33 | Returns: None 34 | """ 35 | redis_host = cfg.redis_host 36 | redis_port = cfg.redis_port 37 | redis_password = cfg.redis_password 38 | self.dimension = 1536 39 | self.redis = redis.Redis( 40 | host=redis_host, 41 | port=redis_port, 42 | password=redis_password, 43 | db=0, # Cannot be changed 44 | ) 45 | self.cfg = cfg 46 | 47 | # Check redis connection 48 | try: 49 | self.redis.ping() 50 | except redis.ConnectionError as e: 51 | logger.typewriter_log( 52 | "FAILED TO CONNECT TO REDIS", 53 | Fore.RED, 54 | Style.BRIGHT + str(e) + Style.RESET_ALL, 55 | ) 56 | logger.double_check( 57 | "Please ensure you have setup and configured Redis properly for use. " 58 | + f"You can check out {Fore.CYAN + Style.BRIGHT}" 59 | f"https://github.com/Torantulino/Auto-GPT#redis-setup{Style.RESET_ALL}" 60 | " to ensure you've set up everything correctly." 61 | ) 62 | exit(1) 63 | 64 | if cfg.wipe_redis_on_start: 65 | self.redis.flushall() 66 | try: 67 | self.redis.ft(f"{cfg.memory_index}").create_index( 68 | fields=SCHEMA, 69 | definition=IndexDefinition( 70 | prefix=[f"{cfg.memory_index}:"], index_type=IndexType.HASH 71 | ), 72 | ) 73 | except Exception as e: 74 | print("Error creating Redis search index: ", e) 75 | existing_vec_num = self.redis.get(f"{cfg.memory_index}-vec_num") 76 | self.vec_num = int(existing_vec_num.decode("utf-8")) if existing_vec_num else 0 77 | 78 | def add(self, data: str) -> str: 79 | """ 80 | Adds a data point to the memory. 81 | 82 | Args: 83 | data: The data to add. 84 | 85 | Returns: Message indicating that the data has been added. 86 | """ 87 | if "Command Error:" in data: 88 | return "" 89 | vector = create_embedding_with_ada(data) 90 | vector = np.array(vector).astype(np.float32).tobytes() 91 | data_dict = {b"data": data, "embedding": vector} 92 | pipe = self.redis.pipeline() 93 | pipe.hset(f"{self.cfg.memory_index}:{self.vec_num}", mapping=data_dict) 94 | _text = ( 95 | f"Inserting data into memory at index: {self.vec_num}:\n" f"data: {data}" 96 | ) 97 | self.vec_num += 1 98 | pipe.set(f"{self.cfg.memory_index}-vec_num", self.vec_num) 99 | pipe.execute() 100 | return _text 101 | 102 | def get(self, data: str) -> Optional[List[Any]]: 103 | """ 104 | Gets the data from the memory that is most relevant to the given data. 105 | 106 | Args: 107 | data: The data to compare to. 108 | 109 | Returns: The most relevant data. 110 | """ 111 | return self.get_relevant(data, 1) 112 | 113 | def clear(self) -> str: 114 | """ 115 | Clears the redis server. 116 | 117 | Returns: A message indicating that the memory has been cleared. 118 | """ 119 | self.redis.flushall() 120 | return "Obliviated" 121 | 122 | def get_relevant(self, data: str, num_relevant: int = 5) -> Optional[List[Any]]: 123 | """ 124 | Returns all the data in the memory that is relevant to the given data. 125 | Args: 126 | data: The data to compare to. 127 | num_relevant: The number of relevant data to return. 128 | 129 | Returns: A list of the most relevant data. 130 | """ 131 | query_embedding = create_embedding_with_ada(data) 132 | base_query = f"*=>[KNN {num_relevant} @embedding $vector AS vector_score]" 133 | query = ( 134 | Query(base_query) 135 | .return_fields("data", "vector_score") 136 | .sort_by("vector_score") 137 | .dialect(2) 138 | ) 139 | query_vector = np.array(query_embedding).astype(np.float32).tobytes() 140 | 141 | try: 142 | results = self.redis.ft(f"{self.cfg.memory_index}").search( 143 | query, query_params={"vector": query_vector} 144 | ) 145 | except Exception as e: 146 | print("Error calling Redis search: ", e) 147 | return None 148 | return [result.data for result in results.docs] 149 | 150 | def get_stats(self): 151 | """ 152 | Returns: The stats of the memory index. 153 | """ 154 | return self.redis.ft(f"{self.cfg.memory_index}").info() 155 | -------------------------------------------------------------------------------- /autogpt/llm_utils.py: -------------------------------------------------------------------------------- 1 | from ast import List 2 | import time 3 | from typing import Dict, Optional 4 | 5 | import openai 6 | from openai.error import APIError, RateLimitError 7 | from colorama import Fore 8 | 9 | from autogpt.config import Config 10 | 11 | CFG = Config() 12 | 13 | openai.api_key = CFG.openai_api_key 14 | 15 | 16 | def call_ai_function( 17 | function: str, args: List, description: str, model: Optional[str] = None 18 | ) -> str: 19 | """Call an AI function 20 | 21 | This is a magic function that can do anything with no-code. See 22 | https://github.com/Torantulino/AI-Functions for more info. 23 | 24 | Args: 25 | function (str): The function to call 26 | args (list): The arguments to pass to the function 27 | description (str): The description of the function 28 | model (str, optional): The model to use. Defaults to None. 29 | 30 | Returns: 31 | str: The response from the function 32 | """ 33 | if model is None: 34 | model = CFG.smart_llm_model 35 | # For each arg, if any are None, convert to "None": 36 | args = [str(arg) if arg is not None else "None" for arg in args] 37 | # parse args to comma separated string 38 | args = ", ".join(args) 39 | messages = [ 40 | { 41 | "role": "system", 42 | "content": f"You are now the following python function: ```# {description}" 43 | f"\n{function}```\n\nOnly respond with your `return` value.", 44 | }, 45 | {"role": "user", "content": args}, 46 | ] 47 | 48 | return create_chat_completion(model=model, messages=messages, temperature=0) 49 | 50 | 51 | # Overly simple abstraction until we create something better 52 | # simple retry mechanism when getting a rate error or a bad gateway 53 | def create_chat_completion( 54 | messages: List, # type: ignore 55 | model: Optional[str] = None, 56 | temperature: float = CFG.temperature, 57 | max_tokens: Optional[int] = None, 58 | ) -> str: 59 | """Create a chat completion using the OpenAI API 60 | 61 | Args: 62 | messages (List[Dict[str, str]]): The messages to send to the chat completion 63 | model (str, optional): The model to use. Defaults to None. 64 | temperature (float, optional): The temperature to use. Defaults to 0.9. 65 | max_tokens (int, optional): The max tokens to use. Defaults to None. 66 | 67 | Returns: 68 | str: The response from the chat completion 69 | """ 70 | response = None 71 | num_retries = 10 72 | if CFG.debug_mode: 73 | print( 74 | Fore.GREEN 75 | + f"Creating chat completion with model {model}, temperature {temperature}," 76 | f" max_tokens {max_tokens}" + Fore.RESET 77 | ) 78 | for attempt in range(num_retries): 79 | backoff = 2 ** (attempt + 2) 80 | try: 81 | if CFG.use_azure: 82 | response = openai.ChatCompletion.create( 83 | deployment_id=CFG.get_azure_deployment_id_for_model(model), 84 | model=model, 85 | messages=messages, 86 | temperature=temperature, 87 | max_tokens=max_tokens, 88 | ) 89 | else: 90 | response = openai.ChatCompletion.create( 91 | model=model, 92 | messages=messages, 93 | temperature=temperature, 94 | max_tokens=max_tokens, 95 | ) 96 | break 97 | except RateLimitError: 98 | if CFG.debug_mode: 99 | print( 100 | Fore.RED + "Error: ", 101 | f"Reached rate limit, passing..." + Fore.RESET, 102 | ) 103 | except APIError as e: 104 | if e.http_status == 502: 105 | pass 106 | else: 107 | raise 108 | if attempt == num_retries - 1: 109 | raise 110 | if CFG.debug_mode: 111 | print( 112 | Fore.RED + "Error: ", 113 | f"API Bad gateway. Waiting {backoff} seconds..." + Fore.RESET, 114 | ) 115 | time.sleep(backoff) 116 | if response is None: 117 | raise RuntimeError(f"Failed to get response after {num_retries} retries") 118 | 119 | return response.choices[0].message["content"] 120 | 121 | 122 | def create_embedding_with_ada(text) -> list: 123 | """Create a embedding with text-ada-002 using the OpenAI SDK""" 124 | num_retries = 10 125 | for attempt in range(num_retries): 126 | backoff = 2 ** (attempt + 2) 127 | try: 128 | if CFG.use_azure: 129 | return openai.Embedding.create( 130 | input=[text], 131 | engine=CFG.get_azure_deployment_id_for_model( 132 | "text-embedding-ada-002" 133 | ), 134 | )["data"][0]["embedding"] 135 | else: 136 | return openai.Embedding.create( 137 | input=[text], model="text-embedding-ada-002" 138 | )["data"][0]["embedding"] 139 | except RateLimitError: 140 | pass 141 | except APIError as e: 142 | if e.http_status == 502: 143 | pass 144 | else: 145 | raise 146 | if attempt == num_retries - 1: 147 | raise 148 | if CFG.debug_mode: 149 | print( 150 | Fore.RED + "Error: ", 151 | f"API Bad gateway. Waiting {backoff} seconds..." + Fore.RESET, 152 | ) 153 | time.sleep(backoff) 154 | -------------------------------------------------------------------------------- /tests/test_json_parser.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | import tests.context 4 | from autogpt.json_fixes.parsing import fix_and_parse_json 5 | 6 | 7 | class TestParseJson(unittest.TestCase): 8 | def test_valid_json(self): 9 | # Test that a valid JSON string is parsed correctly 10 | json_str = '{"name": "John", "age": 30, "city": "New York"}' 11 | obj = fix_and_parse_json(json_str) 12 | self.assertEqual(obj, {"name": "John", "age": 30, "city": "New York"}) 13 | 14 | def test_invalid_json_minor(self): 15 | # Test that an invalid JSON string can be fixed with gpt 16 | json_str = '{"name": "John", "age": 30, "city": "New York",}' 17 | with self.assertRaises(Exception): 18 | fix_and_parse_json(json_str, try_to_fix_with_gpt=False) 19 | 20 | def test_invalid_json_major_with_gpt(self): 21 | # Test that an invalid JSON string raises an error when try_to_fix_with_gpt is False 22 | json_str = 'BEGIN: "name": "John" - "age": 30 - "city": "New York" :END' 23 | with self.assertRaises(Exception): 24 | fix_and_parse_json(json_str, try_to_fix_with_gpt=False) 25 | 26 | def test_invalid_json_major_without_gpt(self): 27 | # Test that a REALLY invalid JSON string raises an error when try_to_fix_with_gpt is False 28 | json_str = 'BEGIN: "name": "John" - "age": 30 - "city": "New York" :END' 29 | # Assert that this raises an exception: 30 | with self.assertRaises(Exception): 31 | fix_and_parse_json(json_str, try_to_fix_with_gpt=False) 32 | 33 | def test_invalid_json_leading_sentence_with_gpt(self): 34 | # Test that a REALLY invalid JSON string raises an error when try_to_fix_with_gpt is False 35 | json_str = """I suggest we start by browsing the repository to find any issues that we can fix. 36 | 37 | { 38 | "command": { 39 | "name": "browse_website", 40 | "args":{ 41 | "url": "https://github.com/Torantulino/Auto-GPT" 42 | } 43 | }, 44 | "thoughts": 45 | { 46 | "text": "I suggest we start browsing the repository to find any issues that we can fix.", 47 | "reasoning": "Browsing the repository will give us an idea of the current state of the codebase and identify any issues that we can address to improve the repo.", 48 | "plan": "- Look through the repository to find any issues.\n- Investigate any issues to determine what needs to be fixed\n- Identify possible solutions to fix the issues\n- Open Pull Requests with fixes", 49 | "criticism": "I should be careful while browsing so as not to accidentally introduce any new bugs or issues.", 50 | "speak": "I will start browsing the repository to find any issues we can fix." 51 | } 52 | }""" 53 | good_obj = { 54 | "command": { 55 | "name": "browse_website", 56 | "args": {"url": "https://github.com/Torantulino/Auto-GPT"}, 57 | }, 58 | "thoughts": { 59 | "text": "I suggest we start browsing the repository to find any issues that we can fix.", 60 | "reasoning": "Browsing the repository will give us an idea of the current state of the codebase and identify any issues that we can address to improve the repo.", 61 | "plan": "- Look through the repository to find any issues.\n- Investigate any issues to determine what needs to be fixed\n- Identify possible solutions to fix the issues\n- Open Pull Requests with fixes", 62 | "criticism": "I should be careful while browsing so as not to accidentally introduce any new bugs or issues.", 63 | "speak": "I will start browsing the repository to find any issues we can fix.", 64 | }, 65 | } 66 | # Assert that this raises an exception: 67 | self.assertEqual( 68 | fix_and_parse_json(json_str, try_to_fix_with_gpt=False), good_obj 69 | ) 70 | 71 | def test_invalid_json_leading_sentence_with_gpt(self): 72 | # Test that a REALLY invalid JSON string raises an error when try_to_fix_with_gpt is False 73 | json_str = """I will first need to browse the repository (https://github.com/Torantulino/Auto-GPT) and identify any potential bugs that need fixing. I will use the "browse_website" command for this. 74 | 75 | { 76 | "command": { 77 | "name": "browse_website", 78 | "args":{ 79 | "url": "https://github.com/Torantulino/Auto-GPT" 80 | } 81 | }, 82 | "thoughts": 83 | { 84 | "text": "Browsing the repository to identify potential bugs", 85 | "reasoning": "Before fixing bugs, I need to identify what needs fixing. I will use the 'browse_website' command to analyze the repository.", 86 | "plan": "- Analyze the repository for potential bugs and areas of improvement", 87 | "criticism": "I need to ensure I am thorough and pay attention to detail while browsing the repository.", 88 | "speak": "I am browsing the repository to identify potential bugs." 89 | } 90 | }""" 91 | good_obj = { 92 | "command": { 93 | "name": "browse_website", 94 | "args": {"url": "https://github.com/Torantulino/Auto-GPT"}, 95 | }, 96 | "thoughts": { 97 | "text": "Browsing the repository to identify potential bugs", 98 | "reasoning": "Before fixing bugs, I need to identify what needs fixing. I will use the 'browse_website' command to analyze the repository.", 99 | "plan": "- Analyze the repository for potential bugs and areas of improvement", 100 | "criticism": "I need to ensure I am thorough and pay attention to detail while browsing the repository.", 101 | "speak": "I am browsing the repository to identify potential bugs.", 102 | }, 103 | } 104 | # Assert that this raises an exception: 105 | self.assertEqual( 106 | fix_and_parse_json(json_str, try_to_fix_with_gpt=False), good_obj 107 | ) 108 | 109 | 110 | if __name__ == "__main__": 111 | unittest.main() 112 | -------------------------------------------------------------------------------- /tests/unit/json_tests.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from autogpt.json_parser import fix_and_parse_json 4 | 5 | 6 | class TestParseJson(unittest.TestCase): 7 | def test_valid_json(self): 8 | # Test that a valid JSON string is parsed correctly 9 | json_str = '{"name": "John", "age": 30, "city": "New York"}' 10 | obj = fix_and_parse_json(json_str) 11 | self.assertEqual(obj, {"name": "John", "age": 30, "city": "New York"}) 12 | 13 | def test_invalid_json_minor(self): 14 | # Test that an invalid JSON string can be fixed with gpt 15 | json_str = '{"name": "John", "age": 30, "city": "New York",}' 16 | self.assertEqual( 17 | fix_and_parse_json(json_str, try_to_fix_with_gpt=False), 18 | {"name": "John", "age": 30, "city": "New York"}, 19 | ) 20 | 21 | def test_invalid_json_major_with_gpt(self): 22 | # Test that an invalid JSON string raises an error when try_to_fix_with_gpt is False 23 | json_str = 'BEGIN: "name": "John" - "age": 30 - "city": "New York" :END' 24 | self.assertEqual( 25 | fix_and_parse_json(json_str, try_to_fix_with_gpt=True), 26 | {"name": "John", "age": 30, "city": "New York"}, 27 | ) 28 | 29 | def test_invalid_json_major_without_gpt(self): 30 | # Test that a REALLY invalid JSON string raises an error when try_to_fix_with_gpt is False 31 | json_str = 'BEGIN: "name": "John" - "age": 30 - "city": "New York" :END' 32 | # Assert that this raises an exception: 33 | with self.assertRaises(Exception): 34 | fix_and_parse_json(json_str, try_to_fix_with_gpt=False) 35 | 36 | def test_invalid_json_leading_sentence_with_gpt(self): 37 | # Test that a REALLY invalid JSON string raises an error when try_to_fix_with_gpt is False 38 | json_str = """I suggest we start by browsing the repository to find any issues that we can fix. 39 | 40 | { 41 | "command": { 42 | "name": "browse_website", 43 | "args":{ 44 | "url": "https://github.com/Torantulino/Auto-GPT" 45 | } 46 | }, 47 | "thoughts": 48 | { 49 | "text": "I suggest we start browsing the repository to find any issues that we can fix.", 50 | "reasoning": "Browsing the repository will give us an idea of the current state of the codebase and identify any issues that we can address to improve the repo.", 51 | "plan": "- Look through the repository to find any issues.\n- Investigate any issues to determine what needs to be fixed\n- Identify possible solutions to fix the issues\n- Open Pull Requests with fixes", 52 | "criticism": "I should be careful while browsing so as not to accidentally introduce any new bugs or issues.", 53 | "speak": "I will start browsing the repository to find any issues we can fix." 54 | } 55 | }""" 56 | good_obj = { 57 | "command": { 58 | "name": "browse_website", 59 | "args": {"url": "https://github.com/Torantulino/Auto-GPT"}, 60 | }, 61 | "thoughts": { 62 | "text": "I suggest we start browsing the repository to find any issues that we can fix.", 63 | "reasoning": "Browsing the repository will give us an idea of the current state of the codebase and identify any issues that we can address to improve the repo.", 64 | "plan": "- Look through the repository to find any issues.\n- Investigate any issues to determine what needs to be fixed\n- Identify possible solutions to fix the issues\n- Open Pull Requests with fixes", 65 | "criticism": "I should be careful while browsing so as not to accidentally introduce any new bugs or issues.", 66 | "speak": "I will start browsing the repository to find any issues we can fix.", 67 | }, 68 | } 69 | # Assert that this raises an exception: 70 | self.assertEqual( 71 | fix_and_parse_json(json_str, try_to_fix_with_gpt=False), good_obj 72 | ) 73 | 74 | def test_invalid_json_leading_sentence_with_gpt(self): 75 | # Test that a REALLY invalid JSON string raises an error when try_to_fix_with_gpt is False 76 | json_str = """I will first need to browse the repository (https://github.com/Torantulino/Auto-GPT) and identify any potential bugs that need fixing. I will use the "browse_website" command for this. 77 | 78 | { 79 | "command": { 80 | "name": "browse_website", 81 | "args":{ 82 | "url": "https://github.com/Torantulino/Auto-GPT" 83 | } 84 | }, 85 | "thoughts": 86 | { 87 | "text": "Browsing the repository to identify potential bugs", 88 | "reasoning": "Before fixing bugs, I need to identify what needs fixing. I will use the 'browse_website' command to analyze the repository.", 89 | "plan": "- Analyze the repository for potential bugs and areas of improvement", 90 | "criticism": "I need to ensure I am thorough and pay attention to detail while browsing the repository.", 91 | "speak": "I am browsing the repository to identify potential bugs." 92 | } 93 | }""" 94 | good_obj = { 95 | "command": { 96 | "name": "browse_website", 97 | "args": {"url": "https://github.com/Torantulino/Auto-GPT"}, 98 | }, 99 | "thoughts": { 100 | "text": "Browsing the repository to identify potential bugs", 101 | "reasoning": "Before fixing bugs, I need to identify what needs fixing. I will use the 'browse_website' command to analyze the repository.", 102 | "plan": "- Analyze the repository for potential bugs and areas of improvement", 103 | "criticism": "I need to ensure I am thorough and pay attention to detail while browsing the repository.", 104 | "speak": "I am browsing the repository to identify potential bugs.", 105 | }, 106 | } 107 | # Assert that this raises an exception: 108 | self.assertEqual( 109 | fix_and_parse_json(json_str, try_to_fix_with_gpt=False), good_obj 110 | ) 111 | 112 | 113 | if __name__ == "__main__": 114 | unittest.main() 115 | -------------------------------------------------------------------------------- /.env.template: -------------------------------------------------------------------------------- 1 | ################################################################################ 2 | ### AUTO-GPT - GENERAL SETTINGS 3 | ################################################################################ 4 | # EXECUTE_LOCAL_COMMANDS - Allow local command execution (Example: False) 5 | EXECUTE_LOCAL_COMMANDS=False 6 | # BROWSE_CHUNK_MAX_LENGTH - When browsing website, define the length of chunk stored in memory 7 | BROWSE_CHUNK_MAX_LENGTH=8192 8 | # BROWSE_SUMMARY_MAX_TOKEN - Define the maximum length of the summary generated by GPT agent when browsing website 9 | BROWSE_SUMMARY_MAX_TOKEN=300 10 | # USER_AGENT - Define the user-agent used by the requests library to browse website (string) 11 | # USER_AGENT="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36" 12 | # AI_SETTINGS_FILE - Specifies which AI Settings file to use (defaults to ai_settings.yaml) 13 | AI_SETTINGS_FILE=ai_settings.yaml 14 | # USE_WEB_BROWSER - Sets the web-browser drivers to use with selenium (defaults to chrome). 15 | # Note: set this to either 'chrome', 'firefox', or 'safari' depending on your current browser 16 | # USE_WEB_BROWSER=chrome 17 | 18 | ################################################################################ 19 | ### LLM PROVIDER 20 | ################################################################################ 21 | 22 | ### OPENAI 23 | # OPENAI_API_KEY - OpenAI API Key (Example: my-openai-api-key) 24 | # TEMPERATURE - Sets temperature in OpenAI (Default: 1) 25 | # USE_AZURE - Use Azure OpenAI or not (Default: False) 26 | OPENAI_API_KEY=your-openai-api-key 27 | TEMPERATURE=0 28 | USE_AZURE=False 29 | 30 | ### AZURE 31 | # cleanup azure env as already moved to `azure.yaml.template` 32 | 33 | ################################################################################ 34 | ### LLM MODELS 35 | ################################################################################ 36 | 37 | # SMART_LLM_MODEL - Smart language model (Default: gpt-4) 38 | # FAST_LLM_MODEL - Fast language model (Default: gpt-3.5-turbo) 39 | SMART_LLM_MODEL=gpt-4 40 | FAST_LLM_MODEL=gpt-3.5-turbo 41 | 42 | ### LLM MODEL SETTINGS 43 | # FAST_TOKEN_LIMIT - Fast token limit for OpenAI (Default: 4000) 44 | # SMART_TOKEN_LIMIT - Smart token limit for OpenAI (Default: 8000) 45 | # When using --gpt3only this needs to be set to 4000. 46 | FAST_TOKEN_LIMIT=4000 47 | SMART_TOKEN_LIMIT=8000 48 | 49 | ################################################################################ 50 | ### MEMORY 51 | ################################################################################ 52 | 53 | # MEMORY_BACKEND - Memory backend type (Default: local) 54 | MEMORY_BACKEND=local 55 | 56 | ### PINECONE 57 | # PINECONE_API_KEY - Pinecone API Key (Example: my-pinecone-api-key) 58 | # PINECONE_ENV - Pinecone environment (region) (Example: us-west-2) 59 | PINECONE_API_KEY=your-pinecone-api-key 60 | PINECONE_ENV=your-pinecone-region 61 | 62 | ### REDIS 63 | # REDIS_HOST - Redis host (Default: localhost) 64 | # REDIS_PORT - Redis port (Default: 6379) 65 | # REDIS_PASSWORD - Redis password (Default: "") 66 | # WIPE_REDIS_ON_START - Wipes data / index on start (Default: False) 67 | # MEMORY_INDEX - Name of index created in Redis database (Default: auto-gpt) 68 | REDIS_HOST=localhost 69 | REDIS_PORT=6379 70 | REDIS_PASSWORD= 71 | WIPE_REDIS_ON_START=False 72 | MEMORY_INDEX=auto-gpt 73 | 74 | ### MILVUS 75 | # MILVUS_ADDR - Milvus remote address (e.g. localhost:19530) 76 | # MILVUS_COLLECTION - Milvus collection, 77 | # change it if you want to start a new memory and retain the old memory. 78 | MILVUS_ADDR=your-milvus-cluster-host-port 79 | MILVUS_COLLECTION=autogpt 80 | 81 | ################################################################################ 82 | ### IMAGE GENERATION PROVIDER 83 | ################################################################################ 84 | 85 | ### OPEN AI 86 | # IMAGE_PROVIDER - Image provider (Example: dalle) 87 | IMAGE_PROVIDER=dalle 88 | 89 | ### HUGGINGFACE 90 | # STABLE DIFFUSION 91 | # (Default URL: https://api-inference.huggingface.co/models/CompVis/stable-diffusion-v1-4) 92 | # Set in image_gen.py) 93 | # HUGGINGFACE_API_TOKEN - HuggingFace API token (Example: my-huggingface-api-token) 94 | HUGGINGFACE_API_TOKEN=your-huggingface-api-token 95 | 96 | ################################################################################ 97 | ### AUDIO TO TEXT PROVIDER 98 | ################################################################################ 99 | 100 | ### HUGGINGFACE 101 | HUGGINGFACE_AUDIO_TO_TEXT_MODEL=facebook/wav2vec2-base-960h 102 | 103 | ################################################################################ 104 | ### GIT Provider for repository actions 105 | ################################################################################ 106 | 107 | ### GITHUB 108 | # GITHUB_API_KEY - Github API key / PAT (Example: github_pat_123) 109 | # GITHUB_USERNAME - Github username 110 | GITHUB_API_KEY=github_pat_123 111 | GITHUB_USERNAME=your-github-username 112 | 113 | ################################################################################ 114 | ### SEARCH PROVIDER 115 | ################################################################################ 116 | 117 | ### GOOGLE 118 | # GOOGLE_API_KEY - Google API key (Example: my-google-api-key) 119 | # CUSTOM_SEARCH_ENGINE_ID - Custom search engine ID (Example: my-custom-search-engine-id) 120 | GOOGLE_API_KEY=your-google-api-key 121 | CUSTOM_SEARCH_ENGINE_ID=your-custom-search-engine-id 122 | 123 | ################################################################################ 124 | ### TTS PROVIDER 125 | ################################################################################ 126 | 127 | ### MAC OS 128 | # USE_MAC_OS_TTS - Use Mac OS TTS or not (Default: False) 129 | USE_MAC_OS_TTS=False 130 | 131 | ### STREAMELEMENTS 132 | # USE_BRIAN_TTS - Use Brian TTS or not (Default: False) 133 | USE_BRIAN_TTS=False 134 | 135 | ### ELEVENLABS 136 | # ELEVENLABS_API_KEY - Eleven Labs API key (Example: my-elevenlabs-api-key) 137 | # ELEVENLABS_VOICE_1_ID - Eleven Labs voice 1 ID (Example: my-voice-id-1) 138 | # ELEVENLABS_VOICE_2_ID - Eleven Labs voice 2 ID (Example: my-voice-id-2) 139 | ELEVENLABS_API_KEY=your-elevenlabs-api-key 140 | ELEVENLABS_VOICE_1_ID=your-voice-id-1 141 | ELEVENLABS_VOICE_2_ID=your-voice-id-2 142 | 143 | ################################################################################ 144 | ### TWITTER API 145 | ################################################################################ 146 | 147 | TW_CONSUMER_KEY= 148 | TW_CONSUMER_SECRET= 149 | TW_ACCESS_TOKEN= 150 | TW_ACCESS_TOKEN_SECRET= 151 | -------------------------------------------------------------------------------- /autogpt/commands/file_operations.py: -------------------------------------------------------------------------------- 1 | """File operations for AutoGPT""" 2 | import os 3 | import os.path 4 | from pathlib import Path 5 | from typing import Generator, List 6 | 7 | # Set a dedicated folder for file I/O 8 | WORKING_DIRECTORY = Path(__file__).parent.parent / "auto_gpt_workspace" 9 | 10 | # Create the directory if it doesn't exist 11 | if not os.path.exists(WORKING_DIRECTORY): 12 | os.makedirs(WORKING_DIRECTORY) 13 | 14 | WORKING_DIRECTORY = str(WORKING_DIRECTORY) 15 | 16 | 17 | def safe_join(base: str, *paths) -> str: 18 | """Join one or more path components intelligently. 19 | 20 | Args: 21 | base (str): The base path 22 | *paths (str): The paths to join to the base path 23 | 24 | Returns: 25 | str: The joined path 26 | """ 27 | new_path = os.path.join(base, *paths) 28 | norm_new_path = os.path.normpath(new_path) 29 | 30 | if os.path.commonprefix([base, norm_new_path]) != base: 31 | raise ValueError("Attempted to access outside of working directory.") 32 | 33 | return norm_new_path 34 | 35 | 36 | def split_file( 37 | content: str, max_length: int = 4000, overlap: int = 0 38 | ) -> Generator[str, None, None]: 39 | """ 40 | Split text into chunks of a specified maximum length with a specified overlap 41 | between chunks. 42 | 43 | :param content: The input text to be split into chunks 44 | :param max_length: The maximum length of each chunk, 45 | default is 4000 (about 1k token) 46 | :param overlap: The number of overlapping characters between chunks, 47 | default is no overlap 48 | :return: A generator yielding chunks of text 49 | """ 50 | start = 0 51 | content_length = len(content) 52 | 53 | while start < content_length: 54 | end = start + max_length 55 | if end + overlap < content_length: 56 | chunk = content[start : end + overlap] 57 | else: 58 | chunk = content[start:content_length] 59 | yield chunk 60 | start += max_length - overlap 61 | 62 | 63 | def read_file(filename: str) -> str: 64 | """Read a file and return the contents 65 | 66 | Args: 67 | filename (str): The name of the file to read 68 | 69 | Returns: 70 | str: The contents of the file 71 | """ 72 | try: 73 | filepath = safe_join(WORKING_DIRECTORY, filename) 74 | with open(filepath, "r", encoding="utf-8") as f: 75 | content = f.read() 76 | return content 77 | except Exception as e: 78 | return f"Error: {str(e)}" 79 | 80 | 81 | def ingest_file( 82 | filename: str, memory, max_length: int = 4000, overlap: int = 200 83 | ) -> None: 84 | """ 85 | Ingest a file by reading its content, splitting it into chunks with a specified 86 | maximum length and overlap, and adding the chunks to the memory storage. 87 | 88 | :param filename: The name of the file to ingest 89 | :param memory: An object with an add() method to store the chunks in memory 90 | :param max_length: The maximum length of each chunk, default is 4000 91 | :param overlap: The number of overlapping characters between chunks, default is 200 92 | """ 93 | try: 94 | print(f"Working with file {filename}") 95 | content = read_file(filename) 96 | content_length = len(content) 97 | print(f"File length: {content_length} characters") 98 | 99 | chunks = list(split_file(content, max_length=max_length, overlap=overlap)) 100 | 101 | num_chunks = len(chunks) 102 | for i, chunk in enumerate(chunks): 103 | print(f"Ingesting chunk {i + 1} / {num_chunks} into memory") 104 | memory_to_add = ( 105 | f"Filename: {filename}\n" f"Content part#{i + 1}/{num_chunks}: {chunk}" 106 | ) 107 | 108 | memory.add(memory_to_add) 109 | 110 | print(f"Done ingesting {num_chunks} chunks from {filename}.") 111 | except Exception as e: 112 | print(f"Error while ingesting file '{filename}': {str(e)}") 113 | 114 | 115 | def write_to_file(filename: str, text: str) -> str: 116 | """Write text to a file 117 | 118 | Args: 119 | filename (str): The name of the file to write to 120 | text (str): The text to write to the file 121 | 122 | Returns: 123 | str: A message indicating success or failure 124 | """ 125 | try: 126 | filepath = safe_join(WORKING_DIRECTORY, filename) 127 | directory = os.path.dirname(filepath) 128 | if not os.path.exists(directory): 129 | os.makedirs(directory) 130 | with open(filepath, "w", encoding="utf-8") as f: 131 | f.write(text) 132 | return "File written to successfully." 133 | except Exception as e: 134 | return f"Error: {str(e)}" 135 | 136 | 137 | def append_to_file(filename: str, text: str) -> str: 138 | """Append text to a file 139 | 140 | Args: 141 | filename (str): The name of the file to append to 142 | text (str): The text to append to the file 143 | 144 | Returns: 145 | str: A message indicating success or failure 146 | """ 147 | try: 148 | filepath = safe_join(WORKING_DIRECTORY, filename) 149 | with open(filepath, "a") as f: 150 | f.write(text) 151 | return "Text appended successfully." 152 | except Exception as e: 153 | return f"Error: {str(e)}" 154 | 155 | 156 | def delete_file(filename: str) -> str: 157 | """Delete a file 158 | 159 | Args: 160 | filename (str): The name of the file to delete 161 | 162 | Returns: 163 | str: A message indicating success or failure 164 | """ 165 | try: 166 | filepath = safe_join(WORKING_DIRECTORY, filename) 167 | os.remove(filepath) 168 | return "File deleted successfully." 169 | except Exception as e: 170 | return f"Error: {str(e)}" 171 | 172 | 173 | def search_files(directory: str) -> List[str]: 174 | """Search for files in a directory 175 | 176 | Args: 177 | directory (str): The directory to search in 178 | 179 | Returns: 180 | List[str]: A list of files found in the directory 181 | """ 182 | found_files = [] 183 | 184 | if directory in {"", "/"}: 185 | search_directory = WORKING_DIRECTORY 186 | else: 187 | search_directory = safe_join(WORKING_DIRECTORY, directory) 188 | 189 | for root, _, files in os.walk(search_directory): 190 | for file in files: 191 | if file.startswith("."): 192 | continue 193 | relative_path = os.path.relpath(os.path.join(root, file), WORKING_DIRECTORY) 194 | found_files.append(relative_path) 195 | 196 | return found_files 197 | --------------------------------------------------------------------------------