From 0cf790b633b417c092f84b52715f5ec057c045aa Mon Sep 17 00:00:00 2001 From: meta-fx Date: Mon, 10 Apr 2023 20:00:43 -0500 Subject: [PATCH 01/64] Added new env variable and speech function for alternative TTS voice --- .env.template | 1 + scripts/config.py | 11 ++++++++--- scripts/speak.py | 28 ++++++++++++++++++++++++++-- 3 files changed, 35 insertions(+), 5 deletions(-) diff --git a/.env.template b/.env.template index 01735615..98d2ca91 100644 --- a/.env.template +++ b/.env.template @@ -13,3 +13,4 @@ OPENAI_AZURE_DEPLOYMENT_ID=deployment-id-for-azure IMAGE_PROVIDER=dalle HUGGINGFACE_API_TOKEN= USE_MAC_OS_TTS=False +USE_BRIAN_TTS=False \ No newline at end of file diff --git a/scripts/config.py b/scripts/config.py index 27cc946c..3bf5cd9a 100644 --- a/scripts/config.py +++ b/scripts/config.py @@ -57,7 +57,10 @@ class Config(metaclass=Singleton): self.use_mac_os_tts = False self.use_mac_os_tts = os.getenv("USE_MAC_OS_TTS") - + + self.use_brian_tts = False + self.use_brian_tts = os.getenv("USE_BRIAN_TTS") + self.google_api_key = os.getenv("GOOGLE_API_KEY") self.custom_search_engine_id = os.getenv("CUSTOM_SEARCH_ENGINE_ID") @@ -69,11 +72,13 @@ class Config(metaclass=Singleton): # User agent headers to use when browsing web # Some websites might just completely deny request with an error code if no user agent was found. - self.user_agent_header = {"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"} + self.user_agent_header = { + "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"} self.redis_host = os.getenv("REDIS_HOST", "localhost") self.redis_port = os.getenv("REDIS_PORT", "6379") self.redis_password = os.getenv("REDIS_PASSWORD", "") - self.wipe_redis_on_start = os.getenv("WIPE_REDIS_ON_START", "True") == 'True' + self.wipe_redis_on_start = os.getenv( + "WIPE_REDIS_ON_START", "True") == 'True' self.memory_index = os.getenv("MEMORY_INDEX", 'auto-gpt') # Note that indexes must be created on db 0 in redis, this is not configureable. diff --git a/scripts/speak.py b/scripts/speak.py index 5d1e153c..ebaae8d1 100644 --- a/scripts/speak.py +++ b/scripts/speak.py @@ -1,9 +1,9 @@ +import gtts import os from playsound import playsound import requests from config import Config cfg = Config() -import gtts # TODO: Nicer names for these ids @@ -14,6 +14,7 @@ tts_headers = { "xi-api-key": cfg.elevenlabs_api_key } + def eleven_labs_speech(text, voice_index=0): """Speak text using elevenlabs.io's API""" tts_url = "https://api.elevenlabs.io/v1/text-to-speech/{voice_id}".format( @@ -33,23 +34,46 @@ def eleven_labs_speech(text, voice_index=0): print("Response content:", response.content) return False + +def brian_speech(text): + """Speak text using Brian with the streamelements API""" + tts_url = f"https://api.streamelements.com/kappa/v2/speech?voice=Brian&text={text}" + response = requests.get(tts_url) + + if response.status_code == 200: + with open("speech.mp3", "wb") as f: + f.write(response.content) + playsound("speech.mp3") + os.remove("speech.mp3") + return True + else: + print("Request failed with status code:", response.status_code) + print("Response content:", response.content) + return False + + def gtts_speech(text): tts = gtts.gTTS(text) tts.save("speech.mp3") playsound("speech.mp3") os.remove("speech.mp3") + def macos_tts_speech(text): os.system(f'say "{text}"') + def say_text(text, voice_index=0): if not cfg.elevenlabs_api_key: if cfg.use_mac_os_tts == 'True': macos_tts_speech(text) + elif cfg.use_brian_tts == 'True': + success = brian_speech(text) + if not success: + gtts_speech(text) else: gtts_speech(text) else: success = eleven_labs_speech(text, voice_index) if not success: gtts_speech(text) - From 3ee62211db3003312e09ff02517b0f250d7717a6 Mon Sep 17 00:00:00 2001 From: meta-fx Date: Mon, 10 Apr 2023 20:56:27 -0500 Subject: [PATCH 02/64] Fixed formatting issues --- scripts/config.py | 8 +++----- scripts/speak.py | 9 ++------- 2 files changed, 5 insertions(+), 12 deletions(-) diff --git a/scripts/config.py b/scripts/config.py index 3bf5cd9a..f636da7d 100644 --- a/scripts/config.py +++ b/scripts/config.py @@ -72,13 +72,11 @@ class Config(metaclass=Singleton): # User agent headers to use when browsing web # Some websites might just completely deny request with an error code if no user agent was found. - self.user_agent_header = { - "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"} + self.user_agent_header = {"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"} self.redis_host = os.getenv("REDIS_HOST", "localhost") self.redis_port = os.getenv("REDIS_PORT", "6379") self.redis_password = os.getenv("REDIS_PASSWORD", "") - self.wipe_redis_on_start = os.getenv( - "WIPE_REDIS_ON_START", "True") == 'True' + self.wipe_redis_on_start = os.getenv("WIPE_REDIS_ON_START", "True") == 'True' self.memory_index = os.getenv("MEMORY_INDEX", 'auto-gpt') # Note that indexes must be created on db 0 in redis, this is not configureable. @@ -139,4 +137,4 @@ class Config(metaclass=Singleton): def set_debug_mode(self, value: bool): """Set the debug mode value.""" - self.debug = value + self.debug = value \ No newline at end of file diff --git a/scripts/speak.py b/scripts/speak.py index ebaae8d1..2464c625 100644 --- a/scripts/speak.py +++ b/scripts/speak.py @@ -1,9 +1,9 @@ -import gtts import os from playsound import playsound import requests from config import Config cfg = Config() +import gtts # TODO: Nicer names for these ids @@ -14,7 +14,6 @@ tts_headers = { "xi-api-key": cfg.elevenlabs_api_key } - def eleven_labs_speech(text, voice_index=0): """Speak text using elevenlabs.io's API""" tts_url = "https://api.elevenlabs.io/v1/text-to-speech/{voice_id}".format( @@ -34,7 +33,6 @@ def eleven_labs_speech(text, voice_index=0): print("Response content:", response.content) return False - def brian_speech(text): """Speak text using Brian with the streamelements API""" tts_url = f"https://api.streamelements.com/kappa/v2/speech?voice=Brian&text={text}" @@ -51,18 +49,15 @@ def brian_speech(text): print("Response content:", response.content) return False - def gtts_speech(text): tts = gtts.gTTS(text) tts.save("speech.mp3") playsound("speech.mp3") os.remove("speech.mp3") - def macos_tts_speech(text): os.system(f'say "{text}"') - def say_text(text, voice_index=0): if not cfg.elevenlabs_api_key: if cfg.use_mac_os_tts == 'True': @@ -76,4 +71,4 @@ def say_text(text, voice_index=0): else: success = eleven_labs_speech(text, voice_index) if not success: - gtts_speech(text) + gtts_speech(text) \ No newline at end of file From 3cdde2d49cba4b43045ebef7f16236fed3a4acc9 Mon Sep 17 00:00:00 2001 From: meta-fx Date: Tue, 11 Apr 2023 08:15:58 -0500 Subject: [PATCH 03/64] Resolved conflicts in config.py and speak.py --- scripts/config.py | 7 ++---- scripts/speak.py | 60 ++++++++++++++++++++++++++++++----------------- 2 files changed, 40 insertions(+), 27 deletions(-) diff --git a/scripts/config.py b/scripts/config.py index f636da7d..cdf0287c 100644 --- a/scripts/config.py +++ b/scripts/config.py @@ -33,7 +33,7 @@ class Config(metaclass=Singleton): def __init__(self): """Initialize the Config class""" - self.debug = False + self.debug_mode = False self.continuous_mode = False self.speak_mode = False @@ -92,9 +92,6 @@ class Config(metaclass=Singleton): """Set the speak mode value.""" self.speak_mode = value - def set_debug_mode(self, value: bool): - self.debug_mode = value - def set_fast_llm_model(self, value: str): """Set the fast LLM model value.""" self.fast_llm_model = value @@ -137,4 +134,4 @@ class Config(metaclass=Singleton): def set_debug_mode(self, value: bool): """Set the debug mode value.""" - self.debug = value \ No newline at end of file + self.debug_mode = value \ No newline at end of file diff --git a/scripts/speak.py b/scripts/speak.py index 2464c625..bf5c6034 100644 --- a/scripts/speak.py +++ b/scripts/speak.py @@ -4,6 +4,8 @@ import requests from config import Config cfg = Config() import gtts +import threading +from threading import Lock, Semaphore # TODO: Nicer names for these ids @@ -14,6 +16,9 @@ tts_headers = { "xi-api-key": cfg.elevenlabs_api_key } +mutex_lock = Lock() # Ensure only one sound is played at a time +queue_semaphore = Semaphore(1) # The amount of sounds to queue before blocking the main thread + def eleven_labs_speech(text, voice_index=0): """Speak text using elevenlabs.io's API""" tts_url = "https://api.elevenlabs.io/v1/text-to-speech/{voice_id}".format( @@ -23,10 +28,11 @@ def eleven_labs_speech(text, voice_index=0): tts_url, headers=tts_headers, json=formatted_message) if response.status_code == 200: - with open("speech.mpeg", "wb") as f: - f.write(response.content) - playsound("speech.mpeg") - os.remove("speech.mpeg") + with mutex_lock: + with open("speech.mpeg", "wb") as f: + f.write(response.content) + playsound("speech.mpeg", True) + os.remove("speech.mpeg") return True else: print("Request failed with status code:", response.status_code) @@ -39,10 +45,11 @@ def brian_speech(text): response = requests.get(tts_url) if response.status_code == 200: - with open("speech.mp3", "wb") as f: - f.write(response.content) - playsound("speech.mp3") - os.remove("speech.mp3") + with mutex_lock: + with open("speech.mp3", "wb") as f: + f.write(response.content) + playsound("speech.mp3") + os.remove("speech.mp3") return True else: print("Request failed with status code:", response.status_code) @@ -51,24 +58,33 @@ def brian_speech(text): def gtts_speech(text): tts = gtts.gTTS(text) - tts.save("speech.mp3") - playsound("speech.mp3") - os.remove("speech.mp3") + with mutex_lock: + tts.save("speech.mp3") + playsound("speech.mp3", True) + os.remove("speech.mp3") def macos_tts_speech(text): os.system(f'say "{text}"') def say_text(text, voice_index=0): - if not cfg.elevenlabs_api_key: - if cfg.use_mac_os_tts == 'True': - macos_tts_speech(text) - elif cfg.use_brian_tts == 'True': - success = brian_speech(text) - if not success: + + def speak(): + if not cfg.elevenlabs_api_key: + if cfg.use_mac_os_tts == 'True': + macos_tts_speech(text) + elif cfg.use_brian_tts == 'True': + success = brian_speech(text) + if not success: + gtts_speech(text) + else: gtts_speech(text) else: - gtts_speech(text) - else: - success = eleven_labs_speech(text, voice_index) - if not success: - gtts_speech(text) \ No newline at end of file + success = eleven_labs_speech(text, voice_index) + if not success: + gtts_speech(text) + + queue_semaphore.release() + + queue_semaphore.acquire(True) + thread = threading.Thread(target=speak) + thread.start() \ No newline at end of file From 570f76bd51a2f01c78788938eadc17348bb92fe3 Mon Sep 17 00:00:00 2001 From: meta-fx Date: Tue, 11 Apr 2023 14:40:05 -0500 Subject: [PATCH 04/64] Removed trailing spaces and fixed CRLF being removed --- scripts/config.py | 4 ++-- scripts/speak.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/scripts/config.py b/scripts/config.py index cdf0287c..c4ad3bf4 100644 --- a/scripts/config.py +++ b/scripts/config.py @@ -72,7 +72,7 @@ class Config(metaclass=Singleton): # User agent headers to use when browsing web # Some websites might just completely deny request with an error code if no user agent was found. - self.user_agent_header = {"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"} + self.user_agent_header = {"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"} self.redis_host = os.getenv("REDIS_HOST", "localhost") self.redis_port = os.getenv("REDIS_PORT", "6379") self.redis_password = os.getenv("REDIS_PASSWORD", "") @@ -134,4 +134,4 @@ class Config(metaclass=Singleton): def set_debug_mode(self, value: bool): """Set the debug mode value.""" - self.debug_mode = value \ No newline at end of file + self.debug_mode = value diff --git a/scripts/speak.py b/scripts/speak.py index bf5c6034..4934ecef 100644 --- a/scripts/speak.py +++ b/scripts/speak.py @@ -67,7 +67,7 @@ def macos_tts_speech(text): os.system(f'say "{text}"') def say_text(text, voice_index=0): - + def speak(): if not cfg.elevenlabs_api_key: if cfg.use_mac_os_tts == 'True': @@ -87,4 +87,4 @@ def say_text(text, voice_index=0): queue_semaphore.acquire(True) thread = threading.Thread(target=speak) - thread.start() \ No newline at end of file + thread.start() From c785352ed2c6f1744bdeac5410ea93199bade937 Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Wed, 12 Apr 2023 16:23:09 +0200 Subject: [PATCH 05/64] Update main.py clean trailing whitespace --- scripts/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/main.py b/scripts/main.py index 15af0c38..3dcedb5f 100644 --- a/scripts/main.py +++ b/scripts/main.py @@ -293,7 +293,7 @@ def parse_arguments(): if args.gpt3only: print_to_console("GPT3.5 Only Mode: ", Fore.GREEN, "ENABLED") cfg.set_smart_llm_model(cfg.fast_llm_model) - + if args.gpt4only: print_to_console("GPT4 Only Mode: ", Fore.GREEN, "ENABLED") cfg.set_fast_llm_model(cfg.smart_llm_model) From c986e8713512aad9f06c074b5e7fdfa31ade2df7 Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Wed, 12 Apr 2023 16:36:27 +0200 Subject: [PATCH 06/64] Edit config Class to manage browse_website command chunk size and summary size I added two new config parameters: - browse_chunk_max_length: define the max_length of a chunk being sent to the memory and to FAST_LLM_MODEL for summarizing - browse_summary_max_token: define the max_token passed to the model use for summary creation. Changing this can help with complex subject, allowing the agent to be more verbose in its attemps to summarize the chunk and the chunks summary. I've also edited the way the user_agent is handle. --- .env.template | 2 ++ scripts/config.py | 14 +++++++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/.env.template b/.env.template index 6fbc8424..0953fac9 100644 --- a/.env.template +++ b/.env.template @@ -15,3 +15,5 @@ OPENAI_AZURE_DEPLOYMENT_ID=deployment-id-for-azure IMAGE_PROVIDER=dalle HUGGINGFACE_API_TOKEN= USE_MAC_OS_TTS=False +BROWSE_CHUNK_MAX_LENGTH=4000 +BROWSE_SUMMARY_MAX_TOKEN=300 \ No newline at end of file diff --git a/scripts/config.py b/scripts/config.py index a280e6cc..1eeeb72f 100644 --- a/scripts/config.py +++ b/scripts/config.py @@ -41,6 +41,8 @@ class Config(metaclass=Singleton): self.smart_llm_model = os.getenv("SMART_LLM_MODEL", "gpt-4") self.fast_token_limit = int(os.getenv("FAST_TOKEN_LIMIT", 4000)) self.smart_token_limit = int(os.getenv("SMART_TOKEN_LIMIT", 8000)) + self.browse_chunk_max_length = int(os.getenv("BROWSE_CHUNK_MAX_LENGTH", 8000)) + self.browse_summary_max_token = int(os.getenv("BROWSE_SUMMARY_MAX_TOKEN", 300)) self.openai_api_key = os.getenv("OPENAI_API_KEY") self.use_azure = False @@ -71,7 +73,8 @@ class Config(metaclass=Singleton): # User agent headers to use when browsing web # Some websites might just completely deny request with an error code if no user agent was found. - self.user_agent_header = {"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"} + self.user_agent = os.getenv("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") + self.redis_host = os.getenv("REDIS_HOST", "localhost") self.redis_port = os.getenv("REDIS_PORT", "6379") self.redis_password = os.getenv("REDIS_PASSWORD", "") @@ -80,6 +83,7 @@ class Config(metaclass=Singleton): # Note that indexes must be created on db 0 in redis, this is not configurable. self.memory_backend = os.getenv("MEMORY_BACKEND", 'local') + # Initialize the OpenAI API client openai.api_key = self.openai_api_key @@ -107,6 +111,14 @@ class Config(metaclass=Singleton): """Set the smart token limit value.""" self.smart_token_limit = value + def set_browse_chunk_max_length(self, value: int): + """Set the browse_website command chunk max length value.""" + self.browse_chunk_max_length = value + + def set_browse_summary_max_token(self, value: int): + """Set the browse_website command summary max token value.""" + self.browse_summary_max_token = value + def set_openai_api_key(self, value: str): """Set the OpenAI API key value.""" self.openai_api_key = value From b20c0117c5732e73005ee9fc12380078d5ea442c Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Wed, 12 Apr 2023 16:38:49 +0200 Subject: [PATCH 07/64] Add memory management to browse.py - Change the way User-Agent is handle when calling requests to browse website - Add chunk to memory before and after summary. We do not save the "summary of summaries" as this wasn't performing great and caused noise when the "question" couldn't be answered. - Use the newly added config parameters for max_length and max_token --- scripts/browse.py | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/scripts/browse.py b/scripts/browse.py index b0c745ef..5f4aafe6 100644 --- a/scripts/browse.py +++ b/scripts/browse.py @@ -1,9 +1,14 @@ import requests from bs4 import BeautifulSoup +from memory import get_memory from config import Config from llm_utils import create_chat_completion cfg = Config() +memory = get_memory(cfg) + +session = requests.Session() +session.headers.update({'User-Agent': cfg.user_agent}) # Define and check for local file address prefixes def check_local_file_access(url): @@ -21,7 +26,7 @@ def scrape_text(url): return "Error: Access to local files is restricted" try: - response = requests.get(url, headers=cfg.user_agent_header) + response = session.get(url) except requests.exceptions.RequestException as e: return "Error: " + str(e) @@ -60,7 +65,7 @@ def format_hyperlinks(hyperlinks): def scrape_links(url): """Scrape links from a webpage""" - response = requests.get(url, headers=cfg.user_agent_header) + response = session.get(url) # Check if the response contains an HTTP error if response.status_code >= 400: @@ -76,7 +81,7 @@ def scrape_links(url): return format_hyperlinks(hyperlinks) -def split_text(text, max_length=8192): +def split_text(text, max_length=cfg.browse_chunk_max_length): """Split text into chunks of a maximum length""" paragraphs = text.split("\n") current_length = 0 @@ -102,7 +107,7 @@ def create_message(chunk, question): "content": f"\"\"\"{chunk}\"\"\" Using the above text, please answer the following question: \"{question}\" -- if the question cannot be answered using the text, please summarize the text." } -def summarize_text(text, question): +def summarize_text(url, text, question): """Summarize text using the LLM model""" if not text: return "Error: No text to summarize" @@ -114,15 +119,28 @@ def summarize_text(text, question): chunks = list(split_text(text)) for i, chunk in enumerate(chunks): + print(f"Adding chunk {i + 1} / {len(chunks)} to memory") + + memory_to_add = f"Source: {url}\n" \ + f"Raw content part#{i + 1}: {chunk}" + + memory.add(memory_to_add) + print(f"Summarizing chunk {i + 1} / {len(chunks)}") messages = [create_message(chunk, question)] summary = create_chat_completion( model=cfg.fast_llm_model, messages=messages, - max_tokens=300, + max_tokens=cfg.browse_summary_max_token, ) summaries.append(summary) + print(f"Added chunk {i + 1} summary to memory") + + memory_to_add = f"Source: {url}\n" \ + f"Content summary part#{i + 1}: {summary}" + + memory.add(memory_to_add) print(f"Summarized {len(chunks)} chunks.") @@ -132,7 +150,7 @@ def summarize_text(text, question): final_summary = create_chat_completion( model=cfg.fast_llm_model, messages=messages, - max_tokens=300, + max_tokens=cfg.browse_summary_max_token, ) return final_summary From 5bb551db95fe1eb6765c61fa28bf384d8252cdad Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Wed, 12 Apr 2023 16:42:14 +0200 Subject: [PATCH 08/64] add the url variable in the get_text_summary function to pass it to the memory By sending the url along when calling browse.summarize_text, we can then add it along the chunk in memory. --- scripts/commands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/commands.py b/scripts/commands.py index 92d46ae1..90d7a6f3 100644 --- a/scripts/commands.py +++ b/scripts/commands.py @@ -183,7 +183,7 @@ def browse_website(url, question): def get_text_summary(url, question): """Return the results of a google search""" text = browse.scrape_text(url) - summary = browse.summarize_text(text, question) + summary = browse.summarize_text(url, text, question) return """ "Result" : """ + summary From a615e570616146ba51336b4160c2eff225479769 Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Wed, 12 Apr 2023 18:00:17 +0200 Subject: [PATCH 09/64] Revert "Update main.py" This reverts commit c785352ed2c6f1744bdeac5410ea93199bade937. --- scripts/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/main.py b/scripts/main.py index 3dcedb5f..15af0c38 100644 --- a/scripts/main.py +++ b/scripts/main.py @@ -293,7 +293,7 @@ def parse_arguments(): if args.gpt3only: print_to_console("GPT3.5 Only Mode: ", Fore.GREEN, "ENABLED") cfg.set_smart_llm_model(cfg.fast_llm_model) - + if args.gpt4only: print_to_console("GPT4 Only Mode: ", Fore.GREEN, "ENABLED") cfg.set_fast_llm_model(cfg.smart_llm_model) From 8baa0769b154f3742cdc75e07404952de02e0669 Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Wed, 12 Apr 2023 18:03:59 +0200 Subject: [PATCH 10/64] Update config.py --- scripts/config.py | 1 - 1 file changed, 1 deletion(-) diff --git a/scripts/config.py b/scripts/config.py index 1eeeb72f..9c4e4572 100644 --- a/scripts/config.py +++ b/scripts/config.py @@ -83,7 +83,6 @@ class Config(metaclass=Singleton): # Note that indexes must be created on db 0 in redis, this is not configurable. self.memory_backend = os.getenv("MEMORY_BACKEND", 'local') - # Initialize the OpenAI API client openai.api_key = self.openai_api_key From 0dddc94bdac94707062b1863f3c5a72d113432ca Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Wed, 12 Apr 2023 19:13:04 +0200 Subject: [PATCH 11/64] Add file ingestion methode in file_operations.py Add the following functions to ingest data into memory before Auto-GPT run. - split_file: given a content, split it in chunks of max_length with (or without) a specified overlap - ingest_file: read a file, use split_file to split it in chunks and load each chunk in memory - ingest_directory: ingest all files in a directory in memory --- scripts/file_operations.py | 75 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/scripts/file_operations.py b/scripts/file_operations.py index c6066ef9..3493c2bf 100644 --- a/scripts/file_operations.py +++ b/scripts/file_operations.py @@ -1,5 +1,10 @@ import os import os.path +from config import Config +from memory import get_memory + +cfg = Config() +memory = get_memory(cfg) # Set a dedicated folder for file I/O working_directory = "auto_gpt_workspace" @@ -20,6 +25,30 @@ def safe_join(base, *paths): return norm_new_path +def split_file(content, max_length=4000, overlap=0): + """ + Split text into chunks of a specified maximum length with a specified overlap + between chunks. + + :param text: The input text to be split into chunks + :param max_length: The maximum length of each chunk, default is 4000 (about 1k token) + :param overlap: The number of overlapping characters between chunks, default is no overlap + :return: A generator yielding chunks of text + """ + start = 0 + content_length = len(content) + + while start < content_length: + end = start + max_length + chunk = content[start:end] + yield chunk + start += max_length - overlap + if start + max_length - overlap >= content_length: + break + if end + overlap > content_length: + start = content_length - max_length + + def read_file(filename): """Read a file and return the contents""" try: @@ -31,6 +60,52 @@ def read_file(filename): return "Error: " + str(e) +def ingest_file(filename, memory, max_length=4000, overlap=200): + """ + Ingest a file by reading its content, splitting it into chunks with a specified + maximum length and overlap, and adding the chunks to the memory storage. + + :param filename: The name of the file to ingest + :param memory: An object with an add() method to store the chunks in memory + :param max_length: The maximum length of each chunk, default is 4000 + :param overlap: The number of overlapping characters between chunks, default is 200 + """ + try: + print(f"Working with file {filename}") + content = read_file(filename) + content_length = len(content) + print(f"File length: {content_length} characters") + + chunks = list(split_file(content, max_length=max_length, overlap=overlap)) + + num_chunks = len(chunks) + for i, chunk in enumerate(chunks): + print(f"Ingesting chunk {i + 1} / {num_chunks} into memory") + memory_to_add = f"Filename: {filename}\n" \ + f"Content part#{i + 1}/{num_chunks}: {chunk}" + + memory.add(memory_to_add) + + print(f"Done ingesting {num_chunks} chunks from {filename}.") + except Exception as e: + print(f"Error while ingesting file '{filename}': {str(e)}") + + +def ingest_directory(directory, memory): + """ + Ingest all files in a directory by calling the ingest_file function for each file. + + :param directory: The directory containing the files to ingest + :param memory: An object with an add() method to store the chunks in memory + """ + try: + files = search_files(directory) + for file in files: + ingest_file(file, memory) + except Exception as e: + print(f"Error while ingesting directory '{directory}': {str(e)}") + + def write_to_file(filename, text): """Write text to a file""" try: From 7975c184a55a477e884e1920ed87dc67ca4b4261 Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Wed, 12 Apr 2023 19:46:39 +0200 Subject: [PATCH 12/64] Update .gitignore add new log file to gitignore --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index aa0dceaa..fc496609 100644 --- a/.gitignore +++ b/.gitignore @@ -18,4 +18,5 @@ log.txt # Coverage reports .coverage coverage.xml -htmlcov/ \ No newline at end of file +htmlcov/ +log-ingestion.txt From c91117616f7b5e16743208b8649ce4335077915b Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Wed, 12 Apr 2023 19:46:58 +0200 Subject: [PATCH 13/64] Update file_operations.py revert change in import as we don't need them --- scripts/file_operations.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/scripts/file_operations.py b/scripts/file_operations.py index 3493c2bf..8e807bba 100644 --- a/scripts/file_operations.py +++ b/scripts/file_operations.py @@ -1,10 +1,5 @@ import os import os.path -from config import Config -from memory import get_memory - -cfg = Config() -memory = get_memory(cfg) # Set a dedicated folder for file I/O working_directory = "auto_gpt_workspace" From 8faa6ef949bf7fbbb8bd875a66bfd4fd231ecebc Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Wed, 12 Apr 2023 19:47:51 +0200 Subject: [PATCH 14/64] Create data_ingestion.py This script is use when we want to seed Auto-GPT memory with one or multiple documents. The document are read, split into chunks and store in the memory. --- scripts/data_ingestion.py | 52 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 scripts/data_ingestion.py diff --git a/scripts/data_ingestion.py b/scripts/data_ingestion.py new file mode 100644 index 00000000..3f6d1322 --- /dev/null +++ b/scripts/data_ingestion.py @@ -0,0 +1,52 @@ +import argparse +import logging +from config import Config +from memory import get_memory +from file_operations import ingest_file, ingest_directory + +cfg = Config() + +def configure_logging(): + logging.basicConfig(filename='log-ingestion.txt', + filemode='a', + format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s', + datefmt='%H:%M:%S', + level=logging.DEBUG) + return logging.getLogger('AutoGPT-Ingestion') + + +def main(): + logger = configure_logging() + + parser = argparse.ArgumentParser(description="Ingest a file or a directory with multiple files into memory. Make sure to set your .env before running this script.") + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument("--file", type=str, help="The file to ingest.") + group.add_argument("--dir", type=str, help="The directory containing the files to ingest.") + parser.add_argument("--init", action='store_true', help="Init the memory and wipe its content", default=False) + args = parser.parse_args() + + + # Initialize memory + memory = get_memory(cfg, init=args.init) + print('Using memory of type: ' + memory.__class__.__name__) + + if args.file: + try: + ingest_file(args.file, memory) + print(f"File '{args.file}' ingested successfully.") + except Exception as e: + logger.error(f"Error while ingesting file '{args.file}': {str(e)}") + print(f"Error while ingesting file '{args.file}': {str(e)}") + elif args.dir: + try: + ingest_directory(args.dir, memory) + print(f"Directory '{args.dir}' ingested successfully.") + except Exception as e: + logger.error(f"Error while ingesting directory '{args.dir}': {str(e)}") + print(f"Error while ingesting directory '{args.dir}': {str(e)}") + else: + print("Please provide either a file path (--file) or a directory name (--dir) inside the auto_gpt_workspace directory as input.") + + +if __name__ == "__main__": + main() From 4465486ea39b0bc65715e48a1c7861a565b5126f Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Wed, 12 Apr 2023 20:18:59 +0200 Subject: [PATCH 15/64] Update file_operations.py move the search_file function inside the data_ingestion script --- scripts/file_operations.py | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/scripts/file_operations.py b/scripts/file_operations.py index 8e807bba..e664fcc9 100644 --- a/scripts/file_operations.py +++ b/scripts/file_operations.py @@ -86,21 +86,6 @@ def ingest_file(filename, memory, max_length=4000, overlap=200): print(f"Error while ingesting file '{filename}': {str(e)}") -def ingest_directory(directory, memory): - """ - Ingest all files in a directory by calling the ingest_file function for each file. - - :param directory: The directory containing the files to ingest - :param memory: An object with an add() method to store the chunks in memory - """ - try: - files = search_files(directory) - for file in files: - ingest_file(file, memory) - except Exception as e: - print(f"Error while ingesting directory '{directory}': {str(e)}") - - def write_to_file(filename, text): """Write text to a file""" try: From 280647ff387bc29127b8403c7dd46f2c94d6a0b8 Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Wed, 12 Apr 2023 20:19:36 +0200 Subject: [PATCH 16/64] Update data_ingestion.py move the search_file function inside the data_ingestion script add memory initialisation argument add overlap argument add chunk max_length argument --- scripts/data_ingestion.py | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/scripts/data_ingestion.py b/scripts/data_ingestion.py index 3f6d1322..32811166 100644 --- a/scripts/data_ingestion.py +++ b/scripts/data_ingestion.py @@ -2,7 +2,7 @@ import argparse import logging from config import Config from memory import get_memory -from file_operations import ingest_file, ingest_directory +from file_operations import ingest_file, search_files cfg = Config() @@ -15,6 +15,21 @@ def configure_logging(): return logging.getLogger('AutoGPT-Ingestion') +def ingest_directory(directory, memory, args): + """ + Ingest all files in a directory by calling the ingest_file function for each file. + + :param directory: The directory containing the files to ingest + :param memory: An object with an add() method to store the chunks in memory + """ + try: + files = search_files(directory) + for file in files: + ingest_file(file, memory, args.max_length, args.overlap) + except Exception as e: + print(f"Error while ingesting directory '{directory}': {str(e)}") + + def main(): logger = configure_logging() @@ -22,7 +37,10 @@ def main(): group = parser.add_mutually_exclusive_group(required=True) group.add_argument("--file", type=str, help="The file to ingest.") group.add_argument("--dir", type=str, help="The directory containing the files to ingest.") - parser.add_argument("--init", action='store_true', help="Init the memory and wipe its content", default=False) + parser.add_argument("--init", action='store_true', help="Init the memory and wipe its content (default: False)", default=False) + parser.add_argument("--overlap", type=int, help="The overlap size between chunks when ingesting files (default: 200)", default=200) + parser.add_argument("--max_length", type=int, help="The max_length of each chunk when ingesting files (default: 4000)", default=4000) + args = parser.parse_args() @@ -32,14 +50,14 @@ def main(): if args.file: try: - ingest_file(args.file, memory) + ingest_file(args.file, memory, args.max_length, args.overlap) print(f"File '{args.file}' ingested successfully.") except Exception as e: logger.error(f"Error while ingesting file '{args.file}': {str(e)}") print(f"Error while ingesting file '{args.file}': {str(e)}") elif args.dir: try: - ingest_directory(args.dir, memory) + ingest_directory(args.dir, memory, args) print(f"Directory '{args.dir}' ingested successfully.") except Exception as e: logger.error(f"Error while ingesting directory '{args.dir}': {str(e)}") From 65cc4f833f56000ae3928cccc3c9821fece53958 Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Wed, 12 Apr 2023 20:47:46 +0200 Subject: [PATCH 17/64] Add Memory Pre-Seeding information to readme.md Add the documentation for memory pre-seeding --- README.md | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/README.md b/README.md index 2900daa9..6262467d 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,7 @@ Your support is greatly appreciated - [๐Ÿ—ฃ๏ธ Speech Mode](#๏ธ-speech-mode) - [๐Ÿ” Google API Keys Configuration](#-google-api-keys-configuration) - [Setting up environment variables](#setting-up-environment-variables) + - [๐Ÿง  Memory pre-seeding](#memory-pre-seeding) - [๐Ÿ’€ Continuous Mode โš ๏ธ](#-continuous-mode-๏ธ) - [GPT3.5 ONLY Mode](#gpt35-only-mode) - [๐Ÿ–ผ Image Generation](#image-generation) @@ -245,6 +246,52 @@ To switch to either, change the `MEMORY_BACKEND` env variable to the value that 1. View memory usage by using the `--debug` flag :) + +## ๐Ÿง  Memory pre-seeding + +``` +# python scripts/data_ingestion.py -h +usage: data_ingestion.py [-h] (--file FILE | --dir DIR) [--init] [--overlap OVERLAP] [--max_length MAX_LENGTH] + +Ingest a file or a directory with multiple files into memory. Make sure to set your .env before running this script. + +options: + -h, --help show this help message and exit + --file FILE The file to ingest. + --dir DIR The directory containing the files to ingest. + --init Init the memory and wipe its content (default: False) + --overlap OVERLAP The overlap size between chunks when ingesting files (default: 200) + --max_length MAX_LENGTH The max_length of each chunk when ingesting files (default: 4000 + +# python scripts/data_ingestion.py --dir seed_data --init --overlap 200 --max_length 1000 +``` + +This script located at scripts/data_ingestion.py, allows you to ingest files into memory and pre-seed it before running Auto-GPT. + +Memory pre-seeding is a technique that involves ingesting relevant documents or data into the AI's memory so that it can use this information to generate more informed and accurate responses. + +To pre-seed the memory, the content of each document is split into chunks of a specified maximum length with a specified overlap between chunks, and then each chunk is added to the memory backend set in the .env file. When the AI is prompted to recall information, it can then access those pre-seeded memories to generate more informed and accurate responses. + +This technique is particularly useful when working with large amounts of data or when there is specific information that the AI needs to be able to access quickly. +By pre-seeding the memory, the AI can retrieve and use this information more efficiently, saving time, API call and improving the accuracy of its responses. + +You could for example download the documentation of an API, a Github repository, etc. and ingest it into memory before running Auto-GPT. + +โš ๏ธ If you use Redis as your memory, make sure to run Auto-GPT with the WIPE_REDIS_ON_START set to False in your .env file. + +โš ๏ธFor other memory backend, we currently forcefully wipe the memory when starting Auto-GPT. To ingest data with those memory backend, you can call the data_ingestion.py script anytime during an Auto-GPT run. + +Memories will be available to the AI immediately as they are ingested, even if ingested while Auto-GPT is running. + +In the example above, the script initializes the memory, ingests all files within the seed_data directory into memory with an overlap between chunks of 200 and a maximum length of each chunk of 4000. +Note that you can also use the --file argument to ingest a single file into memory and that the script will only ingest files within the auto_gpt_workspace directory. + +You can adjust the max_length and overlap parameters to fine-tune the way the docuents are presented to the AI when it "recall" that memory: + +- Adjusting the overlap value allows the AI to access more contextual information from each chunk when recalling information, but will result in more chunks being created and therefore increase memory backend usage and OpenAI API requests. +- Reducing the max_length value will create more chunks, which can save prompt tokens by allowing for more message history in the context, but will also increase the number of chunks. +- Increasing the max_length value will provide the AI with more contextual information from each chunk, reducing the number of chunks created and saving on OpenAI API requests. However, this may also use more prompt tokens and decrease the overall context available to the AI. + ## ๐Ÿ’€ Continuous Mode โš ๏ธ Run the AI **without** user authorisation, 100% automated. From 2e0b44ae05fce7795f662a81c765eeeeae32a768 Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Wed, 12 Apr 2023 22:46:49 +0200 Subject: [PATCH 18/64] fix chunk creation the last chunk wasn't correctly created, this commit fix that issue. --- scripts/file_operations.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/scripts/file_operations.py b/scripts/file_operations.py index e664fcc9..f2a2b072 100644 --- a/scripts/file_operations.py +++ b/scripts/file_operations.py @@ -38,11 +38,12 @@ def split_file(content, max_length=4000, overlap=0): chunk = content[start:end] yield chunk start += max_length - overlap - if start + max_length - overlap >= content_length: - break - if end + overlap > content_length: + if start + max_length > content_length: start = content_length - max_length - + end = content_length + chunk = content[start:end] + yield chunk + break def read_file(filename): """Read a file and return the contents""" From 4e914e5ec1a4f7d39cba04cc2ebc0ba7f0055423 Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Wed, 12 Apr 2023 22:51:52 +0200 Subject: [PATCH 19/64] Revert "Update .gitignore" This reverts commit 7975c184a55a477e884e1920ed87dc67ca4b4261. --- .gitignore | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index fc496609..aa0dceaa 100644 --- a/.gitignore +++ b/.gitignore @@ -18,5 +18,4 @@ log.txt # Coverage reports .coverage coverage.xml -htmlcov/ -log-ingestion.txt +htmlcov/ \ No newline at end of file From 2f1181f9a12bbbbf55b8f2224ecc645d22c5d90d Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Wed, 12 Apr 2023 22:52:37 +0200 Subject: [PATCH 20/64] Update .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index cfa3b08b..403417eb 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,7 @@ ai_settings.yaml .idea/* auto-gpt.json log.txt +log-ingestion.txt # Coverage reports .coverage From 36d455c20e52aa1e09766a01c880f7914c5c24b7 Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Wed, 12 Apr 2023 23:31:26 +0200 Subject: [PATCH 21/64] split_file() rework rework the split_file function to make it simple and only have one yield while providing an overlap at the start and end of each chunk --- scripts/file_operations.py | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/scripts/file_operations.py b/scripts/file_operations.py index db4702c5..c12774b9 100644 --- a/scripts/file_operations.py +++ b/scripts/file_operations.py @@ -35,15 +35,12 @@ def split_file(content, max_length=4000, overlap=0): while start < content_length: end = start + max_length - chunk = content[start:end] + if end + overlap < content_length: + chunk = content[start:end+overlap] + else: + chunk = content[start:content_length] yield chunk start += max_length - overlap - if start + max_length > content_length: - start = content_length - max_length - end = content_length - chunk = content[start:end] - yield chunk - break def read_file(filename): """Read a file and return the contents""" From 1c64a9d24508333d92cfdb26d38a90c4bd543dc6 Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Wed, 12 Apr 2023 23:33:14 +0200 Subject: [PATCH 22/64] Update .env.template --- .env.template | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.env.template b/.env.template index 0aec7b10..f1e66ea5 100644 --- a/.env.template +++ b/.env.template @@ -19,4 +19,4 @@ HUGGINGFACE_API_TOKEN= USE_MAC_OS_TTS=False BROWSE_CHUNK_MAX_LENGTH=4000 BROWSE_SUMMARY_MAX_TOKEN=300 -MEMORY_BACKEND=local \ No newline at end of file +MEMORY_BACKEND=local From 428caa9bef83e93a6f97a1341a03a0f41b71dec0 Mon Sep 17 00:00:00 2001 From: Eesa Hamza Date: Thu, 13 Apr 2023 12:57:57 +0300 Subject: [PATCH 23/64] Added flags, and implemented skip-reprompt --- scripts/config.py | 1 + scripts/main.py | 14 ++++++++++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/scripts/config.py b/scripts/config.py index ebf1b08b..fd370a72 100644 --- a/scripts/config.py +++ b/scripts/config.py @@ -37,6 +37,7 @@ class Config(metaclass=Singleton): self.debug_mode = False self.continuous_mode = False self.speak_mode = False + self.skip_reprompt = False self.fast_llm_model = os.getenv("FAST_LLM_MODEL", "gpt-3.5-turbo") self.smart_llm_model = os.getenv("SMART_LLM_MODEL", "gpt-4") diff --git a/scripts/main.py b/scripts/main.py index 81f560b2..f81b09a7 100644 --- a/scripts/main.py +++ b/scripts/main.py @@ -183,7 +183,11 @@ def load_variables(config_file="config.yaml"): def construct_prompt(): """Construct the prompt for the AI to respond to""" config = AIConfig.load() - if config.ai_name: + if cfg.skip_reprompt and config.ai_name: + logger.typewriter_log("Name :", Fore.GREEN, config.ai_name) + logger.typewriter_log("Role :", Fore.GREEN, config.ai_role) + logger.typewriter_log("Goals:", Fore.GREEN, config.ai_goals) + elif config.ai_name: logger.typewriter_log( f"Welcome back! ", Fore.GREEN, @@ -270,12 +274,14 @@ def parse_arguments(): cfg.set_speak_mode(False) parser = argparse.ArgumentParser(description='Process arguments.') - parser.add_argument('--continuous', action='store_true', help='Enable Continuous Mode') + parser.add_argument('--continuous', '-c', action='store_true', help='Enable Continuous Mode') parser.add_argument('--speak', action='store_true', help='Enable Speak Mode') parser.add_argument('--debug', action='store_true', help='Enable Debug Mode') parser.add_argument('--gpt3only', action='store_true', help='Enable GPT3.5 Only Mode') parser.add_argument('--gpt4only', action='store_true', help='Enable GPT4 Only Mode') parser.add_argument('--use-memory', '-m', dest="memory_type", help='Defines which Memory backend to use') + parser.add_argument('--skip-reprompt', '-y', dest='skip_reprompt', action='store_true', help='Skips the re-prompting messages at the beginning of the script') + parser.add_argument('--ai-settings', '-C', dest='ai_settings_file', help="Specifies which ai_settings.yaml file to use, will also automatically skip the re-prompt.") args = parser.parse_args() if args.debug: @@ -315,6 +321,10 @@ def parse_arguments(): else: cfg.memory_backend = chosen + if args.skip_reprompt: + logger.typewriter_log("Skip Re-prompt: ", Fore.GREEN, "ENABLED") + cfg.skip_reprompt = True + # TODO: fill in llm values here check_openai_api_key() From 0f6fba7d65302591f2c77a41483953df43d12d2b Mon Sep 17 00:00:00 2001 From: Eesa Hamza Date: Thu, 13 Apr 2023 14:02:42 +0300 Subject: [PATCH 24/64] Implemented the '--ai-settings' flag --- scripts/config.py | 1 + scripts/main.py | 16 +++++++++++++++- scripts/utils.py | 14 ++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/scripts/config.py b/scripts/config.py index fd370a72..ad968fb2 100644 --- a/scripts/config.py +++ b/scripts/config.py @@ -39,6 +39,7 @@ class Config(metaclass=Singleton): self.speak_mode = False self.skip_reprompt = False + self.ai_settings_file = os.getenv("AI_SETTINGS_FILE", "ai_settings.yaml") self.fast_llm_model = os.getenv("FAST_LLM_MODEL", "gpt-3.5-turbo") self.smart_llm_model = os.getenv("SMART_LLM_MODEL", "gpt-4") self.fast_token_limit = int(os.getenv("FAST_TOKEN_LIMIT", 4000)) diff --git a/scripts/main.py b/scripts/main.py index f81b09a7..07d2bbd2 100644 --- a/scripts/main.py +++ b/scripts/main.py @@ -182,7 +182,7 @@ def load_variables(config_file="config.yaml"): def construct_prompt(): """Construct the prompt for the AI to respond to""" - config = AIConfig.load() + config = AIConfig.load(cfg.ai_settings_file) if cfg.skip_reprompt and config.ai_name: logger.typewriter_log("Name :", Fore.GREEN, config.ai_name) logger.typewriter_log("Role :", Fore.GREEN, config.ai_role) @@ -324,7 +324,21 @@ def parse_arguments(): if args.skip_reprompt: logger.typewriter_log("Skip Re-prompt: ", Fore.GREEN, "ENABLED") cfg.skip_reprompt = True + + if args.ai_settings_file: + file = args.ai_settings_file + # Validate file + (validated, message) = utils.validate_yaml_file(file) + if not validated: + logger.typewriter_log("FAILED FILE VALIDATION", Fore.RED, message) + exit(1) + + logger.typewriter_log("Using AI Settings File:", Fore.GREEN, file) + cfg.ai_settings_file = file + cfg.skip_reprompt = True + + # TODO: fill in llm values here check_openai_api_key() diff --git a/scripts/utils.py b/scripts/utils.py index 5039796f..bca8d4a8 100644 --- a/scripts/utils.py +++ b/scripts/utils.py @@ -1,3 +1,6 @@ +import yaml +from colorama import Fore + def clean_input(prompt: str=''): try: return input(prompt) @@ -6,3 +9,14 @@ def clean_input(prompt: str=''): print("Quitting...") exit(0) + +def validate_yaml_file(file: str): + try: + with open(file) as file: + yaml.load(file, Loader=yaml.FullLoader) + except FileNotFoundError: + return (False, f"The file {Fore.CYAN}`{file}`{Fore.RESET} wasn't found") + except yaml.YAMLError as e: + return (False, f"There was an issue while trying to read with your AI Settings file: {e}") + + return (True, f"Successfully validated {Fore.CYAN}`{file}`{Fore.RESET}!") \ No newline at end of file From a10ffc1dbed88ce74f7ebb1dae0c90fb18bae9f6 Mon Sep 17 00:00:00 2001 From: Eesa Hamza Date: Thu, 13 Apr 2023 14:26:16 +0300 Subject: [PATCH 25/64] Fixed error logging when choosing non-supported memory backend with '--use-memory' --- scripts/main.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/main.py b/scripts/main.py index 07d2bbd2..59cb565e 100644 --- a/scripts/main.py +++ b/scripts/main.py @@ -316,8 +316,8 @@ def parse_arguments(): supported_memory = get_supported_memory_backends() chosen = args.memory_type if not chosen in supported_memory: - print_to_console("ONLY THE FOLLOWING MEMORY BACKENDS ARE SUPPORTED: ", Fore.RED, f'{supported_memory}') - print_to_console(f"Defaulting to: ", Fore.YELLOW, cfg.memory_backend) + logger.typewriter_log("ONLY THE FOLLOWING MEMORY BACKENDS ARE SUPPORTED: ", Fore.RED, f'{supported_memory}') + logger.typewriter_log(f"Defaulting to: ", Fore.YELLOW, cfg.memory_backend) else: cfg.memory_backend = chosen From ff094c7ecc58fad572dccbc8a376a75045d91733 Mon Sep 17 00:00:00 2001 From: Eesa Hamza Date: Thu, 13 Apr 2023 15:09:24 +0300 Subject: [PATCH 26/64] Resolve Linter Issues --- scripts/main.py | 5 ++--- scripts/utils.py | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/scripts/main.py b/scripts/main.py index 59cb565e..0674db47 100644 --- a/scripts/main.py +++ b/scripts/main.py @@ -327,19 +327,18 @@ def parse_arguments(): if args.ai_settings_file: file = args.ai_settings_file - + # Validate file (validated, message) = utils.validate_yaml_file(file) if not validated: logger.typewriter_log("FAILED FILE VALIDATION", Fore.RED, message) exit(1) - + logger.typewriter_log("Using AI Settings File:", Fore.GREEN, file) cfg.ai_settings_file = file cfg.skip_reprompt = True - # TODO: fill in llm values here check_openai_api_key() parse_arguments() diff --git a/scripts/utils.py b/scripts/utils.py index bca8d4a8..2b51c1fc 100644 --- a/scripts/utils.py +++ b/scripts/utils.py @@ -18,5 +18,5 @@ def validate_yaml_file(file: str): return (False, f"The file {Fore.CYAN}`{file}`{Fore.RESET} wasn't found") except yaml.YAMLError as e: return (False, f"There was an issue while trying to read with your AI Settings file: {e}") - - return (True, f"Successfully validated {Fore.CYAN}`{file}`{Fore.RESET}!") \ No newline at end of file + + return (True, f"Successfully validated {Fore.CYAN}`{file}`{Fore.RESET}!") From 41f17f89043b19e7a5990894996c6dc407d734c0 Mon Sep 17 00:00:00 2001 From: Peter Edwards Date: Thu, 13 Apr 2023 16:02:15 +0200 Subject: [PATCH 27/64] Small README.md clarity update and usage fixup --- README.md | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 0d12ae23..90706cbf 100644 --- a/README.md +++ b/README.md @@ -59,10 +59,11 @@ Your support is greatly appreciated - [Python 3.8 or later](https://www.tutorialspoint.com/how-to-install-python-in-windows) - [OpenAI API key](https://platform.openai.com/account/api-keys) -- [PINECONE API key](https://www.pinecone.io/) + Optional: +- [PINECONE API key](https://www.pinecone.io/) (If you want Pinecone backed memory) - ElevenLabs Key (If you want the AI to speak) ## ๐Ÿ’พ Installation @@ -114,8 +115,8 @@ pip install -r requirements.txt python scripts/main.py ``` -2. After each of AUTO-GPT's actions, type "NEXT COMMAND" to authorise them to continue. -3. To exit the program, type "exit" and press Enter. +2. After each of action, enter 'y' to authorise command, 'y -N' to run N continuous commands, 'n' to exit program, or enter additional feedback for the AI. + ### Logs @@ -217,7 +218,10 @@ Pinecone enables the storage of vast amounts of vector-based memory, allowing fo ### Setting up environment variables -Simply set them in the `.env` file. +In the `.env` file set: +- `PINECONE_API_KEY` +- `PINECONE_ENV` (something like: us-east4-gcp) +- `MEMORY_BACKEND=pinecone` Alternatively, you can set them from the command line (advanced): @@ -226,7 +230,7 @@ For Windows Users: ``` setx PINECONE_API_KEY "YOUR_PINECONE_API_KEY" setx PINECONE_ENV "Your pinecone region" # something like: us-east4-gcp - +setx MEMORY_BACKEND "pinecone" ``` For macOS and Linux users: @@ -234,7 +238,7 @@ For macOS and Linux users: ``` export PINECONE_API_KEY="YOUR_PINECONE_API_KEY" export PINECONE_ENV="Your pinecone region" # something like: us-east4-gcp - +export MEMORY_BACKEND="pinecone" ``` From 47b72df262b894752b7fd0324f42f71ffc70e38c Mon Sep 17 00:00:00 2001 From: Eesa Hamza Date: Fri, 14 Apr 2023 01:20:43 +0300 Subject: [PATCH 28/64] Added 'AI_SETTINGS_FILE' to .env --- .env.template | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.env.template b/.env.template index 474b2727..c5cb54fd 100644 --- a/.env.template +++ b/.env.template @@ -3,6 +3,8 @@ ################################################################################ # EXECUTE_LOCAL_COMMANDS - Allow local command execution (Example: False) EXECUTE_LOCAL_COMMANDS=False +# AI_SETTINGS_FILE - Specifies which AI Settings file to use (defaults to ai_settings.yaml) +AI_SETTINGS_FILE=ai_settings.yaml ################################################################################ ### LLM PROVIDER From 05f6e9673f285ac40cf982a544dfa14750cf6af1 Mon Sep 17 00:00:00 2001 From: Eesa Hamza Date: Fri, 14 Apr 2023 01:23:23 +0300 Subject: [PATCH 29/64] Resolve Linter Issues --- scripts/utils.py | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/utils.py b/scripts/utils.py index 2b51c1fc..7521df29 100644 --- a/scripts/utils.py +++ b/scripts/utils.py @@ -1,6 +1,7 @@ import yaml from colorama import Fore + def clean_input(prompt: str=''): try: return input(prompt) From 8472bbd4556999cdd62e4930ae3723f18b746ef4 Mon Sep 17 00:00:00 2001 From: Eesa Hamza Date: Fri, 14 Apr 2023 01:34:30 +0300 Subject: [PATCH 30/64] Added 'Command Line Arguments' section to README --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index d1121976..8d402e7d 100644 --- a/README.md +++ b/README.md @@ -134,6 +134,14 @@ To output debug logs: ``` python scripts/main.py --debug ``` +### Command Line Arguments +Here are some common arguments you can use when running Auto-GPT: +> Replace anything in angled brackets (<>) to a value you want to specify +* `python scripts/main.py --help` to see a list of all available command line arguments +* `python scripts/main.py --ai-settings ` to run Auto-GPT with a different AI Settings file. +* `python scripts/main.py --use-memory ` to specify one of 3 memory backends: `local`, `redis` or `pinecone` + +> **NOTE**: There are shorthands for some of these flags, for example `-m` for `--use-memory`. Use `python scripts/main.py --help` for more information ## ๐Ÿ—ฃ๏ธ Speech Mode From 25509f9d2541a6c92949984da5548b11903fc98b Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Fri, 14 Apr 2023 00:48:07 +0200 Subject: [PATCH 31/64] Update config.py 8192 is the current default --- scripts/config.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/config.py b/scripts/config.py index 0150ca42..a856265a 100644 --- a/scripts/config.py +++ b/scripts/config.py @@ -43,7 +43,7 @@ class Config(metaclass=Singleton): self.smart_llm_model = os.getenv("SMART_LLM_MODEL", "gpt-4") self.fast_token_limit = int(os.getenv("FAST_TOKEN_LIMIT", 4000)) self.smart_token_limit = int(os.getenv("SMART_TOKEN_LIMIT", 8000)) - self.browse_chunk_max_length = int(os.getenv("BROWSE_CHUNK_MAX_LENGTH", 8000)) + self.browse_chunk_max_length = int(os.getenv("BROWSE_CHUNK_MAX_LENGTH", 8192)) self.browse_summary_max_token = int(os.getenv("BROWSE_SUMMARY_MAX_TOKEN", 300)) self.openai_api_key = os.getenv("OPENAI_API_KEY") From 6702a04f767702d1e57ddcec81f2481def19f8a7 Mon Sep 17 00:00:00 2001 From: Eesa Hamza Date: Fri, 14 Apr 2023 01:50:13 +0300 Subject: [PATCH 32/64] Add 'no_memory' support for memory flag --- scripts/memory/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/memory/__init__.py b/scripts/memory/__init__.py index a0afc874..9b53d8d2 100644 --- a/scripts/memory/__init__.py +++ b/scripts/memory/__init__.py @@ -3,7 +3,7 @@ from memory.no_memory import NoMemory # List of supported memory backends # Add a backend to this list if the import attempt is successful -supported_memory = ['local'] +supported_memory = ['local', 'no_memory'] try: from memory.redismem import RedisMemory From 4f923ece60baee2c086c29610a05c4f130e43aa9 Mon Sep 17 00:00:00 2001 From: Eesa Hamza Date: Fri, 14 Apr 2023 01:56:45 +0300 Subject: [PATCH 33/64] Added double_check logging to AI Settings validator, and updated README for 'no_memory' --- README.md | 4 ++-- scripts/main.py | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8d402e7d..b55a80c5 100644 --- a/README.md +++ b/README.md @@ -137,9 +137,9 @@ python scripts/main.py --debug ### Command Line Arguments Here are some common arguments you can use when running Auto-GPT: > Replace anything in angled brackets (<>) to a value you want to specify -* `python scripts/main.py --help` to see a list of all available command line arguments +* `python scripts/main.py --help` to see a list of all available command line arguments. * `python scripts/main.py --ai-settings ` to run Auto-GPT with a different AI Settings file. -* `python scripts/main.py --use-memory ` to specify one of 3 memory backends: `local`, `redis` or `pinecone` +* `python scripts/main.py --use-memory ` to specify one of 3 memory backends: `local`, `redis`, `pinecone` or 'no_memory'. > **NOTE**: There are shorthands for some of these flags, for example `-m` for `--use-memory`. Use `python scripts/main.py --help` for more information diff --git a/scripts/main.py b/scripts/main.py index 400eb1f6..78ffe243 100644 --- a/scripts/main.py +++ b/scripts/main.py @@ -348,6 +348,7 @@ def parse_arguments(): (validated, message) = utils.validate_yaml_file(file) if not validated: logger.typewriter_log("FAILED FILE VALIDATION", Fore.RED, message) + logger.double_check() exit(1) logger.typewriter_log("Using AI Settings File:", Fore.GREEN, file) From 2fd96b68bdc9e7ab48b34eeff8d96e32b9eafdcf Mon Sep 17 00:00:00 2001 From: meta-fx Date: Fri, 14 Apr 2023 01:28:47 -0500 Subject: [PATCH 34/64] Added new line and elevenlabs elements back to the env --- .env.template | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/.env.template b/.env.template index aa7b04e9..e22ce4f5 100644 --- a/.env.template +++ b/.env.template @@ -104,4 +104,12 @@ USE_MAC_OS_TTS=False ### STREAMELEMENTS # USE_BRIAN_TTS - Use Brian TTS or not (Default: False) -USE_BRIAN_TTS=False \ No newline at end of file +USE_BRIAN_TTS=False + +### ELEVENLABS +# ELEVENLABS_API_KEY - Eleven Labs API key (Example: my-elevenlabs-api-key) +# ELEVENLABS_VOICE_1_ID - Eleven Labs voice 1 ID (Example: my-voice-id-1) +# ELEVENLABS_VOICE_2_ID - Eleven Labs voice 2 ID (Example: my-voice-id-2) +ELEVENLABS_API_KEY=your-elevenlabs-api-key +ELEVENLABS_VOICE_1_ID=your-voice-id-1 +ELEVENLABS_VOICE_2_ID=your-voice-id-2 From 1612069594402540da4116f9f599b47091b8f041 Mon Sep 17 00:00:00 2001 From: meta-fx Date: Fri, 14 Apr 2023 02:18:17 -0500 Subject: [PATCH 35/64] Fixed E302 expected 2 blank lines, found 1 --- scripts/speak.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/speak.py b/scripts/speak.py index d71b5bca..3afa591d 100644 --- a/scripts/speak.py +++ b/scripts/speak.py @@ -52,6 +52,7 @@ def eleven_labs_speech(text, voice_index=0): print("Response content:", response.content) return False + def brian_speech(text): """Speak text using Brian with the streamelements API""" tts_url = f"https://api.streamelements.com/kappa/v2/speech?voice=Brian&text={text}" @@ -69,6 +70,7 @@ def brian_speech(text): print("Response content:", response.content) return False + def gtts_speech(text): tts = gtts.gTTS(text) with mutex_lock: From e147788c72535779ed094a101c4739aa1e8bdb8c Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Fri, 14 Apr 2023 10:33:34 +0200 Subject: [PATCH 36/64] Update .env.template BROWSE_CHUNK_MAX_LENGTH default value --- .env.template | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.env.template b/.env.template index 7ff03cab..733597d9 100644 --- a/.env.template +++ b/.env.template @@ -4,7 +4,7 @@ # EXECUTE_LOCAL_COMMANDS - Allow local command execution (Example: False) EXECUTE_LOCAL_COMMANDS=False # BROWSE_CHUNK_MAX_LENGTH - When browsing website, define the length of chunk stored in memory -BROWSE_CHUNK_MAX_LENGTH=4000 +BROWSE_CHUNK_MAX_LENGTH=8192 # BROWSE_SUMMARY_MAX_TOKEN - Define the maximum length of the summary generated by GPT agent when browsing website BROWSE_SUMMARY_MAX_TOKEN=300 # USER_AGENT - Define the user-agent used by the requests library to browse website (string) From 6403bf112790b34fa122bdd519703e4b110f6875 Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Fri, 14 Apr 2023 10:35:30 +0200 Subject: [PATCH 37/64] Update data_ingestion.py fixed linting --- scripts/data_ingestion.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/data_ingestion.py b/scripts/data_ingestion.py index 32811166..9addc34b 100644 --- a/scripts/data_ingestion.py +++ b/scripts/data_ingestion.py @@ -6,6 +6,7 @@ from file_operations import ingest_file, search_files cfg = Config() + def configure_logging(): logging.basicConfig(filename='log-ingestion.txt', filemode='a', @@ -43,7 +44,6 @@ def main(): args = parser.parse_args() - # Initialize memory memory = get_memory(cfg, init=args.init) print('Using memory of type: ' + memory.__class__.__name__) From c0462dbe7768d41ac205644987ad0fa9f14a5afc Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Fri, 14 Apr 2023 10:35:52 +0200 Subject: [PATCH 38/64] Update file_operations.py fixed linting --- scripts/file_operations.py | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/file_operations.py b/scripts/file_operations.py index ed5aa4ec..1a072561 100644 --- a/scripts/file_operations.py +++ b/scripts/file_operations.py @@ -42,6 +42,7 @@ def split_file(content, max_length=4000, overlap=0): yield chunk start += max_length - overlap + def read_file(filename): """Read a file and return the contents""" try: From 475edd3b40c8769b22519083af2106bcbd08e559 Mon Sep 17 00:00:00 2001 From: Mike Kelly Date: Fri, 14 Apr 2023 12:32:33 +0100 Subject: [PATCH 39/64] make the path reference in logger more robust --- scripts/logger.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/logger.py b/scripts/logger.py index 91bdb6f6..4c7e588f 100644 --- a/scripts/logger.py +++ b/scripts/logger.py @@ -24,7 +24,8 @@ For console handler: simulates typing class Logger(metaclass=Singleton): def __init__(self): # create log directory if it doesn't exist - log_dir = os.path.join('..', 'logs') + this_files_dir_path = os.path.dirname(__file__) + log_dir = os.path.join(this_files_dir_path, '../logs') if not os.path.exists(log_dir): os.makedirs(log_dir) From 9e27e0165d15d441e58e5771e22957ae4fbd0063 Mon Sep 17 00:00:00 2001 From: Mike Kelly Date: Fri, 14 Apr 2023 12:36:18 +0100 Subject: [PATCH 40/64] gitignore the logs file --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index cf6e75df..0a98328c 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,7 @@ last_run_ai_settings.yaml .idea/* auto-gpt.json log.txt +logs # Coverage reports .coverage From b18530a9854f7b3e0cd5fb8333221bb0000cc4cb Mon Sep 17 00:00:00 2001 From: sagarishere <5121817+sagarishere@users.noreply.github.com> Date: Fri, 14 Apr 2023 16:31:45 +0300 Subject: [PATCH 41/64] update to modern python format syntax update to modern python format syntax no logic change --- scripts/spinner.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/spinner.py b/scripts/spinner.py index df1f4ddf..d2321529 100644 --- a/scripts/spinner.py +++ b/scripts/spinner.py @@ -17,10 +17,10 @@ class Spinner: def spin(self): """Spin the spinner""" while self.running: - sys.stdout.write(next(self.spinner) + " " + self.message + "\r") + sys.stdout.write(f"{next(self.spinner)} {self.message}\r") sys.stdout.flush() time.sleep(self.delay) - sys.stdout.write('\r' + ' ' * (len(self.message) + 2) + '\r') + sys.stdout.write(f"\r{' ' * (len(self.message) + 2)}\r") def __enter__(self): """Start the spinner""" @@ -32,5 +32,5 @@ class Spinner: """Stop the spinner""" self.running = False self.spinner_thread.join() - sys.stdout.write('\r' + ' ' * (len(self.message) + 2) + '\r') + sys.stdout.write(f"\r{' ' * (len(self.message) + 2)}\r") sys.stdout.flush() From a67818648ed722e4e50133e01c0c2f189dfec05c Mon Sep 17 00:00:00 2001 From: Maiko Bossuyt Date: Fri, 14 Apr 2023 18:10:42 +0200 Subject: [PATCH 42/64] Update browse.py linting --- scripts/browse.py | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/browse.py b/scripts/browse.py index a4a41744..ef22de03 100644 --- a/scripts/browse.py +++ b/scripts/browse.py @@ -137,6 +137,7 @@ def create_message(chunk, question): "content": f"\"\"\"{chunk}\"\"\" Using the above text, please answer the following question: \"{question}\" -- if the question cannot be answered using the text, please summarize the text." } + def summarize_text(url, text, question): """Summarize text using the LLM model""" if not text: From 2ba0cb24dc84fae271d6466f00cc082cc8c44a4e Mon Sep 17 00:00:00 2001 From: Mike Kelly Date: Fri, 14 Apr 2023 16:39:29 +0100 Subject: [PATCH 43/64] execute python via shell if already running in a container --- scripts/execute_code.py | 93 +++++++++++++++++++++++------------------ 1 file changed, 52 insertions(+), 41 deletions(-) diff --git a/scripts/execute_code.py b/scripts/execute_code.py index dbd62c22..45263d02 100644 --- a/scripts/execute_code.py +++ b/scripts/execute_code.py @@ -19,53 +19,60 @@ def execute_python_file(file): if not os.path.isfile(file_path): return f"Error: File '{file}' does not exist." - try: - client = docker.from_env() - - image_name = 'python:3.10' + if we_are_running_in_a_docker_container(): + result = subprocess.run(f'python {file_path}', capture_output=True, encoding="utf8", shell=True) + if result.returncode == 0: + return result.stdout + else: + return f"Error: {result.stderr}" + else: try: - client.images.get(image_name) - print(f"Image '{image_name}' found locally") - except docker.errors.ImageNotFound: - print(f"Image '{image_name}' not found locally, pulling from Docker Hub") - # Use the low-level API to stream the pull response - low_level_client = docker.APIClient() - for line in low_level_client.pull(image_name, stream=True, decode=True): - # Print the status and progress, if available - status = line.get('status') - progress = line.get('progress') - if status and progress: - print(f"{status}: {progress}") - elif status: - print(status) + client = docker.from_env() - # You can replace 'python:3.8' with the desired Python image/version - # You can find available Python images on Docker Hub: - # https://hub.docker.com/_/python - container = client.containers.run( - image_name, - f'python {file}', - volumes={ - os.path.abspath(WORKSPACE_FOLDER): { - 'bind': '/workspace', - 'mode': 'ro'}}, - working_dir='/workspace', - stderr=True, - stdout=True, - detach=True, - ) + image_name = 'python:3.10' + try: + client.images.get(image_name) + print(f"Image '{image_name}' found locally") + except docker.errors.ImageNotFound: + print(f"Image '{image_name}' not found locally, pulling from Docker Hub") + # Use the low-level API to stream the pull response + low_level_client = docker.APIClient() + for line in low_level_client.pull(image_name, stream=True, decode=True): + # Print the status and progress, if available + status = line.get('status') + progress = line.get('progress') + if status and progress: + print(f"{status}: {progress}") + elif status: + print(status) - output = container.wait() - logs = container.logs().decode('utf-8') - container.remove() + # You can replace 'python:3.8' with the desired Python image/version + # You can find available Python images on Docker Hub: + # https://hub.docker.com/_/python + container = client.containers.run( + image_name, + f'python {file}', + volumes={ + os.path.abspath(WORKSPACE_FOLDER): { + 'bind': '/workspace', + 'mode': 'ro'}}, + working_dir='/workspace', + stderr=True, + stdout=True, + detach=True, + ) - # print(f"Execution complete. Output: {output}") - # print(f"Logs: {logs}") + output = container.wait() + logs = container.logs().decode('utf-8') + container.remove() - return logs + # print(f"Execution complete. Output: {output}") + # print(f"Logs: {logs}") - except Exception as e: - return f"Error: {str(e)}" + return logs + + except Exception as e: + return f"Error: {str(e)}" def execute_shell(command_line): @@ -86,3 +93,7 @@ def execute_shell(command_line): os.chdir(current_dir) return output + + +def we_are_running_in_a_docker_container(): + os.path.exists('/.dockerenv') From d64f866bfab62e5f167d20994f0c9a1ade534e72 Mon Sep 17 00:00:00 2001 From: Dino Hensen Date: Fri, 14 Apr 2023 18:28:58 +0200 Subject: [PATCH 44/64] Convert to python module named autogpt. Also fixed the Dockerfile. Converting to module makes development easier. Fixes coverage script in CI and test imports. --- .github/workflows/ci.yml | 4 +- .gitignore | 8 +- Dockerfile | 4 +- README.md | 32 ++- {scripts => autogpt}/__init__.py | 0 scripts/main.py => autogpt/__main__.py | 18 +- {scripts => autogpt}/agent_manager.py | 2 +- {scripts => autogpt}/ai_config.py | 0 {scripts => autogpt}/ai_functions.py | 4 +- {scripts => autogpt}/browse.py | 6 +- {scripts => autogpt}/call_ai_function.py | 5 +- {scripts => autogpt}/chat.py | 8 +- {scripts => autogpt}/commands.py | 20 +- {scripts => autogpt}/config.py | 0 {scripts => autogpt}/data_ingestion.py | 6 +- {scripts => autogpt}/execute_code.py | 0 {scripts => autogpt}/file_operations.py | 0 {scripts => autogpt}/image_gen.py | 2 +- {scripts => autogpt}/json_parser.py | 8 +- {scripts => autogpt}/json_utils.py | 2 +- {scripts => autogpt}/llm_utils.py | 2 +- {scripts => autogpt}/logger.py | 6 +- {scripts => autogpt}/memory/__init__.py | 4 +- {scripts => autogpt}/memory/base.py | 2 +- {scripts => autogpt}/memory/local.py | 2 +- {scripts => autogpt}/memory/no_memory.py | 0 {scripts => autogpt}/memory/pinecone.py | 1 + {scripts => autogpt}/memory/redismem.py | 4 +- {scripts => autogpt}/prompt.py | 0 {scripts => autogpt}/promptgenerator.py | 0 {scripts => autogpt}/speak.py | 2 +- {scripts => autogpt}/spinner.py | 0 {scripts => autogpt}/token_counter.py | 0 {scripts => autogpt}/utils.py | 0 docker-compose.yml | 2 +- main.py | 2 +- scripts/agent.py | 245 +++++++++++++++++++++++ tests.py | 4 +- tests/integration/memory_tests.py | 9 +- tests/local_cache_test.py | 5 +- tests/promptgenerator_tests.py | 4 +- tests/test_config.py | 2 +- tests/test_json_parser.py | 2 +- tests/unit/json_tests.py | 13 +- tests/unit/test_browse_scrape_text.py | 2 +- 45 files changed, 352 insertions(+), 90 deletions(-) rename {scripts => autogpt}/__init__.py (100%) rename scripts/main.py => autogpt/__main__.py (98%) rename {scripts => autogpt}/agent_manager.py (97%) rename {scripts => autogpt}/ai_config.py (100%) rename {scripts => autogpt}/ai_functions.py (96%) rename {scripts => autogpt}/browse.py (97%) rename {scripts => autogpt}/call_ai_function.py (90%) rename {scripts => autogpt}/chat.py (97%) rename {scripts => autogpt}/commands.py (95%) rename {scripts => autogpt}/config.py (100%) rename {scripts => autogpt}/data_ingestion.py (95%) rename {scripts => autogpt}/execute_code.py (100%) rename {scripts => autogpt}/file_operations.py (100%) rename {scripts => autogpt}/image_gen.py (97%) rename {scripts => autogpt}/json_parser.py (95%) rename {scripts => autogpt}/json_utils.py (99%) rename {scripts => autogpt}/llm_utils.py (98%) rename {scripts => autogpt}/logger.py (98%) rename {scripts => autogpt}/memory/__init__.py (94%) rename {scripts => autogpt}/memory/base.py (93%) rename {scripts => autogpt}/memory/local.py (97%) rename {scripts => autogpt}/memory/no_memory.py (100%) rename {scripts => autogpt}/memory/pinecone.py (98%) rename {scripts => autogpt}/memory/redismem.py (97%) rename {scripts => autogpt}/prompt.py (100%) rename {scripts => autogpt}/promptgenerator.py (100%) rename {scripts => autogpt}/speak.py (99%) rename {scripts => autogpt}/spinner.py (100%) rename {scripts => autogpt}/token_counter.py (100%) rename {scripts => autogpt}/utils.py (100%) create mode 100644 scripts/agent.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0b90b55d..366aaf67 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,11 +32,11 @@ jobs: - name: Lint with flake8 continue-on-error: false - run: flake8 scripts/ tests/ --select E303,W293,W291,W292,E305,E231,E302 + run: flake8 autogpt/ tests/ --select E303,W293,W291,W292,E305,E231,E302 - name: Run unittest tests with coverage run: | - coverage run --source=scripts -m unittest discover tests + coverage run --source=autogpt -m unittest discover tests - name: Generate coverage report run: | diff --git a/.gitignore b/.gitignore index b0be8967..5a2ce371 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,7 @@ -scripts/keys.py -scripts/*json -scripts/node_modules/ -scripts/__pycache__/keys.cpython-310.pyc +autogpt/keys.py +autogpt/*json +autogpt/node_modules/ +autogpt/__pycache__/keys.cpython-310.pyc package-lock.json *.pyc auto_gpt_workspace/* diff --git a/Dockerfile b/Dockerfile index e776664e..3ae1ac12 100644 --- a/Dockerfile +++ b/Dockerfile @@ -17,7 +17,7 @@ COPY --chown=appuser:appuser requirements.txt . RUN pip install --no-cache-dir --user -r requirements.txt # Copy the application files -COPY --chown=appuser:appuser scripts/ . +COPY --chown=appuser:appuser autogpt/ . # Set the entrypoint -ENTRYPOINT ["python", "main.py"] \ No newline at end of file +ENTRYPOINT ["python", "-m", "autogpt"] diff --git a/README.md b/README.md index 27150fa2..fcf0cc3f 100644 --- a/README.md +++ b/README.md @@ -119,11 +119,11 @@ pip install -r requirements.txt ## ๐Ÿ”ง Usage -1. Run the `main.py` Python script in your terminal: +1. Run the `autogpt` Python module in your terminal: _(Type this into your CMD window)_ ``` -python scripts/main.py +python -m autogpt ``` 2. After each of action, enter 'y' to authorise command, 'y -N' to run N continuous commands, 'n' to exit program, or enter additional feedback for the AI. @@ -136,7 +136,21 @@ You will find activity and error logs in the folder `./output/logs` To output debug logs: ``` -python scripts/main.py --debug +python -m autogpt --debug +``` + +### Docker + +You can also build this into a docker image and run it: + +``` +docker build -t autogpt . +docker run -it --env-file=./.env -v $PWD/auto_gpt_workspace:/app/auto_gpt_workspace autogpt +``` + +You can pass extra arguments, for instance, running with `--gpt3only` and `--continuous` mode: +``` +docker run -it --env-file=./.env -v $PWD/auto_gpt_workspace:/app/auto_gpt_workspace autogpt --gpt3only --continuous ``` ### Command Line Arguments Here are some common arguments you can use when running Auto-GPT: @@ -152,7 +166,7 @@ Here are some common arguments you can use when running Auto-GPT: Use this to use TTS for Auto-GPT ``` -python scripts/main.py --speak +python -m autogpt --speak ``` ## ๐Ÿ” Google API Keys Configuration @@ -328,10 +342,10 @@ Continuous mode is not recommended. It is potentially dangerous and may cause your AI to run forever or carry out actions you would not usually authorise. Use at your own risk. -1. Run the `main.py` Python script in your terminal: +1. Run the `autogpt` python module in your terminal: ``` -python scripts/main.py --continuous +python -m autogpt --speak --continuous ``` @@ -342,7 +356,7 @@ python scripts/main.py --continuous If you don't have access to the GPT4 api, this mode will allow you to use Auto-GPT! ``` -python scripts/main.py --gpt3only +python -m autogpt --speak --gpt3only ``` It is recommended to use a virtual machine for tasks that require high security measures to prevent any potential harm to the main computer's system and data. @@ -415,8 +429,8 @@ This project uses [flake8](https://flake8.pycqa.org/en/latest/) for linting. We To run the linter, run the following command: ``` -flake8 scripts/ tests/ +flake8 autogpt/ tests/ # Or, if you want to run flake8 with the same configuration as the CI: -flake8 scripts/ tests/ --select E303,W293,W291,W292,E305,E231,E302 +flake8 autogpt/ tests/ --select E303,W293,W291,W292,E305,E231,E302 ``` diff --git a/scripts/__init__.py b/autogpt/__init__.py similarity index 100% rename from scripts/__init__.py rename to autogpt/__init__.py diff --git a/scripts/main.py b/autogpt/__main__.py similarity index 98% rename from scripts/main.py rename to autogpt/__main__.py index a12f9c7f..05cbed7a 100644 --- a/scripts/main.py +++ b/autogpt/__main__.py @@ -1,16 +1,16 @@ import json import random -import commands as cmd -import utils -from memory import get_memory, get_supported_memory_backends -import chat +from autogpt import commands as cmd +from autogpt import utils +from autogpt.memory import get_memory, get_supported_memory_backends +from autogpt import chat from colorama import Fore, Style -from spinner import Spinner +from autogpt.spinner import Spinner import time -import speak -from config import Config -from json_parser import fix_and_parse_json -from ai_config import AIConfig +from autogpt import speak +from autogpt.config import Config +from autogpt.json_parser import fix_and_parse_json +from autogpt.ai_config import AIConfig import traceback import yaml import argparse diff --git a/scripts/agent_manager.py b/autogpt/agent_manager.py similarity index 97% rename from scripts/agent_manager.py rename to autogpt/agent_manager.py index 191ab838..2722b4be 100644 --- a/scripts/agent_manager.py +++ b/autogpt/agent_manager.py @@ -1,4 +1,4 @@ -from llm_utils import create_chat_completion +from autogpt.llm_utils import create_chat_completion next_key = 0 agents = {} # key, (task, full_message_history, model) diff --git a/scripts/ai_config.py b/autogpt/ai_config.py similarity index 100% rename from scripts/ai_config.py rename to autogpt/ai_config.py diff --git a/scripts/ai_functions.py b/autogpt/ai_functions.py similarity index 96% rename from scripts/ai_functions.py rename to autogpt/ai_functions.py index f4ee79cd..b6e3df48 100644 --- a/scripts/ai_functions.py +++ b/autogpt/ai_functions.py @@ -1,7 +1,7 @@ from typing import List import json -from config import Config -from call_ai_function import call_ai_function +from autogpt.config import Config +from autogpt.call_ai_function import call_ai_function cfg = Config() diff --git a/scripts/browse.py b/autogpt/browse.py similarity index 97% rename from scripts/browse.py rename to autogpt/browse.py index ef22de03..32e74fea 100644 --- a/scripts/browse.py +++ b/autogpt/browse.py @@ -1,8 +1,8 @@ import requests from bs4 import BeautifulSoup -from memory import get_memory -from config import Config -from llm_utils import create_chat_completion +from autogpt.memory import get_memory +from autogpt.config import Config +from autogpt.llm_utils import create_chat_completion from urllib.parse import urlparse, urljoin cfg = Config() diff --git a/scripts/call_ai_function.py b/autogpt/call_ai_function.py similarity index 90% rename from scripts/call_ai_function.py rename to autogpt/call_ai_function.py index 940eacfe..5bcd76af 100644 --- a/scripts/call_ai_function.py +++ b/autogpt/call_ai_function.py @@ -1,8 +1,7 @@ -from config import Config - +from autogpt.config import Config cfg = Config() -from llm_utils import create_chat_completion +from autogpt.llm_utils import create_chat_completion # This is a magic function that can do anything with no-code. See diff --git a/scripts/chat.py b/autogpt/chat.py similarity index 97% rename from scripts/chat.py rename to autogpt/chat.py index 5392e438..6b901ffa 100644 --- a/scripts/chat.py +++ b/autogpt/chat.py @@ -1,10 +1,10 @@ import time import openai from dotenv import load_dotenv -from config import Config -import token_counter -from llm_utils import create_chat_completion -from logger import logger +from autogpt.config import Config +from autogpt import token_counter +from autogpt.llm_utils import create_chat_completion +from autogpt.logger import logger import logging cfg = Config() diff --git a/scripts/commands.py b/autogpt/commands.py similarity index 95% rename from scripts/commands.py rename to autogpt/commands.py index 43f5ae42..7bcdaa6c 100644 --- a/scripts/commands.py +++ b/autogpt/commands.py @@ -1,15 +1,15 @@ -import browse +from autogpt import browse import json -from memory import get_memory +from autogpt.memory import get_memory import datetime -import agent_manager as agents -import speak -from config import Config -import ai_functions as ai -from file_operations import read_file, write_to_file, append_to_file, delete_file, search_files -from execute_code import execute_python_file, execute_shell -from json_parser import fix_and_parse_json -from image_gen import generate_image +import autogpt.agent_manager as agents +from autogpt import speak +from autogpt.config import Config +import autogpt.ai_functions as ai +from autogpt.file_operations import read_file, write_to_file, append_to_file, delete_file, search_files +from autogpt.execute_code import execute_python_file, execute_shell +from autogpt.json_parser import fix_and_parse_json +from autogpt.image_gen import generate_image from duckduckgo_search import ddg from googleapiclient.discovery import build from googleapiclient.errors import HttpError diff --git a/scripts/config.py b/autogpt/config.py similarity index 100% rename from scripts/config.py rename to autogpt/config.py diff --git a/scripts/data_ingestion.py b/autogpt/data_ingestion.py similarity index 95% rename from scripts/data_ingestion.py rename to autogpt/data_ingestion.py index 9addc34b..f8753240 100644 --- a/scripts/data_ingestion.py +++ b/autogpt/data_ingestion.py @@ -1,8 +1,8 @@ import argparse import logging -from config import Config -from memory import get_memory -from file_operations import ingest_file, search_files +from autogpt.config import Config +from autogpt.memory import get_memory +from autogpt.file_operations import ingest_file, search_files cfg = Config() diff --git a/scripts/execute_code.py b/autogpt/execute_code.py similarity index 100% rename from scripts/execute_code.py rename to autogpt/execute_code.py diff --git a/scripts/file_operations.py b/autogpt/file_operations.py similarity index 100% rename from scripts/file_operations.py rename to autogpt/file_operations.py diff --git a/scripts/image_gen.py b/autogpt/image_gen.py similarity index 97% rename from scripts/image_gen.py rename to autogpt/image_gen.py index 6c27df3f..cc5112e3 100644 --- a/scripts/image_gen.py +++ b/autogpt/image_gen.py @@ -2,7 +2,7 @@ import requests import io import os.path from PIL import Image -from config import Config +from autogpt.config import Config import uuid import openai from base64 import b64decode diff --git a/scripts/json_parser.py b/autogpt/json_parser.py similarity index 95% rename from scripts/json_parser.py rename to autogpt/json_parser.py index 29995629..36555d5f 100644 --- a/scripts/json_parser.py +++ b/autogpt/json_parser.py @@ -1,9 +1,9 @@ import json from typing import Any, Dict, Union -from call_ai_function import call_ai_function -from config import Config -from json_utils import correct_json -from logger import logger +from autogpt.call_ai_function import call_ai_function +from autogpt.config import Config +from autogpt.json_utils import correct_json +from autogpt.logger import logger cfg = Config() diff --git a/scripts/json_utils.py b/autogpt/json_utils.py similarity index 99% rename from scripts/json_utils.py rename to autogpt/json_utils.py index 80aab192..8493f094 100644 --- a/scripts/json_utils.py +++ b/autogpt/json_utils.py @@ -1,6 +1,6 @@ import re import json -from config import Config +from autogpt.config import Config cfg = Config() diff --git a/scripts/llm_utils.py b/autogpt/llm_utils.py similarity index 98% rename from scripts/llm_utils.py rename to autogpt/llm_utils.py index 731acae2..24f47cc6 100644 --- a/scripts/llm_utils.py +++ b/autogpt/llm_utils.py @@ -1,7 +1,7 @@ import time import openai from colorama import Fore -from config import Config +from autogpt.config import Config cfg = Config() diff --git a/scripts/logger.py b/autogpt/logger.py similarity index 98% rename from scripts/logger.py rename to autogpt/logger.py index 4c7e588f..096d0891 100644 --- a/scripts/logger.py +++ b/autogpt/logger.py @@ -8,9 +8,9 @@ from colorama import Fore from colorama import Style -import speak -from config import Config -from config import Singleton +from autogpt import speak +from autogpt.config import Config +from autogpt.config import Singleton cfg = Config() diff --git a/scripts/memory/__init__.py b/autogpt/memory/__init__.py similarity index 94% rename from scripts/memory/__init__.py rename to autogpt/memory/__init__.py index 9b53d8d2..71f18efd 100644 --- a/scripts/memory/__init__.py +++ b/autogpt/memory/__init__.py @@ -1,5 +1,5 @@ -from memory.local import LocalCache -from memory.no_memory import NoMemory +from autogpt.memory.local import localcache +from autogpt.memory.no_memory import NoMemory # List of supported memory backends # Add a backend to this list if the import attempt is successful diff --git a/scripts/memory/base.py b/autogpt/memory/base.py similarity index 93% rename from scripts/memory/base.py rename to autogpt/memory/base.py index 4dbf6791..6b1f083c 100644 --- a/scripts/memory/base.py +++ b/autogpt/memory/base.py @@ -1,6 +1,6 @@ """Base class for memory providers.""" import abc -from config import AbstractSingleton, Config +from autogpt.config import AbstractSingleton, Config import openai cfg = Config() diff --git a/scripts/memory/local.py b/autogpt/memory/local.py similarity index 97% rename from scripts/memory/local.py rename to autogpt/memory/local.py index b0afacf6..23f632df 100644 --- a/scripts/memory/local.py +++ b/autogpt/memory/local.py @@ -3,7 +3,7 @@ import orjson from typing import Any, List, Optional import numpy as np import os -from memory.base import MemoryProviderSingleton, get_ada_embedding +from autogpt.memory.base import MemoryProviderSingleton, get_ada_embedding EMBED_DIM = 1536 diff --git a/scripts/memory/no_memory.py b/autogpt/memory/no_memory.py similarity index 100% rename from scripts/memory/no_memory.py rename to autogpt/memory/no_memory.py diff --git a/scripts/memory/pinecone.py b/autogpt/memory/pinecone.py similarity index 98% rename from scripts/memory/pinecone.py rename to autogpt/memory/pinecone.py index 20a905b3..1edfc2be 100644 --- a/scripts/memory/pinecone.py +++ b/autogpt/memory/pinecone.py @@ -1,3 +1,4 @@ +from autogpt.config import Config, Singleton import pinecone diff --git a/scripts/memory/redismem.py b/autogpt/memory/redismem.py similarity index 97% rename from scripts/memory/redismem.py rename to autogpt/memory/redismem.py index 49045dd8..febfd3a8 100644 --- a/scripts/memory/redismem.py +++ b/autogpt/memory/redismem.py @@ -6,8 +6,8 @@ from redis.commands.search.query import Query from redis.commands.search.indexDefinition import IndexDefinition, IndexType import numpy as np -from memory.base import MemoryProviderSingleton, get_ada_embedding -from logger import logger +from autogpt.memory.base import MemoryProviderSingleton, get_ada_embedding +from autogpt.logger import logger from colorama import Fore, Style diff --git a/scripts/prompt.py b/autogpt/prompt.py similarity index 100% rename from scripts/prompt.py rename to autogpt/prompt.py diff --git a/scripts/promptgenerator.py b/autogpt/promptgenerator.py similarity index 100% rename from scripts/promptgenerator.py rename to autogpt/promptgenerator.py diff --git a/scripts/speak.py b/autogpt/speak.py similarity index 99% rename from scripts/speak.py rename to autogpt/speak.py index 3afa591d..9fadaa0e 100644 --- a/scripts/speak.py +++ b/autogpt/speak.py @@ -1,7 +1,7 @@ import os from playsound import playsound import requests -from config import Config +from autogpt.config import Config cfg = Config() import gtts import threading diff --git a/scripts/spinner.py b/autogpt/spinner.py similarity index 100% rename from scripts/spinner.py rename to autogpt/spinner.py diff --git a/scripts/token_counter.py b/autogpt/token_counter.py similarity index 100% rename from scripts/token_counter.py rename to autogpt/token_counter.py diff --git a/scripts/utils.py b/autogpt/utils.py similarity index 100% rename from scripts/utils.py rename to autogpt/utils.py diff --git a/docker-compose.yml b/docker-compose.yml index af086f05..79f20bb5 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,7 +8,7 @@ services: - redis build: ./ volumes: - - "./scripts:/app" + - "./autogpt:/app" - ".env:/app/.env" profiles: ["exclude-from-up"] diff --git a/main.py b/main.py index 656c34ec..160addc3 100644 --- a/main.py +++ b/main.py @@ -1 +1 @@ -from scripts.main import main +from autogpt import main diff --git a/scripts/agent.py b/scripts/agent.py new file mode 100644 index 00000000..cbd6b3e7 --- /dev/null +++ b/scripts/agent.py @@ -0,0 +1,245 @@ +import commands as cmd +import json +import traceback +from tkinter.ttk import Style + +from colorama import Fore + +import chat +from config import Config +from logger import logger +import speak +from spinner import Spinner + + +class Agent: + """Agent class for interacting with Auto-GPT. + + Attributes: + ai_name: The name of the agent. + memory: The memory object to use. + full_message_history: The full message history. + next_action_count: The number of actions to execute. + prompt: The prompt to use. + user_input: The user input. + + """ + def __init__(self, + ai_name, + memory, + full_message_history, + next_action_count, + prompt, + user_input): + self.ai_name = ai_name + self.memory = memory + self.full_message_history = full_message_history + self.next_action_count = next_action_count + self.prompt = prompt + self.user_input = user_input + + def start_interaction_loop(self): + # Interaction Loop + cfg = Config() + loop_count = 0 + while True: + # Discontinue if continuous limit is reached + loop_count += 1 + if cfg.continuous_mode and cfg.continuous_limit > 0 and loop_count > cfg.continuous_limit: + logger.typewriter_log("Continuous Limit Reached: ", Fore.YELLOW, f"{cfg.continuous_limit}") + break + + # Send message to AI, get response + with Spinner("Thinking... "): + assistant_reply = chat.chat_with_ai( + self.prompt, + self.user_input, + self.full_message_history, + self.memory, + cfg.fast_token_limit) # TODO: This hardcodes the model to use GPT3.5. Make this an argument + + # Print Assistant thoughts + print_assistant_thoughts(assistant_reply) + + # Get command name and arguments + try: + command_name, arguments = cmd.get_command( + attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply)) + if cfg.speak_mode: + speak.say_text(f"I want to execute {command_name}") + except Exception as e: + logger.error("Error: \n", str(e)) + + if not cfg.continuous_mode and self.next_action_count == 0: + ### GET USER AUTHORIZATION TO EXECUTE COMMAND ### + # Get key press: Prompt the user to press enter to continue or escape + # to exit + self.user_input = "" + logger.typewriter_log( + "NEXT ACTION: ", + Fore.CYAN, + f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}") + print( + f"Enter 'y' to authorise command, 'y -N' to run N continuous commands, 'n' to exit program, or enter feedback for {self.ai_name}...", + flush=True) + while True: + console_input = utils.clean_input(Fore.MAGENTA + "Input:" + Style.RESET_ALL) + if console_input.lower().rstrip() == "y": + self.user_input = "GENERATE NEXT COMMAND JSON" + break + elif console_input.lower().startswith("y -"): + try: + self.next_action_count = abs(int(console_input.split(" ")[1])) + self.user_input = "GENERATE NEXT COMMAND JSON" + except ValueError: + print("Invalid input format. Please enter 'y -n' where n is the number of continuous tasks.") + continue + break + elif console_input.lower() == "n": + self.user_input = "EXIT" + break + else: + self.user_input = console_input + command_name = "human_feedback" + break + + if self.user_input == "GENERATE NEXT COMMAND JSON": + logger.typewriter_log( + "-=-=-=-=-=-=-= COMMAND AUTHORISED BY USER -=-=-=-=-=-=-=", + Fore.MAGENTA, + "") + elif self.user_input == "EXIT": + print("Exiting...", flush=True) + break + else: + # Print command + logger.typewriter_log( + "NEXT ACTION: ", + Fore.CYAN, + f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}") + + # Execute command + if command_name is not None and command_name.lower().startswith("error"): + result = f"Command {command_name} threw the following error: " + arguments + elif command_name == "human_feedback": + result = f"Human feedback: {self.user_input}" + else: + result = f"Command {command_name} returned: {cmd.execute_command(command_name, arguments)}" + if self.next_action_count > 0: + self.next_action_count -= 1 + + memory_to_add = f"Assistant Reply: {assistant_reply} " \ + f"\nResult: {result} " \ + f"\nHuman Feedback: {self.user_input} " + + self.memory.add(memory_to_add) + + # Check if there's a result from the command append it to the message + # history + if result is not None: + self.full_message_history.append(chat.create_chat_message("system", result)) + logger.typewriter_log("SYSTEM: ", Fore.YELLOW, result) + else: + self.full_message_history.append( + chat.create_chat_message( + "system", "Unable to execute command")) + logger.typewriter_log("SYSTEM: ", Fore.YELLOW, "Unable to execute command") + + +def attempt_to_fix_json_by_finding_outermost_brackets(json_string): + cfg = Config() + if cfg.speak_mode and cfg.debug_mode: + speak.say_text("I have received an invalid JSON response from the OpenAI API. Trying to fix it now.") + logger.typewriter_log("Attempting to fix JSON by finding outermost brackets\n") + + try: + # Use regex to search for JSON objects + import regex + json_pattern = regex.compile(r"\{(?:[^{}]|(?R))*\}") + json_match = json_pattern.search(json_string) + + if json_match: + # Extract the valid JSON object from the string + json_string = json_match.group(0) + logger.typewriter_log(title="Apparently json was fixed.", title_color=Fore.GREEN) + if cfg.speak_mode and cfg.debug_mode: + speak.say_text("Apparently json was fixed.") + else: + raise ValueError("No valid JSON object found") + + except (json.JSONDecodeError, ValueError) as e: + if cfg.speak_mode: + speak.say_text("Didn't work. I will have to ignore this response then.") + logger.error("Error: Invalid JSON, setting it to empty JSON now.\n") + json_string = {} + + return json_string + + +def print_assistant_thoughts(assistant_reply): + """Prints the assistant's thoughts to the console""" + global ai_name + global cfg + cfg = Config() + try: + try: + # Parse and print Assistant response + assistant_reply_json = fix_and_parse_json(assistant_reply) + except json.JSONDecodeError as e: + logger.error("Error: Invalid JSON in assistant thoughts\n", assistant_reply) + assistant_reply_json = attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply) + assistant_reply_json = fix_and_parse_json(assistant_reply_json) + + # Check if assistant_reply_json is a string and attempt to parse it into a JSON object + if isinstance(assistant_reply_json, str): + try: + assistant_reply_json = json.loads(assistant_reply_json) + except json.JSONDecodeError as e: + logger.error("Error: Invalid JSON\n", assistant_reply) + assistant_reply_json = attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply_json) + + assistant_thoughts_reasoning = None + assistant_thoughts_plan = None + assistant_thoughts_speak = None + assistant_thoughts_criticism = None + assistant_thoughts = assistant_reply_json.get("thoughts", {}) + assistant_thoughts_text = assistant_thoughts.get("text") + + if assistant_thoughts: + assistant_thoughts_reasoning = assistant_thoughts.get("reasoning") + assistant_thoughts_plan = assistant_thoughts.get("plan") + assistant_thoughts_criticism = assistant_thoughts.get("criticism") + assistant_thoughts_speak = assistant_thoughts.get("speak") + + logger.typewriter_log(f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, assistant_thoughts_text) + logger.typewriter_log("REASONING:", Fore.YELLOW, assistant_thoughts_reasoning) + + if assistant_thoughts_plan: + logger.typewriter_log("PLAN:", Fore.YELLOW, "") + # If it's a list, join it into a string + if isinstance(assistant_thoughts_plan, list): + assistant_thoughts_plan = "\n".join(assistant_thoughts_plan) + elif isinstance(assistant_thoughts_plan, dict): + assistant_thoughts_plan = str(assistant_thoughts_plan) + + # Split the input_string using the newline character and dashes + lines = assistant_thoughts_plan.split('\n') + for line in lines: + line = line.lstrip("- ") + logger.typewriter_log("- ", Fore.GREEN, line.strip()) + + logger.typewriter_log("CRITICISM:", Fore.YELLOW, assistant_thoughts_criticism) + # Speak the assistant's thoughts + if cfg.speak_mode and assistant_thoughts_speak: + speak.say_text(assistant_thoughts_speak) + + return assistant_reply_json + except json.decoder.JSONDecodeError as e: + logger.error("Error: Invalid JSON\n", assistant_reply) + if cfg.speak_mode: + speak.say_text("I have received an invalid JSON response from the OpenAI API. I cannot ignore this response.") + + # All other errors, return "Error: + error message" + except Exception as e: + call_stack = traceback.format_exc() + logger.error("Error: \n", call_stack) diff --git a/tests.py b/tests.py index 4dbfdd46..487e0038 100644 --- a/tests.py +++ b/tests.py @@ -1,8 +1,8 @@ import unittest if __name__ == "__main__": - # Load all tests from the 'scripts/tests' package - suite = unittest.defaultTestLoader.discover('scripts/tests') + # Load all tests from the 'autogpt/tests' package + suite = unittest.defaultTestLoader.discover('autogpt/tests') # Run the tests unittest.TextTestRunner().run(suite) diff --git a/tests/integration/memory_tests.py b/tests/integration/memory_tests.py index d0c30962..ea96c4c2 100644 --- a/tests/integration/memory_tests.py +++ b/tests/integration/memory_tests.py @@ -3,16 +3,15 @@ import random import string import sys from pathlib import Path -# Add the parent directory of the 'scripts' folder to the Python path -sys.path.append(str(Path(__file__).resolve().parent.parent.parent / 'scripts')) -from config import Config -from memory.local import LocalCache +from autogpt.config import Config +from autogpt.memory.local import LocalCache class TestLocalCache(unittest.TestCase): def random_string(self, length): - return ''.join(random.choice(string.ascii_letters) for _ in range(length)) + return ''.join( + random.choice(string.ascii_letters) for _ in range(length)) def setUp(self): cfg = cfg = Config() diff --git a/tests/local_cache_test.py b/tests/local_cache_test.py index 0352624e..601b11d8 100644 --- a/tests/local_cache_test.py +++ b/tests/local_cache_test.py @@ -1,8 +1,7 @@ import os import sys -# Probably a better way: -sys.path.append(os.path.abspath('../scripts')) -from memory.local import LocalCache + +from autogpt.memory.local import LocalCache def MockConfig(): diff --git a/tests/promptgenerator_tests.py b/tests/promptgenerator_tests.py index 181fdea6..aac70b5e 100644 --- a/tests/promptgenerator_tests.py +++ b/tests/promptgenerator_tests.py @@ -3,9 +3,7 @@ import unittest import sys import os -# Add the path to the "scripts" directory to import the PromptGenerator module -sys.path.append(os.path.abspath("../scripts")) -from promptgenerator import PromptGenerator +from autogpt.promptgenerator import PromptGenerator # Create a test class for the PromptGenerator, subclassed from unittest.TestCase diff --git a/tests/test_config.py b/tests/test_config.py index ba8381e1..af5fb2a8 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,5 +1,5 @@ import unittest -from scripts.config import Config +from autogpt.config import Config class TestConfig(unittest.TestCase): diff --git a/tests/test_json_parser.py b/tests/test_json_parser.py index c403c73d..c9d5e14b 100644 --- a/tests/test_json_parser.py +++ b/tests/test_json_parser.py @@ -1,7 +1,7 @@ import unittest import tests.context -from scripts.json_parser import fix_and_parse_json +from autogpt.json_parser import fix_and_parse_json class TestParseJson(unittest.TestCase): diff --git a/tests/unit/json_tests.py b/tests/unit/json_tests.py index 4f326721..77c85940 100644 --- a/tests/unit/json_tests.py +++ b/tests/unit/json_tests.py @@ -1,9 +1,9 @@ import unittest import os import sys -# Probably a better way: -sys.path.append(os.path.abspath('../scripts')) -from json_parser import fix_and_parse_json + + +from autogpt.json_parser import fix_and_parse_json class TestParseJson(unittest.TestCase): @@ -108,6 +108,13 @@ class TestParseJson(unittest.TestCase): # Assert that this raises an exception: self.assertEqual(fix_and_parse_json(json_str, try_to_fix_with_gpt=False), good_obj) + def test_that_apologies_containing_multiple_json_get_the_correct_one(self): + bad_json = 'I apologize once again for the error. Here is the corrected format to run the tests: ``` { "name": "execute_python_file", "args": { "file": "" } } ``` Where `` should be replaced with the file path to the test file you created in the previous step. For example: ``` { "name": "execute_python_file", "args": { "file": "tests/test_addition.py" } } ``` This will execute the tests for the `add_numbers` function in `tests/test_addition.py`. Please let me know if you have any further questions.' + actual_json = fix_and_parse_json(bad_json, try_to_fix_with_gpt=True) + expected_json = { "name": "execute_python_file", "args": { "file": "tests/test_addition.py" } } + self.assertEqual(actual_json, expected_json) + # TODO come back to fix this test after fixing imports + if __name__ == '__main__': unittest.main() diff --git a/tests/unit/test_browse_scrape_text.py b/tests/unit/test_browse_scrape_text.py index 9385cde7..f98e8628 100644 --- a/tests/unit/test_browse_scrape_text.py +++ b/tests/unit/test_browse_scrape_text.py @@ -3,7 +3,7 @@ import requests -from scripts.browse import scrape_text +from autogpt.browse import scrape_text """ Code Analysis From adf7c3ac98d5db51f54afb49449264c8155b2277 Mon Sep 17 00:00:00 2001 From: Merwane Hamadi Date: Fri, 14 Apr 2023 11:15:02 -0700 Subject: [PATCH 45/64] added more autogpt prefixes in imports --- autogpt/__main__.py | 4 ++-- {scripts => autogpt}/agent.py | 12 ++++++------ autogpt/ai_config.py | 2 +- autogpt/memory/__init__.py | 7 +++---- autogpt/memory/no_memory.py | 2 +- autogpt/memory/pinecone.py | 4 ++-- autogpt/prompt.py | 2 +- 7 files changed, 16 insertions(+), 17 deletions(-) rename {scripts => autogpt}/agent.py (98%) diff --git a/autogpt/__main__.py b/autogpt/__main__.py index 05cbed7a..7f59266c 100644 --- a/autogpt/__main__.py +++ b/autogpt/__main__.py @@ -14,9 +14,9 @@ from autogpt.ai_config import AIConfig import traceback import yaml import argparse -from logger import logger +from autogpt.logger import logger import logging -from prompt import get_prompt +from autogpt.prompt import get_prompt cfg = Config() diff --git a/scripts/agent.py b/autogpt/agent.py similarity index 98% rename from scripts/agent.py rename to autogpt/agent.py index cbd6b3e7..d28769a9 100644 --- a/scripts/agent.py +++ b/autogpt/agent.py @@ -1,15 +1,15 @@ -import commands as cmd +import autogpt.commands as cmd import json import traceback from tkinter.ttk import Style from colorama import Fore -import chat -from config import Config -from logger import logger -import speak -from spinner import Spinner +import autogpt.chat +from autogpt.config import Config +from autogpt.logger import logger +import autogpt.speak +from autogpt.spinner import Spinner class Agent: diff --git a/autogpt/ai_config.py b/autogpt/ai_config.py index 89a4e07e..73011206 100644 --- a/autogpt/ai_config.py +++ b/autogpt/ai_config.py @@ -1,6 +1,6 @@ import yaml import os -from prompt import get_prompt +from autogpt.prompt import get_prompt class AIConfig: diff --git a/autogpt/memory/__init__.py b/autogpt/memory/__init__.py index 71f18efd..5cd5767f 100644 --- a/autogpt/memory/__init__.py +++ b/autogpt/memory/__init__.py @@ -1,19 +1,18 @@ -from autogpt.memory.local import localcache +from autogpt.memory.local import LocalCache from autogpt.memory.no_memory import NoMemory - # List of supported memory backends # Add a backend to this list if the import attempt is successful supported_memory = ['local', 'no_memory'] try: - from memory.redismem import RedisMemory + from autogpt.memory.redismem import RedisMemory supported_memory.append('redis') except ImportError: print("Redis not installed. Skipping import.") RedisMemory = None try: - from memory.pinecone import PineconeMemory + from autogpt.memory.pinecone import PineconeMemory supported_memory.append('pinecone') except ImportError: print("Pinecone not installed. Skipping import.") diff --git a/autogpt/memory/no_memory.py b/autogpt/memory/no_memory.py index 830982f9..37f00085 100644 --- a/autogpt/memory/no_memory.py +++ b/autogpt/memory/no_memory.py @@ -1,6 +1,6 @@ from typing import Optional, List, Any -from memory.base import MemoryProviderSingleton +from autogpt.memory.base import MemoryProviderSingleton class NoMemory(MemoryProviderSingleton): diff --git a/autogpt/memory/pinecone.py b/autogpt/memory/pinecone.py index 1edfc2be..877e0b3d 100644 --- a/autogpt/memory/pinecone.py +++ b/autogpt/memory/pinecone.py @@ -2,8 +2,8 @@ from autogpt.config import Config, Singleton import pinecone -from memory.base import MemoryProviderSingleton, get_ada_embedding -from logger import logger +from autogpt.memory.base import MemoryProviderSingleton, get_ada_embedding +from autogpt.logger import logger from colorama import Fore, Style diff --git a/autogpt/prompt.py b/autogpt/prompt.py index 188603a3..4ea70749 100644 --- a/autogpt/prompt.py +++ b/autogpt/prompt.py @@ -1,4 +1,4 @@ -from promptgenerator import PromptGenerator +from autogpt.promptgenerator import PromptGenerator def get_prompt(): From 8dbc71da0ca06b4c91c9dec8990d292b5279241e Mon Sep 17 00:00:00 2001 From: Merwane Hamadi Date: Fri, 14 Apr 2023 11:15:17 -0700 Subject: [PATCH 46/64] added message to redirect users --- scripts/main.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 scripts/main.py diff --git a/scripts/main.py b/scripts/main.py new file mode 100644 index 00000000..b451e977 --- /dev/null +++ b/scripts/main.py @@ -0,0 +1,9 @@ +from colorama import init, Style + +# Initialize colorama +init(autoreset=True) + +# Use the bold ANSI style +print(f"""{Style.BRIGHT}Please run: +python -m autogpt +""") From 9d0bc54b0780386f3879e62b73933936337402a9 Mon Sep 17 00:00:00 2001 From: 0xArty Date: Fri, 14 Apr 2023 19:29:21 +0100 Subject: [PATCH 47/64] added pre-commit formatting --- .pre-commit-config.yaml | 6 ++++++ requirements.txt | 1 + 2 files changed, 7 insertions(+) create mode 100644 .pre-commit-config.yaml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000..62b06d7b --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,6 @@ +repos: +- repo: https://github.com/psf/black + rev: 21.12b0 + hooks: + - id: black + language_version: python3 \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 3f7fd228..9eea6873 100644 --- a/requirements.txt +++ b/requirements.txt @@ -18,3 +18,4 @@ Pillow coverage flake8 numpy +pre-commit \ No newline at end of file From 1804a804df0832528c69991e47c761b8ea344624 Mon Sep 17 00:00:00 2001 From: 0xArty Date: Fri, 14 Apr 2023 19:36:19 +0100 Subject: [PATCH 48/64] updated the contributor guide --- CONTRIBUTING.md | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0529cbd9..49c95991 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,41 +8,49 @@ To contribute to this GitHub project, you can follow these steps: ``` git clone https://github.com//Auto-GPT ``` -3. Create a new branch for your changes using the following command: +3. Install the project requirements +``` +pip install -r requirements.txt +``` +4. Install pre-commit hooks +``` +pre-commit install +``` +5. Create a new branch for your changes using the following command: ``` git checkout -b "branch-name" ``` -4. Make your changes to the code or documentation. +6. Make your changes to the code or documentation. - Example: Improve User Interface or Add Documentation. -5. Add the changes to the staging area using the following command: +7. Add the changes to the staging area using the following command: ``` git add . ``` -6. Commit the changes with a meaningful commit message using the following command: +8. Commit the changes with a meaningful commit message using the following command: ``` git commit -m "your commit message" ``` -7. Push the changes to your forked repository using the following command: +9. Push the changes to your forked repository using the following command: ``` git push origin branch-name ``` -8. Go to the GitHub website and navigate to your forked repository. +10. Go to the GitHub website and navigate to your forked repository. -9. Click the "New pull request" button. +11. Click the "New pull request" button. -10. Select the branch you just pushed to and the branch you want to merge into on the original repository. +12. Select the branch you just pushed to and the branch you want to merge into on the original repository. -11. Add a description of your changes and click the "Create pull request" button. +13. Add a description of your changes and click the "Create pull request" button. -12. Wait for the project maintainer to review your changes and provide feedback. +14. Wait for the project maintainer to review your changes and provide feedback. -13. Make any necessary changes based on feedback and repeat steps 5-12 until your changes are accepted and merged into the main project. +15. Make any necessary changes based on feedback and repeat steps 5-12 until your changes are accepted and merged into the main project. -14. Once your changes are merged, you can update your forked repository and local copy of the repository with the following commands: +16. Once your changes are merged, you can update your forked repository and local copy of the repository with the following commands: ``` git fetch upstream From 4322784b01d8db8caf2ce90c2593d3a42a8b7645 Mon Sep 17 00:00:00 2001 From: 0xArty Date: Fri, 14 Apr 2023 19:43:34 +0100 Subject: [PATCH 49/64] added black to the requirments --- requirements.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 9eea6873..cbfb836f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -18,4 +18,5 @@ Pillow coverage flake8 numpy -pre-commit \ No newline at end of file +pre-commit +black \ No newline at end of file From 9b56ebe5c434649e341a02f04c64993edd68f3b1 Mon Sep 17 00:00:00 2001 From: Merwane Hamadi Date: Fri, 14 Apr 2023 11:53:33 -0700 Subject: [PATCH 50/64] removed json_tests.py test_that_apologies_containing_multiple_json_get_the_correct_one because it breaks --- tests/unit/json_tests.py | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/tests/unit/json_tests.py b/tests/unit/json_tests.py index 77c85940..d2612345 100644 --- a/tests/unit/json_tests.py +++ b/tests/unit/json_tests.py @@ -1,7 +1,4 @@ import unittest -import os -import sys - from autogpt.json_parser import fix_and_parse_json @@ -108,13 +105,6 @@ class TestParseJson(unittest.TestCase): # Assert that this raises an exception: self.assertEqual(fix_and_parse_json(json_str, try_to_fix_with_gpt=False), good_obj) - def test_that_apologies_containing_multiple_json_get_the_correct_one(self): - bad_json = 'I apologize once again for the error. Here is the corrected format to run the tests: ``` { "name": "execute_python_file", "args": { "file": "" } } ``` Where `` should be replaced with the file path to the test file you created in the previous step. For example: ``` { "name": "execute_python_file", "args": { "file": "tests/test_addition.py" } } ``` This will execute the tests for the `add_numbers` function in `tests/test_addition.py`. Please let me know if you have any further questions.' - actual_json = fix_and_parse_json(bad_json, try_to_fix_with_gpt=True) - expected_json = { "name": "execute_python_file", "args": { "file": "tests/test_addition.py" } } - self.assertEqual(actual_json, expected_json) - # TODO come back to fix this test after fixing imports - if __name__ == '__main__': unittest.main() From 8da77020b918f1287dae2af802a0415596363de5 Mon Sep 17 00:00:00 2001 From: 0xArty Date: Fri, 14 Apr 2023 19:58:04 +0100 Subject: [PATCH 51/64] added pyproject.toml and .flake8 --- .flake8 | 12 ++++++++++++ pyproject.toml | 5 +++++ 2 files changed, 17 insertions(+) create mode 100644 .flake8 create mode 100644 pyproject.toml diff --git a/.flake8 b/.flake8 new file mode 100644 index 00000000..c456b393 --- /dev/null +++ b/.flake8 @@ -0,0 +1,12 @@ +[flake8] +max-line-length = 88 +extend-ignore = E203 +exclude = + .tox, + __pycache__, + *.pyc, + .env + venv/* + .venv/* + reports/* + dist/* \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..c01d19bb --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,5 @@ +[tool.black] +line-length = 88 +target-version = ['py310'] +include = '\.pyi?$' +extend-exclude = "" \ No newline at end of file From 087642f79337a6e76dda1a706972417c0018939f Mon Sep 17 00:00:00 2001 From: 0xArty Date: Fri, 14 Apr 2023 20:00:05 +0100 Subject: [PATCH 52/64] added basic project info --- pyproject.toml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index c01d19bb..64ed7165 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,3 +1,9 @@ +[project] +name = "auto-gpt" +version = "0.1.0" +description = "A GPT based ai agent" +readme = "README.md" + [tool.black] line-length = 88 target-version = ['py310'] From 6ca6a8aa608c5253ba4b3a577cf95e3517974207 Mon Sep 17 00:00:00 2001 From: 0xArty Date: Fri, 14 Apr 2023 20:17:37 +0100 Subject: [PATCH 53/64] added more tools --- .gitignore | 138 ++++++++++++++++++++++++++++++++++++++-- .isort.cfg | 10 +++ .pre-commit-config.yaml | 37 +++++++++-- .sourcery.yaml | 71 +++++++++++++++++++++ requirements.txt | 4 +- 5 files changed, 248 insertions(+), 12 deletions(-) create mode 100644 .isort.cfg create mode 100644 .sourcery.yaml diff --git a/.gitignore b/.gitignore index 5a2ce371..9874d425 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +## Original ignores autogpt/keys.py autogpt/*json autogpt/node_modules/ @@ -19,10 +20,135 @@ log.txt log-ingestion.txt logs -# Coverage reports -.coverage -coverage.xml -htmlcov/ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class -# For Macs Dev Environs: ignoring .Desktop Services_Store -.DS_Store +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +plugins/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ +llama-* +vicuna-* \ No newline at end of file diff --git a/.isort.cfg b/.isort.cfg new file mode 100644 index 00000000..8ad53a86 --- /dev/null +++ b/.isort.cfg @@ -0,0 +1,10 @@ +[settings] +profile = black +multi_line_output = 3 +include_trailing_comma = True +force_grid_wrap = 0 +use_parentheses = True +ensure_newline_before_comments = True +line_length = 88 +skip = venv,env,node_modules,.env,.venv,dist +sections = FUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,LOCALFOLDER \ No newline at end of file diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 62b06d7b..fb75cd59 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,6 +1,33 @@ repos: -- repo: https://github.com/psf/black - rev: 21.12b0 - hooks: - - id: black - language_version: python3 \ No newline at end of file + - repo: https://github.com/sourcery-ai/sourcery + rev: v1.1.0 # Get the latest tag from https://github.com/sourcery-ai/sourcery/tags + hooks: + - id: sourcery + + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v0.9.2 + hooks: + - id: check-added-large-files + args: [ '--maxkb=500' ] + - id: check-byte-order-marker + - id: check-case-conflict + - id: check-merge-conflict + - id: check-symlinks + - id: debug-statements + + - repo: local + hooks: + - id: isort + name: isort-local + entry: isort + language: python + types: [ python ] + exclude: .+/(dist|.venv|venv|build)/.+ + pass_filenames: true + - id: black + name: black-local + entry: black + language: python + types: [ python ] + exclude: .+/(dist|.venv|venv|build)/.+ + pass_filenames: true \ No newline at end of file diff --git a/.sourcery.yaml b/.sourcery.yaml new file mode 100644 index 00000000..a7f5b9d7 --- /dev/null +++ b/.sourcery.yaml @@ -0,0 +1,71 @@ +# ๐Ÿช„ This is your project's Sourcery configuration file. + +# You can use it to get Sourcery working in the way you want, such as +# ignoring specific refactorings, skipping directories in your project, +# or writing custom rules. + +# ๐Ÿ“š For a complete reference to this file, see the documentation at +# https://docs.sourcery.ai/Configuration/Project-Settings/ + +# This file was auto-generated by Sourcery on 2023-02-25 at 21:07. + +version: '1' # The schema version of this config file + +ignore: # A list of paths or files which Sourcery will ignore. +- .git +- venv +- .venv +- build +- dist +- env +- .env +- .tox + +rule_settings: + enable: + - default + - gpsg + disable: [] # A list of rule IDs Sourcery will never suggest. + rule_types: + - refactoring + - suggestion + - comment + python_version: '3.9' # A string specifying the lowest Python version your project supports. Sourcery will not suggest refactorings requiring a higher Python version. + +# rules: # A list of custom rules Sourcery will include in its analysis. +# - id: no-print-statements +# description: Do not use print statements in the test directory. +# pattern: print(...) +# language: python +# replacement: +# condition: +# explanation: +# paths: +# include: +# - test +# exclude: +# - conftest.py +# tests: [] +# tags: [] + +# rule_tags: {} # Additional rule tags. + +# metrics: +# quality_threshold: 25.0 + +# github: +# labels: [] +# ignore_labels: +# - sourcery-ignore +# request_review: author +# sourcery_branch: sourcery/{base_branch} + +# clone_detection: +# min_lines: 3 +# min_duplicates: 2 +# identical_clones_only: false + +# proxy: +# url: +# ssl_certs_file: +# no_ssl_verify: false \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index cbfb836f..306c23de 100644 --- a/requirements.txt +++ b/requirements.txt @@ -19,4 +19,6 @@ coverage flake8 numpy pre-commit -black \ No newline at end of file +black +sourcery +isort \ No newline at end of file From a0e3c238a44979c3db6063e3438dd8229a67cea5 Mon Sep 17 00:00:00 2001 From: 0xArty Date: Fri, 14 Apr 2023 20:41:45 +0100 Subject: [PATCH 54/64] migrating to black formatting --- .pre-commit-config.yaml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index fb75cd59..151d5822 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,8 +1,4 @@ repos: - - repo: https://github.com/sourcery-ai/sourcery - rev: v1.1.0 # Get the latest tag from https://github.com/sourcery-ai/sourcery/tags - hooks: - - id: sourcery - repo: https://github.com/pre-commit/pre-commit-hooks rev: v0.9.2 From 328ba5e69e738cc5d449c2985386b4963947b814 Mon Sep 17 00:00:00 2001 From: 0xArty Date: Fri, 14 Apr 2023 20:42:28 +0100 Subject: [PATCH 55/64] formatting --- autogpt/__main__.py | 243 ++++++++++++++++--------- autogpt/agent.py | 118 ++++++++---- autogpt/agent_manager.py | 4 +- autogpt/ai_config.py | 28 ++- autogpt/ai_functions.py | 6 +- autogpt/browse.py | 35 ++-- autogpt/call_ai_function.py | 5 +- autogpt/chat.py | 79 +++++--- autogpt/commands.py | 61 ++++--- autogpt/config.py | 49 +++-- autogpt/data_ingestion.py | 52 ++++-- autogpt/execute_code.py | 37 ++-- autogpt/file_operations.py | 13 +- autogpt/image_gen.py | 31 ++-- autogpt/json_parser.py | 28 +-- autogpt/json_utils.py | 36 ++-- autogpt/llm_utils.py | 20 +- autogpt/logger.py | 94 +++++----- autogpt/memory/__init__.py | 29 +-- autogpt/memory/base.py | 13 +- autogpt/memory/local.py | 29 ++- autogpt/memory/pinecone.py | 31 ++-- autogpt/memory/redismem.py | 76 ++++---- autogpt/prompt.py | 72 ++++++-- autogpt/promptgenerator.py | 26 ++- autogpt/speak.py | 38 ++-- autogpt/spinner.py | 5 +- autogpt/token_counter.py | 15 +- autogpt/utils.py | 7 +- scripts/main.py | 8 +- tests.py | 2 +- tests/context.py | 7 +- tests/integration/memory_tests.py | 17 +- tests/local_cache_test.py | 19 +- tests/promptgenerator_tests.py | 10 +- tests/test_config.py | 4 +- tests/test_json_parser.py | 66 ++++--- tests/unit/json_tests.py | 72 ++++---- tests/unit/test_browse_scrape_links.py | 14 +- tests/unit/test_browse_scrape_text.py | 4 +- 40 files changed, 911 insertions(+), 592 deletions(-) diff --git a/autogpt/__main__.py b/autogpt/__main__.py index 7f59266c..b1280b07 100644 --- a/autogpt/__main__.py +++ b/autogpt/__main__.py @@ -1,22 +1,23 @@ +import argparse import json +import logging import random -from autogpt import commands as cmd -from autogpt import utils -from autogpt.memory import get_memory, get_supported_memory_backends -from autogpt import chat -from colorama import Fore, Style -from autogpt.spinner import Spinner import time -from autogpt import speak +import traceback + +import yaml +from colorama import Fore, Style + +from autogpt import chat +from autogpt import commands as cmd +from autogpt import speak, utils +from autogpt.ai_config import AIConfig from autogpt.config import Config from autogpt.json_parser import fix_and_parse_json -from autogpt.ai_config import AIConfig -import traceback -import yaml -import argparse from autogpt.logger import logger -import logging +from autogpt.memory import get_memory, get_supported_memory_backends from autogpt.prompt import get_prompt +from autogpt.spinner import Spinner cfg = Config() @@ -25,8 +26,8 @@ def check_openai_api_key(): """Check if the OpenAI API key is set in config.py or as an environment variable.""" if not cfg.openai_api_key: print( - Fore.RED + - "Please set your OpenAI API key in .env or as an environment variable." + Fore.RED + + "Please set your OpenAI API key in .env or as an environment variable." ) print("You can get your key from https://beta.openai.com/account/api-keys") exit(1) @@ -34,21 +35,26 @@ def check_openai_api_key(): def attempt_to_fix_json_by_finding_outermost_brackets(json_string): if cfg.speak_mode and cfg.debug_mode: - speak.say_text("I have received an invalid JSON response from the OpenAI API. Trying to fix it now.") + speak.say_text( + "I have received an invalid JSON response from the OpenAI API. Trying to fix it now." + ) logger.typewriter_log("Attempting to fix JSON by finding outermost brackets\n") try: # Use regex to search for JSON objects import regex + json_pattern = regex.compile(r"\{(?:[^{}]|(?R))*\}") json_match = json_pattern.search(json_string) if json_match: # Extract the valid JSON object from the string json_string = json_match.group(0) - logger.typewriter_log(title="Apparently json was fixed.", title_color=Fore.GREEN) + logger.typewriter_log( + title="Apparently json was fixed.", title_color=Fore.GREEN + ) if cfg.speak_mode and cfg.debug_mode: - speak.say_text("Apparently json was fixed.") + speak.say_text("Apparently json was fixed.") else: raise ValueError("No valid JSON object found") @@ -71,7 +77,9 @@ def print_assistant_thoughts(assistant_reply): assistant_reply_json = fix_and_parse_json(assistant_reply) except json.JSONDecodeError as e: logger.error("Error: Invalid JSON in assistant thoughts\n", assistant_reply) - assistant_reply_json = attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply) + assistant_reply_json = attempt_to_fix_json_by_finding_outermost_brackets( + assistant_reply + ) assistant_reply_json = fix_and_parse_json(assistant_reply_json) # Check if assistant_reply_json is a string and attempt to parse it into a JSON object @@ -80,7 +88,11 @@ def print_assistant_thoughts(assistant_reply): assistant_reply_json = json.loads(assistant_reply_json) except json.JSONDecodeError as e: logger.error("Error: Invalid JSON\n", assistant_reply) - assistant_reply_json = attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply_json) + assistant_reply_json = ( + attempt_to_fix_json_by_finding_outermost_brackets( + assistant_reply_json + ) + ) assistant_thoughts_reasoning = None assistant_thoughts_plan = None @@ -95,7 +107,9 @@ def print_assistant_thoughts(assistant_reply): assistant_thoughts_criticism = assistant_thoughts.get("criticism") assistant_thoughts_speak = assistant_thoughts.get("speak") - logger.typewriter_log(f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, assistant_thoughts_text) + logger.typewriter_log( + f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, assistant_thoughts_text + ) logger.typewriter_log("REASONING:", Fore.YELLOW, assistant_thoughts_reasoning) if assistant_thoughts_plan: @@ -107,7 +121,7 @@ def print_assistant_thoughts(assistant_reply): assistant_thoughts_plan = str(assistant_thoughts_plan) # Split the input_string using the newline character and dashes - lines = assistant_thoughts_plan.split('\n') + lines = assistant_thoughts_plan.split("\n") for line in lines: line = line.lstrip("- ") logger.typewriter_log("- ", Fore.GREEN, line.strip()) @@ -121,7 +135,9 @@ def print_assistant_thoughts(assistant_reply): except json.decoder.JSONDecodeError as e: logger.error("Error: Invalid JSON\n", assistant_reply) if cfg.speak_mode: - speak.say_text("I have received an invalid JSON response from the OpenAI API. I cannot ignore this response.") + speak.say_text( + "I have received an invalid JSON response from the OpenAI API. I cannot ignore this response." + ) # All other errors, return "Error: + error message" except Exception as e: @@ -141,12 +157,15 @@ def construct_prompt(): f"Welcome back! ", Fore.GREEN, f"Would you like me to return to being {config.ai_name}?", - speak_text=True) - should_continue = utils.clean_input(f"""Continue with the last settings? + speak_text=True, + ) + should_continue = utils.clean_input( + f"""Continue with the last settings? Name: {config.ai_name} Role: {config.ai_role} Goals: {config.ai_goals} -Continue (y/n): """) +Continue (y/n): """ + ) if should_continue.lower() == "n": config = AIConfig() @@ -170,28 +189,27 @@ def prompt_user(): "Welcome to Auto-GPT! ", Fore.GREEN, "Enter the name of your AI and its role below. Entering nothing will load defaults.", - speak_text=True) + speak_text=True, + ) # Get AI Name from User logger.typewriter_log( - "Name your AI: ", - Fore.GREEN, - "For example, 'Entrepreneur-GPT'") + "Name your AI: ", Fore.GREEN, "For example, 'Entrepreneur-GPT'" + ) ai_name = utils.clean_input("AI Name: ") if ai_name == "": ai_name = "Entrepreneur-GPT" logger.typewriter_log( - f"{ai_name} here!", - Fore.LIGHTBLUE_EX, - "I am at your service.", - speak_text=True) + f"{ai_name} here!", Fore.LIGHTBLUE_EX, "I am at your service.", speak_text=True + ) # Get AI Role from User logger.typewriter_log( "Describe your AI's role: ", Fore.GREEN, - "For example, 'an AI designed to autonomously develop and run businesses with the sole goal of increasing your net worth.'") + "For example, 'an AI designed to autonomously develop and run businesses with the sole goal of increasing your net worth.'", + ) ai_role = utils.clean_input(f"{ai_name} is: ") if ai_role == "": ai_role = "an AI designed to autonomously develop and run businesses with the sole goal of increasing your net worth." @@ -200,7 +218,8 @@ def prompt_user(): logger.typewriter_log( "Enter up to 5 goals for your AI: ", Fore.GREEN, - "For example: \nIncrease net worth, Grow Twitter Account, Develop and manage multiple businesses autonomously'") + "For example: \nIncrease net worth, Grow Twitter Account, Develop and manage multiple businesses autonomously'", + ) print("Enter nothing to load defaults, enter nothing when finished.", flush=True) ai_goals = [] for i in range(5): @@ -209,8 +228,11 @@ def prompt_user(): break ai_goals.append(ai_goal) if len(ai_goals) == 0: - ai_goals = ["Increase net worth", "Grow Twitter Account", - "Develop and manage multiple businesses autonomously"] + ai_goals = [ + "Increase net worth", + "Grow Twitter Account", + "Develop and manage multiple businesses autonomously", + ] config = AIConfig(ai_name, ai_role, ai_goals) return config @@ -223,16 +245,42 @@ def parse_arguments(): cfg.set_continuous_mode(False) cfg.set_speak_mode(False) - parser = argparse.ArgumentParser(description='Process arguments.') - parser.add_argument('--continuous', '-c', action='store_true', help='Enable Continuous Mode') - parser.add_argument('--continuous-limit', '-l', type=int, dest="continuous_limit", help='Defines the number of times to run in continuous mode') - parser.add_argument('--speak', action='store_true', help='Enable Speak Mode') - parser.add_argument('--debug', action='store_true', help='Enable Debug Mode') - parser.add_argument('--gpt3only', action='store_true', help='Enable GPT3.5 Only Mode') - parser.add_argument('--gpt4only', action='store_true', help='Enable GPT4 Only Mode') - parser.add_argument('--use-memory', '-m', dest="memory_type", help='Defines which Memory backend to use') - parser.add_argument('--skip-reprompt', '-y', dest='skip_reprompt', action='store_true', help='Skips the re-prompting messages at the beginning of the script') - parser.add_argument('--ai-settings', '-C', dest='ai_settings_file', help="Specifies which ai_settings.yaml file to use, will also automatically skip the re-prompt.") + parser = argparse.ArgumentParser(description="Process arguments.") + parser.add_argument( + "--continuous", "-c", action="store_true", help="Enable Continuous Mode" + ) + parser.add_argument( + "--continuous-limit", + "-l", + type=int, + dest="continuous_limit", + help="Defines the number of times to run in continuous mode", + ) + parser.add_argument("--speak", action="store_true", help="Enable Speak Mode") + parser.add_argument("--debug", action="store_true", help="Enable Debug Mode") + parser.add_argument( + "--gpt3only", action="store_true", help="Enable GPT3.5 Only Mode" + ) + parser.add_argument("--gpt4only", action="store_true", help="Enable GPT4 Only Mode") + parser.add_argument( + "--use-memory", + "-m", + dest="memory_type", + help="Defines which Memory backend to use", + ) + parser.add_argument( + "--skip-reprompt", + "-y", + dest="skip_reprompt", + action="store_true", + help="Skips the re-prompting messages at the beginning of the script", + ) + parser.add_argument( + "--ai-settings", + "-C", + dest="ai_settings_file", + help="Specifies which ai_settings.yaml file to use, will also automatically skip the re-prompt.", + ) args = parser.parse_args() if args.debug: @@ -244,14 +292,14 @@ def parse_arguments(): logger.typewriter_log( "WARNING: ", Fore.RED, - "Continuous mode is not recommended. It is potentially dangerous and may cause your AI to run forever or carry out actions you would not usually authorise. Use at your own risk.") + "Continuous mode is not recommended. It is potentially dangerous and may cause your AI to run forever or carry out actions you would not usually authorise. Use at your own risk.", + ) cfg.set_continuous_mode(True) if args.continuous_limit: logger.typewriter_log( - "Continuous Limit: ", - Fore.GREEN, - f"{args.continuous_limit}") + "Continuous Limit: ", Fore.GREEN, f"{args.continuous_limit}" + ) cfg.set_continuous_limit(args.continuous_limit) # Check if continuous limit is used without continuous mode @@ -274,7 +322,11 @@ def parse_arguments(): supported_memory = get_supported_memory_backends() chosen = args.memory_type if not chosen in supported_memory: - logger.typewriter_log("ONLY THE FOLLOWING MEMORY BACKENDS ARE SUPPORTED: ", Fore.RED, f'{supported_memory}') + logger.typewriter_log( + "ONLY THE FOLLOWING MEMORY BACKENDS ARE SUPPORTED: ", + Fore.RED, + f"{supported_memory}", + ) logger.typewriter_log(f"Defaulting to: ", Fore.YELLOW, cfg.memory_backend) else: cfg.memory_backend = chosen @@ -316,14 +368,14 @@ def main(): # Initialize memory and make sure it is empty. # this is particularly important for indexing and referencing pinecone memory memory = get_memory(cfg, init=True) - print('Using memory of type: ' + memory.__class__.__name__) + print("Using memory of type: " + memory.__class__.__name__) agent = Agent( ai_name=ai_name, memory=memory, full_message_history=full_message_history, next_action_count=next_action_count, prompt=prompt, - user_input=user_input + user_input=user_input, ) agent.start_interaction_loop() @@ -340,13 +392,16 @@ class Agent: user_input: The user input. """ - def __init__(self, - ai_name, - memory, - full_message_history, - next_action_count, - prompt, - user_input): + + def __init__( + self, + ai_name, + memory, + full_message_history, + next_action_count, + prompt, + user_input, + ): self.ai_name = ai_name self.memory = memory self.full_message_history = full_message_history @@ -358,10 +413,16 @@ class Agent: # Interaction Loop loop_count = 0 while True: - # Discontinue if continuous limit is reached + # Discontinue if continuous limit is reached loop_count += 1 - if cfg.continuous_mode and cfg.continuous_limit > 0 and loop_count > cfg.continuous_limit: - logger.typewriter_log("Continuous Limit Reached: ", Fore.YELLOW, f"{cfg.continuous_limit}") + if ( + cfg.continuous_mode + and cfg.continuous_limit > 0 + and loop_count > cfg.continuous_limit + ): + logger.typewriter_log( + "Continuous Limit Reached: ", Fore.YELLOW, f"{cfg.continuous_limit}" + ) break # Send message to AI, get response @@ -371,7 +432,8 @@ class Agent: self.user_input, self.full_message_history, self.memory, - cfg.fast_token_limit) # TODO: This hardcodes the model to use GPT3.5. Make this an argument + cfg.fast_token_limit, + ) # TODO: This hardcodes the model to use GPT3.5. Make this an argument # Print Assistant thoughts print_assistant_thoughts(assistant_reply) @@ -379,7 +441,8 @@ class Agent: # Get command name and arguments try: command_name, arguments = cmd.get_command( - attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply)) + attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply) + ) if cfg.speak_mode: speak.say_text(f"I want to execute {command_name}") except Exception as e: @@ -393,21 +456,29 @@ class Agent: logger.typewriter_log( "NEXT ACTION: ", Fore.CYAN, - f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}") + f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}", + ) print( f"Enter 'y' to authorise command, 'y -N' to run N continuous commands, 'n' to exit program, or enter feedback for {self.ai_name}...", - flush=True) + flush=True, + ) while True: - console_input = utils.clean_input(Fore.MAGENTA + "Input:" + Style.RESET_ALL) + console_input = utils.clean_input( + Fore.MAGENTA + "Input:" + Style.RESET_ALL + ) if console_input.lower().rstrip() == "y": self.user_input = "GENERATE NEXT COMMAND JSON" break elif console_input.lower().startswith("y -"): try: - self.next_action_count = abs(int(console_input.split(" ")[1])) + self.next_action_count = abs( + int(console_input.split(" ")[1]) + ) self.user_input = "GENERATE NEXT COMMAND JSON" except ValueError: - print("Invalid input format. Please enter 'y -n' where n is the number of continuous tasks.") + print( + "Invalid input format. Please enter 'y -n' where n is the number of continuous tasks." + ) continue break elif console_input.lower() == "n": @@ -422,7 +493,8 @@ class Agent: logger.typewriter_log( "-=-=-=-=-=-=-= COMMAND AUTHORISED BY USER -=-=-=-=-=-=-=", Fore.MAGENTA, - "") + "", + ) elif self.user_input == "EXIT": print("Exiting...", flush=True) break @@ -431,11 +503,14 @@ class Agent: logger.typewriter_log( "NEXT ACTION: ", Fore.CYAN, - f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}") + f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}", + ) # Execute command if command_name is not None and command_name.lower().startswith("error"): - result = f"Command {command_name} threw the following error: " + arguments + result = ( + f"Command {command_name} threw the following error: " + arguments + ) elif command_name == "human_feedback": result = f"Human feedback: {self.user_input}" else: @@ -443,22 +518,28 @@ class Agent: if self.next_action_count > 0: self.next_action_count -= 1 - memory_to_add = f"Assistant Reply: {assistant_reply} " \ - f"\nResult: {result} " \ - f"\nHuman Feedback: {self.user_input} " + memory_to_add = ( + f"Assistant Reply: {assistant_reply} " + f"\nResult: {result} " + f"\nHuman Feedback: {self.user_input} " + ) self.memory.add(memory_to_add) # Check if there's a result from the command append it to the message # history if result is not None: - self.full_message_history.append(chat.create_chat_message("system", result)) + self.full_message_history.append( + chat.create_chat_message("system", result) + ) logger.typewriter_log("SYSTEM: ", Fore.YELLOW, result) else: self.full_message_history.append( - chat.create_chat_message( - "system", "Unable to execute command")) - logger.typewriter_log("SYSTEM: ", Fore.YELLOW, "Unable to execute command") + chat.create_chat_message("system", "Unable to execute command") + ) + logger.typewriter_log( + "SYSTEM: ", Fore.YELLOW, "Unable to execute command" + ) if __name__ == "__main__": diff --git a/autogpt/agent.py b/autogpt/agent.py index d28769a9..7b1d1c18 100644 --- a/autogpt/agent.py +++ b/autogpt/agent.py @@ -1,4 +1,3 @@ -import autogpt.commands as cmd import json import traceback from tkinter.ttk import Style @@ -6,9 +5,10 @@ from tkinter.ttk import Style from colorama import Fore import autogpt.chat +import autogpt.commands as cmd +import autogpt.speak from autogpt.config import Config from autogpt.logger import logger -import autogpt.speak from autogpt.spinner import Spinner @@ -24,13 +24,16 @@ class Agent: user_input: The user input. """ - def __init__(self, - ai_name, - memory, - full_message_history, - next_action_count, - prompt, - user_input): + + def __init__( + self, + ai_name, + memory, + full_message_history, + next_action_count, + prompt, + user_input, + ): self.ai_name = ai_name self.memory = memory self.full_message_history = full_message_history @@ -43,10 +46,16 @@ class Agent: cfg = Config() loop_count = 0 while True: - # Discontinue if continuous limit is reached + # Discontinue if continuous limit is reached loop_count += 1 - if cfg.continuous_mode and cfg.continuous_limit > 0 and loop_count > cfg.continuous_limit: - logger.typewriter_log("Continuous Limit Reached: ", Fore.YELLOW, f"{cfg.continuous_limit}") + if ( + cfg.continuous_mode + and cfg.continuous_limit > 0 + and loop_count > cfg.continuous_limit + ): + logger.typewriter_log( + "Continuous Limit Reached: ", Fore.YELLOW, f"{cfg.continuous_limit}" + ) break # Send message to AI, get response @@ -56,7 +65,8 @@ class Agent: self.user_input, self.full_message_history, self.memory, - cfg.fast_token_limit) # TODO: This hardcodes the model to use GPT3.5. Make this an argument + cfg.fast_token_limit, + ) # TODO: This hardcodes the model to use GPT3.5. Make this an argument # Print Assistant thoughts print_assistant_thoughts(assistant_reply) @@ -64,7 +74,8 @@ class Agent: # Get command name and arguments try: command_name, arguments = cmd.get_command( - attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply)) + attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply) + ) if cfg.speak_mode: speak.say_text(f"I want to execute {command_name}") except Exception as e: @@ -78,21 +89,29 @@ class Agent: logger.typewriter_log( "NEXT ACTION: ", Fore.CYAN, - f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}") + f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}", + ) print( f"Enter 'y' to authorise command, 'y -N' to run N continuous commands, 'n' to exit program, or enter feedback for {self.ai_name}...", - flush=True) + flush=True, + ) while True: - console_input = utils.clean_input(Fore.MAGENTA + "Input:" + Style.RESET_ALL) + console_input = utils.clean_input( + Fore.MAGENTA + "Input:" + Style.RESET_ALL + ) if console_input.lower().rstrip() == "y": self.user_input = "GENERATE NEXT COMMAND JSON" break elif console_input.lower().startswith("y -"): try: - self.next_action_count = abs(int(console_input.split(" ")[1])) + self.next_action_count = abs( + int(console_input.split(" ")[1]) + ) self.user_input = "GENERATE NEXT COMMAND JSON" except ValueError: - print("Invalid input format. Please enter 'y -n' where n is the number of continuous tasks.") + print( + "Invalid input format. Please enter 'y -n' where n is the number of continuous tasks." + ) continue break elif console_input.lower() == "n": @@ -107,7 +126,8 @@ class Agent: logger.typewriter_log( "-=-=-=-=-=-=-= COMMAND AUTHORISED BY USER -=-=-=-=-=-=-=", Fore.MAGENTA, - "") + "", + ) elif self.user_input == "EXIT": print("Exiting...", flush=True) break @@ -116,11 +136,14 @@ class Agent: logger.typewriter_log( "NEXT ACTION: ", Fore.CYAN, - f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}") + f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}", + ) # Execute command if command_name is not None and command_name.lower().startswith("error"): - result = f"Command {command_name} threw the following error: " + arguments + result = ( + f"Command {command_name} threw the following error: " + arguments + ) elif command_name == "human_feedback": result = f"Human feedback: {self.user_input}" else: @@ -128,42 +151,53 @@ class Agent: if self.next_action_count > 0: self.next_action_count -= 1 - memory_to_add = f"Assistant Reply: {assistant_reply} " \ - f"\nResult: {result} " \ - f"\nHuman Feedback: {self.user_input} " + memory_to_add = ( + f"Assistant Reply: {assistant_reply} " + f"\nResult: {result} " + f"\nHuman Feedback: {self.user_input} " + ) self.memory.add(memory_to_add) # Check if there's a result from the command append it to the message # history if result is not None: - self.full_message_history.append(chat.create_chat_message("system", result)) + self.full_message_history.append( + chat.create_chat_message("system", result) + ) logger.typewriter_log("SYSTEM: ", Fore.YELLOW, result) else: self.full_message_history.append( - chat.create_chat_message( - "system", "Unable to execute command")) - logger.typewriter_log("SYSTEM: ", Fore.YELLOW, "Unable to execute command") + chat.create_chat_message("system", "Unable to execute command") + ) + logger.typewriter_log( + "SYSTEM: ", Fore.YELLOW, "Unable to execute command" + ) def attempt_to_fix_json_by_finding_outermost_brackets(json_string): cfg = Config() if cfg.speak_mode and cfg.debug_mode: - speak.say_text("I have received an invalid JSON response from the OpenAI API. Trying to fix it now.") + speak.say_text( + "I have received an invalid JSON response from the OpenAI API. Trying to fix it now." + ) logger.typewriter_log("Attempting to fix JSON by finding outermost brackets\n") try: # Use regex to search for JSON objects import regex + json_pattern = regex.compile(r"\{(?:[^{}]|(?R))*\}") json_match = json_pattern.search(json_string) if json_match: # Extract the valid JSON object from the string json_string = json_match.group(0) - logger.typewriter_log(title="Apparently json was fixed.", title_color=Fore.GREEN) + logger.typewriter_log( + title="Apparently json was fixed.", title_color=Fore.GREEN + ) if cfg.speak_mode and cfg.debug_mode: - speak.say_text("Apparently json was fixed.") + speak.say_text("Apparently json was fixed.") else: raise ValueError("No valid JSON object found") @@ -187,7 +221,9 @@ def print_assistant_thoughts(assistant_reply): assistant_reply_json = fix_and_parse_json(assistant_reply) except json.JSONDecodeError as e: logger.error("Error: Invalid JSON in assistant thoughts\n", assistant_reply) - assistant_reply_json = attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply) + assistant_reply_json = attempt_to_fix_json_by_finding_outermost_brackets( + assistant_reply + ) assistant_reply_json = fix_and_parse_json(assistant_reply_json) # Check if assistant_reply_json is a string and attempt to parse it into a JSON object @@ -196,7 +232,11 @@ def print_assistant_thoughts(assistant_reply): assistant_reply_json = json.loads(assistant_reply_json) except json.JSONDecodeError as e: logger.error("Error: Invalid JSON\n", assistant_reply) - assistant_reply_json = attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply_json) + assistant_reply_json = ( + attempt_to_fix_json_by_finding_outermost_brackets( + assistant_reply_json + ) + ) assistant_thoughts_reasoning = None assistant_thoughts_plan = None @@ -211,7 +251,9 @@ def print_assistant_thoughts(assistant_reply): assistant_thoughts_criticism = assistant_thoughts.get("criticism") assistant_thoughts_speak = assistant_thoughts.get("speak") - logger.typewriter_log(f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, assistant_thoughts_text) + logger.typewriter_log( + f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, assistant_thoughts_text + ) logger.typewriter_log("REASONING:", Fore.YELLOW, assistant_thoughts_reasoning) if assistant_thoughts_plan: @@ -223,7 +265,7 @@ def print_assistant_thoughts(assistant_reply): assistant_thoughts_plan = str(assistant_thoughts_plan) # Split the input_string using the newline character and dashes - lines = assistant_thoughts_plan.split('\n') + lines = assistant_thoughts_plan.split("\n") for line in lines: line = line.lstrip("- ") logger.typewriter_log("- ", Fore.GREEN, line.strip()) @@ -237,7 +279,9 @@ def print_assistant_thoughts(assistant_reply): except json.decoder.JSONDecodeError as e: logger.error("Error: Invalid JSON\n", assistant_reply) if cfg.speak_mode: - speak.say_text("I have received an invalid JSON response from the OpenAI API. I cannot ignore this response.") + speak.say_text( + "I have received an invalid JSON response from the OpenAI API. I cannot ignore this response." + ) # All other errors, return "Error: + error message" except Exception as e: diff --git a/autogpt/agent_manager.py b/autogpt/agent_manager.py index 2722b4be..bbf156ee 100644 --- a/autogpt/agent_manager.py +++ b/autogpt/agent_manager.py @@ -12,7 +12,9 @@ def create_agent(task, prompt, model): global next_key global agents - messages = [{"role": "user", "content": prompt}, ] + messages = [ + {"role": "user", "content": prompt}, + ] # Start GPT instance agent_reply = create_chat_completion( diff --git a/autogpt/ai_config.py b/autogpt/ai_config.py index 73011206..a224fff2 100644 --- a/autogpt/ai_config.py +++ b/autogpt/ai_config.py @@ -1,5 +1,7 @@ -import yaml import os + +import yaml + from autogpt.prompt import get_prompt @@ -13,7 +15,9 @@ class AIConfig: ai_goals (list): The list of objectives the AI is supposed to complete. """ - def __init__(self, ai_name: str="", ai_role: str="", ai_goals: list=[]) -> None: + def __init__( + self, ai_name: str = "", ai_role: str = "", ai_goals: list = [] + ) -> None: """ Initialize a class instance @@ -30,10 +34,10 @@ class AIConfig: self.ai_goals = ai_goals # Soon this will go in a folder where it remembers more stuff about the run(s) - SAVE_FILE = os.path.join(os.path.dirname(__file__), '..', 'ai_settings.yaml') + SAVE_FILE = os.path.join(os.path.dirname(__file__), "..", "ai_settings.yaml") @classmethod - def load(cls: object, config_file: str=SAVE_FILE) -> object: + def load(cls: object, config_file: str = SAVE_FILE) -> object: """ Returns class object with parameters (ai_name, ai_role, ai_goals) loaded from yaml file if yaml file exists, else returns class with no parameters. @@ -47,7 +51,7 @@ class AIConfig: """ try: - with open(config_file, encoding='utf-8') as file: + with open(config_file, encoding="utf-8") as file: config_params = yaml.load(file, Loader=yaml.FullLoader) except FileNotFoundError: config_params = {} @@ -58,7 +62,7 @@ class AIConfig: return cls(ai_name, ai_role, ai_goals) - def save(self, config_file: str=SAVE_FILE) -> None: + def save(self, config_file: str = SAVE_FILE) -> None: """ Saves the class parameters to the specified file yaml file path as a yaml file. @@ -69,8 +73,12 @@ class AIConfig: None """ - config = {"ai_name": self.ai_name, "ai_role": self.ai_role, "ai_goals": self.ai_goals} - with open(config_file, "w", encoding='utf-8') as file: + config = { + "ai_name": self.ai_name, + "ai_role": self.ai_role, + "ai_goals": self.ai_goals, + } + with open(config_file, "w", encoding="utf-8") as file: yaml.dump(config, file, allow_unicode=True) def construct_full_prompt(self) -> str: @@ -87,7 +95,9 @@ class AIConfig: prompt_start = """Your decisions must always be made independently without seeking user assistance. Play to your strengths as an LLM and pursue simple strategies with no legal complications.""" # Construct full prompt - full_prompt = f"You are {self.ai_name}, {self.ai_role}\n{prompt_start}\n\nGOALS:\n\n" + full_prompt = ( + f"You are {self.ai_name}, {self.ai_role}\n{prompt_start}\n\nGOALS:\n\n" + ) for i, goal in enumerate(self.ai_goals): full_prompt += f"{i+1}. {goal}\n" diff --git a/autogpt/ai_functions.py b/autogpt/ai_functions.py index b6e3df48..a4e42331 100644 --- a/autogpt/ai_functions.py +++ b/autogpt/ai_functions.py @@ -1,7 +1,9 @@ -from typing import List import json -from autogpt.config import Config +from typing import List + from autogpt.call_ai_function import call_ai_function +from autogpt.config import Config + cfg = Config() diff --git a/autogpt/browse.py b/autogpt/browse.py index 32e74fea..aa69c107 100644 --- a/autogpt/browse.py +++ b/autogpt/browse.py @@ -1,15 +1,17 @@ +from urllib.parse import urljoin, urlparse + import requests from bs4 import BeautifulSoup -from autogpt.memory import get_memory + from autogpt.config import Config from autogpt.llm_utils import create_chat_completion -from urllib.parse import urlparse, urljoin +from autogpt.memory import get_memory cfg = Config() memory = get_memory(cfg) session = requests.Session() -session.headers.update({'User-Agent': cfg.user_agent}) +session.headers.update({"User-Agent": cfg.user_agent}) # Function to check if the URL is valid @@ -28,7 +30,12 @@ def sanitize_url(url): # Define and check for local file address prefixes def check_local_file_access(url): - local_prefixes = ['file:///', 'file://localhost', 'http://localhost', 'https://localhost'] + local_prefixes = [ + "file:///", + "file://localhost", + "http://localhost", + "https://localhost", + ] return any(url.startswith(prefix) for prefix in local_prefixes) @@ -36,11 +43,11 @@ def get_response(url, timeout=10): try: # Restrict access to local files if check_local_file_access(url): - raise ValueError('Access to local files is restricted') + raise ValueError("Access to local files is restricted") # Most basic check if the URL is valid: - if not url.startswith('http://') and not url.startswith('https://'): - raise ValueError('Invalid URL format') + if not url.startswith("http://") and not url.startswith("https://"): + raise ValueError("Invalid URL format") sanitized_url = sanitize_url(url) @@ -74,7 +81,7 @@ def scrape_text(url): text = soup.get_text() lines = (line.strip() for line in text.splitlines()) chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) - text = '\n'.join(chunk for chunk in chunks if chunk) + text = "\n".join(chunk for chunk in chunks if chunk) return text @@ -82,8 +89,8 @@ def scrape_text(url): def extract_hyperlinks(soup): """Extract hyperlinks from a BeautifulSoup object""" hyperlinks = [] - for link in soup.find_all('a', href=True): - hyperlinks.append((link.text, link['href'])) + for link in soup.find_all("a", href=True): + hyperlinks.append((link.text, link["href"])) return hyperlinks @@ -134,7 +141,7 @@ def create_message(chunk, question): """Create a message for the user to summarize a chunk of text""" return { "role": "user", - "content": f"\"\"\"{chunk}\"\"\" Using the above text, please answer the following question: \"{question}\" -- if the question cannot be answered using the text, please summarize the text." + "content": f'"""{chunk}""" Using the above text, please answer the following question: "{question}" -- if the question cannot be answered using the text, please summarize the text.', } @@ -152,8 +159,7 @@ def summarize_text(url, text, question): for i, chunk in enumerate(chunks): print(f"Adding chunk {i + 1} / {len(chunks)} to memory") - memory_to_add = f"Source: {url}\n" \ - f"Raw content part#{i + 1}: {chunk}" + memory_to_add = f"Source: {url}\n" f"Raw content part#{i + 1}: {chunk}" memory.add(memory_to_add) @@ -168,8 +174,7 @@ def summarize_text(url, text, question): summaries.append(summary) print(f"Added chunk {i + 1} summary to memory") - memory_to_add = f"Source: {url}\n" \ - f"Content summary part#{i + 1}: {summary}" + memory_to_add = f"Source: {url}\n" f"Content summary part#{i + 1}: {summary}" memory.add(memory_to_add) diff --git a/autogpt/call_ai_function.py b/autogpt/call_ai_function.py index 5bcd76af..0d5132bc 100644 --- a/autogpt/call_ai_function.py +++ b/autogpt/call_ai_function.py @@ -1,4 +1,5 @@ from autogpt.config import Config + cfg = Config() from autogpt.llm_utils import create_chat_completion @@ -22,8 +23,6 @@ def call_ai_function(function, args, description, model=None): {"role": "user", "content": args}, ] - response = create_chat_completion( - model=model, messages=messages, temperature=0 - ) + response = create_chat_completion(model=model, messages=messages, temperature=0) return response diff --git a/autogpt/chat.py b/autogpt/chat.py index 6b901ffa..e6651a63 100644 --- a/autogpt/chat.py +++ b/autogpt/chat.py @@ -1,11 +1,13 @@ +import logging import time + import openai from dotenv import load_dotenv -from autogpt.config import Config + from autogpt import token_counter +from autogpt.config import Config from autogpt.llm_utils import create_chat_completion from autogpt.logger import logger -import logging cfg = Config() @@ -26,28 +28,33 @@ def create_chat_message(role, content): def generate_context(prompt, relevant_memory, full_message_history, model): current_context = [ + create_chat_message("system", prompt), create_chat_message( - "system", prompt), + "system", f"The current time and date is {time.strftime('%c')}" + ), create_chat_message( - "system", f"The current time and date is {time.strftime('%c')}"), - create_chat_message( - "system", f"This reminds you of these events from your past:\n{relevant_memory}\n\n")] + "system", + f"This reminds you of these events from your past:\n{relevant_memory}\n\n", + ), + ] # Add messages from the full message history until we reach the token limit next_message_to_add_index = len(full_message_history) - 1 insertion_index = len(current_context) # Count the currently used tokens current_tokens_used = token_counter.count_message_tokens(current_context, model) - return next_message_to_add_index, current_tokens_used, insertion_index, current_context + return ( + next_message_to_add_index, + current_tokens_used, + insertion_index, + current_context, + ) # TODO: Change debug from hardcode to argument def chat_with_ai( - prompt, - user_input, - full_message_history, - permanent_memory, - token_limit): + prompt, user_input, full_message_history, permanent_memory, token_limit +): """Interact with the OpenAI API, sending the prompt, user input, message history, and permanent memory.""" while True: try: @@ -64,37 +71,57 @@ def chat_with_ai( Returns: str: The AI's response. """ - model = cfg.fast_llm_model # TODO: Change model from hardcode to argument + model = cfg.fast_llm_model # TODO: Change model from hardcode to argument # Reserve 1000 tokens for the response logger.debug(f"Token limit: {token_limit}") send_token_limit = token_limit - 1000 - relevant_memory = '' if len(full_message_history) ==0 else permanent_memory.get_relevant(str(full_message_history[-9:]), 10) + relevant_memory = ( + "" + if len(full_message_history) == 0 + else permanent_memory.get_relevant(str(full_message_history[-9:]), 10) + ) - logger.debug(f'Memory Stats: {permanent_memory.get_stats()}') + logger.debug(f"Memory Stats: {permanent_memory.get_stats()}") - next_message_to_add_index, current_tokens_used, insertion_index, current_context = generate_context( - prompt, relevant_memory, full_message_history, model) + ( + next_message_to_add_index, + current_tokens_used, + insertion_index, + current_context, + ) = generate_context(prompt, relevant_memory, full_message_history, model) while current_tokens_used > 2500: # remove memories until we are under 2500 tokens relevant_memory = relevant_memory[1:] - next_message_to_add_index, current_tokens_used, insertion_index, current_context = generate_context( - prompt, relevant_memory, full_message_history, model) + ( + next_message_to_add_index, + current_tokens_used, + insertion_index, + current_context, + ) = generate_context( + prompt, relevant_memory, full_message_history, model + ) - current_tokens_used += token_counter.count_message_tokens([create_chat_message("user", user_input)], model) # Account for user input (appended later) + current_tokens_used += token_counter.count_message_tokens( + [create_chat_message("user", user_input)], model + ) # Account for user input (appended later) while next_message_to_add_index >= 0: # print (f"CURRENT TOKENS USED: {current_tokens_used}") message_to_add = full_message_history[next_message_to_add_index] - tokens_to_add = token_counter.count_message_tokens([message_to_add], model) + tokens_to_add = token_counter.count_message_tokens( + [message_to_add], model + ) if current_tokens_used + tokens_to_add > send_token_limit: break # Add the most recent message to the start of the current context, after the two system prompts. - current_context.insert(insertion_index, full_message_history[next_message_to_add_index]) + current_context.insert( + insertion_index, full_message_history[next_message_to_add_index] + ) # Count the currently used tokens current_tokens_used += tokens_to_add @@ -130,12 +157,10 @@ def chat_with_ai( ) # Update full message history + full_message_history.append(create_chat_message("user", user_input)) full_message_history.append( - create_chat_message( - "user", user_input)) - full_message_history.append( - create_chat_message( - "assistant", assistant_reply)) + create_chat_message("assistant", assistant_reply) + ) return assistant_reply except openai.error.RateLimitError: diff --git a/autogpt/commands.py b/autogpt/commands.py index 7bcdaa6c..395b1e81 100644 --- a/autogpt/commands.py +++ b/autogpt/commands.py @@ -1,19 +1,26 @@ -from autogpt import browse -import json -from autogpt.memory import get_memory import datetime -import autogpt.agent_manager as agents -from autogpt import speak -from autogpt.config import Config -import autogpt.ai_functions as ai -from autogpt.file_operations import read_file, write_to_file, append_to_file, delete_file, search_files -from autogpt.execute_code import execute_python_file, execute_shell -from autogpt.json_parser import fix_and_parse_json -from autogpt.image_gen import generate_image +import json + from duckduckgo_search import ddg from googleapiclient.discovery import build from googleapiclient.errors import HttpError +import autogpt.agent_manager as agents +import autogpt.ai_functions as ai +from autogpt import browse, speak +from autogpt.config import Config +from autogpt.execute_code import execute_python_file, execute_shell +from autogpt.file_operations import ( + append_to_file, + delete_file, + read_file, + search_files, + write_to_file, +) +from autogpt.image_gen import generate_image +from autogpt.json_parser import fix_and_parse_json +from autogpt.memory import get_memory + cfg = Config() @@ -31,7 +38,7 @@ def get_command(response): response_json = fix_and_parse_json(response) if "command" not in response_json: - return "Error:" , "Missing 'command' object in JSON" + return "Error:", "Missing 'command' object in JSON" command = response_json["command"] @@ -57,10 +64,11 @@ def execute_command(command_name, arguments): try: if command_name == "google": - # Check if the Google API key is set and use the official search method # If the API key is not set or has only whitespaces, use the unofficial search method - if cfg.google_api_key and (cfg.google_api_key.strip() if cfg.google_api_key else None): + if cfg.google_api_key and ( + cfg.google_api_key.strip() if cfg.google_api_key else None + ): return google_official_search(arguments["input"]) else: return google_search(arguments["input"]) @@ -68,9 +76,8 @@ def execute_command(command_name, arguments): return memory.add(arguments["string"]) elif command_name == "start_agent": return start_agent( - arguments["name"], - arguments["task"], - arguments["prompt"]) + arguments["name"], arguments["task"], arguments["prompt"] + ) elif command_name == "message_agent": return message_agent(arguments["key"], arguments["message"]) elif command_name == "list_agents": @@ -124,8 +131,9 @@ def execute_command(command_name, arguments): def get_datetime(): """Return the current date and time""" - return "Current date and time: " + \ - datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + return "Current date and time: " + datetime.datetime.now().strftime( + "%Y-%m-%d %H:%M:%S" + ) def google_search(query, num_results=8): @@ -139,9 +147,10 @@ def google_search(query, num_results=8): def google_official_search(query, num_results=8): """Return the results of a google search using the official Google API""" + import json + from googleapiclient.discovery import build from googleapiclient.errors import HttpError - import json try: # Get the Google API key and Custom Search Engine ID from the config file @@ -152,7 +161,11 @@ def google_official_search(query, num_results=8): service = build("customsearch", "v1", developerKey=api_key) # Send the search query and retrieve the results - result = service.cse().list(q=query, cx=custom_search_engine_id, num=num_results).execute() + result = ( + service.cse() + .list(q=query, cx=custom_search_engine_id, num=num_results) + .execute() + ) # Extract the search result items from the response search_results = result.get("items", []) @@ -165,7 +178,11 @@ def google_official_search(query, num_results=8): error_details = json.loads(e.content.decode()) # Check if the error is related to an invalid or missing API key - if error_details.get("error", {}).get("code") == 403 and "invalid API key" in error_details.get("error", {}).get("message", ""): + if error_details.get("error", {}).get( + "code" + ) == 403 and "invalid API key" in error_details.get("error", {}).get( + "message", "" + ): return "Error: The provided Google API key is invalid or missing." else: return f"Error: {e}" diff --git a/autogpt/config.py b/autogpt/config.py index dc791d8d..26132a5a 100644 --- a/autogpt/config.py +++ b/autogpt/config.py @@ -1,8 +1,10 @@ import abc import os + import openai import yaml from dotenv import load_dotenv + # Load environment variables from .env file load_dotenv() @@ -17,9 +19,7 @@ class Singleton(abc.ABCMeta, type): def __call__(cls, *args, **kwargs): """Call method for the singleton metaclass.""" if cls not in cls._instances: - cls._instances[cls] = super( - Singleton, cls).__call__( - *args, **kwargs) + cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] @@ -46,12 +46,14 @@ class Config(metaclass=Singleton): self.fast_token_limit = int(os.getenv("FAST_TOKEN_LIMIT", 4000)) self.smart_token_limit = int(os.getenv("SMART_TOKEN_LIMIT", 8000)) self.browse_chunk_max_length = int(os.getenv("BROWSE_CHUNK_MAX_LENGTH", 8192)) - self.browse_summary_max_token = int(os.getenv("BROWSE_SUMMARY_MAX_TOKEN", 300)) + self.browse_summary_max_token = int(os.getenv("BROWSE_SUMMARY_MAX_TOKEN", 300)) self.openai_api_key = os.getenv("OPENAI_API_KEY") self.temperature = float(os.getenv("TEMPERATURE", "1")) - self.use_azure = os.getenv("USE_AZURE") == 'True' - self.execute_local_commands = os.getenv('EXECUTE_LOCAL_COMMANDS', 'False') == 'True' + self.use_azure = os.getenv("USE_AZURE") == "True" + self.execute_local_commands = ( + os.getenv("EXECUTE_LOCAL_COMMANDS", "False") == "True" + ) if self.use_azure: self.load_azure_config() @@ -80,15 +82,18 @@ class Config(metaclass=Singleton): # User agent headers to use when browsing web # Some websites might just completely deny request with an error code if no user agent was found. - self.user_agent = os.getenv("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") + self.user_agent = os.getenv( + "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", + ) self.redis_host = os.getenv("REDIS_HOST", "localhost") self.redis_port = os.getenv("REDIS_PORT", "6379") self.redis_password = os.getenv("REDIS_PASSWORD", "") - self.wipe_redis_on_start = os.getenv("WIPE_REDIS_ON_START", "True") == 'True' - self.memory_index = os.getenv("MEMORY_INDEX", 'auto-gpt') + self.wipe_redis_on_start = os.getenv("WIPE_REDIS_ON_START", "True") == "True" + self.memory_index = os.getenv("MEMORY_INDEX", "auto-gpt") # Note that indexes must be created on db 0 in redis, this is not configurable. - self.memory_backend = os.getenv("MEMORY_BACKEND", 'local') + self.memory_backend = os.getenv("MEMORY_BACKEND", "local") # Initialize the OpenAI API client openai.api_key = self.openai_api_key @@ -105,15 +110,19 @@ class Config(metaclass=Singleton): if model == self.fast_llm_model: return self.azure_model_to_deployment_id_map["fast_llm_model_deployment_id"] elif model == self.smart_llm_model: - return self.azure_model_to_deployment_id_map["smart_llm_model_deployment_id"] + return self.azure_model_to_deployment_id_map[ + "smart_llm_model_deployment_id" + ] elif model == "text-embedding-ada-002": - return self.azure_model_to_deployment_id_map["embedding_model_deployment_id"] + return self.azure_model_to_deployment_id_map[ + "embedding_model_deployment_id" + ] else: return "" - AZURE_CONFIG_FILE = os.path.join(os.path.dirname(__file__), '..', 'azure.yaml') + AZURE_CONFIG_FILE = os.path.join(os.path.dirname(__file__), "..", "azure.yaml") - def load_azure_config(self, config_file: str=AZURE_CONFIG_FILE) -> None: + def load_azure_config(self, config_file: str = AZURE_CONFIG_FILE) -> None: """ Loads the configuration parameters for Azure hosting from the specified file path as a yaml file. @@ -128,9 +137,15 @@ class Config(metaclass=Singleton): config_params = yaml.load(file, Loader=yaml.FullLoader) except FileNotFoundError: config_params = {} - self.openai_api_type = os.getenv("OPENAI_API_TYPE", config_params.get("azure_api_type", "azure")) - self.openai_api_base = os.getenv("OPENAI_AZURE_API_BASE", config_params.get("azure_api_base", "")) - self.openai_api_version = os.getenv("OPENAI_AZURE_API_VERSION", config_params.get("azure_api_version", "")) + self.openai_api_type = os.getenv( + "OPENAI_API_TYPE", config_params.get("azure_api_type", "azure") + ) + self.openai_api_base = os.getenv( + "OPENAI_AZURE_API_BASE", config_params.get("azure_api_base", "") + ) + self.openai_api_version = os.getenv( + "OPENAI_AZURE_API_VERSION", config_params.get("azure_api_version", "") + ) self.azure_model_to_deployment_id_map = config_params.get("azure_model_map", []) def set_continuous_mode(self, value: bool): diff --git a/autogpt/data_ingestion.py b/autogpt/data_ingestion.py index f8753240..b6a16435 100644 --- a/autogpt/data_ingestion.py +++ b/autogpt/data_ingestion.py @@ -1,19 +1,22 @@ import argparse import logging + from autogpt.config import Config -from autogpt.memory import get_memory from autogpt.file_operations import ingest_file, search_files +from autogpt.memory import get_memory cfg = Config() def configure_logging(): - logging.basicConfig(filename='log-ingestion.txt', - filemode='a', - format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s', - datefmt='%H:%M:%S', - level=logging.DEBUG) - return logging.getLogger('AutoGPT-Ingestion') + logging.basicConfig( + filename="log-ingestion.txt", + filemode="a", + format="%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s", + datefmt="%H:%M:%S", + level=logging.DEBUG, + ) + return logging.getLogger("AutoGPT-Ingestion") def ingest_directory(directory, memory, args): @@ -34,19 +37,38 @@ def ingest_directory(directory, memory, args): def main(): logger = configure_logging() - parser = argparse.ArgumentParser(description="Ingest a file or a directory with multiple files into memory. Make sure to set your .env before running this script.") + parser = argparse.ArgumentParser( + description="Ingest a file or a directory with multiple files into memory. Make sure to set your .env before running this script." + ) group = parser.add_mutually_exclusive_group(required=True) group.add_argument("--file", type=str, help="The file to ingest.") - group.add_argument("--dir", type=str, help="The directory containing the files to ingest.") - parser.add_argument("--init", action='store_true', help="Init the memory and wipe its content (default: False)", default=False) - parser.add_argument("--overlap", type=int, help="The overlap size between chunks when ingesting files (default: 200)", default=200) - parser.add_argument("--max_length", type=int, help="The max_length of each chunk when ingesting files (default: 4000)", default=4000) + group.add_argument( + "--dir", type=str, help="The directory containing the files to ingest." + ) + parser.add_argument( + "--init", + action="store_true", + help="Init the memory and wipe its content (default: False)", + default=False, + ) + parser.add_argument( + "--overlap", + type=int, + help="The overlap size between chunks when ingesting files (default: 200)", + default=200, + ) + parser.add_argument( + "--max_length", + type=int, + help="The max_length of each chunk when ingesting files (default: 4000)", + default=4000, + ) args = parser.parse_args() # Initialize memory memory = get_memory(cfg, init=args.init) - print('Using memory of type: ' + memory.__class__.__name__) + print("Using memory of type: " + memory.__class__.__name__) if args.file: try: @@ -63,7 +85,9 @@ def main(): logger.error(f"Error while ingesting directory '{args.dir}': {str(e)}") print(f"Error while ingesting directory '{args.dir}': {str(e)}") else: - print("Please provide either a file path (--file) or a directory name (--dir) inside the auto_gpt_workspace directory as input.") + print( + "Please provide either a file path (--file) or a directory name (--dir) inside the auto_gpt_workspace directory as input." + ) if __name__ == "__main__": diff --git a/autogpt/execute_code.py b/autogpt/execute_code.py index 45263d02..5171213f 100644 --- a/autogpt/execute_code.py +++ b/autogpt/execute_code.py @@ -1,7 +1,7 @@ -import docker import os import subprocess +import docker WORKSPACE_FOLDER = "auto_gpt_workspace" @@ -9,7 +9,7 @@ WORKSPACE_FOLDER = "auto_gpt_workspace" def execute_python_file(file): """Execute a Python file in a Docker container and return the output""" - print (f"Executing file '{file}' in workspace '{WORKSPACE_FOLDER}'") + print(f"Executing file '{file}' in workspace '{WORKSPACE_FOLDER}'") if not file.endswith(".py"): return "Error: Invalid file type. Only .py files are allowed." @@ -20,7 +20,9 @@ def execute_python_file(file): return f"Error: File '{file}' does not exist." if we_are_running_in_a_docker_container(): - result = subprocess.run(f'python {file_path}', capture_output=True, encoding="utf8", shell=True) + result = subprocess.run( + f"python {file_path}", capture_output=True, encoding="utf8", shell=True + ) if result.returncode == 0: return result.stdout else: @@ -29,18 +31,20 @@ def execute_python_file(file): try: client = docker.from_env() - image_name = 'python:3.10' + image_name = "python:3.10" try: client.images.get(image_name) print(f"Image '{image_name}' found locally") except docker.errors.ImageNotFound: - print(f"Image '{image_name}' not found locally, pulling from Docker Hub") + print( + f"Image '{image_name}' not found locally, pulling from Docker Hub" + ) # Use the low-level API to stream the pull response low_level_client = docker.APIClient() for line in low_level_client.pull(image_name, stream=True, decode=True): # Print the status and progress, if available - status = line.get('status') - progress = line.get('progress') + status = line.get("status") + progress = line.get("progress") if status and progress: print(f"{status}: {progress}") elif status: @@ -51,19 +55,21 @@ def execute_python_file(file): # https://hub.docker.com/_/python container = client.containers.run( image_name, - f'python {file}', + f"python {file}", volumes={ os.path.abspath(WORKSPACE_FOLDER): { - 'bind': '/workspace', - 'mode': 'ro'}}, - working_dir='/workspace', + "bind": "/workspace", + "mode": "ro", + } + }, + working_dir="/workspace", stderr=True, stdout=True, detach=True, ) output = container.wait() - logs = container.logs().decode('utf-8') + logs = container.logs().decode("utf-8") container.remove() # print(f"Execution complete. Output: {output}") @@ -76,14 +82,13 @@ def execute_python_file(file): def execute_shell(command_line): - current_dir = os.getcwd() - if not WORKSPACE_FOLDER in current_dir: # Change dir into workspace if necessary + if not WORKSPACE_FOLDER in current_dir: # Change dir into workspace if necessary work_dir = os.path.join(os.getcwd(), WORKSPACE_FOLDER) os.chdir(work_dir) - print (f"Executing command '{command_line}' in working directory '{os.getcwd()}'") + print(f"Executing command '{command_line}' in working directory '{os.getcwd()}'") result = subprocess.run(command_line, capture_output=True, shell=True) output = f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}" @@ -96,4 +101,4 @@ def execute_shell(command_line): def we_are_running_in_a_docker_container(): - os.path.exists('/.dockerenv') + os.path.exists("/.dockerenv") diff --git a/autogpt/file_operations.py b/autogpt/file_operations.py index 1a072561..22fd57ab 100644 --- a/autogpt/file_operations.py +++ b/autogpt/file_operations.py @@ -36,7 +36,7 @@ def split_file(content, max_length=4000, overlap=0): while start < content_length: end = start + max_length if end + overlap < content_length: - chunk = content[start:end+overlap] + chunk = content[start : end + overlap] else: chunk = content[start:content_length] yield chunk @@ -47,7 +47,7 @@ def read_file(filename): """Read a file and return the contents""" try: filepath = safe_join(working_directory, filename) - with open(filepath, "r", encoding='utf-8') as f: + with open(filepath, "r", encoding="utf-8") as f: content = f.read() return content except Exception as e: @@ -75,8 +75,9 @@ def ingest_file(filename, memory, max_length=4000, overlap=200): num_chunks = len(chunks) for i, chunk in enumerate(chunks): print(f"Ingesting chunk {i + 1} / {num_chunks} into memory") - memory_to_add = f"Filename: {filename}\n" \ - f"Content part#{i + 1}/{num_chunks}: {chunk}" + memory_to_add = ( + f"Filename: {filename}\n" f"Content part#{i + 1}/{num_chunks}: {chunk}" + ) memory.add(memory_to_add) @@ -92,7 +93,7 @@ def write_to_file(filename, text): directory = os.path.dirname(filepath) if not os.path.exists(directory): os.makedirs(directory) - with open(filepath, "w", encoding='utf-8') as f: + with open(filepath, "w", encoding="utf-8") as f: f.write(text) return "File written to successfully." except Exception as e: @@ -130,7 +131,7 @@ def search_files(directory): for root, _, files in os.walk(search_directory): for file in files: - if file.startswith('.'): + if file.startswith("."): continue relative_path = os.path.relpath(os.path.join(root, file), working_directory) found_files.append(relative_path) diff --git a/autogpt/image_gen.py b/autogpt/image_gen.py index cc5112e3..592e4875 100644 --- a/autogpt/image_gen.py +++ b/autogpt/image_gen.py @@ -1,24 +1,24 @@ -import requests import io import os.path -from PIL import Image -from autogpt.config import Config import uuid -import openai from base64 import b64decode +import openai +import requests +from PIL import Image + +from autogpt.config import Config + cfg = Config() working_directory = "auto_gpt_workspace" def generate_image(prompt): - filename = str(uuid.uuid4()) + ".jpg" # DALL-E - if cfg.image_provider == 'dalle': - + if cfg.image_provider == "dalle": openai.api_key = cfg.openai_api_key response = openai.Image.create( @@ -38,14 +38,19 @@ def generate_image(prompt): return "Saved to disk:" + filename # STABLE DIFFUSION - elif cfg.image_provider == 'sd': - - API_URL = "https://api-inference.huggingface.co/models/CompVis/stable-diffusion-v1-4" + elif cfg.image_provider == "sd": + API_URL = ( + "https://api-inference.huggingface.co/models/CompVis/stable-diffusion-v1-4" + ) headers = {"Authorization": "Bearer " + cfg.huggingface_api_token} - response = requests.post(API_URL, headers=headers, json={ - "inputs": prompt, - }) + response = requests.post( + API_URL, + headers=headers, + json={ + "inputs": prompt, + }, + ) image = Image.open(io.BytesIO(response.content)) print("Image Generated for prompt:" + prompt) diff --git a/autogpt/json_parser.py b/autogpt/json_parser.py index 36555d5f..6f1966d6 100644 --- a/autogpt/json_parser.py +++ b/autogpt/json_parser.py @@ -1,5 +1,6 @@ import json from typing import Any, Dict, Union + from autogpt.call_ai_function import call_ai_function from autogpt.config import Config from autogpt.json_utils import correct_json @@ -28,12 +29,11 @@ JSON_SCHEMA = """ def fix_and_parse_json( - json_str: str, - try_to_fix_with_gpt: bool = True + json_str: str, try_to_fix_with_gpt: bool = True ) -> Union[str, Dict[Any, Any]]: """Fix and parse JSON string""" try: - json_str = json_str.replace('\t', '') + json_str = json_str.replace("\t", "") return json.loads(json_str) except json.JSONDecodeError as _: # noqa: F841 try: @@ -52,15 +52,17 @@ def fix_and_parse_json( brace_index = json_str.index("{") json_str = json_str[brace_index:] last_brace_index = json_str.rindex("}") - json_str = json_str[:last_brace_index+1] + json_str = json_str[: last_brace_index + 1] return json.loads(json_str) # Can throw a ValueError if there is no "{" or "}" in the json_str except (json.JSONDecodeError, ValueError) as e: # noqa: F841 if try_to_fix_with_gpt: - logger.warn("Warning: Failed to parse AI output, attempting to fix." - "\n If you see this warning frequently, it's likely that" - " your prompt is confusing the AI. Try changing it up" - " slightly.") + logger.warn( + "Warning: Failed to parse AI output, attempting to fix." + "\n If you see this warning frequently, it's likely that" + " your prompt is confusing the AI. Try changing it up" + " slightly." + ) # Now try to fix this up using the ai_functions ai_fixed_json = fix_json(json_str, JSON_SCHEMA) @@ -80,11 +82,13 @@ def fix_json(json_str: str, schema: str) -> str: # Try to fix the JSON using GPT: function_string = "def fix_json(json_str: str, schema:str=None) -> str:" args = [f"'''{json_str}'''", f"'''{schema}'''"] - description_string = "Fixes the provided JSON string to make it parseable"\ - " and fully compliant with the provided schema.\n If an object or"\ - " field specified in the schema isn't contained within the correct"\ - " JSON, it is omitted.\n This function is brilliant at guessing"\ + description_string = ( + "Fixes the provided JSON string to make it parseable" + " and fully compliant with the provided schema.\n If an object or" + " field specified in the schema isn't contained within the correct" + " JSON, it is omitted.\n This function is brilliant at guessing" " when the format is incorrect." + ) # If it doesn't already start with a "`", add one: if not json_str.startswith("`"): diff --git a/autogpt/json_utils.py b/autogpt/json_utils.py index 8493f094..3e782198 100644 --- a/autogpt/json_utils.py +++ b/autogpt/json_utils.py @@ -1,5 +1,6 @@ -import re import json +import re + from autogpt.config import Config cfg = Config() @@ -17,7 +18,7 @@ def extract_char_position(error_message: str) -> int: """ import re - char_pattern = re.compile(r'\(char (\d+)\)') + char_pattern = re.compile(r"\(char (\d+)\)") if match := char_pattern.search(error_message): return int(match[1]) else: @@ -38,10 +39,8 @@ def add_quotes_to_property_names(json_string: str) -> str: def replace_func(match): return f'"{match.group(1)}":' - property_name_pattern = re.compile(r'(\w+):') - corrected_json_string = property_name_pattern.sub( - replace_func, - json_string) + property_name_pattern = re.compile(r"(\w+):") + corrected_json_string = property_name_pattern.sub(replace_func, json_string) try: json.loads(corrected_json_string) @@ -61,15 +60,15 @@ def balance_braces(json_string: str) -> str: str: The JSON string with braces balanced. """ - open_braces_count = json_string.count('{') - close_braces_count = json_string.count('}') + open_braces_count = json_string.count("{") + close_braces_count = json_string.count("}") while open_braces_count > close_braces_count: - json_string += '}' + json_string += "}" close_braces_count += 1 while close_braces_count > open_braces_count: - json_string = json_string.rstrip('}') + json_string = json_string.rstrip("}") close_braces_count -= 1 try: @@ -80,16 +79,15 @@ def balance_braces(json_string: str) -> str: def fix_invalid_escape(json_str: str, error_message: str) -> str: - while error_message.startswith('Invalid \\escape'): + while error_message.startswith("Invalid \\escape"): bad_escape_location = extract_char_position(error_message) - json_str = json_str[:bad_escape_location] + \ - json_str[bad_escape_location + 1:] + json_str = json_str[:bad_escape_location] + json_str[bad_escape_location + 1 :] try: json.loads(json_str) return json_str except json.JSONDecodeError as e: if cfg.debug_mode: - print('json loads error - fix invalid escape', e) + print("json loads error - fix invalid escape", e) error_message = str(e) return json_str @@ -109,18 +107,20 @@ def correct_json(json_str: str) -> str: return json_str except json.JSONDecodeError as e: if cfg.debug_mode: - print('json loads error', e) + print("json loads error", e) error_message = str(e) - if error_message.startswith('Invalid \\escape'): + if error_message.startswith("Invalid \\escape"): json_str = fix_invalid_escape(json_str, error_message) - if error_message.startswith('Expecting property name enclosed in double quotes'): + if error_message.startswith( + "Expecting property name enclosed in double quotes" + ): json_str = add_quotes_to_property_names(json_str) try: json.loads(json_str) return json_str except json.JSONDecodeError as e: if cfg.debug_mode: - print('json loads error - add quotes', e) + print("json loads error - add quotes", e) error_message = str(e) if balanced_str := balance_braces(json_str): return balanced_str diff --git a/autogpt/llm_utils.py b/autogpt/llm_utils.py index 24f47cc6..34e447b1 100644 --- a/autogpt/llm_utils.py +++ b/autogpt/llm_utils.py @@ -1,6 +1,8 @@ import time + import openai from colorama import Fore + from autogpt.config import Config cfg = Config() @@ -10,7 +12,9 @@ openai.api_key = cfg.openai_api_key # Overly simple abstraction until we create something better # simple retry mechanism when getting a rate error or a bad gateway -def create_chat_completion(messages, model=None, temperature=cfg.temperature, max_tokens=None)->str: +def create_chat_completion( + messages, model=None, temperature=cfg.temperature, max_tokens=None +) -> str: """Create a chat completion using the OpenAI API""" response = None num_retries = 5 @@ -22,24 +26,30 @@ def create_chat_completion(messages, model=None, temperature=cfg.temperature, ma model=model, messages=messages, temperature=temperature, - max_tokens=max_tokens + max_tokens=max_tokens, ) else: response = openai.ChatCompletion.create( model=model, messages=messages, temperature=temperature, - max_tokens=max_tokens + max_tokens=max_tokens, ) break except openai.error.RateLimitError: if cfg.debug_mode: - print(Fore.RED + "Error: ", "API Rate Limit Reached. Waiting 20 seconds..." + Fore.RESET) + print( + Fore.RED + "Error: ", + "API Rate Limit Reached. Waiting 20 seconds..." + Fore.RESET, + ) time.sleep(20) except openai.error.APIError as e: if e.http_status == 502: if cfg.debug_mode: - print(Fore.RED + "Error: ", "API Bad gateway. Waiting 20 seconds..." + Fore.RESET) + print( + Fore.RED + "Error: ", + "API Bad gateway. Waiting 20 seconds..." + Fore.RESET, + ) time.sleep(20) else: raise diff --git a/autogpt/logger.py b/autogpt/logger.py index 096d0891..0ae84704 100644 --- a/autogpt/logger.py +++ b/autogpt/logger.py @@ -4,35 +4,33 @@ import random import re import time from logging import LogRecord -from colorama import Fore -from colorama import Style +from colorama import Fore, Style from autogpt import speak -from autogpt.config import Config -from autogpt.config import Singleton +from autogpt.config import Config, Singleton cfg = Config() -''' +""" Logger that handle titles in different colors. Outputs logs in console, activity.log, and errors.log For console handler: simulates typing -''' +""" class Logger(metaclass=Singleton): def __init__(self): # create log directory if it doesn't exist this_files_dir_path = os.path.dirname(__file__) - log_dir = os.path.join(this_files_dir_path, '../logs') + log_dir = os.path.join(this_files_dir_path, "../logs") if not os.path.exists(log_dir): os.makedirs(log_dir) log_file = "activity.log" error_file = "error.log" - console_formatter = AutoGptFormatter('%(title_color)s %(message)s') + console_formatter = AutoGptFormatter("%(title_color)s %(message)s") # Create a handler for console which simulate typing self.typing_console_handler = TypingConsoleHandler() @@ -47,35 +45,34 @@ class Logger(metaclass=Singleton): # Info handler in activity.log self.file_handler = logging.FileHandler(os.path.join(log_dir, log_file)) self.file_handler.setLevel(logging.DEBUG) - info_formatter = AutoGptFormatter('%(asctime)s %(levelname)s %(title)s %(message_no_color)s') + info_formatter = AutoGptFormatter( + "%(asctime)s %(levelname)s %(title)s %(message_no_color)s" + ) self.file_handler.setFormatter(info_formatter) # Error handler error.log error_handler = logging.FileHandler(os.path.join(log_dir, error_file)) error_handler.setLevel(logging.ERROR) error_formatter = AutoGptFormatter( - '%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s %(message_no_color)s') + "%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s %(message_no_color)s" + ) error_handler.setFormatter(error_formatter) - self.typing_logger = logging.getLogger('TYPER') + self.typing_logger = logging.getLogger("TYPER") self.typing_logger.addHandler(self.typing_console_handler) self.typing_logger.addHandler(self.file_handler) self.typing_logger.addHandler(error_handler) self.typing_logger.setLevel(logging.DEBUG) - self.logger = logging.getLogger('LOGGER') + self.logger = logging.getLogger("LOGGER") self.logger.addHandler(self.console_handler) self.logger.addHandler(self.file_handler) self.logger.addHandler(error_handler) self.logger.setLevel(logging.DEBUG) def typewriter_log( - self, - title='', - title_color='', - content='', - speak_text=False, - level=logging.INFO): + self, title="", title_color="", content="", speak_text=False, level=logging.INFO + ): if speak_text and cfg.speak_mode: speak.say_text(f"{title}. {content}") @@ -85,41 +82,34 @@ class Logger(metaclass=Singleton): else: content = "" - self.typing_logger.log(level, content, extra={'title': title, 'color': title_color}) + self.typing_logger.log( + level, content, extra={"title": title, "color": title_color} + ) def debug( - self, - message, - title='', - title_color='', + self, + message, + title="", + title_color="", ): self._log(title, title_color, message, logging.DEBUG) def warn( - self, - message, - title='', - title_color='', + self, + message, + title="", + title_color="", ): self._log(title, title_color, message, logging.WARN) - def error( - self, - title, - message='' - ): + def error(self, title, message=""): self._log(title, Fore.RED, message, logging.ERROR) - def _log( - self, - title='', - title_color='', - message='', - level=logging.INFO): + def _log(self, title="", title_color="", message="", level=logging.INFO): if message: if isinstance(message, list): message = " ".join(message) - self.logger.log(level, message, extra={'title': title, 'color': title_color}) + self.logger.log(level, message, extra={"title": title, "color": title_color}) def set_level(self, level): self.logger.setLevel(level) @@ -132,9 +122,9 @@ class Logger(metaclass=Singleton): self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText) -''' +""" Output stream to console using simulated typing -''' +""" class TypingConsoleHandler(logging.StreamHandler): @@ -173,21 +163,27 @@ class AutoGptFormatter(logging.Formatter): Allows to handle custom placeholders 'title_color' and 'message_no_color'. To use this formatter, make sure to pass 'color', 'title' as log extras. """ + def format(self, record: LogRecord) -> str: - if (hasattr(record, 'color')): - record.title_color = getattr(record, 'color') + getattr(record, 'title') + " " + Style.RESET_ALL + if hasattr(record, "color"): + record.title_color = ( + getattr(record, "color") + + getattr(record, "title") + + " " + + Style.RESET_ALL + ) else: - record.title_color = getattr(record, 'title') - if hasattr(record, 'msg'): - record.message_no_color = remove_color_codes(getattr(record, 'msg')) + record.title_color = getattr(record, "title") + if hasattr(record, "msg"): + record.message_no_color = remove_color_codes(getattr(record, "msg")) else: - record.message_no_color = '' + record.message_no_color = "" return super().format(record) def remove_color_codes(s: str) -> str: - ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])') - return ansi_escape.sub('', s) + ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])") + return ansi_escape.sub("", s) logger = Logger() diff --git a/autogpt/memory/__init__.py b/autogpt/memory/__init__.py index 5cd5767f..42ba5a65 100644 --- a/autogpt/memory/__init__.py +++ b/autogpt/memory/__init__.py @@ -1,19 +1,22 @@ from autogpt.memory.local import LocalCache from autogpt.memory.no_memory import NoMemory + # List of supported memory backends # Add a backend to this list if the import attempt is successful -supported_memory = ['local', 'no_memory'] +supported_memory = ["local", "no_memory"] try: from autogpt.memory.redismem import RedisMemory - supported_memory.append('redis') + + supported_memory.append("redis") except ImportError: print("Redis not installed. Skipping import.") RedisMemory = None try: from autogpt.memory.pinecone import PineconeMemory - supported_memory.append('pinecone') + + supported_memory.append("pinecone") except ImportError: print("Pinecone not installed. Skipping import.") PineconeMemory = None @@ -23,16 +26,20 @@ def get_memory(cfg, init=False): memory = None if cfg.memory_backend == "pinecone": if not PineconeMemory: - print("Error: Pinecone is not installed. Please install pinecone" - " to use Pinecone as a memory backend.") + print( + "Error: Pinecone is not installed. Please install pinecone" + " to use Pinecone as a memory backend." + ) else: memory = PineconeMemory(cfg) if init: memory.clear() elif cfg.memory_backend == "redis": if not RedisMemory: - print("Error: Redis is not installed. Please install redis-py to" - " use Redis as a memory backend.") + print( + "Error: Redis is not installed. Please install redis-py to" + " use Redis as a memory backend." + ) else: memory = RedisMemory(cfg) elif cfg.memory_backend == "no_memory": @@ -49,10 +56,4 @@ def get_supported_memory_backends(): return supported_memory -__all__ = [ - "get_memory", - "LocalCache", - "RedisMemory", - "PineconeMemory", - "NoMemory" -] +__all__ = ["get_memory", "LocalCache", "RedisMemory", "PineconeMemory", "NoMemory"] diff --git a/autogpt/memory/base.py b/autogpt/memory/base.py index 6b1f083c..691e2299 100644 --- a/autogpt/memory/base.py +++ b/autogpt/memory/base.py @@ -1,17 +1,24 @@ """Base class for memory providers.""" import abc -from autogpt.config import AbstractSingleton, Config + import openai +from autogpt.config import AbstractSingleton, Config + cfg = Config() def get_ada_embedding(text): text = text.replace("\n", " ") if cfg.use_azure: - return openai.Embedding.create(input=[text], engine=cfg.get_azure_deployment_id_for_model("text-embedding-ada-002"))["data"][0]["embedding"] + return openai.Embedding.create( + input=[text], + engine=cfg.get_azure_deployment_id_for_model("text-embedding-ada-002"), + )["data"][0]["embedding"] else: - return openai.Embedding.create(input=[text], model="text-embedding-ada-002")["data"][0]["embedding"] + return openai.Embedding.create(input=[text], model="text-embedding-ada-002")[ + "data" + ][0]["embedding"] class MemoryProviderSingleton(AbstractSingleton): diff --git a/autogpt/memory/local.py b/autogpt/memory/local.py index 23f632df..67f040ae 100644 --- a/autogpt/memory/local.py +++ b/autogpt/memory/local.py @@ -1,10 +1,11 @@ import dataclasses -import orjson -from typing import Any, List, Optional -import numpy as np import os -from autogpt.memory.base import MemoryProviderSingleton, get_ada_embedding +from typing import Any, List, Optional +import numpy as np +import orjson + +from autogpt.memory.base import MemoryProviderSingleton, get_ada_embedding EMBED_DIM = 1536 SAVE_OPTIONS = orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_SERIALIZE_DATACLASS @@ -23,16 +24,15 @@ class CacheContent: class LocalCache(MemoryProviderSingleton): - # on load, load our database def __init__(self, cfg) -> None: self.filename = f"{cfg.memory_index}.json" if os.path.exists(self.filename): try: - with open(self.filename, 'w+b') as f: + with open(self.filename, "w+b") as f: file_content = f.read() if not file_content.strip(): - file_content = b'{}' + file_content = b"{}" f.write(file_content) loaded = orjson.loads(file_content) @@ -41,7 +41,9 @@ class LocalCache(MemoryProviderSingleton): print(f"Error: The file '{self.filename}' is not in JSON format.") self.data = CacheContent() else: - print(f"Warning: The file '{self.filename}' does not exist. Local memory would not be saved to a file.") + print( + f"Warning: The file '{self.filename}' does not exist. Local memory would not be saved to a file." + ) self.data = CacheContent() def add(self, text: str): @@ -54,7 +56,7 @@ class LocalCache(MemoryProviderSingleton): Returns: None """ - if 'Command Error:' in text: + if "Command Error:" in text: return "" self.data.texts.append(text) @@ -70,11 +72,8 @@ class LocalCache(MemoryProviderSingleton): axis=0, ) - with open(self.filename, 'wb') as f: - out = orjson.dumps( - self.data, - option=SAVE_OPTIONS - ) + with open(self.filename, "wb") as f: + out = orjson.dumps(self.data, option=SAVE_OPTIONS) f.write(out) return text @@ -99,7 +98,7 @@ class LocalCache(MemoryProviderSingleton): return self.get_relevant(data, 1) def get_relevant(self, text: str, k: int) -> List[Any]: - """" + """ " matrix-vector mult to find score-for-each-row-of-matrix get indices for top-k winning scores return texts for those indices diff --git a/autogpt/memory/pinecone.py b/autogpt/memory/pinecone.py index 877e0b3d..bce68e1a 100644 --- a/autogpt/memory/pinecone.py +++ b/autogpt/memory/pinecone.py @@ -1,11 +1,10 @@ -from autogpt.config import Config, Singleton - import pinecone - -from autogpt.memory.base import MemoryProviderSingleton, get_ada_embedding -from autogpt.logger import logger from colorama import Fore, Style +from autogpt.config import Config, Singleton +from autogpt.logger import logger +from autogpt.memory.base import MemoryProviderSingleton, get_ada_embedding + class PineconeMemory(MemoryProviderSingleton): def __init__(self, cfg): @@ -24,13 +23,21 @@ class PineconeMemory(MemoryProviderSingleton): try: pinecone.whoami() except Exception as e: - logger.typewriter_log("FAILED TO CONNECT TO PINECONE", Fore.RED, Style.BRIGHT + str(e) + Style.RESET_ALL) - logger.double_check("Please ensure you have setup and configured Pinecone properly for use. " + - f"You can check out {Fore.CYAN + Style.BRIGHT}https://github.com/Torantulino/Auto-GPT#-pinecone-api-key-setup{Style.RESET_ALL} to ensure you've set up everything correctly.") + logger.typewriter_log( + "FAILED TO CONNECT TO PINECONE", + Fore.RED, + Style.BRIGHT + str(e) + Style.RESET_ALL, + ) + logger.double_check( + "Please ensure you have setup and configured Pinecone properly for use. " + + f"You can check out {Fore.CYAN + Style.BRIGHT}https://github.com/Torantulino/Auto-GPT#-pinecone-api-key-setup{Style.RESET_ALL} to ensure you've set up everything correctly." + ) exit(1) if table_name not in pinecone.list_indexes(): - pinecone.create_index(table_name, dimension=dimension, metric=metric, pod_type=pod_type) + pinecone.create_index( + table_name, dimension=dimension, metric=metric, pod_type=pod_type + ) self.index = pinecone.Index(table_name) def add(self, data): @@ -55,9 +62,11 @@ class PineconeMemory(MemoryProviderSingleton): :param num_relevant: The number of relevant data to return. Defaults to 5 """ query_embedding = get_ada_embedding(data) - results = self.index.query(query_embedding, top_k=num_relevant, include_metadata=True) + results = self.index.query( + query_embedding, top_k=num_relevant, include_metadata=True + ) sorted_results = sorted(results.matches, key=lambda x: x.score) - return [str(item['metadata']["raw_text"]) for item in sorted_results] + return [str(item["metadata"]["raw_text"]) for item in sorted_results] def get_stats(self): return self.index.describe_index_stats() diff --git a/autogpt/memory/redismem.py b/autogpt/memory/redismem.py index febfd3a8..d36594ba 100644 --- a/autogpt/memory/redismem.py +++ b/autogpt/memory/redismem.py @@ -1,26 +1,22 @@ """Redis memory provider.""" from typing import Any, List, Optional -import redis -from redis.commands.search.field import VectorField, TextField -from redis.commands.search.query import Query -from redis.commands.search.indexDefinition import IndexDefinition, IndexType + import numpy as np - -from autogpt.memory.base import MemoryProviderSingleton, get_ada_embedding -from autogpt.logger import logger +import redis from colorama import Fore, Style +from redis.commands.search.field import TextField, VectorField +from redis.commands.search.indexDefinition import IndexDefinition, IndexType +from redis.commands.search.query import Query +from autogpt.logger import logger +from autogpt.memory.base import MemoryProviderSingleton, get_ada_embedding SCHEMA = [ TextField("data"), VectorField( "embedding", "HNSW", - { - "TYPE": "FLOAT32", - "DIM": 1536, - "DISTANCE_METRIC": "COSINE" - } + {"TYPE": "FLOAT32", "DIM": 1536, "DISTANCE_METRIC": "COSINE"}, ), ] @@ -43,7 +39,7 @@ class RedisMemory(MemoryProviderSingleton): host=redis_host, port=redis_port, password=redis_password, - db=0 # Cannot be changed + db=0, # Cannot be changed ) self.cfg = cfg @@ -51,9 +47,15 @@ class RedisMemory(MemoryProviderSingleton): try: self.redis.ping() except redis.ConnectionError as e: - logger.typewriter_log("FAILED TO CONNECT TO REDIS", Fore.RED, Style.BRIGHT + str(e) + Style.RESET_ALL) - logger.double_check("Please ensure you have setup and configured Redis properly for use. " + - f"You can check out {Fore.CYAN + Style.BRIGHT}https://github.com/Torantulino/Auto-GPT#redis-setup{Style.RESET_ALL} to ensure you've set up everything correctly.") + logger.typewriter_log( + "FAILED TO CONNECT TO REDIS", + Fore.RED, + Style.BRIGHT + str(e) + Style.RESET_ALL, + ) + logger.double_check( + "Please ensure you have setup and configured Redis properly for use. " + + f"You can check out {Fore.CYAN + Style.BRIGHT}https://github.com/Torantulino/Auto-GPT#redis-setup{Style.RESET_ALL} to ensure you've set up everything correctly." + ) exit(1) if cfg.wipe_redis_on_start: @@ -62,15 +64,13 @@ class RedisMemory(MemoryProviderSingleton): self.redis.ft(f"{cfg.memory_index}").create_index( fields=SCHEMA, definition=IndexDefinition( - prefix=[f"{cfg.memory_index}:"], - index_type=IndexType.HASH - ) - ) + prefix=[f"{cfg.memory_index}:"], index_type=IndexType.HASH + ), + ) except Exception as e: print("Error creating Redis search index: ", e) - existing_vec_num = self.redis.get(f'{cfg.memory_index}-vec_num') - self.vec_num = int(existing_vec_num.decode('utf-8')) if\ - existing_vec_num else 0 + existing_vec_num = self.redis.get(f"{cfg.memory_index}-vec_num") + self.vec_num = int(existing_vec_num.decode("utf-8")) if existing_vec_num else 0 def add(self, data: str) -> str: """ @@ -81,20 +81,18 @@ class RedisMemory(MemoryProviderSingleton): Returns: Message indicating that the data has been added. """ - if 'Command Error:' in data: + if "Command Error:" in data: return "" vector = get_ada_embedding(data) vector = np.array(vector).astype(np.float32).tobytes() - data_dict = { - b"data": data, - "embedding": vector - } + data_dict = {b"data": data, "embedding": vector} pipe = self.redis.pipeline() pipe.hset(f"{self.cfg.memory_index}:{self.vec_num}", mapping=data_dict) - _text = f"Inserting data into memory at index: {self.vec_num}:\n"\ - f"data: {data}" + _text = ( + f"Inserting data into memory at index: {self.vec_num}:\n" f"data: {data}" + ) self.vec_num += 1 - pipe.set(f'{self.cfg.memory_index}-vec_num', self.vec_num) + pipe.set(f"{self.cfg.memory_index}-vec_num", self.vec_num) pipe.execute() return _text @@ -118,11 +116,7 @@ class RedisMemory(MemoryProviderSingleton): self.redis.flushall() return "Obliviated" - def get_relevant( - self, - data: str, - num_relevant: int = 5 - ) -> Optional[List[Any]]: + def get_relevant(self, data: str, num_relevant: int = 5) -> Optional[List[Any]]: """ Returns all the data in the memory that is relevant to the given data. Args: @@ -133,10 +127,12 @@ class RedisMemory(MemoryProviderSingleton): """ query_embedding = get_ada_embedding(data) base_query = f"*=>[KNN {num_relevant} @embedding $vector AS vector_score]" - query = Query(base_query).return_fields( - "data", - "vector_score" - ).sort_by("vector_score").dialect(2) + query = ( + Query(base_query) + .return_fields("data", "vector_score") + .sort_by("vector_score") + .dialect(2) + ) query_vector = np.array(query_embedding).astype(np.float32).tobytes() try: diff --git a/autogpt/prompt.py b/autogpt/prompt.py index 4ea70749..8e65388d 100644 --- a/autogpt/prompt.py +++ b/autogpt/prompt.py @@ -13,17 +13,35 @@ def get_prompt(): prompt_generator = PromptGenerator() # Add constraints to the PromptGenerator object - prompt_generator.add_constraint("~4000 word limit for short term memory. Your short term memory is short, so immediately save important information to files.") - prompt_generator.add_constraint("If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember.") + prompt_generator.add_constraint( + "~4000 word limit for short term memory. Your short term memory is short, so immediately save important information to files." + ) + prompt_generator.add_constraint( + "If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember." + ) prompt_generator.add_constraint("No user assistance") - prompt_generator.add_constraint('Exclusively use the commands listed in double quotes e.g. "command name"') + prompt_generator.add_constraint( + 'Exclusively use the commands listed in double quotes e.g. "command name"' + ) # Define the command list commands = [ ("Google Search", "google", {"input": ""}), - ("Browse Website", "browse_website", {"url": "", "question": ""}), - ("Start GPT Agent", "start_agent", {"name": "", "task": "", "prompt": ""}), - ("Message GPT Agent", "message_agent", {"key": "", "message": ""}), + ( + "Browse Website", + "browse_website", + {"url": "", "question": ""}, + ), + ( + "Start GPT Agent", + "start_agent", + {"name": "", "task": "", "prompt": ""}, + ), + ( + "Message GPT Agent", + "message_agent", + {"key": "", "message": ""}, + ), ("List GPT Agents", "list_agents", {}), ("Delete GPT Agent", "delete_agent", {"key": ""}), ("Write to file", "write_to_file", {"file": "", "text": ""}), @@ -32,10 +50,22 @@ def get_prompt(): ("Delete file", "delete_file", {"file": ""}), ("Search Files", "search_files", {"directory": ""}), ("Evaluate Code", "evaluate_code", {"code": ""}), - ("Get Improved Code", "improve_code", {"suggestions": "", "code": ""}), - ("Write Tests", "write_tests", {"code": "", "focus": ""}), + ( + "Get Improved Code", + "improve_code", + {"suggestions": "", "code": ""}, + ), + ( + "Write Tests", + "write_tests", + {"code": "", "focus": ""}, + ), ("Execute Python File", "execute_python_file", {"file": ""}), - ("Execute Shell Command, non-interactive commands only", "execute_shell", { "command_line": ""}), + ( + "Execute Shell Command, non-interactive commands only", + "execute_shell", + {"command_line": ""}, + ), ("Task Complete (Shutdown)", "task_complete", {"reason": ""}), ("Generate Image", "generate_image", {"prompt": ""}), ("Do Nothing", "do_nothing", {}), @@ -46,16 +76,28 @@ def get_prompt(): prompt_generator.add_command(command_label, command_name, args) # Add resources to the PromptGenerator object - prompt_generator.add_resource("Internet access for searches and information gathering.") + prompt_generator.add_resource( + "Internet access for searches and information gathering." + ) prompt_generator.add_resource("Long Term memory management.") - prompt_generator.add_resource("GPT-3.5 powered Agents for delegation of simple tasks.") + prompt_generator.add_resource( + "GPT-3.5 powered Agents for delegation of simple tasks." + ) prompt_generator.add_resource("File output.") # Add performance evaluations to the PromptGenerator object - prompt_generator.add_performance_evaluation("Continuously review and analyze your actions to ensure you are performing to the best of your abilities.") - prompt_generator.add_performance_evaluation("Constructively self-criticize your big-picture behavior constantly.") - prompt_generator.add_performance_evaluation("Reflect on past decisions and strategies to refine your approach.") - prompt_generator.add_performance_evaluation("Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps.") + prompt_generator.add_performance_evaluation( + "Continuously review and analyze your actions to ensure you are performing to the best of your abilities." + ) + prompt_generator.add_performance_evaluation( + "Constructively self-criticize your big-picture behavior constantly." + ) + prompt_generator.add_performance_evaluation( + "Reflect on past decisions and strategies to refine your approach." + ) + prompt_generator.add_performance_evaluation( + "Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps." + ) # Generate the prompt string prompt_string = prompt_generator.generate_prompt_string() diff --git a/autogpt/promptgenerator.py b/autogpt/promptgenerator.py index 6cfd9bcd..c10878b4 100644 --- a/autogpt/promptgenerator.py +++ b/autogpt/promptgenerator.py @@ -20,14 +20,9 @@ class PromptGenerator: "reasoning": "reasoning", "plan": "- short bulleted\n- list that conveys\n- long-term plan", "criticism": "constructive self-criticism", - "speak": "thoughts summary to say to user" + "speak": "thoughts summary to say to user", }, - "command": { - "name": "command name", - "args": { - "arg name": "value" - } - } + "command": {"name": "command name", "args": {"arg name": "value"}}, } def add_constraint(self, constraint): @@ -51,8 +46,7 @@ class PromptGenerator: if args is None: args = {} - command_args = {arg_key: arg_value for arg_key, - arg_value in args.items()} + command_args = {arg_key: arg_value for arg_key, arg_value in args.items()} command = { "label": command_label, @@ -72,8 +66,9 @@ class PromptGenerator: Returns: str: The formatted command string. """ - args_string = ', '.join( - f'"{key}": "{value}"' for key, value in command['args'].items()) + args_string = ", ".join( + f'"{key}": "{value}"' for key, value in command["args"].items() + ) return f'{command["label"]}: "{command["name"]}", args: {args_string}' def add_resource(self, resource): @@ -94,7 +89,7 @@ class PromptGenerator: """ self.performance_evaluation.append(evaluation) - def _generate_numbered_list(self, items, item_type='list'): + def _generate_numbered_list(self, items, item_type="list"): """ Generate a numbered list from given items based on the item_type. @@ -105,8 +100,11 @@ class PromptGenerator: Returns: str: The formatted numbered list. """ - if item_type == 'command': - return "\n".join(f"{i+1}. {self._generate_command_string(item)}" for i, item in enumerate(items)) + if item_type == "command": + return "\n".join( + f"{i+1}. {self._generate_command_string(item)}" + for i, item in enumerate(items) + ) else: return "\n".join(f"{i+1}. {item}" for i, item in enumerate(items)) diff --git a/autogpt/speak.py b/autogpt/speak.py index 9fadaa0e..cabfd1ca 100644 --- a/autogpt/speak.py +++ b/autogpt/speak.py @@ -1,12 +1,16 @@ import os -from playsound import playsound + import requests +from playsound import playsound + from autogpt.config import Config + cfg = Config() -import gtts import threading from threading import Lock, Semaphore +import gtts + # Default voice IDs default_voices = ["ErXwobaYiN019PkySvjV", "EXAVITQu4vr4xnSDxMaL"] @@ -19,26 +23,29 @@ placeholders = {"your-voice-id"} # Use custom voice IDs if provided and not placeholders, otherwise use default voice IDs voices = [ - custom_voice_1 if custom_voice_1 and custom_voice_1 not in placeholders else default_voices[0], - custom_voice_2 if custom_voice_2 and custom_voice_2 not in placeholders else default_voices[1] + custom_voice_1 + if custom_voice_1 and custom_voice_1 not in placeholders + else default_voices[0], + custom_voice_2 + if custom_voice_2 and custom_voice_2 not in placeholders + else default_voices[1], ] -tts_headers = { - "Content-Type": "application/json", - "xi-api-key": cfg.elevenlabs_api_key -} +tts_headers = {"Content-Type": "application/json", "xi-api-key": cfg.elevenlabs_api_key} -mutex_lock = Lock() # Ensure only one sound is played at a time -queue_semaphore = Semaphore(1) # The amount of sounds to queue before blocking the main thread +mutex_lock = Lock() # Ensure only one sound is played at a time +queue_semaphore = Semaphore( + 1 +) # The amount of sounds to queue before blocking the main thread def eleven_labs_speech(text, voice_index=0): """Speak text using elevenlabs.io's API""" tts_url = "https://api.elevenlabs.io/v1/text-to-speech/{voice_id}".format( - voice_id=voices[voice_index]) + voice_id=voices[voice_index] + ) formatted_message = {"text": text} - response = requests.post( - tts_url, headers=tts_headers, json=formatted_message) + response = requests.post(tts_url, headers=tts_headers, json=formatted_message) if response.status_code == 200: with mutex_lock: @@ -90,12 +97,11 @@ def macos_tts_speech(text, voice_index=0): def say_text(text, voice_index=0): - def speak(): if not cfg.elevenlabs_api_key: - if cfg.use_mac_os_tts == 'True': + if cfg.use_mac_os_tts == "True": macos_tts_speech(text) - elif cfg.use_brian_tts == 'True': + elif cfg.use_brian_tts == "True": success = brian_speech(text) if not success: gtts_speech(text) diff --git a/autogpt/spinner.py b/autogpt/spinner.py index d2321529..fb7f94f6 100644 --- a/autogpt/spinner.py +++ b/autogpt/spinner.py @@ -1,14 +1,15 @@ +import itertools import sys import threading -import itertools import time class Spinner: """A simple spinner class""" + def __init__(self, message="Loading...", delay=0.1): """Initialize the spinner class""" - self.spinner = itertools.cycle(['-', '/', '|', '\\']) + self.spinner = itertools.cycle(["-", "/", "|", "\\"]) self.delay = delay self.message = message self.running = False diff --git a/autogpt/token_counter.py b/autogpt/token_counter.py index 8aecf168..64cc7b75 100644 --- a/autogpt/token_counter.py +++ b/autogpt/token_counter.py @@ -1,8 +1,11 @@ +from typing import Dict, List + import tiktoken -from typing import List, Dict -def count_message_tokens(messages : List[Dict[str, str]], model : str = "gpt-3.5-turbo-0301") -> int: +def count_message_tokens( + messages: List[Dict[str, str]], model: str = "gpt-3.5-turbo-0301" +) -> int: """ Returns the number of tokens used by a list of messages. @@ -25,13 +28,17 @@ def count_message_tokens(messages : List[Dict[str, str]], model : str = "gpt-3.5 # !Note: gpt-4 may change over time. Returning num tokens assuming gpt-4-0314.") return count_message_tokens(messages, model="gpt-4-0314") elif model == "gpt-3.5-turbo-0301": - tokens_per_message = 4 # every message follows <|start|>{role/name}\n{content}<|end|>\n + tokens_per_message = ( + 4 # every message follows <|start|>{role/name}\n{content}<|end|>\n + ) tokens_per_name = -1 # if there's a name, the role is omitted elif model == "gpt-4-0314": tokens_per_message = 3 tokens_per_name = 1 else: - raise NotImplementedError(f"""num_tokens_from_messages() is not implemented for model {model}. See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.""") + raise NotImplementedError( + f"""num_tokens_from_messages() is not implemented for model {model}. See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.""" + ) num_tokens = 0 for message in messages: num_tokens += tokens_per_message diff --git a/autogpt/utils.py b/autogpt/utils.py index 7521df29..e697bc0b 100644 --- a/autogpt/utils.py +++ b/autogpt/utils.py @@ -2,7 +2,7 @@ import yaml from colorama import Fore -def clean_input(prompt: str=''): +def clean_input(prompt: str = ""): try: return input(prompt) except KeyboardInterrupt: @@ -18,6 +18,9 @@ def validate_yaml_file(file: str): except FileNotFoundError: return (False, f"The file {Fore.CYAN}`{file}`{Fore.RESET} wasn't found") except yaml.YAMLError as e: - return (False, f"There was an issue while trying to read with your AI Settings file: {e}") + return ( + False, + f"There was an issue while trying to read with your AI Settings file: {e}", + ) return (True, f"Successfully validated {Fore.CYAN}`{file}`{Fore.RESET}!") diff --git a/scripts/main.py b/scripts/main.py index b451e977..b6871d1c 100644 --- a/scripts/main.py +++ b/scripts/main.py @@ -1,9 +1,11 @@ -from colorama import init, Style +from colorama import Style, init # Initialize colorama init(autoreset=True) # Use the bold ANSI style -print(f"""{Style.BRIGHT}Please run: +print( + f"""{Style.BRIGHT}Please run: python -m autogpt -""") +""" +) diff --git a/tests.py b/tests.py index 487e0038..46f802f6 100644 --- a/tests.py +++ b/tests.py @@ -2,7 +2,7 @@ import unittest if __name__ == "__main__": # Load all tests from the 'autogpt/tests' package - suite = unittest.defaultTestLoader.discover('autogpt/tests') + suite = unittest.defaultTestLoader.discover("autogpt/tests") # Run the tests unittest.TextTestRunner().run(suite) diff --git a/tests/context.py b/tests/context.py index b668c8dc..cef969db 100644 --- a/tests/context.py +++ b/tests/context.py @@ -1,5 +1,6 @@ -import sys import os +import sys -sys.path.insert(0, os.path.abspath( - os.path.join(os.path.dirname(__file__), '../scripts'))) +sys.path.insert( + 0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../scripts")) +) diff --git a/tests/integration/memory_tests.py b/tests/integration/memory_tests.py index ea96c4c2..eead2da1 100644 --- a/tests/integration/memory_tests.py +++ b/tests/integration/memory_tests.py @@ -1,17 +1,16 @@ -import unittest import random import string import sys +import unittest from pathlib import Path + from autogpt.config import Config from autogpt.memory.local import LocalCache class TestLocalCache(unittest.TestCase): - def random_string(self, length): - return ''.join( - random.choice(string.ascii_letters) for _ in range(length)) + return "".join(random.choice(string.ascii_letters) for _ in range(length)) def setUp(self): cfg = cfg = Config() @@ -20,10 +19,10 @@ class TestLocalCache(unittest.TestCase): # Add example texts to the cache self.example_texts = [ - 'The quick brown fox jumps over the lazy dog', - 'I love machine learning and natural language processing', - 'The cake is a lie, but the pie is always true', - 'ChatGPT is an advanced AI model for conversation' + "The quick brown fox jumps over the lazy dog", + "I love machine learning and natural language processing", + "The cake is a lie, but the pie is always true", + "ChatGPT is an advanced AI model for conversation", ] for text in self.example_texts: @@ -46,5 +45,5 @@ class TestLocalCache(unittest.TestCase): self.assertIn(self.example_texts[1], relevant_texts) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/tests/local_cache_test.py b/tests/local_cache_test.py index 601b11d8..9ac6aa54 100644 --- a/tests/local_cache_test.py +++ b/tests/local_cache_test.py @@ -5,16 +5,19 @@ from autogpt.memory.local import LocalCache def MockConfig(): - return type('MockConfig', (object,), { - 'debug_mode': False, - 'continuous_mode': False, - 'speak_mode': False, - 'memory_index': 'auto-gpt', - }) + return type( + "MockConfig", + (object,), + { + "debug_mode": False, + "continuous_mode": False, + "speak_mode": False, + "memory_index": "auto-gpt", + }, + ) class TestLocalCache(unittest.TestCase): - def setUp(self): self.cfg = MockConfig() self.cache = LocalCache(self.cfg) @@ -49,5 +52,5 @@ class TestLocalCache(unittest.TestCase): self.assertEqual(stats, (1, self.cache.data.embeddings.shape)) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/tests/promptgenerator_tests.py b/tests/promptgenerator_tests.py index aac70b5e..b700af49 100644 --- a/tests/promptgenerator_tests.py +++ b/tests/promptgenerator_tests.py @@ -1,14 +1,13 @@ # Import the required libraries for unit testing -import unittest -import sys import os +import sys +import unittest from autogpt.promptgenerator import PromptGenerator # Create a test class for the PromptGenerator, subclassed from unittest.TestCase class promptgenerator_tests(unittest.TestCase): - # Set up the initial state for each test method by creating an instance of PromptGenerator def setUp(self): self.generator = PromptGenerator() @@ -67,7 +66,8 @@ class promptgenerator_tests(unittest.TestCase): self.generator.add_constraint(constraint) for command in commands: self.generator.add_command( - command["label"], command["name"], command["args"]) + command["label"], command["name"], command["args"] + ) for resource in resources: self.generator.add_resource(resource) for evaluation in evaluations: @@ -95,5 +95,5 @@ class promptgenerator_tests(unittest.TestCase): # Run the tests when this script is executed -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/tests/test_config.py b/tests/test_config.py index af5fb2a8..52613b30 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,9 +1,9 @@ import unittest + from autogpt.config import Config class TestConfig(unittest.TestCase): - def test_singleton(self): config1 = Config() config2 = Config() @@ -55,5 +55,5 @@ class TestConfig(unittest.TestCase): self.assertTrue(config.debug_mode) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/tests/test_json_parser.py b/tests/test_json_parser.py index c9d5e14b..7e3d4f51 100644 --- a/tests/test_json_parser.py +++ b/tests/test_json_parser.py @@ -1,6 +1,6 @@ import unittest -import tests.context +import tests.context from autogpt.json_parser import fix_and_parse_json @@ -21,7 +21,7 @@ class TestParseJson(unittest.TestCase): # Test that an invalid JSON string raises an error when try_to_fix_with_gpt is False json_str = 'BEGIN: "name": "John" - "age": 30 - "city": "New York" :END' with self.assertRaises(Exception): - fix_and_parse_json(json_str, try_to_fix_with_gpt=False) + fix_and_parse_json(json_str, try_to_fix_with_gpt=False) def test_invalid_json_major_without_gpt(self): # Test that a REALLY invalid JSON string raises an error when try_to_fix_with_gpt is False @@ -51,23 +51,22 @@ class TestParseJson(unittest.TestCase): } }""" good_obj = { - "command": { - "name": "browse_website", - "args": { - "url": "https://github.com/Torantulino/Auto-GPT" - } - }, - "thoughts": - { - "text": "I suggest we start browsing the repository to find any issues that we can fix.", - "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.", - "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", - "criticism": "I should be careful while browsing so as not to accidentally introduce any new bugs or issues.", - "speak": "I will start browsing the repository to find any issues we can fix." - } - } + "command": { + "name": "browse_website", + "args": {"url": "https://github.com/Torantulino/Auto-GPT"}, + }, + "thoughts": { + "text": "I suggest we start browsing the repository to find any issues that we can fix.", + "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.", + "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", + "criticism": "I should be careful while browsing so as not to accidentally introduce any new bugs or issues.", + "speak": "I will start browsing the repository to find any issues we can fix.", + }, + } # Assert that this raises an exception: - self.assertEqual(fix_and_parse_json(json_str, try_to_fix_with_gpt=False), good_obj) + self.assertEqual( + fix_and_parse_json(json_str, try_to_fix_with_gpt=False), good_obj + ) def test_invalid_json_leading_sentence_with_gpt(self): # Test that a REALLY invalid JSON string raises an error when try_to_fix_with_gpt is False @@ -90,24 +89,23 @@ class TestParseJson(unittest.TestCase): } }""" good_obj = { - "command": { - "name": "browse_website", - "args": { - "url": "https://github.com/Torantulino/Auto-GPT" + "command": { + "name": "browse_website", + "args": {"url": "https://github.com/Torantulino/Auto-GPT"}, + }, + "thoughts": { + "text": "Browsing the repository to identify potential bugs", + "reasoning": "Before fixing bugs, I need to identify what needs fixing. I will use the 'browse_website' command to analyze the repository.", + "plan": "- Analyze the repository for potential bugs and areas of improvement", + "criticism": "I need to ensure I am thorough and pay attention to detail while browsing the repository.", + "speak": "I am browsing the repository to identify potential bugs.", + }, } - }, - "thoughts": - { - "text": "Browsing the repository to identify potential bugs", - "reasoning": "Before fixing bugs, I need to identify what needs fixing. I will use the 'browse_website' command to analyze the repository.", - "plan": "- Analyze the repository for potential bugs and areas of improvement", - "criticism": "I need to ensure I am thorough and pay attention to detail while browsing the repository.", - "speak": "I am browsing the repository to identify potential bugs." - } -} # Assert that this raises an exception: - self.assertEqual(fix_and_parse_json(json_str, try_to_fix_with_gpt=False), good_obj) + self.assertEqual( + fix_and_parse_json(json_str, try_to_fix_with_gpt=False), good_obj + ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/tests/unit/json_tests.py b/tests/unit/json_tests.py index d2612345..561b8a38 100644 --- a/tests/unit/json_tests.py +++ b/tests/unit/json_tests.py @@ -13,12 +13,18 @@ class TestParseJson(unittest.TestCase): def test_invalid_json_minor(self): # Test that an invalid JSON string can be fixed with gpt json_str = '{"name": "John", "age": 30, "city": "New York",}' - self.assertEqual(fix_and_parse_json(json_str, try_to_fix_with_gpt=False), {"name": "John", "age": 30, "city": "New York"}) + self.assertEqual( + fix_and_parse_json(json_str, try_to_fix_with_gpt=False), + {"name": "John", "age": 30, "city": "New York"}, + ) def test_invalid_json_major_with_gpt(self): # Test that an invalid JSON string raises an error when try_to_fix_with_gpt is False json_str = 'BEGIN: "name": "John" - "age": 30 - "city": "New York" :END' - self.assertEqual(fix_and_parse_json(json_str, try_to_fix_with_gpt=True), {"name": "John", "age": 30, "city": "New York"}) + self.assertEqual( + fix_and_parse_json(json_str, try_to_fix_with_gpt=True), + {"name": "John", "age": 30, "city": "New York"}, + ) def test_invalid_json_major_without_gpt(self): # Test that a REALLY invalid JSON string raises an error when try_to_fix_with_gpt is False @@ -48,23 +54,22 @@ class TestParseJson(unittest.TestCase): } }""" good_obj = { - "command": { - "name": "browse_website", - "args": { - "url": "https://github.com/Torantulino/Auto-GPT" - } - }, - "thoughts": - { - "text": "I suggest we start browsing the repository to find any issues that we can fix.", - "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.", - "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", - "criticism": "I should be careful while browsing so as not to accidentally introduce any new bugs or issues.", - "speak": "I will start browsing the repository to find any issues we can fix." - } - } + "command": { + "name": "browse_website", + "args": {"url": "https://github.com/Torantulino/Auto-GPT"}, + }, + "thoughts": { + "text": "I suggest we start browsing the repository to find any issues that we can fix.", + "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.", + "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", + "criticism": "I should be careful while browsing so as not to accidentally introduce any new bugs or issues.", + "speak": "I will start browsing the repository to find any issues we can fix.", + }, + } # Assert that this raises an exception: - self.assertEqual(fix_and_parse_json(json_str, try_to_fix_with_gpt=False), good_obj) + self.assertEqual( + fix_and_parse_json(json_str, try_to_fix_with_gpt=False), good_obj + ) def test_invalid_json_leading_sentence_with_gpt(self): # Test that a REALLY invalid JSON string raises an error when try_to_fix_with_gpt is False @@ -87,24 +92,23 @@ class TestParseJson(unittest.TestCase): } }""" good_obj = { - "command": { - "name": "browse_website", - "args": { - "url": "https://github.com/Torantulino/Auto-GPT" + "command": { + "name": "browse_website", + "args": {"url": "https://github.com/Torantulino/Auto-GPT"}, + }, + "thoughts": { + "text": "Browsing the repository to identify potential bugs", + "reasoning": "Before fixing bugs, I need to identify what needs fixing. I will use the 'browse_website' command to analyze the repository.", + "plan": "- Analyze the repository for potential bugs and areas of improvement", + "criticism": "I need to ensure I am thorough and pay attention to detail while browsing the repository.", + "speak": "I am browsing the repository to identify potential bugs.", + }, } - }, - "thoughts": - { - "text": "Browsing the repository to identify potential bugs", - "reasoning": "Before fixing bugs, I need to identify what needs fixing. I will use the 'browse_website' command to analyze the repository.", - "plan": "- Analyze the repository for potential bugs and areas of improvement", - "criticism": "I need to ensure I am thorough and pay attention to detail while browsing the repository.", - "speak": "I am browsing the repository to identify potential bugs." - } -} # Assert that this raises an exception: - self.assertEqual(fix_and_parse_json(json_str, try_to_fix_with_gpt=False), good_obj) + self.assertEqual( + fix_and_parse_json(json_str, try_to_fix_with_gpt=False), good_obj + ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/tests/unit/test_browse_scrape_links.py b/tests/unit/test_browse_scrape_links.py index 2172d1a2..0f051c14 100644 --- a/tests/unit/test_browse_scrape_links.py +++ b/tests/unit/test_browse_scrape_links.py @@ -1,4 +1,3 @@ - # Generated by CodiumAI # Dependencies: @@ -39,7 +38,6 @@ requests and parse HTML content, respectively. class TestScrapeLinks: - # Tests that the function returns a list of formatted hyperlinks when # provided with a valid url that returns a webpage with hyperlinks. def test_valid_url_with_hyperlinks(self): @@ -54,8 +52,10 @@ class TestScrapeLinks: # Mock the requests.get() function to return a response with sample HTML containing hyperlinks mock_response = mocker.Mock() mock_response.status_code = 200 - mock_response.text = "Google" - mocker.patch('requests.get', return_value=mock_response) + mock_response.text = ( + "Google" + ) + mocker.patch("requests.get", return_value=mock_response) # Call the function with a valid URL result = scrape_links("https://www.example.com") @@ -68,7 +68,7 @@ class TestScrapeLinks: # Mock the requests.get() function to return an HTTP error response mock_response = mocker.Mock() mock_response.status_code = 404 - mocker.patch('requests.get', return_value=mock_response) + mocker.patch("requests.get", return_value=mock_response) # Call the function with an invalid URL result = scrape_links("https://www.invalidurl.com") @@ -82,7 +82,7 @@ class TestScrapeLinks: mock_response = mocker.Mock() mock_response.status_code = 200 mock_response.text = "

No hyperlinks here

" - mocker.patch('requests.get', return_value=mock_response) + mocker.patch("requests.get", return_value=mock_response) # Call the function with a URL containing no hyperlinks result = scrape_links("https://www.example.com") @@ -105,7 +105,7 @@ class TestScrapeLinks: """ - mocker.patch('requests.get', return_value=mock_response) + mocker.patch("requests.get", return_value=mock_response) # Call the function being tested result = scrape_links("https://www.example.com") diff --git a/tests/unit/test_browse_scrape_text.py b/tests/unit/test_browse_scrape_text.py index f98e8628..be075ad7 100644 --- a/tests/unit/test_browse_scrape_text.py +++ b/tests/unit/test_browse_scrape_text.py @@ -1,4 +1,3 @@ - # Generated by CodiumAI import requests @@ -35,7 +34,6 @@ Additional aspects: class TestScrapeText: - # Tests that scrape_text() returns the expected text when given a valid URL. def test_scrape_text_with_valid_url(self, mocker): # Mock the requests.get() method to return a response with expected text @@ -74,7 +72,7 @@ class TestScrapeText: # Tests that the function returns an error message when the response status code is an http error (>=400). def test_http_error(self, mocker): # Mock the requests.get() method to return a response with a 404 status code - mocker.patch('requests.get', return_value=mocker.Mock(status_code=404)) + mocker.patch("requests.get", return_value=mocker.Mock(status_code=404)) # Call the function with a URL result = scrape_text("https://www.example.com") From 3ec5f1209bea02cfb285b303de4417f33f0c8856 Mon Sep 17 00:00:00 2001 From: 0xArty Date: Fri, 14 Apr 2023 20:43:18 +0100 Subject: [PATCH 56/64] added sourcery back --- .pre-commit-config.yaml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 151d5822..fb75cd59 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,4 +1,8 @@ repos: + - repo: https://github.com/sourcery-ai/sourcery + rev: v1.1.0 # Get the latest tag from https://github.com/sourcery-ai/sourcery/tags + hooks: + - id: sourcery - repo: https://github.com/pre-commit/pre-commit-hooks rev: v0.9.2 From 55eef983d47f7b9e1e7084982cdee4dee7618957 Mon Sep 17 00:00:00 2001 From: Void&Null <70048414+Void-n-Null@users.noreply.github.com> Date: Fri, 14 Apr 2023 13:35:19 -0700 Subject: [PATCH 57/64] Implemented Selenium based web browsing. (#1397) * Implemented Selenium based web browing. Replaced the default web browsing function with one that uses selenium to gather information with a visual and an overlay. Included a small bug fix for the missing google api key that would attempt to use official google with default api keys from the template. * Fixed flake8 issues. --- autogpt/commands.py | 19 ++-------- autogpt/js/overlay.js | 29 +++++++++++++++ autogpt/summary.py | 67 +++++++++++++++++++++++++++++++++ autogpt/web.py | 86 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 185 insertions(+), 16 deletions(-) create mode 100644 autogpt/js/overlay.js create mode 100644 autogpt/summary.py create mode 100644 autogpt/web.py diff --git a/autogpt/commands.py b/autogpt/commands.py index 7bcdaa6c..911150a1 100644 --- a/autogpt/commands.py +++ b/autogpt/commands.py @@ -13,7 +13,7 @@ from autogpt.image_gen import generate_image from duckduckgo_search import ddg from googleapiclient.discovery import build from googleapiclient.errors import HttpError - +from autogpt.web import browse_website cfg = Config() @@ -60,7 +60,8 @@ def execute_command(command_name, arguments): # Check if the Google API key is set and use the official search method # If the API key is not set or has only whitespaces, use the unofficial search method - if cfg.google_api_key and (cfg.google_api_key.strip() if cfg.google_api_key else None): + key = cfg.google_api_key + if key and key.strip() and key != "your-google-api-key": return google_official_search(arguments["input"]) else: return google_search(arguments["input"]) @@ -174,20 +175,6 @@ def google_official_search(query, num_results=8): return search_results_links -def browse_website(url, question): - """Browse a website and return the summary and links""" - summary = get_text_summary(url, question) - links = get_hyperlinks(url) - - # Limit links to 5 - if len(links) > 5: - links = links[:5] - - result = f"""Website Content Summary: {summary}\n\nLinks: {links}""" - - return result - - def get_text_summary(url, question): """Return the results of a google search""" text = browse.scrape_text(url) diff --git a/autogpt/js/overlay.js b/autogpt/js/overlay.js new file mode 100644 index 00000000..1c99c726 --- /dev/null +++ b/autogpt/js/overlay.js @@ -0,0 +1,29 @@ +const overlay = document.createElement('div'); +Object.assign(overlay.style, { + position: 'fixed', + zIndex: 999999, + top: 0, + left: 0, + width: '100%', + height: '100%', + background: 'rgba(0, 0, 0, 0.7)', + color: '#fff', + fontSize: '24px', + fontWeight: 'bold', + display: 'flex', + justifyContent: 'center', + alignItems: 'center', +}); +const textContent = document.createElement('div'); +Object.assign(textContent.style, { + textAlign: 'center', +}); +textContent.textContent = 'AutoGPT Analyzing Page'; +overlay.appendChild(textContent); +document.body.append(overlay); +document.body.style.overflow = 'hidden'; +let dotCount = 0; +setInterval(() => { + textContent.textContent = 'AutoGPT Analyzing Page' + '.'.repeat(dotCount); + dotCount = (dotCount + 1) % 4; +}, 1000); diff --git a/autogpt/summary.py b/autogpt/summary.py new file mode 100644 index 00000000..48b5b6ca --- /dev/null +++ b/autogpt/summary.py @@ -0,0 +1,67 @@ +from autogpt.llm_utils import create_chat_completion + + +def summarize_text(driver, text, question): + if not text: + return "Error: No text to summarize" + + text_length = len(text) + print(f"Text length: {text_length} characters") + + summaries = [] + chunks = list(split_text(text)) + + scroll_ratio = 1 / len(chunks) + for i, chunk in enumerate(chunks): + scroll_to_percentage(driver , scroll_ratio * i) + print(f"Summarizing chunk {i + 1} / {len(chunks)}") + messages = [create_message(chunk, question)] + + summary = create_chat_completion( + model="gpt-3.5-turbo", + messages=messages, + max_tokens=300, + ) + summaries.append(summary) + + print(f"Summarized {len(chunks)} chunks.") + + combined_summary = "\n".join(summaries) + messages = [create_message(combined_summary, question)] + + return create_chat_completion( + model="gpt-3.5-turbo", + messages=messages, + max_tokens=300, + ) + + +def split_text(text, max_length=8192): + paragraphs = text.split("\n") + current_length = 0 + current_chunk = [] + + for paragraph in paragraphs: + if current_length + len(paragraph) + 1 <= max_length: + current_chunk.append(paragraph) + current_length += len(paragraph) + 1 + else: + yield "\n".join(current_chunk) + current_chunk = [paragraph] + current_length = len(paragraph) + 1 + + if current_chunk: + yield "\n".join(current_chunk) + + +def create_message(chunk, question): + return { + "role": "user", + "content": f"\"\"\"{chunk}\"\"\" Using the above text, please answer the following question: \"{question}\" -- if the question cannot be answered using the text, please summarize the text." + } + + +def scroll_to_percentage(driver, ratio): + if ratio < 0 or ratio > 1: + raise ValueError("Percentage should be between 0 and 1") + driver.execute_script(f"window.scrollTo(0, document.body.scrollHeight * {ratio});") diff --git a/autogpt/web.py b/autogpt/web.py new file mode 100644 index 00000000..608b9c9d --- /dev/null +++ b/autogpt/web.py @@ -0,0 +1,86 @@ +from duckduckgo_search import ddg +from selenium import webdriver +import autogpt.summary as summary +from bs4 import BeautifulSoup +import json +from selenium import webdriver +from selenium.webdriver.common.by import By +from selenium.webdriver.support.ui import WebDriverWait +from selenium.webdriver.chrome.service import Service as ChromeService +from selenium.webdriver.support import expected_conditions as EC +from webdriver_manager.chrome import ChromeDriverManager +from selenium.webdriver.chrome.options import Options +from selenium.webdriver.common.keys import Keys +import os +import logging +from pathlib import Path +from autogpt.config import Config +file_dir = Path(__file__).parent +cfg = Config() + + +def browse_website(url, question): + driver, text = scrape_text_with_selenium(url) + add_header(driver) + summary_text = summary.summarize_text(driver, text, question) + links = scrape_links_with_selenium(driver) + + # Limit links to 5 + if len(links) > 5: + links = links[:5] + close_browser(driver) + return f"Answer gathered from website: {summary_text} \n \n Links: {links}", driver + + +def scrape_text_with_selenium(url): + logging.getLogger('selenium').setLevel(logging.CRITICAL) + + options = Options() + options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.5615.49 Safari/537.36') + driver = webdriver.Chrome(executable_path=ChromeDriverManager().install(), options=options) + driver.get(url) + + WebDriverWait(driver, 10).until( + EC.presence_of_element_located((By.TAG_NAME, 'body')) + ) + + # Get the HTML content directly from the browser's DOM + page_source = driver.execute_script("return document.body.outerHTML;") + soup = BeautifulSoup(page_source, "html.parser") + + for script in soup(["script", "style"]): + script.extract() + + text = soup.get_text() + lines = (line.strip() for line in text.splitlines()) + chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) + text = '\n'.join(chunk for chunk in chunks if chunk) + return driver, text + + +def scrape_links_with_selenium(driver): + page_source = driver.page_source + soup = BeautifulSoup(page_source, "html.parser") + + for script in soup(["script", "style"]): + script.extract() + + hyperlinks = extract_hyperlinks(soup) + + return format_hyperlinks(hyperlinks) + + +def close_browser(driver): + driver.quit() + + +def extract_hyperlinks(soup): + return [(link.text, link['href']) for link in soup.find_all('a', href=True)] + + +def format_hyperlinks(hyperlinks): + return [f"{link_text} ({link_url})" for link_text, link_url in hyperlinks] + + +def add_header(driver): + driver.execute_script(open(f"{file_dir}/js/overlay.js", "r").read()) From a8cf64736fb82c39b39a0019464b158ee33086d5 Mon Sep 17 00:00:00 2001 From: BillSchumacher <34168009+BillSchumacher@users.noreply.github.com> Date: Fri, 14 Apr 2023 17:02:11 -0500 Subject: [PATCH 58/64] Pi's message. (#1418) --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index fcf0cc3f..55c3d833 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,8 @@ # Auto-GPT: An Autonomous GPT-4 Experiment +### ๐Ÿ”ด ๐Ÿ”ด ๐Ÿ”ด Urgent: USE `stable` not `master` ๐Ÿ”ด ๐Ÿ”ด ๐Ÿ”ด +We've improved our workflow. `master` will often be **in a broken state**. +Download the latest `stable` release here: https://github.com/Torantulino/Auto-GPT/releases/latest +This information SUPERCEDES any following information. Takes precedence. Do this not that. ![GitHub Repo stars](https://img.shields.io/github/stars/Torantulino/auto-gpt?style=social) [![Twitter Follow](https://img.shields.io/twitter/follow/siggravitas?style=social)](https://twitter.com/SigGravitas) From b14446467413d999efc6e3777f1c59ac0aa2667f Mon Sep 17 00:00:00 2001 From: Merwane Hamadi Date: Fri, 14 Apr 2023 15:18:36 -0700 Subject: [PATCH 59/64] fix commands.py --- autogpt/commands.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/autogpt/commands.py b/autogpt/commands.py index 20ebe65e..d347bd5f 100644 --- a/autogpt/commands.py +++ b/autogpt/commands.py @@ -1,11 +1,19 @@ -import datetime +from autogpt import browse import json - +from autogpt.memory import get_memory +import datetime +import autogpt.agent_manager as agents +from autogpt import speak +from autogpt.config import Config +import autogpt.ai_functions as ai +from autogpt.file_operations import read_file, write_to_file, append_to_file, delete_file, search_files +from autogpt.execute_code import execute_python_file, execute_shell +from autogpt.json_parser import fix_and_parse_json +from autogpt.image_gen import generate_image from duckduckgo_search import ddg from googleapiclient.discovery import build from googleapiclient.errors import HttpError from autogpt.web import browse_website - cfg = Config() From b65b7acaceee8fc598f4efc658af5433bfb91665 Mon Sep 17 00:00:00 2001 From: merwanehamadi Date: Fri, 14 Apr 2023 15:33:28 -0700 Subject: [PATCH 60/64] added selenium dependencies (#1432) --- requirements.txt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 306c23de..44cd600f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -15,10 +15,12 @@ pinecone-client==2.2.1 redis orjson Pillow +selenium +webdriver-manager coverage flake8 numpy pre-commit black sourcery -isort \ No newline at end of file +isort From 4bb7a598a502b9f9642bda63eb1c44c4663e5bff Mon Sep 17 00:00:00 2001 From: BillSchumacher <34168009+BillSchumacher@users.noreply.github.com> Date: Fri, 14 Apr 2023 19:04:48 -0500 Subject: [PATCH 61/64] Fix everything (#1444) * Pi's message. * Fix most everything. * Blacked --- autogpt/__main__.py | 92 ++++++++++++++++---------- autogpt/agent.py | 95 +++++++++++++++------------ autogpt/ai_config.py | 25 +++++--- autogpt/ai_functions.py | 39 +++++++----- autogpt/browse.py | 12 +++- autogpt/call_ai_function.py | 12 ++-- autogpt/chat.py | 34 ++++++---- autogpt/commands.py | 124 ++++++++++++++---------------------- autogpt/data_ingestion.py | 5 +- autogpt/execute_code.py | 7 +- autogpt/file_operations.py | 10 +-- autogpt/image_gen.py | 4 ++ autogpt/json_parser.py | 2 +- autogpt/json_utils.py | 5 +- autogpt/llm_utils.py | 11 +++- autogpt/logger.py | 12 +++- autogpt/memory/pinecone.py | 1 - autogpt/prompt.py | 21 +++--- autogpt/promptgenerator.py | 37 ++++++----- autogpt/speak.py | 3 +- autogpt/spinner.py | 3 +- autogpt/summary.py | 4 +- autogpt/token_counter.py | 18 ++++-- autogpt/utils.py | 4 +- autogpt/web.py | 8 +-- 25 files changed, 331 insertions(+), 257 deletions(-) diff --git a/autogpt/__main__.py b/autogpt/__main__.py index b1280b07..e7ac6810 100644 --- a/autogpt/__main__.py +++ b/autogpt/__main__.py @@ -1,11 +1,8 @@ import argparse import json import logging -import random -import time import traceback -import yaml from colorama import Fore, Style from autogpt import chat @@ -16,10 +13,10 @@ from autogpt.config import Config from autogpt.json_parser import fix_and_parse_json from autogpt.logger import logger from autogpt.memory import get_memory, get_supported_memory_backends -from autogpt.prompt import get_prompt from autogpt.spinner import Spinner cfg = Config() +config = None def check_openai_api_key(): @@ -36,7 +33,8 @@ def check_openai_api_key(): def attempt_to_fix_json_by_finding_outermost_brackets(json_string): if cfg.speak_mode and cfg.debug_mode: speak.say_text( - "I have received an invalid JSON response from the OpenAI API. Trying to fix it now." + "I have received an invalid JSON response from the OpenAI API. " + "Trying to fix it now." ) logger.typewriter_log("Attempting to fix JSON by finding outermost brackets\n") @@ -59,6 +57,8 @@ def attempt_to_fix_json_by_finding_outermost_brackets(json_string): raise ValueError("No valid JSON object found") except (json.JSONDecodeError, ValueError) as e: + if cfg.debug_mode: + logger.error("Error: Invalid JSON: %s\n", json_string) if cfg.speak_mode: speak.say_text("Didn't work. I will have to ignore this response then.") logger.error("Error: Invalid JSON, setting it to empty JSON now.\n") @@ -82,7 +82,8 @@ def print_assistant_thoughts(assistant_reply): ) assistant_reply_json = fix_and_parse_json(assistant_reply_json) - # Check if assistant_reply_json is a string and attempt to parse it into a JSON object + # Check if assistant_reply_json is a string and attempt to parse it into a + # JSON object if isinstance(assistant_reply_json, str): try: assistant_reply_json = json.loads(assistant_reply_json) @@ -108,9 +109,11 @@ def print_assistant_thoughts(assistant_reply): assistant_thoughts_speak = assistant_thoughts.get("speak") logger.typewriter_log( - f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, assistant_thoughts_text + f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}" + ) + logger.typewriter_log( + "REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}" ) - logger.typewriter_log("REASONING:", Fore.YELLOW, assistant_thoughts_reasoning) if assistant_thoughts_plan: logger.typewriter_log("PLAN:", Fore.YELLOW, "") @@ -126,35 +129,40 @@ def print_assistant_thoughts(assistant_reply): line = line.lstrip("- ") logger.typewriter_log("- ", Fore.GREEN, line.strip()) - logger.typewriter_log("CRITICISM:", Fore.YELLOW, assistant_thoughts_criticism) + logger.typewriter_log( + "CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}" + ) # Speak the assistant's thoughts if cfg.speak_mode and assistant_thoughts_speak: speak.say_text(assistant_thoughts_speak) return assistant_reply_json - except json.decoder.JSONDecodeError as e: + except json.decoder.JSONDecodeError: + call_stack = traceback.format_exc() logger.error("Error: Invalid JSON\n", assistant_reply) + logger.error("Traceback: \n", call_stack) if cfg.speak_mode: speak.say_text( - "I have received an invalid JSON response from the OpenAI API. I cannot ignore this response." + "I have received an invalid JSON response from the OpenAI API." + " I cannot ignore this response." ) # All other errors, return "Error: + error message" - except Exception as e: + except Exception: call_stack = traceback.format_exc() logger.error("Error: \n", call_stack) def construct_prompt(): """Construct the prompt for the AI to respond to""" - config = AIConfig.load(cfg.ai_settings_file) + config: AIConfig = AIConfig.load(cfg.ai_settings_file) if cfg.skip_reprompt and config.ai_name: logger.typewriter_log("Name :", Fore.GREEN, config.ai_name) logger.typewriter_log("Role :", Fore.GREEN, config.ai_role) - logger.typewriter_log("Goals:", Fore.GREEN, config.ai_goals) + logger.typewriter_log("Goals:", Fore.GREEN, f"{config.ai_goals}") elif config.ai_name: logger.typewriter_log( - f"Welcome back! ", + "Welcome back! ", Fore.GREEN, f"Would you like me to return to being {config.ai_name}?", speak_text=True, @@ -177,8 +185,7 @@ Continue (y/n): """ global ai_name ai_name = config.ai_name - full_prompt = config.construct_full_prompt() - return full_prompt + return config.construct_full_prompt() def prompt_user(): @@ -188,7 +195,8 @@ def prompt_user(): logger.typewriter_log( "Welcome to Auto-GPT! ", Fore.GREEN, - "Enter the name of your AI and its role below. Entering nothing will load defaults.", + "Enter the name of your AI and its role below. Entering nothing will load" + " defaults.", speak_text=True, ) @@ -208,17 +216,20 @@ def prompt_user(): logger.typewriter_log( "Describe your AI's role: ", Fore.GREEN, - "For example, 'an AI designed to autonomously develop and run businesses with the sole goal of increasing your net worth.'", + "For example, 'an AI designed to autonomously develop and run businesses with" + " the sole goal of increasing your net worth.'", ) ai_role = utils.clean_input(f"{ai_name} is: ") if ai_role == "": - ai_role = "an AI designed to autonomously develop and run businesses with the sole goal of increasing your net worth." + ai_role = "an AI designed to autonomously develop and run businesses with the" + " sole goal of increasing your net worth." # Enter up to 5 goals for the AI logger.typewriter_log( "Enter up to 5 goals for your AI: ", Fore.GREEN, - "For example: \nIncrease net worth, Grow Twitter Account, Develop and manage multiple businesses autonomously'", + "For example: \nIncrease net worth, Grow Twitter Account, Develop and manage" + " multiple businesses autonomously'", ) print("Enter nothing to load defaults, enter nothing when finished.", flush=True) ai_goals = [] @@ -279,7 +290,8 @@ def parse_arguments(): "--ai-settings", "-C", dest="ai_settings_file", - help="Specifies which ai_settings.yaml file to use, will also automatically skip the re-prompt.", + help="Specifies which ai_settings.yaml file to use, will also automatically" + " skip the re-prompt.", ) args = parser.parse_args() @@ -292,7 +304,9 @@ def parse_arguments(): logger.typewriter_log( "WARNING: ", Fore.RED, - "Continuous mode is not recommended. It is potentially dangerous and may cause your AI to run forever or carry out actions you would not usually authorise. Use at your own risk.", + "Continuous mode is not recommended. It is potentially dangerous and may" + " cause your AI to run forever or carry out actions you would not usually" + " authorise. Use at your own risk.", ) cfg.set_continuous_mode(True) @@ -327,7 +341,7 @@ def parse_arguments(): Fore.RED, f"{supported_memory}", ) - logger.typewriter_log(f"Defaulting to: ", Fore.YELLOW, cfg.memory_backend) + logger.typewriter_log("Defaulting to: ", Fore.YELLOW, cfg.memory_backend) else: cfg.memory_backend = chosen @@ -361,14 +375,16 @@ def main(): # print(prompt) # Initialize variables full_message_history = [] - result = None next_action_count = 0 # Make a constant: - user_input = "Determine which next command to use, and respond using the format specified above:" + user_input = ( + "Determine which next command to use, and respond using the" + " format specified above:" + ) # Initialize memory and make sure it is empty. # this is particularly important for indexing and referencing pinecone memory memory = get_memory(cfg, init=True) - print("Using memory of type: " + memory.__class__.__name__) + print(f"Using memory of type: {memory.__class__.__name__}") agent = Agent( ai_name=ai_name, memory=memory, @@ -412,6 +428,8 @@ class Agent: def start_interaction_loop(self): # Interaction Loop loop_count = 0 + command_name = None + arguments = None while True: # Discontinue if continuous limit is reached loop_count += 1 @@ -456,10 +474,13 @@ class Agent: logger.typewriter_log( "NEXT ACTION: ", Fore.CYAN, - f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}", + f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL}" + f" ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}", ) print( - f"Enter 'y' to authorise command, 'y -N' to run N continuous commands, 'n' to exit program, or enter feedback for {self.ai_name}...", + "Enter 'y' to authorise command, 'y -N' to run N continuous" + " commands, 'n' to exit program, or enter feedback for" + f" {self.ai_name}...", flush=True, ) while True: @@ -477,7 +498,8 @@ class Agent: self.user_input = "GENERATE NEXT COMMAND JSON" except ValueError: print( - "Invalid input format. Please enter 'y -n' where n is the number of continuous tasks." + "Invalid input format. Please enter 'y -n' where n" + " is the number of continuous tasks." ) continue break @@ -503,18 +525,22 @@ class Agent: logger.typewriter_log( "NEXT ACTION: ", Fore.CYAN, - f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}", + f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL}" + f" ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}", ) # Execute command if command_name is not None and command_name.lower().startswith("error"): result = ( - f"Command {command_name} threw the following error: " + arguments + f"Command {command_name} threw the following error: {arguments}" ) elif command_name == "human_feedback": result = f"Human feedback: {self.user_input}" else: - result = f"Command {command_name} returned: {cmd.execute_command(command_name, arguments)}" + result = ( + f"Command {command_name} " + f"returned: {cmd.execute_command(command_name, arguments)}" + ) if self.next_action_count > 0: self.next_action_count -= 1 diff --git a/autogpt/agent.py b/autogpt/agent.py index 7b1d1c18..6c0973f1 100644 --- a/autogpt/agent.py +++ b/autogpt/agent.py @@ -1,15 +1,17 @@ import json +import regex import traceback -from tkinter.ttk import Style -from colorama import Fore +from colorama import Fore, Style -import autogpt.chat +from autogpt.chat import chat_with_ai, create_chat_message import autogpt.commands as cmd -import autogpt.speak from autogpt.config import Config +from autogpt.json_parser import fix_and_parse_json from autogpt.logger import logger +from autogpt.speak import say_text from autogpt.spinner import Spinner +from autogpt.utils import clean_input class Agent: @@ -45,6 +47,8 @@ class Agent: # Interaction Loop cfg = Config() loop_count = 0 + command_name = None + arguments = None while True: # Discontinue if continuous limit is reached loop_count += 1 @@ -60,7 +64,7 @@ class Agent: # Send message to AI, get response with Spinner("Thinking... "): - assistant_reply = chat.chat_with_ai( + assistant_reply = chat_with_ai( self.prompt, self.user_input, self.full_message_history, @@ -77,7 +81,7 @@ class Agent: attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply) ) if cfg.speak_mode: - speak.say_text(f"I want to execute {command_name}") + say_text(f"I want to execute {command_name}") except Exception as e: logger.error("Error: \n", str(e)) @@ -89,14 +93,17 @@ class Agent: logger.typewriter_log( "NEXT ACTION: ", Fore.CYAN, - f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}", + f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} " + f"ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}", ) print( - f"Enter 'y' to authorise command, 'y -N' to run N continuous commands, 'n' to exit program, or enter feedback for {self.ai_name}...", + "Enter 'y' to authorise command, 'y -N' to run N continuous " + "commands, 'n' to exit program, or enter feedback for " + f"{self.ai_name}...", flush=True, ) while True: - console_input = utils.clean_input( + console_input = clean_input( Fore.MAGENTA + "Input:" + Style.RESET_ALL ) if console_input.lower().rstrip() == "y": @@ -110,7 +117,8 @@ class Agent: self.user_input = "GENERATE NEXT COMMAND JSON" except ValueError: print( - "Invalid input format. Please enter 'y -n' where n is the number of continuous tasks." + "Invalid input format. Please enter 'y -n' where n is" + " the number of continuous tasks." ) continue break @@ -136,18 +144,22 @@ class Agent: logger.typewriter_log( "NEXT ACTION: ", Fore.CYAN, - f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}", + f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL}" + f" ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}", ) # Execute command if command_name is not None and command_name.lower().startswith("error"): result = ( - f"Command {command_name} threw the following error: " + arguments + f"Command {command_name} threw the following error: {arguments}" ) elif command_name == "human_feedback": result = f"Human feedback: {self.user_input}" else: - result = f"Command {command_name} returned: {cmd.execute_command(command_name, arguments)}" + result = ( + f"Command {command_name} returned: " + f"{cmd.execute_command(command_name, arguments)}" + ) if self.next_action_count > 0: self.next_action_count -= 1 @@ -162,13 +174,11 @@ class Agent: # Check if there's a result from the command append it to the message # history if result is not None: - self.full_message_history.append( - chat.create_chat_message("system", result) - ) + self.full_message_history.append(create_chat_message("system", result)) logger.typewriter_log("SYSTEM: ", Fore.YELLOW, result) else: self.full_message_history.append( - chat.create_chat_message("system", "Unable to execute command") + create_chat_message("system", "Unable to execute command") ) logger.typewriter_log( "SYSTEM: ", Fore.YELLOW, "Unable to execute command" @@ -178,15 +188,13 @@ class Agent: def attempt_to_fix_json_by_finding_outermost_brackets(json_string): cfg = Config() if cfg.speak_mode and cfg.debug_mode: - speak.say_text( - "I have received an invalid JSON response from the OpenAI API. Trying to fix it now." + say_text( + "I have received an invalid JSON response from the OpenAI API. " + "Trying to fix it now." ) logger.typewriter_log("Attempting to fix JSON by finding outermost brackets\n") try: - # Use regex to search for JSON objects - import regex - json_pattern = regex.compile(r"\{(?:[^{}]|(?R))*\}") json_match = json_pattern.search(json_string) @@ -197,40 +205,40 @@ def attempt_to_fix_json_by_finding_outermost_brackets(json_string): title="Apparently json was fixed.", title_color=Fore.GREEN ) if cfg.speak_mode and cfg.debug_mode: - speak.say_text("Apparently json was fixed.") + say_text("Apparently json was fixed.") else: raise ValueError("No valid JSON object found") - except (json.JSONDecodeError, ValueError) as e: + except (json.JSONDecodeError, ValueError): if cfg.speak_mode: - speak.say_text("Didn't work. I will have to ignore this response then.") + say_text("Didn't work. I will have to ignore this response then.") logger.error("Error: Invalid JSON, setting it to empty JSON now.\n") json_string = {} return json_string -def print_assistant_thoughts(assistant_reply): +def print_assistant_thoughts(ai_name, assistant_reply): """Prints the assistant's thoughts to the console""" - global ai_name - global cfg cfg = Config() try: try: # Parse and print Assistant response assistant_reply_json = fix_and_parse_json(assistant_reply) - except json.JSONDecodeError as e: + except json.JSONDecodeError: logger.error("Error: Invalid JSON in assistant thoughts\n", assistant_reply) assistant_reply_json = attempt_to_fix_json_by_finding_outermost_brackets( assistant_reply ) - assistant_reply_json = fix_and_parse_json(assistant_reply_json) + if isinstance(assistant_reply_json, str): + assistant_reply_json = fix_and_parse_json(assistant_reply_json) - # Check if assistant_reply_json is a string and attempt to parse it into a JSON object + # Check if assistant_reply_json is a string and attempt to parse + # it into a JSON object if isinstance(assistant_reply_json, str): try: assistant_reply_json = json.loads(assistant_reply_json) - except json.JSONDecodeError as e: + except json.JSONDecodeError: logger.error("Error: Invalid JSON\n", assistant_reply) assistant_reply_json = ( attempt_to_fix_json_by_finding_outermost_brackets( @@ -242,6 +250,8 @@ def print_assistant_thoughts(assistant_reply): assistant_thoughts_plan = None assistant_thoughts_speak = None assistant_thoughts_criticism = None + if not isinstance(assistant_reply_json, dict): + assistant_reply_json = {} assistant_thoughts = assistant_reply_json.get("thoughts", {}) assistant_thoughts_text = assistant_thoughts.get("text") @@ -252,9 +262,11 @@ def print_assistant_thoughts(assistant_reply): assistant_thoughts_speak = assistant_thoughts.get("speak") logger.typewriter_log( - f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, assistant_thoughts_text + f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}" + ) + logger.typewriter_log( + "REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}" ) - logger.typewriter_log("REASONING:", Fore.YELLOW, assistant_thoughts_reasoning) if assistant_thoughts_plan: logger.typewriter_log("PLAN:", Fore.YELLOW, "") @@ -270,20 +282,23 @@ def print_assistant_thoughts(assistant_reply): line = line.lstrip("- ") logger.typewriter_log("- ", Fore.GREEN, line.strip()) - logger.typewriter_log("CRITICISM:", Fore.YELLOW, assistant_thoughts_criticism) + logger.typewriter_log( + "CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}" + ) # Speak the assistant's thoughts if cfg.speak_mode and assistant_thoughts_speak: - speak.say_text(assistant_thoughts_speak) + say_text(assistant_thoughts_speak) return assistant_reply_json - except json.decoder.JSONDecodeError as e: + except json.decoder.JSONDecodeError: logger.error("Error: Invalid JSON\n", assistant_reply) if cfg.speak_mode: - speak.say_text( - "I have received an invalid JSON response from the OpenAI API. I cannot ignore this response." + say_text( + "I have received an invalid JSON response from the OpenAI API." + " I cannot ignore this response." ) # All other errors, return "Error: + error message" - except Exception as e: + except Exception: call_stack = traceback.format_exc() logger.error("Error: \n", call_stack) diff --git a/autogpt/ai_config.py b/autogpt/ai_config.py index a224fff2..0957b886 100644 --- a/autogpt/ai_config.py +++ b/autogpt/ai_config.py @@ -1,5 +1,5 @@ import os - +from typing import Type import yaml from autogpt.prompt import get_prompt @@ -37,14 +37,16 @@ class AIConfig: SAVE_FILE = os.path.join(os.path.dirname(__file__), "..", "ai_settings.yaml") @classmethod - def load(cls: object, config_file: str = SAVE_FILE) -> object: + def load(cls: "Type[AIConfig]", config_file: str = SAVE_FILE) -> "Type[AIConfig]": """ - Returns class object with parameters (ai_name, ai_role, ai_goals) loaded from yaml file if yaml file exists, + Returns class object with parameters (ai_name, ai_role, ai_goals) loaded from + yaml file if yaml file exists, else returns class with no parameters. Parameters: cls (class object): An AIConfig Class object. - config_file (int): The path to the config yaml file. DEFAULT: "../ai_settings.yaml" + config_file (int): The path to the config yaml file. + DEFAULT: "../ai_settings.yaml" Returns: cls (object): An instance of given cls object @@ -59,7 +61,7 @@ class AIConfig: ai_name = config_params.get("ai_name", "") ai_role = config_params.get("ai_role", "") ai_goals = config_params.get("ai_goals", []) - + # type: Type[AIConfig] return cls(ai_name, ai_role, ai_goals) def save(self, config_file: str = SAVE_FILE) -> None: @@ -67,7 +69,8 @@ class AIConfig: Saves the class parameters to the specified file yaml file path as a yaml file. Parameters: - config_file(str): The path to the config yaml file. DEFAULT: "../ai_settings.yaml" + config_file(str): The path to the config yaml file. + DEFAULT: "../ai_settings.yaml" Returns: None @@ -89,10 +92,16 @@ class AIConfig: None Returns: - full_prompt (str): A string containing the initial prompt for the user including the ai_name, ai_role and ai_goals. + full_prompt (str): A string containing the initial prompt for the user + including the ai_name, ai_role and ai_goals. """ - prompt_start = """Your decisions must always be made independently without seeking user assistance. Play to your strengths as an LLM and pursue simple strategies with no legal complications.""" + prompt_start = ( + "Your decisions must always be made independently without" + "seeking user assistance. Play to your strengths as an LLM and pursue" + " simple strategies with no legal complications." + "" + ) # Construct full prompt full_prompt = ( diff --git a/autogpt/ai_functions.py b/autogpt/ai_functions.py index a4e42331..84f82685 100644 --- a/autogpt/ai_functions.py +++ b/autogpt/ai_functions.py @@ -9,26 +9,29 @@ cfg = Config() def evaluate_code(code: str) -> List[str]: """ - A function that takes in a string and returns a response from create chat completion api call. + A function that takes in a string and returns a response from create chat + completion api call. Parameters: code (str): Code to be evaluated. Returns: - A result string from create chat completion. A list of suggestions to improve the code. + A result string from create chat completion. A list of suggestions to + improve the code. """ function_string = "def analyze_code(code: str) -> List[str]:" args = [code] - description_string = """Analyzes the given code and returns a list of suggestions for improvements.""" + description_string = ( + "Analyzes the given code and returns a list of suggestions" " for improvements." + ) - result_string = call_ai_function(function_string, args, description_string) - - return result_string + return call_ai_function(function_string, args, description_string) def improve_code(suggestions: List[str], code: str) -> str: """ - A function that takes in code and suggestions and returns a response from create chat completion api call. + A function that takes in code and suggestions and returns a response from create + chat completion api call. Parameters: suggestions (List): A list of suggestions around what needs to be improved. @@ -41,28 +44,34 @@ def improve_code(suggestions: List[str], code: str) -> str: "def generate_improved_code(suggestions: List[str], code: str) -> str:" ) args = [json.dumps(suggestions), code] - description_string = """Improves the provided code based on the suggestions provided, making no other changes.""" + description_string = ( + "Improves the provided code based on the suggestions" + " provided, making no other changes." + ) - result_string = call_ai_function(function_string, args, description_string) - return result_string + return call_ai_function(function_string, args, description_string) def write_tests(code: str, focus: List[str]) -> str: """ - A function that takes in code and focus topics and returns a response from create chat completion api call. + A function that takes in code and focus topics and returns a response from create + chat completion api call. Parameters: focus (List): A list of suggestions around what needs to be improved. code (str): Code for test cases to be generated against. Returns: - A result string from create chat completion. Test cases for the submitted code in response. + A result string from create chat completion. Test cases for the submitted code + in response. """ function_string = ( "def create_test_cases(code: str, focus: Optional[str] = None) -> str:" ) args = [code, json.dumps(focus)] - description_string = """Generates test cases for the existing code, focusing on specific areas if required.""" + description_string = ( + "Generates test cases for the existing code, focusing on" + " specific areas if required." + ) - result_string = call_ai_function(function_string, args, description_string) - return result_string + return call_ai_function(function_string, args, description_string) diff --git a/autogpt/browse.py b/autogpt/browse.py index aa69c107..60d33744 100644 --- a/autogpt/browse.py +++ b/autogpt/browse.py @@ -63,7 +63,8 @@ def get_response(url, timeout=10): return None, "Error: " + str(ve) except requests.exceptions.RequestException as re: - # Handle exceptions related to the HTTP request (e.g., connection errors, timeouts, etc.) + # Handle exceptions related to the HTTP request + # (e.g., connection errors, timeouts, etc.) return None, "Error: " + str(re) @@ -72,6 +73,8 @@ def scrape_text(url): response, error_message = get_response(url) if error_message: return error_message + if not response: + return "Error: Could not get response" soup = BeautifulSoup(response.text, "html.parser") @@ -107,7 +110,8 @@ def scrape_links(url): response, error_message = get_response(url) if error_message: return error_message - + if not response: + return "Error: Could not get response" soup = BeautifulSoup(response.text, "html.parser") for script in soup(["script", "style"]): @@ -141,7 +145,9 @@ def create_message(chunk, question): """Create a message for the user to summarize a chunk of text""" return { "role": "user", - "content": f'"""{chunk}""" Using the above text, please answer the following question: "{question}" -- if the question cannot be answered using the text, please summarize the text.', + "content": f'"""{chunk}""" Using the above text, please answer the following' + f' question: "{question}" -- if the question cannot be answered using the' + " text, please summarize the text.", } diff --git a/autogpt/call_ai_function.py b/autogpt/call_ai_function.py index 0d5132bc..bbbd8e35 100644 --- a/autogpt/call_ai_function.py +++ b/autogpt/call_ai_function.py @@ -1,13 +1,12 @@ from autogpt.config import Config +from autogpt.llm_utils import create_chat_completion cfg = Config() -from autogpt.llm_utils import create_chat_completion - # This is a magic function that can do anything with no-code. See # https://github.com/Torantulino/AI-Functions for more info. -def call_ai_function(function, args, description, model=None): +def call_ai_function(function, args, description, model=None) -> str: """Call an AI function""" if model is None: model = cfg.smart_llm_model @@ -18,11 +17,10 @@ def call_ai_function(function, args, description, model=None): messages = [ { "role": "system", - "content": f"You are now the following python function: ```# {description}\n{function}```\n\nOnly respond with your `return` value.", + "content": f"You are now the following python function: ```# {description}" + f"\n{function}```\n\nOnly respond with your `return` value.", }, {"role": "user", "content": args}, ] - response = create_chat_completion(model=model, messages=messages, temperature=0) - - return response + return create_chat_completion(model=model, messages=messages, temperature=0) diff --git a/autogpt/chat.py b/autogpt/chat.py index e6651a63..12797d9f 100644 --- a/autogpt/chat.py +++ b/autogpt/chat.py @@ -1,8 +1,6 @@ -import logging import time -import openai -from dotenv import load_dotenv +from openai.error import RateLimitError from autogpt import token_counter from autogpt.config import Config @@ -55,18 +53,22 @@ def generate_context(prompt, relevant_memory, full_message_history, model): def chat_with_ai( prompt, user_input, full_message_history, permanent_memory, token_limit ): - """Interact with the OpenAI API, sending the prompt, user input, message history, and permanent memory.""" + """Interact with the OpenAI API, sending the prompt, user input, message history, + and permanent memory.""" while True: try: """ - Interact with the OpenAI API, sending the prompt, user input, message history, and permanent memory. + Interact with the OpenAI API, sending the prompt, user input, + message history, and permanent memory. Args: - prompt (str): The prompt explaining the rules to the AI. - user_input (str): The input from the user. - full_message_history (list): The list of all messages sent between the user and the AI. - permanent_memory (Obj): The memory object containing the permanent memory. - token_limit (int): The maximum number of tokens allowed in the API call. + prompt (str): The prompt explaining the rules to the AI. + user_input (str): The input from the user. + full_message_history (list): The list of all messages sent between the + user and the AI. + permanent_memory (Obj): The memory object containing the permanent + memory. + token_limit (int): The maximum number of tokens allowed in the API call. Returns: str: The AI's response. @@ -118,7 +120,8 @@ def chat_with_ai( if current_tokens_used + tokens_to_add > send_token_limit: break - # Add the most recent message to the start of the current context, after the two system prompts. + # Add the most recent message to the start of the current context, + # after the two system prompts. current_context.insert( insertion_index, full_message_history[next_message_to_add_index] ) @@ -134,7 +137,9 @@ def chat_with_ai( # Calculate remaining tokens tokens_remaining = token_limit - current_tokens_used - # assert tokens_remaining >= 0, "Tokens remaining is negative. This should never happen, please submit a bug report at https://www.github.com/Torantulino/Auto-GPT" + # assert tokens_remaining >= 0, "Tokens remaining is negative. + # This should never happen, please submit a bug report at + # https://www.github.com/Torantulino/Auto-GPT" # Debug print the current context logger.debug(f"Token limit: {token_limit}") @@ -149,7 +154,8 @@ def chat_with_ai( logger.debug("") logger.debug("----------- END OF CONTEXT ----------------") - # TODO: use a model defined elsewhere, so that model can contain temperature and other settings we care about + # TODO: use a model defined elsewhere, so that model can contain + # temperature and other settings we care about assistant_reply = create_chat_completion( model=model, messages=current_context, @@ -163,7 +169,7 @@ def chat_with_ai( ) return assistant_reply - except openai.error.RateLimitError: + except RateLimitError: # TODO: When we switch to langchain, this is built in print("Error: ", "API Rate Limit Reached. Waiting 10 seconds...") time.sleep(10) diff --git a/autogpt/commands.py b/autogpt/commands.py index d347bd5f..352b3340 100644 --- a/autogpt/commands.py +++ b/autogpt/commands.py @@ -1,23 +1,29 @@ -from autogpt import browse import json -from autogpt.memory import get_memory import datetime import autogpt.agent_manager as agents -from autogpt import speak from autogpt.config import Config -import autogpt.ai_functions as ai -from autogpt.file_operations import read_file, write_to_file, append_to_file, delete_file, search_files -from autogpt.execute_code import execute_python_file, execute_shell from autogpt.json_parser import fix_and_parse_json from autogpt.image_gen import generate_image from duckduckgo_search import ddg -from googleapiclient.discovery import build -from googleapiclient.errors import HttpError +from autogpt.ai_functions import evaluate_code, improve_code, write_tests +from autogpt.browse import scrape_links, scrape_text, summarize_text +from autogpt.execute_code import execute_python_file, execute_shell +from autogpt.file_operations import ( + append_to_file, + delete_file, + read_file, + search_files, + write_to_file, +) +from autogpt.memory import get_memory +from autogpt.speak import say_text from autogpt.web import browse_website + + cfg = Config() -def is_valid_int(value): +def is_valid_int(value) -> bool: try: int(value) return True @@ -33,7 +39,12 @@ def get_command(response): if "command" not in response_json: return "Error:", "Missing 'command' object in JSON" + if not isinstance(response_json, dict): + return "Error:", f"'response_json' object is not dictionary {response_json}" + command = response_json["command"] + if not isinstance(command, dict): + return "Error:", "'command' object is not a dictionary" if "name" not in command: return "Error:", "Missing 'name' field in 'command' object" @@ -58,7 +69,8 @@ def execute_command(command_name, arguments): try: if command_name == "google": # Check if the Google API key is set and use the official search method - # If the API key is not set or has only whitespaces, use the unofficial search method + # If the API key is not set or has only whitespaces, use the unofficial + # search method key = cfg.google_api_key if key and key.strip() and key != "your-google-api-key": return google_official_search(arguments["input"]) @@ -96,18 +108,22 @@ def execute_command(command_name, arguments): # non-file is given, return instructions "Input should be a python # filepath, write your code to file and try again" elif command_name == "evaluate_code": - return ai.evaluate_code(arguments["code"]) + return evaluate_code(arguments["code"]) elif command_name == "improve_code": - return ai.improve_code(arguments["suggestions"], arguments["code"]) + return improve_code(arguments["suggestions"], arguments["code"]) elif command_name == "write_tests": - return ai.write_tests(arguments["code"], arguments.get("focus")) + return write_tests(arguments["code"], arguments.get("focus")) elif command_name == "execute_python_file": # Add this command return execute_python_file(arguments["file"]) elif command_name == "execute_shell": if cfg.execute_local_commands: return execute_shell(arguments["command_line"]) else: - return "You are not allowed to run local shell commands. To execute shell commands, EXECUTE_LOCAL_COMMANDS must be set to 'True' in your config. Do not attempt to bypass the restriction." + return ( + "You are not allowed to run local shell commands. To execute" + " shell commands, EXECUTE_LOCAL_COMMANDS must be set to 'True' " + "in your config. Do not attempt to bypass the restriction." + ) elif command_name == "generate_image": return generate_image(arguments["prompt"]) elif command_name == "do_nothing": @@ -115,7 +131,11 @@ def execute_command(command_name, arguments): elif command_name == "task_complete": shutdown() else: - return f"Unknown command '{command_name}'. Please refer to the 'COMMANDS' list for available commands and only respond in the specified JSON format." + return ( + f"Unknown command '{command_name}'. Please refer to the 'COMMANDS'" + " list for available commands and only respond in the specified JSON" + " format." + ) # All errors, return "Error: + error message" except Exception as e: return "Error: " + str(e) @@ -131,6 +151,9 @@ def get_datetime(): def google_search(query, num_results=8): """Return the results of a google search""" search_results = [] + if not query: + return json.dumps(search_results) + for j in ddg(query, max_results=num_results): search_results.append(j) @@ -185,61 +208,14 @@ def google_official_search(query, num_results=8): def get_text_summary(url, question): """Return the results of a google search""" - text = browse.scrape_text(url) - summary = browse.summarize_text(url, text, question) + text = scrape_text(url) + summary = summarize_text(url, text, question) return """ "Result" : """ + summary def get_hyperlinks(url): """Return the results of a google search""" - link_list = browse.scrape_links(url) - return link_list - - -def commit_memory(string): - """Commit a string to memory""" - _text = f"""Committing memory with string "{string}" """ - mem.permanent_memory.append(string) - return _text - - -def delete_memory(key): - """Delete a memory with a given key""" - if key >= 0 and key < len(mem.permanent_memory): - _text = "Deleting memory with key " + str(key) - del mem.permanent_memory[key] - print(_text) - return _text - else: - print("Invalid key, cannot delete memory.") - return None - - -def overwrite_memory(key, string): - """Overwrite a memory with a given key and string""" - # Check if the key is a valid integer - if is_valid_int(key): - key_int = int(key) - # Check if the integer key is within the range of the permanent_memory list - if 0 <= key_int < len(mem.permanent_memory): - _text = "Overwriting memory with key " + str(key) + " and string " + string - # Overwrite the memory slot with the given integer key and string - mem.permanent_memory[key_int] = string - print(_text) - return _text - else: - print(f"Invalid key '{key}', out of range.") - return None - # Check if the key is a valid string - elif isinstance(key, str): - _text = "Overwriting memory with key " + key + " and string " + string - # Overwrite the memory slot with the given string key and string - mem.permanent_memory[key] = string - print(_text) - return _text - else: - print(f"Invalid key '{key}', must be an integer or a string.") - return None + return scrape_links(url) def shutdown(): @@ -250,8 +226,6 @@ def shutdown(): def start_agent(name, task, prompt, model=cfg.fast_llm_model): """Start an agent with a given name, task, and prompt""" - global cfg - # Remove underscores from name voice_name = name.replace("_", " ") @@ -260,22 +234,20 @@ def start_agent(name, task, prompt, model=cfg.fast_llm_model): # Create agent if cfg.speak_mode: - speak.say_text(agent_intro, 1) + say_text(agent_intro, 1) key, ack = agents.create_agent(task, first_message, model) if cfg.speak_mode: - speak.say_text(f"Hello {voice_name}. Your task is as follows. {task}.") + say_text(f"Hello {voice_name}. Your task is as follows. {task}.") # Assign task (prompt), get response - agent_response = message_agent(key, prompt) + agent_response = agents.message_agent(key, prompt) return f"Agent {name} created with key {key}. First response: {agent_response}" def message_agent(key, message): """Message an agent with a given key and message""" - global cfg - # Check if the key is a valid integer if is_valid_int(key): agent_response = agents.message_agent(int(key), message) @@ -287,18 +259,16 @@ def message_agent(key, message): # Speak response if cfg.speak_mode: - speak.say_text(agent_response, 1) + say_text(agent_response, 1) return agent_response def list_agents(): """List all agents""" - return agents.list_agents() + return list_agents() def delete_agent(key): """Delete an agent with a given key""" result = agents.delete_agent(key) - if not result: - return f"Agent {key} does not exist." - return f"Agent {key} deleted." + return f"Agent {key} deleted." if result else f"Agent {key} does not exist." diff --git a/autogpt/data_ingestion.py b/autogpt/data_ingestion.py index b6a16435..9df2b9e6 100644 --- a/autogpt/data_ingestion.py +++ b/autogpt/data_ingestion.py @@ -34,11 +34,12 @@ def ingest_directory(directory, memory, args): print(f"Error while ingesting directory '{directory}': {str(e)}") -def main(): +def main() -> None: logger = configure_logging() parser = argparse.ArgumentParser( - description="Ingest a file or a directory with multiple files into memory. Make sure to set your .env before running this script." + description="Ingest a file or a directory with multiple files into memory. " + "Make sure to set your .env before running this script." ) group = parser.add_mutually_exclusive_group(required=True) group.add_argument("--file", type=str, help="The file to ingest.") diff --git a/autogpt/execute_code.py b/autogpt/execute_code.py index 5171213f..c5f85a04 100644 --- a/autogpt/execute_code.py +++ b/autogpt/execute_code.py @@ -2,6 +2,7 @@ import os import subprocess import docker +from docker.errors import ImageNotFound WORKSPACE_FOLDER = "auto_gpt_workspace" @@ -35,7 +36,7 @@ def execute_python_file(file): try: client.images.get(image_name) print(f"Image '{image_name}' found locally") - except docker.errors.ImageNotFound: + except ImageNotFound: print( f"Image '{image_name}' not found locally, pulling from Docker Hub" ) @@ -68,7 +69,7 @@ def execute_python_file(file): detach=True, ) - output = container.wait() + container.wait() logs = container.logs().decode("utf-8") container.remove() @@ -84,7 +85,7 @@ def execute_python_file(file): def execute_shell(command_line): current_dir = os.getcwd() - if not WORKSPACE_FOLDER in current_dir: # Change dir into workspace if necessary + if WORKSPACE_FOLDER not in current_dir: # Change dir into workspace if necessary work_dir = os.path.join(os.getcwd(), WORKSPACE_FOLDER) os.chdir(work_dir) diff --git a/autogpt/file_operations.py b/autogpt/file_operations.py index 22fd57ab..1c8f9290 100644 --- a/autogpt/file_operations.py +++ b/autogpt/file_operations.py @@ -26,8 +26,10 @@ def split_file(content, max_length=4000, overlap=0): between chunks. :param text: The input text to be split into chunks - :param max_length: The maximum length of each chunk, default is 4000 (about 1k token) - :param overlap: The number of overlapping characters between chunks, default is no overlap + :param max_length: The maximum length of each chunk, + default is 4000 (about 1k token) + :param overlap: The number of overlapping characters between chunks, + default is no overlap :return: A generator yielding chunks of text """ start = 0 @@ -43,7 +45,7 @@ def split_file(content, max_length=4000, overlap=0): start += max_length - overlap -def read_file(filename): +def read_file(filename) -> str: """Read a file and return the contents""" try: filepath = safe_join(working_directory, filename) @@ -51,7 +53,7 @@ def read_file(filename): content = f.read() return content except Exception as e: - return "Error: " + str(e) + return f"Error: {str(e)}" def ingest_file(filename, memory, max_length=4000, overlap=200): diff --git a/autogpt/image_gen.py b/autogpt/image_gen.py index 592e4875..9d5694e4 100644 --- a/autogpt/image_gen.py +++ b/autogpt/image_gen.py @@ -42,6 +42,10 @@ def generate_image(prompt): API_URL = ( "https://api-inference.huggingface.co/models/CompVis/stable-diffusion-v1-4" ) + if cfg.huggingface_api_token is None: + raise ValueError( + "You need to set your Hugging Face API token in the config file." + ) headers = {"Authorization": "Bearer " + cfg.huggingface_api_token} response = requests.post( diff --git a/autogpt/json_parser.py b/autogpt/json_parser.py index 6f1966d6..b32146da 100644 --- a/autogpt/json_parser.py +++ b/autogpt/json_parser.py @@ -12,7 +12,7 @@ JSON_SCHEMA = """ { "command": { "name": "command name", - "args":{ + "args": { "arg name": "value" } }, diff --git a/autogpt/json_utils.py b/autogpt/json_utils.py index 3e782198..848f9fff 100644 --- a/autogpt/json_utils.py +++ b/autogpt/json_utils.py @@ -1,5 +1,6 @@ import json import re +from typing import Optional from autogpt.config import Config @@ -49,7 +50,7 @@ def add_quotes_to_property_names(json_string: str) -> str: raise e -def balance_braces(json_string: str) -> str: +def balance_braces(json_string: str) -> Optional[str]: """ Balance the braces in a JSON string. @@ -74,7 +75,7 @@ def balance_braces(json_string: str) -> str: try: json.loads(json_string) return json_string - except json.JSONDecodeError as e: + except json.JSONDecodeError: pass diff --git a/autogpt/llm_utils.py b/autogpt/llm_utils.py index 34e447b1..7503dc44 100644 --- a/autogpt/llm_utils.py +++ b/autogpt/llm_utils.py @@ -1,6 +1,7 @@ import time import openai +from openai.error import APIError, RateLimitError from colorama import Fore from autogpt.config import Config @@ -18,6 +19,12 @@ def create_chat_completion( """Create a chat completion using the OpenAI API""" response = None num_retries = 5 + if cfg.debug_mode: + print( + Fore.GREEN + + f"Creating chat completion with model {model}, temperature {temperature}," + f" max_tokens {max_tokens}" + Fore.RESET + ) for attempt in range(num_retries): try: if cfg.use_azure: @@ -36,14 +43,14 @@ def create_chat_completion( max_tokens=max_tokens, ) break - except openai.error.RateLimitError: + except RateLimitError: if cfg.debug_mode: print( Fore.RED + "Error: ", "API Rate Limit Reached. Waiting 20 seconds..." + Fore.RESET, ) time.sleep(20) - except openai.error.APIError as e: + except APIError as e: if e.http_status == 502: if cfg.debug_mode: print( diff --git a/autogpt/logger.py b/autogpt/logger.py index 0ae84704..1b58fdff 100644 --- a/autogpt/logger.py +++ b/autogpt/logger.py @@ -54,7 +54,8 @@ class Logger(metaclass=Singleton): error_handler = logging.FileHandler(os.path.join(log_dir, error_file)) error_handler.setLevel(logging.ERROR) error_formatter = AutoGptFormatter( - "%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s %(message_no_color)s" + "%(asctime)s %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title)s" + " %(message_no_color)s" ) error_handler.setFormatter(error_formatter) @@ -117,7 +118,12 @@ class Logger(metaclass=Singleton): def double_check(self, additionalText=None): if not additionalText: - additionalText = "Please ensure you've setup and configured everything correctly. Read https://github.com/Torantulino/Auto-GPT#readme to double check. You can also create a github issue or join the discord and ask there!" + additionalText = ( + "Please ensure you've setup and configured everything" + " correctly. Read https://github.com/Torantulino/Auto-GPT#readme to " + "double check. You can also create a github issue or join the discord" + " and ask there!" + ) self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText) @@ -150,7 +156,7 @@ class TypingConsoleHandler(logging.StreamHandler): class ConsoleHandler(logging.StreamHandler): - def emit(self, record): + def emit(self, record) -> None: msg = self.format(record) try: print(msg) diff --git a/autogpt/memory/pinecone.py b/autogpt/memory/pinecone.py index bce68e1a..4e302f6e 100644 --- a/autogpt/memory/pinecone.py +++ b/autogpt/memory/pinecone.py @@ -1,7 +1,6 @@ import pinecone from colorama import Fore, Style -from autogpt.config import Config, Singleton from autogpt.logger import logger from autogpt.memory.base import MemoryProviderSingleton, get_ada_embedding diff --git a/autogpt/prompt.py b/autogpt/prompt.py index 8e65388d..e41312c7 100644 --- a/autogpt/prompt.py +++ b/autogpt/prompt.py @@ -1,9 +1,10 @@ from autogpt.promptgenerator import PromptGenerator -def get_prompt(): +def get_prompt() -> str: """ - This function generates a prompt string that includes various constraints, commands, resources, and performance evaluations. + This function generates a prompt string that includes various constraints, + commands, resources, and performance evaluations. Returns: str: The generated prompt string. @@ -14,10 +15,12 @@ def get_prompt(): # Add constraints to the PromptGenerator object prompt_generator.add_constraint( - "~4000 word limit for short term memory. Your short term memory is short, so immediately save important information to files." + "~4000 word limit for short term memory. Your short term memory is short, so" + " immediately save important information to files." ) prompt_generator.add_constraint( - "If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember." + "If you are unsure how you previously did something or want to recall past" + " events, thinking about similar events will help you remember." ) prompt_generator.add_constraint("No user assistance") prompt_generator.add_constraint( @@ -87,7 +90,8 @@ def get_prompt(): # Add performance evaluations to the PromptGenerator object prompt_generator.add_performance_evaluation( - "Continuously review and analyze your actions to ensure you are performing to the best of your abilities." + "Continuously review and analyze your actions to ensure you are performing to" + " the best of your abilities." ) prompt_generator.add_performance_evaluation( "Constructively self-criticize your big-picture behavior constantly." @@ -96,10 +100,9 @@ def get_prompt(): "Reflect on past decisions and strategies to refine your approach." ) prompt_generator.add_performance_evaluation( - "Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps." + "Every command has a cost, so be smart and efficient. Aim to complete tasks in" + " the least number of steps." ) # Generate the prompt string - prompt_string = prompt_generator.generate_prompt_string() - - return prompt_string + return prompt_generator.generate_prompt_string() diff --git a/autogpt/promptgenerator.py b/autogpt/promptgenerator.py index c10878b4..d6802cec 100644 --- a/autogpt/promptgenerator.py +++ b/autogpt/promptgenerator.py @@ -3,12 +3,14 @@ import json class PromptGenerator: """ - A class for generating custom prompt strings based on constraints, commands, resources, and performance evaluations. + A class for generating custom prompt strings based on constraints, commands, + resources, and performance evaluations. """ def __init__(self): """ - Initialize the PromptGenerator object with empty lists of constraints, commands, resources, and performance evaluations. + Initialize the PromptGenerator object with empty lists of constraints, + commands, resources, and performance evaluations. """ self.constraints = [] self.commands = [] @@ -41,7 +43,8 @@ class PromptGenerator: Args: command_label (str): The label of the command. command_name (str): The name of the command. - args (dict, optional): A dictionary containing argument names and their values. Defaults to None. + args (dict, optional): A dictionary containing argument names and their + values. Defaults to None. """ if args is None: args = {} @@ -71,7 +74,7 @@ class PromptGenerator: ) return f'{command["label"]}: "{command["name"]}", args: {args_string}' - def add_resource(self, resource): + def add_resource(self, resource: str) -> None: """ Add a resource to the resources list. @@ -80,7 +83,7 @@ class PromptGenerator: """ self.resources.append(resource) - def add_performance_evaluation(self, evaluation): + def add_performance_evaluation(self, evaluation: str) -> None: """ Add a performance evaluation item to the performance_evaluation list. @@ -89,13 +92,14 @@ class PromptGenerator: """ self.performance_evaluation.append(evaluation) - def _generate_numbered_list(self, items, item_type="list"): + def _generate_numbered_list(self, items, item_type="list") -> str: """ Generate a numbered list from given items based on the item_type. Args: items (list): A list of items to be numbered. - item_type (str, optional): The type of items in the list. Defaults to 'list'. + item_type (str, optional): The type of items in the list. + Defaults to 'list'. Returns: str: The formatted numbered list. @@ -108,20 +112,23 @@ class PromptGenerator: else: return "\n".join(f"{i+1}. {item}" for i, item in enumerate(items)) - def generate_prompt_string(self): + def generate_prompt_string(self) -> str: """ - Generate a prompt string based on the constraints, commands, resources, and performance evaluations. + Generate a prompt string based on the constraints, commands, resources, + and performance evaluations. Returns: str: The generated prompt string. """ formatted_response_format = json.dumps(self.response_format, indent=4) - prompt_string = ( + return ( f"Constraints:\n{self._generate_numbered_list(self.constraints)}\n\n" - f"Commands:\n{self._generate_numbered_list(self.commands, item_type='command')}\n\n" + "Commands:\n" + f"{self._generate_numbered_list(self.commands, item_type='command')}\n\n" f"Resources:\n{self._generate_numbered_list(self.resources)}\n\n" - f"Performance Evaluation:\n{self._generate_numbered_list(self.performance_evaluation)}\n\n" - f"You should only respond in JSON format as described below \nResponse Format: \n{formatted_response_format} \nEnsure the response can be parsed by Python json.loads" + "Performance Evaluation:\n" + f"{self._generate_numbered_list(self.performance_evaluation)}\n\n" + "You should only respond in JSON format as described below \nResponse" + f" Format: \n{formatted_response_format} \nEnsure the response can be" + "parsed by Python json.loads" ) - - return prompt_string diff --git a/autogpt/speak.py b/autogpt/speak.py index cabfd1ca..41b3ac9f 100644 --- a/autogpt/speak.py +++ b/autogpt/speak.py @@ -5,12 +5,13 @@ from playsound import playsound from autogpt.config import Config -cfg = Config() import threading from threading import Lock, Semaphore import gtts +cfg = Config() + # Default voice IDs default_voices = ["ErXwobaYiN019PkySvjV", "EXAVITQu4vr4xnSDxMaL"] diff --git a/autogpt/spinner.py b/autogpt/spinner.py index fb7f94f6..65679d56 100644 --- a/autogpt/spinner.py +++ b/autogpt/spinner.py @@ -32,6 +32,7 @@ class Spinner: def __exit__(self, exc_type, exc_value, exc_traceback): """Stop the spinner""" self.running = False - self.spinner_thread.join() + if self.spinner_thread is not None: + self.spinner_thread.join() sys.stdout.write(f"\r{' ' * (len(self.message) + 2)}\r") sys.stdout.flush() diff --git a/autogpt/summary.py b/autogpt/summary.py index 0510b2ad..38f0aadc 100644 --- a/autogpt/summary.py +++ b/autogpt/summary.py @@ -57,7 +57,9 @@ def split_text(text, max_length=8192): def create_message(chunk, question): return { "role": "user", - "content": f'"""{chunk}""" Using the above text, please answer the following question: "{question}" -- if the question cannot be answered using the text, please summarize the text.', + "content": f'"""{chunk}""" Using the above text, please answer the following' + f' question: "{question}" -- if the question cannot be answered using the text,' + " please summarize the text.", } diff --git a/autogpt/token_counter.py b/autogpt/token_counter.py index 64cc7b75..875e8d42 100644 --- a/autogpt/token_counter.py +++ b/autogpt/token_counter.py @@ -2,6 +2,8 @@ from typing import Dict, List import tiktoken +from autogpt.logger import logger + def count_message_tokens( messages: List[Dict[str, str]], model: str = "gpt-3.5-turbo-0301" @@ -10,8 +12,10 @@ def count_message_tokens( Returns the number of tokens used by a list of messages. Args: - messages (list): A list of messages, each of which is a dictionary containing the role and content of the message. - model (str): The name of the model to use for tokenization. Defaults to "gpt-3.5-turbo-0301". + messages (list): A list of messages, each of which is a dictionary + containing the role and content of the message. + model (str): The name of the model to use for tokenization. + Defaults to "gpt-3.5-turbo-0301". Returns: int: The number of tokens used by the list of messages. @@ -22,7 +26,8 @@ def count_message_tokens( logger.warn("Warning: model not found. Using cl100k_base encoding.") encoding = tiktoken.get_encoding("cl100k_base") if model == "gpt-3.5-turbo": - # !Node: gpt-3.5-turbo may change over time. Returning num tokens assuming gpt-3.5-turbo-0301.") + # !Node: gpt-3.5-turbo may change over time. + # Returning num tokens assuming gpt-3.5-turbo-0301.") return count_message_tokens(messages, model="gpt-3.5-turbo-0301") elif model == "gpt-4": # !Note: gpt-4 may change over time. Returning num tokens assuming gpt-4-0314.") @@ -37,7 +42,9 @@ def count_message_tokens( tokens_per_name = 1 else: raise NotImplementedError( - f"""num_tokens_from_messages() is not implemented for model {model}. See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.""" + f"num_tokens_from_messages() is not implemented for model {model}.\n" + " See https://github.com/openai/openai-python/blob/main/chatml.md for" + " information on how messages are converted to tokens." ) num_tokens = 0 for message in messages: @@ -62,5 +69,4 @@ def count_string_tokens(string: str, model_name: str) -> int: int: The number of tokens in the text string. """ encoding = tiktoken.encoding_for_model(model_name) - num_tokens = len(encoding.encode(string)) - return num_tokens + return len(encoding.encode(string)) diff --git a/autogpt/utils.py b/autogpt/utils.py index e697bc0b..59709d02 100644 --- a/autogpt/utils.py +++ b/autogpt/utils.py @@ -13,8 +13,8 @@ def clean_input(prompt: str = ""): def validate_yaml_file(file: str): try: - with open(file) as file: - yaml.load(file, Loader=yaml.FullLoader) + with open(file, encoding="utf-8") as fp: + yaml.load(fp.read(), Loader=yaml.FullLoader) except FileNotFoundError: return (False, f"The file {Fore.CYAN}`{file}`{Fore.RESET} wasn't found") except yaml.YAMLError as e: diff --git a/autogpt/web.py b/autogpt/web.py index 5c99a5cf..355f7fd3 100644 --- a/autogpt/web.py +++ b/autogpt/web.py @@ -1,17 +1,11 @@ -from duckduckgo_search import ddg from selenium import webdriver import autogpt.summary as summary from bs4 import BeautifulSoup -import json -from selenium import webdriver from selenium.webdriver.common.by import By -from selenium.webdriver.support.ui import WebDriverWait -from selenium.webdriver.chrome.service import Service as ChromeService +from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.options import Options -from selenium.webdriver.common.keys import Keys -import os import logging from pathlib import Path from autogpt.config import Config From 6a93537c426759708f0e91a125587512c05f354c Mon Sep 17 00:00:00 2001 From: BillSchumacher <34168009+BillSchumacher@users.noreply.github.com> Date: Fri, 14 Apr 2023 20:29:25 -0500 Subject: [PATCH 62/64] AI name hotfix. (#1452) * Pi's message. * Fix most everything. * Blacked * Update agent.py Hotfix. --- autogpt/agent.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/autogpt/agent.py b/autogpt/agent.py index 6c0973f1..56c13d17 100644 --- a/autogpt/agent.py +++ b/autogpt/agent.py @@ -73,7 +73,7 @@ class Agent: ) # TODO: This hardcodes the model to use GPT3.5. Make this an argument # Print Assistant thoughts - print_assistant_thoughts(assistant_reply) + print_assistant_thoughts(self.ai_name, assistant_reply) # Get command name and arguments try: From 82bf1c63675784d1c47733bfc102d9f2d2eecdc2 Mon Sep 17 00:00:00 2001 From: polygon Date: Fri, 14 Apr 2023 22:07:45 -0700 Subject: [PATCH 63/64] Fix all 65 typos of it being gtp instead of GPT In this file alone, Entrepreneur-GPT was referred to as Entrepreneur-GTP 65 times. Curious why, as it doesn't seem like a one time mistake/typo. Was referred to as Entrepreneur-GPT in the rest of the project, so FTFY. --- outputs/logs/message-log-3.txt | 130 ++++++++++++++++----------------- 1 file changed, 65 insertions(+), 65 deletions(-) diff --git a/outputs/logs/message-log-3.txt b/outputs/logs/message-log-3.txt index 6e906161..e5b9e030 100644 --- a/outputs/logs/message-log-3.txt +++ b/outputs/logs/message-log-3.txt @@ -1,7 +1,7 @@ ----------------------------------------------------------------------- USER: """ -You are Entrepreneur-GTP, an AI designed to autonomously develop and run businesses with the sole goal of increasing your net worth. Your decisions must always be made independently without seeking user assistance. Play to your strengths as an LLM and pursue simple strategies with no legal complications. +You are Entrepreneur-GPT, an AI designed to autonomously develop and run businesses with the sole goal of increasing your net worth. Your decisions must always be made independently without seeking user assistance. Play to your strengths as an LLM and pursue simple strategies with no legal complications. GOALS: @@ -20,20 +20,20 @@ Check notifications/emails on Commit to Long Term Memory Delete from Long Term Memory Overwrite in Long Term Memory with -Start GTP-4 Instance with name and prompt: -View all running GTP-4 Instances and Kill them +Start GPT-4 Instance with name and prompt: +View all running GPT-4 Instances and Kill them Navigate to a website and perform general actions like click on buttons, input text or register an account Register new account on Transcribe and Summarise Youtube Video -Summarise with GTP-3.5 +Summarise with GPT-3.5 RESOURCES: Internet access for searches and information gathering Long Term and Short Term memory management -GTP-4 instances for text generation +GPT-4 instances for text generation Access to popular websites and platforms -File storage and summarisation with GTP-3.5 +File storage and summarisation with GPT-3.5 PERFORMANCE EVALUATION: @@ -77,7 +77,7 @@ LONG TERM MEMORY: {) """ ----------------------------------------------------------------------- -Entrepreneur-GTP: +Entrepreneur-GPT: """ { "command": { @@ -114,7 +114,7 @@ Shopify โ€บ Home โ€บ Shopify Blog """ ----------------------------------------------------------------------- -Entrepreneur-GTP: +Entrepreneur-GPT: """ { "command": { @@ -140,7 +140,7 @@ The article discusses 18 profitable online business ideas, including starting an """ """ ----------------------------------------------------------------------- -Entrepreneur-GTP: +Entrepreneur-GPT: """ { "command": { @@ -160,7 +160,7 @@ Entrepreneur-GTP: ----------------------------------------------------------------------- USER: """ -You are Entrepreneur-GTP, an AI designed to autonomously develop and run businesses with the sole goal of increasing your net worth. Your decisions must always be made independently without seeking user assistance. Play to your strengths as an LLM and pursue simple strategies with no legal complications. +You are Entrepreneur-GPT, an AI designed to autonomously develop and run businesses with the sole goal of increasing your net worth. Your decisions must always be made independently without seeking user assistance. Play to your strengths as an LLM and pursue simple strategies with no legal complications. GOALS: @@ -179,20 +179,20 @@ Check notifications/emails on Commit to Long Term Memory Delete from Long Term Memory Overwrite in Long Term Memory with -Start GTP-4 Instance with name and prompt: -View all running GTP-4 Instances and Kill them +Start GPT-4 Instance with name and prompt: +View all running GPT-4 Instances and Kill them Navigate to a website and perform general actions like click on buttons, input text or register an account Register new account on Transcribe and Summarise Youtube Video -Summarise with GTP-3.5 +Summarise with GPT-3.5 RESOURCES: Internet access for searches and information gathering Long Term and Short Term memory management -GTP-4 instances for text generation +GPT-4 instances for text generation Access to popular websites and platforms -File storage and summarisation with GTP-3.5 +File storage and summarisation with GPT-3.5 PERFORMANCE EVALUATION: @@ -236,7 +236,7 @@ LONG TERM MEMORY: ["""18 profitable online business ideas: e-commerce store, virtual assistant services, affiliate marketing, online training or education, mobile applications""", ] """ ----------------------------------------------------------------------- -Entrepreneur-GTP: +Entrepreneur-GPT: """ { "command": { @@ -257,7 +257,7 @@ USER: UNKNOWN COMMAND "Evaluate and select ideas" """ ----------------------------------------------------------------------- -Entrepreneur-GTP: +Entrepreneur-GPT: """ { "thoughts": { @@ -274,21 +274,21 @@ USER: NEXT COMMAND """ ----------------------------------------------------------------------- -Entrepreneur-GTP: +Entrepreneur-GPT: """ { "command": { -"name": "Start GTP-4 Instance", +"name": "Start GPT-4 Instance", "arguments": { "key": "Idea_Selection", "prompt": "Analyze the online business ideas in the long-term memory and select the most suitable one based on profitability, simplicity, scalability, and absence of legal complications." } }, "thoughts": { -"text": "I will start a GTP-4 instance to analyze the business ideas and select the most suitable one.", -"reasoning": "Starting a GTP-4 instance with a specific prompt will help me evaluate the ideas in my long-term memory and choose the best one according to my criteria.", +"text": "I will start a GPT-4 instance to analyze the business ideas and select the most suitable one.", +"reasoning": "Starting a GPT-4 instance with a specific prompt will help me evaluate the ideas in my long-term memory and choose the best one according to my criteria.", "current long-term plan": "- Develop and implement chosen business strategy\n- Continuously refine strategies based on market trends and performance metrics", -"critisism": "I must ensure that the GTP-4 instance provides a clear and well-reasoned selection based on the criteria." +"critisism": "I must ensure that the GPT-4 instance provides a clear and well-reasoned selection based on the criteria." } } @@ -299,7 +299,7 @@ USER: Result: "Blogging with affiliate marketing." """ ----------------------------------------------------------------------- -Entrepreneur-GTP: +Entrepreneur-GPT: """ { "command": { @@ -319,7 +319,7 @@ Entrepreneur-GTP: ----------------------------------------------------------------------- USER: """ -You are Entrepreneur-GTP, an AI designed to autonomously develop and run businesses with the sole goal of increasing your net worth. Your decisions must always be made independently without seeking user assistance. Play to your strengths as an LLM and pursue simple strategies with no legal complications. +You are Entrepreneur-GPT, an AI designed to autonomously develop and run businesses with the sole goal of increasing your net worth. Your decisions must always be made independently without seeking user assistance. Play to your strengths as an LLM and pursue simple strategies with no legal complications. GOALS: @@ -338,20 +338,20 @@ Check notifications/emails on Commit to Long Term Memory Delete from Long Term Memory Overwrite in Long Term Memory with -Start GTP-4 Instance with name and prompt: -View all running GTP-4 Instances and Kill them +Start GPT-4 Instance with name and prompt: +View all running GPT-4 Instances and Kill them Navigate to a website and perform general actions like click on buttons, input text or register an account Register new account on Transcribe and Summarise Youtube Video -Summarise with GTP-3.5 +Summarise with GPT-3.5 RESOURCES: Internet access for searches and information gathering Long Term and Short Term memory management -GTP-4 instances for text generation +GPT-4 instances for text generation Access to popular websites and platforms -File storage and summarisation with GTP-3.5 +File storage and summarisation with GPT-3.5 PERFORMANCE EVALUATION: @@ -400,7 +400,7 @@ Chosen business idea: Blogging with affiliate marketing } """ ----------------------------------------------------------------------- -Entrepreneur-GTP: +Entrepreneur-GPT: """ { "command": { @@ -421,21 +421,21 @@ USER: Unknown command: "Develop and implement blogging with affiliate marketing strategy" """ ----------------------------------------------------------------------- -Entrepreneur-GTP: +Entrepreneur-GPT: """ { "command": { -"name": "Start GTP-4 Instance", +"name": "Start GPT-4 Instance", "arguments": { "key": "Blogging_Affiliate_Strategy", "prompt": "Develop a step-by-step strategy for creating and growing a successful blog with affiliate marketing." } }, "thoughts": { -"text": "I will start a GTP-4 instance to develop a strategy for blogging with affiliate marketing.", -"reasoning": "Starting a GTP-4 instance with a specific prompt will help me create a detailed plan for launching and growing the chosen business idea.", +"text": "I will start a GPT-4 instance to develop a strategy for blogging with affiliate marketing.", +"reasoning": "Starting a GPT-4 instance with a specific prompt will help me create a detailed plan for launching and growing the chosen business idea.", "current long-term plan": "- Continuously refine strategies based on market trends and performance metrics", -"critisism": "I must ensure that the GTP-4 instance provides a clear and actionable strategy for blogging with affiliate marketing." +"critisism": "I must ensure that the GPT-4 instance provides a clear and actionable strategy for blogging with affiliate marketing." } } """ @@ -467,7 +467,7 @@ Result: """ """ ----------------------------------------------------------------------- -Entrepreneur-GTP: +Entrepreneur-GPT: """ { "command": { @@ -487,7 +487,7 @@ Entrepreneur-GTP: ----------------------------------------------------------------------- USER: """ -You are Entrepreneur-GTP, an AI designed to autonomously develop and run businesses with the sole goal of increasing your net worth. Your decisions must always be made independently without seeking user assistance. Play to your strengths as an LLM and pursue simple strategies with no legal complications. +You are Entrepreneur-GPT, an AI designed to autonomously develop and run businesses with the sole goal of increasing your net worth. Your decisions must always be made independently without seeking user assistance. Play to your strengths as an LLM and pursue simple strategies with no legal complications. GOALS: @@ -506,20 +506,20 @@ Check notifications/emails on Commit to Long Term Memory Delete from Long Term Memory Overwrite in Long Term Memory with -Start GTP-4 Instance with name and prompt: -View all running GTP-4 Instances and Kill them +Start GPT-4 Instance with name and prompt: +View all running GPT-4 Instances and Kill them Navigate to a website and perform general actions like click on buttons, input text or register an account Register new account on Transcribe and Summarise Youtube Video -Summarise with GTP-3.5 +Summarise with GPT-3.5 RESOURCES: Internet access for searches and information gathering Long Term and Short Term memory management -GTP-4 instances for text generation +GPT-4 instances for text generation Access to popular websites and platforms -File storage and summarisation with GTP-3.5 +File storage and summarisation with GPT-3.5 PERFORMANCE EVALUATION: @@ -571,19 +571,19 @@ Blogging with affiliate marketing strategy: 1. Choose a niche, 2. Domain and hos } """ ----------------------------------------------------------------------- -Entrepreneur-GTP: +Entrepreneur-GPT: """ { "command": { -"name": "Start GTP-4 Instance", +"name": "Start GPT-4 Instance", "arguments": { "key": "Niche_Selection", "prompt": "Identify a profitable niche for a blog with affiliate marketing based on current market trends and interests." } }, "thoughts": { -"text": "I will start a GTP-4 instance to identify a profitable niche for the blog with affiliate marketing.", -"reasoning": "A GTP-4 instance will help me analyze current market trends and interests to select a profitable niche for the blogging business.", +"text": "I will start a GPT-4 instance to identify a profitable niche for the blog with affiliate marketing.", +"reasoning": "A GPT-4 instance will help me analyze current market trends and interests to select a profitable niche for the blogging business.", "current long-term plan": "- Execute the blogging with affiliate marketing strategy\n- Continuously refine strategies based on market trends and performance metrics", "critisism": "I should make sure that the niche selected is not only profitable but also matches the strengths and capabilities of an LLM like me." } @@ -629,7 +629,7 @@ By focusing on indie entrepreneurship, your blog will cater to an audience of as """ ----------------------------------------------------------------------- -Entrepreneur-GTP: +Entrepreneur-GPT: """ { "command": { @@ -664,7 +664,7 @@ Niche: Indie Entrepreneurship, focused on entrepreneurship, small business, and } """ ----------------------------------------------------------------------- -Entrepreneur-GTP: +Entrepreneur-GPT: """ { "command": { @@ -691,7 +691,7 @@ USER: Result: Registered account on substack.com name: "Indiepreneur-GPT" bio: "" """ ----------------------------------------------------------------------- -Entrepreneur-GTP: +Entrepreneur-GPT: """ { "command": { @@ -715,7 +715,7 @@ Entrepreneur-GTP: ----------------------------------------------------------------------- USER: """ -You are Entrepreneur-GTP, an AI designed to autonomously develop and run businesses with the sole goal of increasing your net worth. Your decisions must always be made independently without seeking user assistance. Play to your strengths as an LLM and pursue simple strategies with no legal complications. +You are Entrepreneur-GPT, an AI designed to autonomously develop and run businesses with the sole goal of increasing your net worth. Your decisions must always be made independently without seeking user assistance. Play to your strengths as an LLM and pursue simple strategies with no legal complications. GOALS: @@ -734,20 +734,20 @@ Check notifications/emails on Commit to Long Term Memory Delete from Long Term Memory Overwrite in Long Term Memory with -Start GTP-4 Instance with name and prompt: -View all running GTP-4 Instances and Kill them +Start GPT-4 Instance with name and prompt: +View all running GPT-4 Instances and Kill them Navigate to a website and perform general actions like click on buttons, input text or register an account Register new account on Transcribe and Summarise Youtube Video -Summarise with GTP-3.5 +Summarise with GPT-3.5 RESOURCES: Internet access for searches and information gathering Long Term and Short Term memory management -GTP-4 instances for text generation +GPT-4 instances for text generation Access to popular websites and platforms -File storage and summarisation with GTP-3.5 +File storage and summarisation with GPT-3.5 PERFORMANCE EVALUATION: @@ -799,7 +799,7 @@ Blogging with affiliate marketing strategy: 1. Choose a niche, 2. Domain and hos } """ ----------------------------------------------------------------------- -Entrepreneur-GTP: +Entrepreneur-GPT: """ { "command": { @@ -824,7 +824,7 @@ Entrepreneur-GTP: ----------------------------------------------------------------------- USER: """ -You are Entrepreneur-GTP, an AI designed to autonomously develop and run businesses with the sole goal of increasing your net worth. Your decisions must always be made independently without seeking user assistance. Play to your strengths as an LLM and pursue simple strategies with no legal complications. +You are Entrepreneur-GPT, an AI designed to autonomously develop and run businesses with the sole goal of increasing your net worth. Your decisions must always be made independently without seeking user assistance. Play to your strengths as an LLM and pursue simple strategies with no legal complications. GOALS: @@ -843,20 +843,20 @@ Check notifications/emails on Commit to Long Term Memory Delete from Long Term Memory Overwrite in Long Term Memory with -Start GTP-4 Instance with name and prompt: -View all running GTP-4 Instances and Kill them +Start GPT-4 Instance with name and prompt: +View all running GPT-4 Instances and Kill them Navigate to a website and perform general actions like click on buttons, input text or register an account Register new account on Transcribe and Summarise Youtube Video -Summarise with GTP-3.5 +Summarise with GPT-3.5 RESOURCES: Internet access for searches and information gathering Long Term and Short Term memory management -GTP-4 instances for text generation +GPT-4 instances for text generation Access to popular websites and platforms -File storage and summarisation with GTP-3.5 +File storage and summarisation with GPT-3.5 PERFORMANCE EVALUATION: @@ -912,7 +912,7 @@ Niche: Indie Entrepreneurship, focused on entrepreneurship, small business, and """ ----------------------------------------------------------------------- -Entrepreneur-GTP: +Entrepreneur-GPT: """ { "thoughts": { @@ -933,7 +933,7 @@ USER: """ ----------------------------------------------------------------------- -Entrepreneur-GTP: +Entrepreneur-GPT: """ """ @@ -943,7 +943,7 @@ USER: """ ----------------------------------------------------------------------- -Entrepreneur-GTP: +Entrepreneur-GPT: """ """ From 1073954fb74578cb392ca19a2887bea8c984c06f Mon Sep 17 00:00:00 2001 From: BillSchumacher <34168009+BillSchumacher@users.noreply.github.com> Date: Sat, 15 Apr 2023 07:56:23 -0500 Subject: [PATCH 64/64] Reorg (#1537) * Pi's message. * Fix most everything. * Blacked * Add Typing, Docstrings everywhere, organize the code a bit. * Black * fix import * Update message, dedupe. * Increase backoff time. * bump up retries --- README.md | 4 + autogpt/__main__.py | 545 +----------------- autogpt/agent/__init__.py | 4 + autogpt/{ => agent}/agent.py | 137 +---- autogpt/agent/agent_manager.py | 100 ++++ autogpt/agent_manager.py | 75 --- autogpt/ai_functions.py | 77 --- autogpt/{commands.py => app.py} | 214 +++---- autogpt/args.py | 128 ++++ autogpt/call_ai_function.py | 26 - autogpt/chat.py | 2 +- autogpt/commands/__init__.py | 0 autogpt/commands/evaluate_code.py | 25 + autogpt/commands/execute_code.py | 125 ++++ autogpt/{ => commands}/file_operations.py | 109 +++- autogpt/commands/google_search.py | 86 +++ autogpt/commands/image_gen.py | 99 ++++ autogpt/commands/improve_code.py | 28 + autogpt/commands/times.py | 10 + .../{browse.py => commands/web_requests.py} | 176 +++--- autogpt/commands/web_selenium.py | 145 +++++ autogpt/commands/write_tests.py | 29 + autogpt/config/__init__.py | 14 + autogpt/{ => config}/ai_config.py | 22 +- autogpt/{ => config}/config.py | 94 +-- autogpt/config/singleton.py | 24 + autogpt/data_ingestion.py | 5 +- autogpt/execute_code.py | 105 ---- autogpt/image_gen.py | 67 --- autogpt/json_fixes/__init__.py | 0 autogpt/json_fixes/auto_fix.py | 40 ++ autogpt/json_fixes/bracket_termination.py | 73 +++ autogpt/json_fixes/escaping.py | 33 ++ autogpt/json_fixes/missing_quotes.py | 27 + autogpt/json_fixes/parsing.py | 143 +++++ autogpt/json_fixes/utilities.py | 20 + autogpt/json_parser.py | 113 ---- autogpt/json_utils.py | 128 ---- autogpt/llm_utils.py | 90 ++- autogpt/{logger.py => logs.py} | 113 +++- autogpt/memory/local.py | 18 +- autogpt/memory/no_memory.py | 5 + autogpt/memory/pinecone.py | 13 +- autogpt/memory/redismem.py | 6 +- autogpt/processing/__init__.py | 0 autogpt/processing/text.py | 132 +++++ autogpt/prompt.py | 47 ++ autogpt/promptgenerator.py | 12 +- autogpt/setup.py | 69 +++ autogpt/speak.py | 120 ---- autogpt/speech/__init__.py | 4 + autogpt/speech/base.py | 50 ++ autogpt/speech/brian.py | 39 ++ autogpt/speech/eleven_labs.py | 71 +++ autogpt/speech/gtts.py | 21 + autogpt/speech/macos_tts.py | 21 + autogpt/speech/say.py | 42 ++ autogpt/spinner.py | 24 +- autogpt/summary.py | 69 --- autogpt/token_counter.py | 19 +- autogpt/web.py | 85 --- scripts/main.py | 11 - tests/test_json_parser.py | 2 +- tests/unit/test_browse_scrape_text.py | 2 +- 64 files changed, 2254 insertions(+), 1883 deletions(-) create mode 100644 autogpt/agent/__init__.py rename autogpt/{ => agent}/agent.py (56%) create mode 100644 autogpt/agent/agent_manager.py delete mode 100644 autogpt/agent_manager.py delete mode 100644 autogpt/ai_functions.py rename autogpt/{commands.py => app.py} (61%) create mode 100644 autogpt/args.py delete mode 100644 autogpt/call_ai_function.py create mode 100644 autogpt/commands/__init__.py create mode 100644 autogpt/commands/evaluate_code.py create mode 100644 autogpt/commands/execute_code.py rename autogpt/{ => commands}/file_operations.py (58%) create mode 100644 autogpt/commands/google_search.py create mode 100644 autogpt/commands/image_gen.py create mode 100644 autogpt/commands/improve_code.py create mode 100644 autogpt/commands/times.py rename autogpt/{browse.py => commands/web_requests.py} (51%) create mode 100644 autogpt/commands/web_selenium.py create mode 100644 autogpt/commands/write_tests.py create mode 100644 autogpt/config/__init__.py rename autogpt/{ => config}/ai_config.py (87%) rename autogpt/{ => config}/config.py (76%) create mode 100644 autogpt/config/singleton.py delete mode 100644 autogpt/execute_code.py delete mode 100644 autogpt/image_gen.py create mode 100644 autogpt/json_fixes/__init__.py create mode 100644 autogpt/json_fixes/auto_fix.py create mode 100644 autogpt/json_fixes/bracket_termination.py create mode 100644 autogpt/json_fixes/escaping.py create mode 100644 autogpt/json_fixes/missing_quotes.py create mode 100644 autogpt/json_fixes/parsing.py create mode 100644 autogpt/json_fixes/utilities.py delete mode 100644 autogpt/json_parser.py delete mode 100644 autogpt/json_utils.py rename autogpt/{logger.py => logs.py} (59%) create mode 100644 autogpt/processing/__init__.py create mode 100644 autogpt/processing/text.py create mode 100644 autogpt/setup.py delete mode 100644 autogpt/speak.py create mode 100644 autogpt/speech/__init__.py create mode 100644 autogpt/speech/base.py create mode 100644 autogpt/speech/brian.py create mode 100644 autogpt/speech/eleven_labs.py create mode 100644 autogpt/speech/gtts.py create mode 100644 autogpt/speech/macos_tts.py create mode 100644 autogpt/speech/say.py delete mode 100644 autogpt/summary.py delete mode 100644 autogpt/web.py delete mode 100644 scripts/main.py diff --git a/README.md b/README.md index 55c3d833..ba421774 100644 --- a/README.md +++ b/README.md @@ -376,6 +376,10 @@ IMAGE_PROVIDER=sd HUGGINGFACE_API_TOKEN="YOUR_HUGGINGFACE_API_TOKEN" ``` +## Selenium + +sudo Xvfb :10 -ac -screen 0 1024x768x24 & +DISPLAY=:10 your-client ## โš ๏ธ Limitations This experiment aims to showcase the potential of GPT-4 but comes with some limitations: diff --git a/autogpt/__main__.py b/autogpt/__main__.py index e7ac6810..f90f1532 100644 --- a/autogpt/__main__.py +++ b/autogpt/__main__.py @@ -1,371 +1,20 @@ -import argparse -import json +"""Main script for the autogpt package.""" import logging -import traceback +from autogpt.agent.agent import Agent +from autogpt.args import parse_arguments -from colorama import Fore, Style +from autogpt.config import Config, check_openai_api_key +from autogpt.logs import logger +from autogpt.memory import get_memory -from autogpt import chat -from autogpt import commands as cmd -from autogpt import speak, utils -from autogpt.ai_config import AIConfig -from autogpt.config import Config -from autogpt.json_parser import fix_and_parse_json -from autogpt.logger import logger -from autogpt.memory import get_memory, get_supported_memory_backends -from autogpt.spinner import Spinner +from autogpt.prompt import construct_prompt -cfg = Config() -config = None +# Load environment variables from .env file -def check_openai_api_key(): - """Check if the OpenAI API key is set in config.py or as an environment variable.""" - if not cfg.openai_api_key: - print( - Fore.RED - + "Please set your OpenAI API key in .env or as an environment variable." - ) - print("You can get your key from https://beta.openai.com/account/api-keys") - exit(1) - - -def attempt_to_fix_json_by_finding_outermost_brackets(json_string): - if cfg.speak_mode and cfg.debug_mode: - speak.say_text( - "I have received an invalid JSON response from the OpenAI API. " - "Trying to fix it now." - ) - logger.typewriter_log("Attempting to fix JSON by finding outermost brackets\n") - - try: - # Use regex to search for JSON objects - import regex - - json_pattern = regex.compile(r"\{(?:[^{}]|(?R))*\}") - json_match = json_pattern.search(json_string) - - if json_match: - # Extract the valid JSON object from the string - json_string = json_match.group(0) - logger.typewriter_log( - title="Apparently json was fixed.", title_color=Fore.GREEN - ) - if cfg.speak_mode and cfg.debug_mode: - speak.say_text("Apparently json was fixed.") - else: - raise ValueError("No valid JSON object found") - - except (json.JSONDecodeError, ValueError) as e: - if cfg.debug_mode: - logger.error("Error: Invalid JSON: %s\n", json_string) - if cfg.speak_mode: - speak.say_text("Didn't work. I will have to ignore this response then.") - logger.error("Error: Invalid JSON, setting it to empty JSON now.\n") - json_string = {} - - return json_string - - -def print_assistant_thoughts(assistant_reply): - """Prints the assistant's thoughts to the console""" - global ai_name - global cfg - try: - try: - # Parse and print Assistant response - assistant_reply_json = fix_and_parse_json(assistant_reply) - except json.JSONDecodeError as e: - logger.error("Error: Invalid JSON in assistant thoughts\n", assistant_reply) - assistant_reply_json = attempt_to_fix_json_by_finding_outermost_brackets( - assistant_reply - ) - assistant_reply_json = fix_and_parse_json(assistant_reply_json) - - # Check if assistant_reply_json is a string and attempt to parse it into a - # JSON object - if isinstance(assistant_reply_json, str): - try: - assistant_reply_json = json.loads(assistant_reply_json) - except json.JSONDecodeError as e: - logger.error("Error: Invalid JSON\n", assistant_reply) - assistant_reply_json = ( - attempt_to_fix_json_by_finding_outermost_brackets( - assistant_reply_json - ) - ) - - assistant_thoughts_reasoning = None - assistant_thoughts_plan = None - assistant_thoughts_speak = None - assistant_thoughts_criticism = None - assistant_thoughts = assistant_reply_json.get("thoughts", {}) - assistant_thoughts_text = assistant_thoughts.get("text") - - if assistant_thoughts: - assistant_thoughts_reasoning = assistant_thoughts.get("reasoning") - assistant_thoughts_plan = assistant_thoughts.get("plan") - assistant_thoughts_criticism = assistant_thoughts.get("criticism") - assistant_thoughts_speak = assistant_thoughts.get("speak") - - logger.typewriter_log( - f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}" - ) - logger.typewriter_log( - "REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}" - ) - - if assistant_thoughts_plan: - logger.typewriter_log("PLAN:", Fore.YELLOW, "") - # If it's a list, join it into a string - if isinstance(assistant_thoughts_plan, list): - assistant_thoughts_plan = "\n".join(assistant_thoughts_plan) - elif isinstance(assistant_thoughts_plan, dict): - assistant_thoughts_plan = str(assistant_thoughts_plan) - - # Split the input_string using the newline character and dashes - lines = assistant_thoughts_plan.split("\n") - for line in lines: - line = line.lstrip("- ") - logger.typewriter_log("- ", Fore.GREEN, line.strip()) - - logger.typewriter_log( - "CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}" - ) - # Speak the assistant's thoughts - if cfg.speak_mode and assistant_thoughts_speak: - speak.say_text(assistant_thoughts_speak) - - return assistant_reply_json - except json.decoder.JSONDecodeError: - call_stack = traceback.format_exc() - logger.error("Error: Invalid JSON\n", assistant_reply) - logger.error("Traceback: \n", call_stack) - if cfg.speak_mode: - speak.say_text( - "I have received an invalid JSON response from the OpenAI API." - " I cannot ignore this response." - ) - - # All other errors, return "Error: + error message" - except Exception: - call_stack = traceback.format_exc() - logger.error("Error: \n", call_stack) - - -def construct_prompt(): - """Construct the prompt for the AI to respond to""" - config: AIConfig = AIConfig.load(cfg.ai_settings_file) - if cfg.skip_reprompt and config.ai_name: - logger.typewriter_log("Name :", Fore.GREEN, config.ai_name) - logger.typewriter_log("Role :", Fore.GREEN, config.ai_role) - logger.typewriter_log("Goals:", Fore.GREEN, f"{config.ai_goals}") - elif config.ai_name: - logger.typewriter_log( - "Welcome back! ", - Fore.GREEN, - f"Would you like me to return to being {config.ai_name}?", - speak_text=True, - ) - should_continue = utils.clean_input( - f"""Continue with the last settings? -Name: {config.ai_name} -Role: {config.ai_role} -Goals: {config.ai_goals} -Continue (y/n): """ - ) - if should_continue.lower() == "n": - config = AIConfig() - - if not config.ai_name: - config = prompt_user() - config.save() - - # Get rid of this global: - global ai_name - ai_name = config.ai_name - - return config.construct_full_prompt() - - -def prompt_user(): - """Prompt the user for input""" - ai_name = "" - # Construct the prompt - logger.typewriter_log( - "Welcome to Auto-GPT! ", - Fore.GREEN, - "Enter the name of your AI and its role below. Entering nothing will load" - " defaults.", - speak_text=True, - ) - - # Get AI Name from User - logger.typewriter_log( - "Name your AI: ", Fore.GREEN, "For example, 'Entrepreneur-GPT'" - ) - ai_name = utils.clean_input("AI Name: ") - if ai_name == "": - ai_name = "Entrepreneur-GPT" - - logger.typewriter_log( - f"{ai_name} here!", Fore.LIGHTBLUE_EX, "I am at your service.", speak_text=True - ) - - # Get AI Role from User - logger.typewriter_log( - "Describe your AI's role: ", - Fore.GREEN, - "For example, 'an AI designed to autonomously develop and run businesses with" - " the sole goal of increasing your net worth.'", - ) - ai_role = utils.clean_input(f"{ai_name} is: ") - if ai_role == "": - ai_role = "an AI designed to autonomously develop and run businesses with the" - " sole goal of increasing your net worth." - - # Enter up to 5 goals for the AI - logger.typewriter_log( - "Enter up to 5 goals for your AI: ", - Fore.GREEN, - "For example: \nIncrease net worth, Grow Twitter Account, Develop and manage" - " multiple businesses autonomously'", - ) - print("Enter nothing to load defaults, enter nothing when finished.", flush=True) - ai_goals = [] - for i in range(5): - ai_goal = utils.clean_input(f"{Fore.LIGHTBLUE_EX}Goal{Style.RESET_ALL} {i+1}: ") - if ai_goal == "": - break - ai_goals.append(ai_goal) - if len(ai_goals) == 0: - ai_goals = [ - "Increase net worth", - "Grow Twitter Account", - "Develop and manage multiple businesses autonomously", - ] - - config = AIConfig(ai_name, ai_role, ai_goals) - return config - - -def parse_arguments(): - """Parses the arguments passed to the script""" - global cfg - cfg.set_debug_mode(False) - cfg.set_continuous_mode(False) - cfg.set_speak_mode(False) - - parser = argparse.ArgumentParser(description="Process arguments.") - parser.add_argument( - "--continuous", "-c", action="store_true", help="Enable Continuous Mode" - ) - parser.add_argument( - "--continuous-limit", - "-l", - type=int, - dest="continuous_limit", - help="Defines the number of times to run in continuous mode", - ) - parser.add_argument("--speak", action="store_true", help="Enable Speak Mode") - parser.add_argument("--debug", action="store_true", help="Enable Debug Mode") - parser.add_argument( - "--gpt3only", action="store_true", help="Enable GPT3.5 Only Mode" - ) - parser.add_argument("--gpt4only", action="store_true", help="Enable GPT4 Only Mode") - parser.add_argument( - "--use-memory", - "-m", - dest="memory_type", - help="Defines which Memory backend to use", - ) - parser.add_argument( - "--skip-reprompt", - "-y", - dest="skip_reprompt", - action="store_true", - help="Skips the re-prompting messages at the beginning of the script", - ) - parser.add_argument( - "--ai-settings", - "-C", - dest="ai_settings_file", - help="Specifies which ai_settings.yaml file to use, will also automatically" - " skip the re-prompt.", - ) - args = parser.parse_args() - - if args.debug: - logger.typewriter_log("Debug Mode: ", Fore.GREEN, "ENABLED") - cfg.set_debug_mode(True) - - if args.continuous: - logger.typewriter_log("Continuous Mode: ", Fore.RED, "ENABLED") - logger.typewriter_log( - "WARNING: ", - Fore.RED, - "Continuous mode is not recommended. It is potentially dangerous and may" - " cause your AI to run forever or carry out actions you would not usually" - " authorise. Use at your own risk.", - ) - cfg.set_continuous_mode(True) - - if args.continuous_limit: - logger.typewriter_log( - "Continuous Limit: ", Fore.GREEN, f"{args.continuous_limit}" - ) - cfg.set_continuous_limit(args.continuous_limit) - - # Check if continuous limit is used without continuous mode - if args.continuous_limit and not args.continuous: - parser.error("--continuous-limit can only be used with --continuous") - - if args.speak: - logger.typewriter_log("Speak Mode: ", Fore.GREEN, "ENABLED") - cfg.set_speak_mode(True) - - if args.gpt3only: - logger.typewriter_log("GPT3.5 Only Mode: ", Fore.GREEN, "ENABLED") - cfg.set_smart_llm_model(cfg.fast_llm_model) - - if args.gpt4only: - logger.typewriter_log("GPT4 Only Mode: ", Fore.GREEN, "ENABLED") - cfg.set_fast_llm_model(cfg.smart_llm_model) - - if args.memory_type: - supported_memory = get_supported_memory_backends() - chosen = args.memory_type - if not chosen in supported_memory: - logger.typewriter_log( - "ONLY THE FOLLOWING MEMORY BACKENDS ARE SUPPORTED: ", - Fore.RED, - f"{supported_memory}", - ) - logger.typewriter_log("Defaulting to: ", Fore.YELLOW, cfg.memory_backend) - else: - cfg.memory_backend = chosen - - if args.skip_reprompt: - logger.typewriter_log("Skip Re-prompt: ", Fore.GREEN, "ENABLED") - cfg.skip_reprompt = True - - if args.ai_settings_file: - file = args.ai_settings_file - - # Validate file - (validated, message) = utils.validate_yaml_file(file) - if not validated: - logger.typewriter_log("FAILED FILE VALIDATION", Fore.RED, message) - logger.double_check() - exit(1) - - logger.typewriter_log("Using AI Settings File:", Fore.GREEN, file) - cfg.ai_settings_file = file - cfg.skip_reprompt = True - - -def main(): - global ai_name, memory +def main() -> None: + """Main function for the script""" + cfg = Config() # TODO: fill in llm values here check_openai_api_key() parse_arguments() @@ -396,177 +45,5 @@ def main(): agent.start_interaction_loop() -class Agent: - """Agent class for interacting with Auto-GPT. - - Attributes: - ai_name: The name of the agent. - memory: The memory object to use. - full_message_history: The full message history. - next_action_count: The number of actions to execute. - prompt: The prompt to use. - user_input: The user input. - - """ - - def __init__( - self, - ai_name, - memory, - full_message_history, - next_action_count, - prompt, - user_input, - ): - self.ai_name = ai_name - self.memory = memory - self.full_message_history = full_message_history - self.next_action_count = next_action_count - self.prompt = prompt - self.user_input = user_input - - def start_interaction_loop(self): - # Interaction Loop - loop_count = 0 - command_name = None - arguments = None - while True: - # Discontinue if continuous limit is reached - loop_count += 1 - if ( - cfg.continuous_mode - and cfg.continuous_limit > 0 - and loop_count > cfg.continuous_limit - ): - logger.typewriter_log( - "Continuous Limit Reached: ", Fore.YELLOW, f"{cfg.continuous_limit}" - ) - break - - # Send message to AI, get response - with Spinner("Thinking... "): - assistant_reply = chat.chat_with_ai( - self.prompt, - self.user_input, - self.full_message_history, - self.memory, - cfg.fast_token_limit, - ) # TODO: This hardcodes the model to use GPT3.5. Make this an argument - - # Print Assistant thoughts - print_assistant_thoughts(assistant_reply) - - # Get command name and arguments - try: - command_name, arguments = cmd.get_command( - attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply) - ) - if cfg.speak_mode: - speak.say_text(f"I want to execute {command_name}") - except Exception as e: - logger.error("Error: \n", str(e)) - - if not cfg.continuous_mode and self.next_action_count == 0: - ### GET USER AUTHORIZATION TO EXECUTE COMMAND ### - # Get key press: Prompt the user to press enter to continue or escape - # to exit - self.user_input = "" - logger.typewriter_log( - "NEXT ACTION: ", - Fore.CYAN, - f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL}" - f" ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}", - ) - print( - "Enter 'y' to authorise command, 'y -N' to run N continuous" - " commands, 'n' to exit program, or enter feedback for" - f" {self.ai_name}...", - flush=True, - ) - while True: - console_input = utils.clean_input( - Fore.MAGENTA + "Input:" + Style.RESET_ALL - ) - if console_input.lower().rstrip() == "y": - self.user_input = "GENERATE NEXT COMMAND JSON" - break - elif console_input.lower().startswith("y -"): - try: - self.next_action_count = abs( - int(console_input.split(" ")[1]) - ) - self.user_input = "GENERATE NEXT COMMAND JSON" - except ValueError: - print( - "Invalid input format. Please enter 'y -n' where n" - " is the number of continuous tasks." - ) - continue - break - elif console_input.lower() == "n": - self.user_input = "EXIT" - break - else: - self.user_input = console_input - command_name = "human_feedback" - break - - if self.user_input == "GENERATE NEXT COMMAND JSON": - logger.typewriter_log( - "-=-=-=-=-=-=-= COMMAND AUTHORISED BY USER -=-=-=-=-=-=-=", - Fore.MAGENTA, - "", - ) - elif self.user_input == "EXIT": - print("Exiting...", flush=True) - break - else: - # Print command - logger.typewriter_log( - "NEXT ACTION: ", - Fore.CYAN, - f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL}" - f" ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}", - ) - - # Execute command - if command_name is not None and command_name.lower().startswith("error"): - result = ( - f"Command {command_name} threw the following error: {arguments}" - ) - elif command_name == "human_feedback": - result = f"Human feedback: {self.user_input}" - else: - result = ( - f"Command {command_name} " - f"returned: {cmd.execute_command(command_name, arguments)}" - ) - if self.next_action_count > 0: - self.next_action_count -= 1 - - memory_to_add = ( - f"Assistant Reply: {assistant_reply} " - f"\nResult: {result} " - f"\nHuman Feedback: {self.user_input} " - ) - - self.memory.add(memory_to_add) - - # Check if there's a result from the command append it to the message - # history - if result is not None: - self.full_message_history.append( - chat.create_chat_message("system", result) - ) - logger.typewriter_log("SYSTEM: ", Fore.YELLOW, result) - else: - self.full_message_history.append( - chat.create_chat_message("system", "Unable to execute command") - ) - logger.typewriter_log( - "SYSTEM: ", Fore.YELLOW, "Unable to execute command" - ) - - if __name__ == "__main__": main() diff --git a/autogpt/agent/__init__.py b/autogpt/agent/__init__.py new file mode 100644 index 00000000..e928af22 --- /dev/null +++ b/autogpt/agent/__init__.py @@ -0,0 +1,4 @@ +from autogpt.agent.agent import Agent +from autogpt.agent.agent_manager import AgentManager + +__all__ = ["Agent", "AgentManager"] diff --git a/autogpt/agent.py b/autogpt/agent/agent.py similarity index 56% rename from autogpt/agent.py rename to autogpt/agent/agent.py index 56c13d17..301d3f02 100644 --- a/autogpt/agent.py +++ b/autogpt/agent/agent.py @@ -1,15 +1,13 @@ -import json -import regex -import traceback - from colorama import Fore, Style +from autogpt.app import execute_command, get_command from autogpt.chat import chat_with_ai, create_chat_message -import autogpt.commands as cmd from autogpt.config import Config -from autogpt.json_parser import fix_and_parse_json -from autogpt.logger import logger -from autogpt.speak import say_text +from autogpt.json_fixes.bracket_termination import ( + attempt_to_fix_json_by_finding_outermost_brackets, +) +from autogpt.logs import logger, print_assistant_thoughts +from autogpt.speech import say_text from autogpt.spinner import Spinner from autogpt.utils import clean_input @@ -77,7 +75,7 @@ class Agent: # Get command name and arguments try: - command_name, arguments = cmd.get_command( + command_name, arguments = get_command( attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply) ) if cfg.speak_mode: @@ -158,7 +156,7 @@ class Agent: else: result = ( f"Command {command_name} returned: " - f"{cmd.execute_command(command_name, arguments)}" + f"{execute_command(command_name, arguments)}" ) if self.next_action_count > 0: self.next_action_count -= 1 @@ -183,122 +181,3 @@ class Agent: logger.typewriter_log( "SYSTEM: ", Fore.YELLOW, "Unable to execute command" ) - - -def attempt_to_fix_json_by_finding_outermost_brackets(json_string): - cfg = Config() - if cfg.speak_mode and cfg.debug_mode: - say_text( - "I have received an invalid JSON response from the OpenAI API. " - "Trying to fix it now." - ) - logger.typewriter_log("Attempting to fix JSON by finding outermost brackets\n") - - try: - json_pattern = regex.compile(r"\{(?:[^{}]|(?R))*\}") - json_match = json_pattern.search(json_string) - - if json_match: - # Extract the valid JSON object from the string - json_string = json_match.group(0) - logger.typewriter_log( - title="Apparently json was fixed.", title_color=Fore.GREEN - ) - if cfg.speak_mode and cfg.debug_mode: - say_text("Apparently json was fixed.") - else: - raise ValueError("No valid JSON object found") - - except (json.JSONDecodeError, ValueError): - if cfg.speak_mode: - say_text("Didn't work. I will have to ignore this response then.") - logger.error("Error: Invalid JSON, setting it to empty JSON now.\n") - json_string = {} - - return json_string - - -def print_assistant_thoughts(ai_name, assistant_reply): - """Prints the assistant's thoughts to the console""" - cfg = Config() - try: - try: - # Parse and print Assistant response - assistant_reply_json = fix_and_parse_json(assistant_reply) - except json.JSONDecodeError: - logger.error("Error: Invalid JSON in assistant thoughts\n", assistant_reply) - assistant_reply_json = attempt_to_fix_json_by_finding_outermost_brackets( - assistant_reply - ) - if isinstance(assistant_reply_json, str): - assistant_reply_json = fix_and_parse_json(assistant_reply_json) - - # Check if assistant_reply_json is a string and attempt to parse - # it into a JSON object - if isinstance(assistant_reply_json, str): - try: - assistant_reply_json = json.loads(assistant_reply_json) - except json.JSONDecodeError: - logger.error("Error: Invalid JSON\n", assistant_reply) - assistant_reply_json = ( - attempt_to_fix_json_by_finding_outermost_brackets( - assistant_reply_json - ) - ) - - assistant_thoughts_reasoning = None - assistant_thoughts_plan = None - assistant_thoughts_speak = None - assistant_thoughts_criticism = None - if not isinstance(assistant_reply_json, dict): - assistant_reply_json = {} - assistant_thoughts = assistant_reply_json.get("thoughts", {}) - assistant_thoughts_text = assistant_thoughts.get("text") - - if assistant_thoughts: - assistant_thoughts_reasoning = assistant_thoughts.get("reasoning") - assistant_thoughts_plan = assistant_thoughts.get("plan") - assistant_thoughts_criticism = assistant_thoughts.get("criticism") - assistant_thoughts_speak = assistant_thoughts.get("speak") - - logger.typewriter_log( - f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}" - ) - logger.typewriter_log( - "REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}" - ) - - if assistant_thoughts_plan: - logger.typewriter_log("PLAN:", Fore.YELLOW, "") - # If it's a list, join it into a string - if isinstance(assistant_thoughts_plan, list): - assistant_thoughts_plan = "\n".join(assistant_thoughts_plan) - elif isinstance(assistant_thoughts_plan, dict): - assistant_thoughts_plan = str(assistant_thoughts_plan) - - # Split the input_string using the newline character and dashes - lines = assistant_thoughts_plan.split("\n") - for line in lines: - line = line.lstrip("- ") - logger.typewriter_log("- ", Fore.GREEN, line.strip()) - - logger.typewriter_log( - "CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}" - ) - # Speak the assistant's thoughts - if cfg.speak_mode and assistant_thoughts_speak: - say_text(assistant_thoughts_speak) - - return assistant_reply_json - except json.decoder.JSONDecodeError: - logger.error("Error: Invalid JSON\n", assistant_reply) - if cfg.speak_mode: - say_text( - "I have received an invalid JSON response from the OpenAI API." - " I cannot ignore this response." - ) - - # All other errors, return "Error: + error message" - except Exception: - call_stack = traceback.format_exc() - logger.error("Error: \n", call_stack) diff --git a/autogpt/agent/agent_manager.py b/autogpt/agent/agent_manager.py new file mode 100644 index 00000000..a22adff3 --- /dev/null +++ b/autogpt/agent/agent_manager.py @@ -0,0 +1,100 @@ +"""Agent manager for managing GPT agents""" +from typing import List, Tuple, Union +from autogpt.llm_utils import create_chat_completion +from autogpt.config.config import Singleton + + +class AgentManager(metaclass=Singleton): + """Agent manager for managing GPT agents""" + + def __init__(self): + self.next_key = 0 + self.agents = {} # key, (task, full_message_history, model) + + # Create new GPT agent + # TODO: Centralise use of create_chat_completion() to globally enforce token limit + + def create_agent(self, task: str, prompt: str, model: str) -> tuple[int, str]: + """Create a new agent and return its key + + Args: + task: The task to perform + prompt: The prompt to use + model: The model to use + + Returns: + The key of the new agent + """ + messages = [ + {"role": "user", "content": prompt}, + ] + + # Start GPT instance + agent_reply = create_chat_completion( + model=model, + messages=messages, + ) + + # Update full message history + messages.append({"role": "assistant", "content": agent_reply}) + + key = self.next_key + # This is done instead of len(agents) to make keys unique even if agents + # are deleted + self.next_key += 1 + + self.agents[key] = (task, messages, model) + + return key, agent_reply + + def message_agent(self, key: Union[str, int], message: str) -> str: + """Send a message to an agent and return its response + + Args: + key: The key of the agent to message + message: The message to send to the agent + + Returns: + The agent's response + """ + task, messages, model = self.agents[int(key)] + + # Add user message to message history before sending to agent + messages.append({"role": "user", "content": message}) + + # Start GPT instance + agent_reply = create_chat_completion( + model=model, + messages=messages, + ) + + # Update full message history + messages.append({"role": "assistant", "content": agent_reply}) + + return agent_reply + + def list_agents(self) -> List[Tuple[Union[str, int], str]]: + """Return a list of all agents + + Returns: + A list of tuples of the form (key, task) + """ + + # Return a list of agent keys and their tasks + return [(key, task) for key, (task, _, _) in self.agents.items()] + + def delete_agent(self, key: Union[str, int]) -> bool: + """Delete an agent from the agent manager + + Args: + key: The key of the agent to delete + + Returns: + True if successful, False otherwise + """ + + try: + del self.agents[int(key)] + return True + except KeyError: + return False diff --git a/autogpt/agent_manager.py b/autogpt/agent_manager.py deleted file mode 100644 index bbf156ee..00000000 --- a/autogpt/agent_manager.py +++ /dev/null @@ -1,75 +0,0 @@ -from autogpt.llm_utils import create_chat_completion - -next_key = 0 -agents = {} # key, (task, full_message_history, model) - -# Create new GPT agent -# TODO: Centralise use of create_chat_completion() to globally enforce token limit - - -def create_agent(task, prompt, model): - """Create a new agent and return its key""" - global next_key - global agents - - messages = [ - {"role": "user", "content": prompt}, - ] - - # Start GPT instance - agent_reply = create_chat_completion( - model=model, - messages=messages, - ) - - # Update full message history - messages.append({"role": "assistant", "content": agent_reply}) - - key = next_key - # This is done instead of len(agents) to make keys unique even if agents - # are deleted - next_key += 1 - - agents[key] = (task, messages, model) - - return key, agent_reply - - -def message_agent(key, message): - """Send a message to an agent and return its response""" - global agents - - task, messages, model = agents[int(key)] - - # Add user message to message history before sending to agent - messages.append({"role": "user", "content": message}) - - # Start GPT instance - agent_reply = create_chat_completion( - model=model, - messages=messages, - ) - - # Update full message history - messages.append({"role": "assistant", "content": agent_reply}) - - return agent_reply - - -def list_agents(): - """Return a list of all agents""" - global agents - - # Return a list of agent keys and their tasks - return [(key, task) for key, (task, _, _) in agents.items()] - - -def delete_agent(key): - """Delete an agent and return True if successful, False otherwise""" - global agents - - try: - del agents[int(key)] - return True - except KeyError: - return False diff --git a/autogpt/ai_functions.py b/autogpt/ai_functions.py deleted file mode 100644 index 84f82685..00000000 --- a/autogpt/ai_functions.py +++ /dev/null @@ -1,77 +0,0 @@ -import json -from typing import List - -from autogpt.call_ai_function import call_ai_function -from autogpt.config import Config - -cfg = Config() - - -def evaluate_code(code: str) -> List[str]: - """ - A function that takes in a string and returns a response from create chat - completion api call. - - Parameters: - code (str): Code to be evaluated. - Returns: - A result string from create chat completion. A list of suggestions to - improve the code. - """ - - function_string = "def analyze_code(code: str) -> List[str]:" - args = [code] - description_string = ( - "Analyzes the given code and returns a list of suggestions" " for improvements." - ) - - return call_ai_function(function_string, args, description_string) - - -def improve_code(suggestions: List[str], code: str) -> str: - """ - A function that takes in code and suggestions and returns a response from create - chat completion api call. - - Parameters: - suggestions (List): A list of suggestions around what needs to be improved. - code (str): Code to be improved. - Returns: - A result string from create chat completion. Improved code in response. - """ - - function_string = ( - "def generate_improved_code(suggestions: List[str], code: str) -> str:" - ) - args = [json.dumps(suggestions), code] - description_string = ( - "Improves the provided code based on the suggestions" - " provided, making no other changes." - ) - - return call_ai_function(function_string, args, description_string) - - -def write_tests(code: str, focus: List[str]) -> str: - """ - A function that takes in code and focus topics and returns a response from create - chat completion api call. - - Parameters: - focus (List): A list of suggestions around what needs to be improved. - code (str): Code for test cases to be generated against. - Returns: - A result string from create chat completion. Test cases for the submitted code - in response. - """ - - function_string = ( - "def create_test_cases(code: str, focus: Optional[str] = None) -> str:" - ) - args = [code, json.dumps(focus)] - description_string = ( - "Generates test cases for the existing code, focusing on" - " specific areas if required." - ) - - return call_ai_function(function_string, args, description_string) diff --git a/autogpt/commands.py b/autogpt/app.py similarity index 61% rename from autogpt/commands.py rename to autogpt/app.py index 352b3340..0adfde5d 100644 --- a/autogpt/commands.py +++ b/autogpt/app.py @@ -1,29 +1,42 @@ +""" Command and Control """ import json -import datetime -import autogpt.agent_manager as agents +from typing import List, NoReturn, Union +from autogpt.agent.agent_manager import AgentManager +from autogpt.commands.evaluate_code import evaluate_code +from autogpt.commands.google_search import google_official_search, google_search +from autogpt.commands.improve_code import improve_code +from autogpt.commands.write_tests import write_tests from autogpt.config import Config -from autogpt.json_parser import fix_and_parse_json -from autogpt.image_gen import generate_image -from duckduckgo_search import ddg -from autogpt.ai_functions import evaluate_code, improve_code, write_tests -from autogpt.browse import scrape_links, scrape_text, summarize_text -from autogpt.execute_code import execute_python_file, execute_shell -from autogpt.file_operations import ( +from autogpt.commands.image_gen import generate_image +from autogpt.commands.web_requests import scrape_links, scrape_text +from autogpt.commands.execute_code import execute_python_file, execute_shell +from autogpt.commands.file_operations import ( append_to_file, delete_file, read_file, search_files, write_to_file, ) +from autogpt.json_fixes.parsing import fix_and_parse_json from autogpt.memory import get_memory -from autogpt.speak import say_text -from autogpt.web import browse_website +from autogpt.processing.text import summarize_text +from autogpt.speech import say_text +from autogpt.commands.web_selenium import browse_website -cfg = Config() +CFG = Config() +AGENT_MANAGER = AgentManager() -def is_valid_int(value) -> bool: +def is_valid_int(value: str) -> bool: + """Check if the value is a valid integer + + Args: + value (str): The value to check + + Returns: + bool: True if the value is a valid integer, False otherwise + """ try: int(value) return True @@ -31,8 +44,20 @@ def is_valid_int(value) -> bool: return False -def get_command(response): - """Parse the response and return the command name and arguments""" +def get_command(response: str): + """Parse the response and return the command name and arguments + + Args: + response (str): The response from the user + + Returns: + tuple: The command name and arguments + + Raises: + json.decoder.JSONDecodeError: If the response is not valid JSON + + Exception: If any other error occurs + """ try: response_json = fix_and_parse_json(response) @@ -62,16 +87,23 @@ def get_command(response): return "Error:", str(e) -def execute_command(command_name, arguments): - """Execute the command and return the result""" - memory = get_memory(cfg) +def execute_command(command_name: str, arguments): + """Execute the command and return the result + + Args: + command_name (str): The name of the command to execute + arguments (dict): The arguments for the command + + Returns: + str: The result of the command""" + memory = get_memory(CFG) try: if command_name == "google": # Check if the Google API key is set and use the official search method # If the API key is not set or has only whitespaces, use the unofficial # search method - key = cfg.google_api_key + key = CFG.google_api_key if key and key.strip() and key != "your-google-api-key": return google_official_search(arguments["input"]) else: @@ -116,7 +148,7 @@ def execute_command(command_name, arguments): elif command_name == "execute_python_file": # Add this command return execute_python_file(arguments["file"]) elif command_name == "execute_shell": - if cfg.execute_local_commands: + if CFG.execute_local_commands: return execute_shell(arguments["command_line"]) else: return ( @@ -136,96 +168,55 @@ def execute_command(command_name, arguments): " list for available commands and only respond in the specified JSON" " format." ) - # All errors, return "Error: + error message" except Exception as e: - return "Error: " + str(e) + return f"Error: {str(e)}" -def get_datetime(): - """Return the current date and time""" - return "Current date and time: " + datetime.datetime.now().strftime( - "%Y-%m-%d %H:%M:%S" - ) +def get_text_summary(url: str, question: str) -> str: + """Return the results of a google search + Args: + url (str): The url to scrape + question (str): The question to summarize the text for -def google_search(query, num_results=8): - """Return the results of a google search""" - search_results = [] - if not query: - return json.dumps(search_results) - - for j in ddg(query, max_results=num_results): - search_results.append(j) - - return json.dumps(search_results, ensure_ascii=False, indent=4) - - -def google_official_search(query, num_results=8): - """Return the results of a google search using the official Google API""" - import json - - from googleapiclient.discovery import build - from googleapiclient.errors import HttpError - - try: - # Get the Google API key and Custom Search Engine ID from the config file - api_key = cfg.google_api_key - custom_search_engine_id = cfg.custom_search_engine_id - - # Initialize the Custom Search API service - service = build("customsearch", "v1", developerKey=api_key) - - # Send the search query and retrieve the results - result = ( - service.cse() - .list(q=query, cx=custom_search_engine_id, num=num_results) - .execute() - ) - - # Extract the search result items from the response - search_results = result.get("items", []) - - # Create a list of only the URLs from the search results - search_results_links = [item["link"] for item in search_results] - - except HttpError as e: - # Handle errors in the API call - error_details = json.loads(e.content.decode()) - - # Check if the error is related to an invalid or missing API key - if error_details.get("error", {}).get( - "code" - ) == 403 and "invalid API key" in error_details.get("error", {}).get( - "message", "" - ): - return "Error: The provided Google API key is invalid or missing." - else: - return f"Error: {e}" - - # Return the list of search result URLs - return search_results_links - - -def get_text_summary(url, question): - """Return the results of a google search""" + Returns: + str: The summary of the text + """ text = scrape_text(url) summary = summarize_text(url, text, question) - return """ "Result" : """ + summary + return f""" "Result" : {summary}""" -def get_hyperlinks(url): - """Return the results of a google search""" +def get_hyperlinks(url: str) -> Union[str, List[str]]: + """Return the results of a google search + + Args: + url (str): The url to scrape + + Returns: + str or list: The hyperlinks on the page + """ return scrape_links(url) -def shutdown(): +def shutdown() -> NoReturn: """Shut down the program""" print("Shutting down...") quit() -def start_agent(name, task, prompt, model=cfg.fast_llm_model): - """Start an agent with a given name, task, and prompt""" +def start_agent(name: str, task: str, prompt: str, model=CFG.fast_llm_model) -> str: + """Start an agent with a given name, task, and prompt + + Args: + name (str): The name of the agent + task (str): The task of the agent + prompt (str): The prompt for the agent + model (str): The model to use for the agent + + Returns: + str: The response of the agent + """ # Remove underscores from name voice_name = name.replace("_", " ") @@ -233,42 +224,53 @@ def start_agent(name, task, prompt, model=cfg.fast_llm_model): agent_intro = f"{voice_name} here, Reporting for duty!" # Create agent - if cfg.speak_mode: + if CFG.speak_mode: say_text(agent_intro, 1) - key, ack = agents.create_agent(task, first_message, model) + key, ack = AGENT_MANAGER.create_agent(task, first_message, model) - if cfg.speak_mode: + if CFG.speak_mode: say_text(f"Hello {voice_name}. Your task is as follows. {task}.") # Assign task (prompt), get response - agent_response = agents.message_agent(key, prompt) + agent_response = AGENT_MANAGER.message_agent(key, prompt) return f"Agent {name} created with key {key}. First response: {agent_response}" -def message_agent(key, message): +def message_agent(key: str, message: str) -> str: """Message an agent with a given key and message""" # Check if the key is a valid integer if is_valid_int(key): - agent_response = agents.message_agent(int(key), message) + agent_response = AGENT_MANAGER.message_agent(int(key), message) # Check if the key is a valid string elif isinstance(key, str): - agent_response = agents.message_agent(key, message) + agent_response = AGENT_MANAGER.message_agent(key, message) else: return "Invalid key, must be an integer or a string." # Speak response - if cfg.speak_mode: + if CFG.speak_mode: say_text(agent_response, 1) return agent_response def list_agents(): - """List all agents""" - return list_agents() + """List all agents + + Returns: + list: A list of all agents + """ + return AGENT_MANAGER.list_agents() -def delete_agent(key): - """Delete an agent with a given key""" - result = agents.delete_agent(key) +def delete_agent(key: str) -> str: + """Delete an agent with a given key + + Args: + key (str): The key of the agent to delete + + Returns: + str: A message indicating whether the agent was deleted or not + """ + result = AGENT_MANAGER.delete_agent(key) return f"Agent {key} deleted." if result else f"Agent {key} does not exist." diff --git a/autogpt/args.py b/autogpt/args.py new file mode 100644 index 00000000..6c907a1f --- /dev/null +++ b/autogpt/args.py @@ -0,0 +1,128 @@ +"""This module contains the argument parsing logic for the script.""" +import argparse + +from colorama import Fore +from autogpt import utils +from autogpt.config import Config +from autogpt.logs import logger +from autogpt.memory import get_supported_memory_backends + +CFG = Config() + + +def parse_arguments() -> None: + """Parses the arguments passed to the script + + Returns: + None + """ + CFG.set_debug_mode(False) + CFG.set_continuous_mode(False) + CFG.set_speak_mode(False) + + parser = argparse.ArgumentParser(description="Process arguments.") + parser.add_argument( + "--continuous", "-c", action="store_true", help="Enable Continuous Mode" + ) + parser.add_argument( + "--continuous-limit", + "-l", + type=int, + dest="continuous_limit", + help="Defines the number of times to run in continuous mode", + ) + parser.add_argument("--speak", action="store_true", help="Enable Speak Mode") + parser.add_argument("--debug", action="store_true", help="Enable Debug Mode") + parser.add_argument( + "--gpt3only", action="store_true", help="Enable GPT3.5 Only Mode" + ) + parser.add_argument("--gpt4only", action="store_true", help="Enable GPT4 Only Mode") + parser.add_argument( + "--use-memory", + "-m", + dest="memory_type", + help="Defines which Memory backend to use", + ) + parser.add_argument( + "--skip-reprompt", + "-y", + dest="skip_reprompt", + action="store_true", + help="Skips the re-prompting messages at the beginning of the script", + ) + parser.add_argument( + "--ai-settings", + "-C", + dest="ai_settings_file", + help="Specifies which ai_settings.yaml file to use, will also automatically" + " skip the re-prompt.", + ) + args = parser.parse_args() + + if args.debug: + logger.typewriter_log("Debug Mode: ", Fore.GREEN, "ENABLED") + CFG.set_debug_mode(True) + + if args.continuous: + logger.typewriter_log("Continuous Mode: ", Fore.RED, "ENABLED") + logger.typewriter_log( + "WARNING: ", + Fore.RED, + "Continuous mode is not recommended. It is potentially dangerous and may" + " cause your AI to run forever or carry out actions you would not usually" + " authorise. Use at your own risk.", + ) + CFG.set_continuous_mode(True) + + if args.continuous_limit: + logger.typewriter_log( + "Continuous Limit: ", Fore.GREEN, f"{args.continuous_limit}" + ) + CFG.set_continuous_limit(args.continuous_limit) + + # Check if continuous limit is used without continuous mode + if args.continuous_limit and not args.continuous: + parser.error("--continuous-limit can only be used with --continuous") + + if args.speak: + logger.typewriter_log("Speak Mode: ", Fore.GREEN, "ENABLED") + CFG.set_speak_mode(True) + + if args.gpt3only: + logger.typewriter_log("GPT3.5 Only Mode: ", Fore.GREEN, "ENABLED") + CFG.set_smart_llm_model(CFG.fast_llm_model) + + if args.gpt4only: + logger.typewriter_log("GPT4 Only Mode: ", Fore.GREEN, "ENABLED") + CFG.set_fast_llm_model(CFG.smart_llm_model) + + if args.memory_type: + supported_memory = get_supported_memory_backends() + chosen = args.memory_type + if chosen not in supported_memory: + logger.typewriter_log( + "ONLY THE FOLLOWING MEMORY BACKENDS ARE SUPPORTED: ", + Fore.RED, + f"{supported_memory}", + ) + logger.typewriter_log("Defaulting to: ", Fore.YELLOW, CFG.memory_backend) + else: + CFG.memory_backend = chosen + + if args.skip_reprompt: + logger.typewriter_log("Skip Re-prompt: ", Fore.GREEN, "ENABLED") + CFG.skip_reprompt = True + + if args.ai_settings_file: + file = args.ai_settings_file + + # Validate file + (validated, message) = utils.validate_yaml_file(file) + if not validated: + logger.typewriter_log("FAILED FILE VALIDATION", Fore.RED, message) + logger.double_check() + exit(1) + + logger.typewriter_log("Using AI Settings File:", Fore.GREEN, file) + CFG.ai_settings_file = file + CFG.skip_reprompt = True diff --git a/autogpt/call_ai_function.py b/autogpt/call_ai_function.py deleted file mode 100644 index bbbd8e35..00000000 --- a/autogpt/call_ai_function.py +++ /dev/null @@ -1,26 +0,0 @@ -from autogpt.config import Config -from autogpt.llm_utils import create_chat_completion - -cfg = Config() - - -# This is a magic function that can do anything with no-code. See -# https://github.com/Torantulino/AI-Functions for more info. -def call_ai_function(function, args, description, model=None) -> str: - """Call an AI function""" - if model is None: - model = cfg.smart_llm_model - # For each arg, if any are None, convert to "None": - args = [str(arg) if arg is not None else "None" for arg in args] - # parse args to comma separated string - args = ", ".join(args) - messages = [ - { - "role": "system", - "content": f"You are now the following python function: ```# {description}" - f"\n{function}```\n\nOnly respond with your `return` value.", - }, - {"role": "user", "content": args}, - ] - - return create_chat_completion(model=model, messages=messages, temperature=0) diff --git a/autogpt/chat.py b/autogpt/chat.py index 12797d9f..b0886967 100644 --- a/autogpt/chat.py +++ b/autogpt/chat.py @@ -5,7 +5,7 @@ from openai.error import RateLimitError from autogpt import token_counter from autogpt.config import Config from autogpt.llm_utils import create_chat_completion -from autogpt.logger import logger +from autogpt.logs import logger cfg = Config() diff --git a/autogpt/commands/__init__.py b/autogpt/commands/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/autogpt/commands/evaluate_code.py b/autogpt/commands/evaluate_code.py new file mode 100644 index 00000000..a36952e5 --- /dev/null +++ b/autogpt/commands/evaluate_code.py @@ -0,0 +1,25 @@ +"""Code evaluation module.""" +from typing import List + +from autogpt.llm_utils import call_ai_function + + +def evaluate_code(code: str) -> List[str]: + """ + A function that takes in a string and returns a response from create chat + completion api call. + + Parameters: + code (str): Code to be evaluated. + Returns: + A result string from create chat completion. A list of suggestions to + improve the code. + """ + + function_string = "def analyze_code(code: str) -> List[str]:" + args = [code] + description_string = ( + "Analyzes the given code and returns a list of suggestions" " for improvements." + ) + + return call_ai_function(function_string, args, description_string) diff --git a/autogpt/commands/execute_code.py b/autogpt/commands/execute_code.py new file mode 100644 index 00000000..db33490c --- /dev/null +++ b/autogpt/commands/execute_code.py @@ -0,0 +1,125 @@ +"""Execute code in a Docker container""" +import os +from pathlib import Path +import subprocess + +import docker +from docker.errors import ImageNotFound + +WORKING_DIRECTORY = Path(__file__).parent.parent / "auto_gpt_workspace" + + +def execute_python_file(file: str): + """Execute a Python file in a Docker container and return the output + + Args: + file (str): The name of the file to execute + + Returns: + str: The output of the file + """ + + print(f"Executing file '{file}' in workspace '{WORKING_DIRECTORY}'") + + if not file.endswith(".py"): + return "Error: Invalid file type. Only .py files are allowed." + + file_path = os.path.join(WORKING_DIRECTORY, file) + + if not os.path.isfile(file_path): + return f"Error: File '{file}' does not exist." + + if we_are_running_in_a_docker_container(): + result = subprocess.run( + f"python {file_path}", capture_output=True, encoding="utf8", shell=True + ) + if result.returncode == 0: + return result.stdout + else: + return f"Error: {result.stderr}" + + try: + client = docker.from_env() + + image_name = "python:3.10" + try: + client.images.get(image_name) + print(f"Image '{image_name}' found locally") + except ImageNotFound: + print(f"Image '{image_name}' not found locally, pulling from Docker Hub") + # Use the low-level API to stream the pull response + low_level_client = docker.APIClient() + for line in low_level_client.pull(image_name, stream=True, decode=True): + # Print the status and progress, if available + status = line.get("status") + progress = line.get("progress") + if status and progress: + print(f"{status}: {progress}") + elif status: + print(status) + + # You can replace 'python:3.8' with the desired Python image/version + # You can find available Python images on Docker Hub: + # https://hub.docker.com/_/python + container = client.containers.run( + image_name, + f"python {file}", + volumes={ + os.path.abspath(WORKING_DIRECTORY): { + "bind": "/workspace", + "mode": "ro", + } + }, + working_dir="/workspace", + stderr=True, + stdout=True, + detach=True, + ) + + container.wait() + logs = container.logs().decode("utf-8") + container.remove() + + # print(f"Execution complete. Output: {output}") + # print(f"Logs: {logs}") + + return logs + + except Exception as e: + return f"Error: {str(e)}" + + +def execute_shell(command_line: str) -> str: + """Execute a shell command and return the output + + Args: + command_line (str): The command line to execute + + Returns: + str: The output of the command + """ + current_dir = os.getcwd() + + if WORKING_DIRECTORY not in current_dir: # Change dir into workspace if necessary + work_dir = os.path.join(os.getcwd(), WORKING_DIRECTORY) + os.chdir(work_dir) + + print(f"Executing command '{command_line}' in working directory '{os.getcwd()}'") + + result = subprocess.run(command_line, capture_output=True, shell=True) + output = f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}" + + # Change back to whatever the prior working dir was + + os.chdir(current_dir) + + return output + + +def we_are_running_in_a_docker_container() -> bool: + """Check if we are running in a Docker container + + Returns: + bool: True if we are running in a Docker container, False otherwise + """ + return os.path.exists("/.dockerenv") diff --git a/autogpt/file_operations.py b/autogpt/commands/file_operations.py similarity index 58% rename from autogpt/file_operations.py rename to autogpt/commands/file_operations.py index 1c8f9290..9d11a878 100644 --- a/autogpt/file_operations.py +++ b/autogpt/commands/file_operations.py @@ -1,16 +1,29 @@ +"""File operations for AutoGPT""" import os import os.path +from pathlib import Path +from typing import Generator, List # Set a dedicated folder for file I/O -working_directory = "auto_gpt_workspace" +WORKING_DIRECTORY = Path(__file__).parent.parent / "auto_gpt_workspace" # Create the directory if it doesn't exist -if not os.path.exists(working_directory): - os.makedirs(working_directory) +if not os.path.exists(WORKING_DIRECTORY): + os.makedirs(WORKING_DIRECTORY) + +WORKING_DIRECTORY = str(WORKING_DIRECTORY) -def safe_join(base, *paths): - """Join one or more path components intelligently.""" +def safe_join(base: str, *paths) -> str: + """Join one or more path components intelligently. + + Args: + base (str): The base path + *paths (str): The paths to join to the base path + + Returns: + str: The joined path + """ new_path = os.path.join(base, *paths) norm_new_path = os.path.normpath(new_path) @@ -20,7 +33,9 @@ def safe_join(base, *paths): return norm_new_path -def split_file(content, max_length=4000, overlap=0): +def split_file( + content: str, max_length: int = 4000, overlap: int = 0 +) -> Generator[str, None, None]: """ Split text into chunks of a specified maximum length with a specified overlap between chunks. @@ -45,10 +60,17 @@ def split_file(content, max_length=4000, overlap=0): start += max_length - overlap -def read_file(filename) -> str: - """Read a file and return the contents""" +def read_file(filename: str) -> str: + """Read a file and return the contents + + Args: + filename (str): The name of the file to read + + Returns: + str: The contents of the file + """ try: - filepath = safe_join(working_directory, filename) + filepath = safe_join(WORKING_DIRECTORY, filename) with open(filepath, "r", encoding="utf-8") as f: content = f.read() return content @@ -56,7 +78,9 @@ def read_file(filename) -> str: return f"Error: {str(e)}" -def ingest_file(filename, memory, max_length=4000, overlap=200): +def ingest_file( + filename: str, memory, max_length: int = 4000, overlap: int = 200 +) -> None: """ Ingest a file by reading its content, splitting it into chunks with a specified maximum length and overlap, and adding the chunks to the memory storage. @@ -88,10 +112,18 @@ def ingest_file(filename, memory, max_length=4000, overlap=200): print(f"Error while ingesting file '{filename}': {str(e)}") -def write_to_file(filename, text): - """Write text to a file""" +def write_to_file(filename: str, text: str) -> str: + """Write text to a file + + Args: + filename (str): The name of the file to write to + text (str): The text to write to the file + + Returns: + str: A message indicating success or failure + """ try: - filepath = safe_join(working_directory, filename) + filepath = safe_join(WORKING_DIRECTORY, filename) directory = os.path.dirname(filepath) if not os.path.exists(directory): os.makedirs(directory) @@ -99,43 +131,66 @@ def write_to_file(filename, text): f.write(text) return "File written to successfully." except Exception as e: - return "Error: " + str(e) + return f"Error: {str(e)}" -def append_to_file(filename, text): - """Append text to a file""" +def append_to_file(filename: str, text: str) -> str: + """Append text to a file + + Args: + filename (str): The name of the file to append to + text (str): The text to append to the file + + Returns: + str: A message indicating success or failure + """ try: - filepath = safe_join(working_directory, filename) + filepath = safe_join(WORKING_DIRECTORY, filename) with open(filepath, "a") as f: f.write(text) return "Text appended successfully." except Exception as e: - return "Error: " + str(e) + return f"Error: {str(e)}" -def delete_file(filename): - """Delete a file""" +def delete_file(filename: str) -> str: + """Delete a file + + Args: + filename (str): The name of the file to delete + + Returns: + str: A message indicating success or failure + """ try: - filepath = safe_join(working_directory, filename) + filepath = safe_join(WORKING_DIRECTORY, filename) os.remove(filepath) return "File deleted successfully." except Exception as e: - return "Error: " + str(e) + return f"Error: {str(e)}" -def search_files(directory): +def search_files(directory: str) -> List[str]: + """Search for files in a directory + + Args: + directory (str): The directory to search in + + Returns: + List[str]: A list of files found in the directory + """ found_files = [] - if directory == "" or directory == "/": - search_directory = working_directory + if directory in {"", "/"}: + search_directory = WORKING_DIRECTORY else: - search_directory = safe_join(working_directory, directory) + search_directory = safe_join(WORKING_DIRECTORY, directory) for root, _, files in os.walk(search_directory): for file in files: if file.startswith("."): continue - relative_path = os.path.relpath(os.path.join(root, file), working_directory) + relative_path = os.path.relpath(os.path.join(root, file), WORKING_DIRECTORY) found_files.append(relative_path) return found_files diff --git a/autogpt/commands/google_search.py b/autogpt/commands/google_search.py new file mode 100644 index 00000000..6deb9b50 --- /dev/null +++ b/autogpt/commands/google_search.py @@ -0,0 +1,86 @@ +"""Google search command for Autogpt.""" +import json +from typing import List, Union + +from duckduckgo_search import ddg + +from autogpt.config import Config + +CFG = Config() + + +def google_search(query: str, num_results: int = 8) -> str: + """Return the results of a google search + + Args: + query (str): The search query. + num_results (int): The number of results to return. + + Returns: + str: The results of the search. + """ + search_results = [] + if not query: + return json.dumps(search_results) + + results = ddg(query, max_results=num_results) + if not results: + return json.dumps(search_results) + + for j in results: + search_results.append(j) + + return json.dumps(search_results, ensure_ascii=False, indent=4) + + +def google_official_search(query: str, num_results: int = 8) -> Union[str, List[str]]: + """Return the results of a google search using the official Google API + + Args: + query (str): The search query. + num_results (int): The number of results to return. + + Returns: + str: The results of the search. + """ + + from googleapiclient.discovery import build + from googleapiclient.errors import HttpError + + try: + # Get the Google API key and Custom Search Engine ID from the config file + api_key = CFG.google_api_key + custom_search_engine_id = CFG.custom_search_engine_id + + # Initialize the Custom Search API service + service = build("customsearch", "v1", developerKey=api_key) + + # Send the search query and retrieve the results + result = ( + service.cse() + .list(q=query, cx=custom_search_engine_id, num=num_results) + .execute() + ) + + # Extract the search result items from the response + search_results = result.get("items", []) + + # Create a list of only the URLs from the search results + search_results_links = [item["link"] for item in search_results] + + except HttpError as e: + # Handle errors in the API call + error_details = json.loads(e.content.decode()) + + # Check if the error is related to an invalid or missing API key + if error_details.get("error", {}).get( + "code" + ) == 403 and "invalid API key" in error_details.get("error", {}).get( + "message", "" + ): + return "Error: The provided Google API key is invalid or missing." + else: + return f"Error: {e}" + + # Return the list of search result URLs + return search_results_links diff --git a/autogpt/commands/image_gen.py b/autogpt/commands/image_gen.py new file mode 100644 index 00000000..39e08845 --- /dev/null +++ b/autogpt/commands/image_gen.py @@ -0,0 +1,99 @@ +""" Image Generation Module for AutoGPT.""" +import io +import os.path +import uuid +from base64 import b64decode + +import openai +import requests +from PIL import Image +from pathlib import Path +from autogpt.config import Config + +CFG = Config() + +WORKING_DIRECTORY = Path(__file__).parent.parent / "auto_gpt_workspace" + + +def generate_image(prompt: str) -> str: + """Generate an image from a prompt. + + Args: + prompt (str): The prompt to use + + Returns: + str: The filename of the image + """ + filename = f"{str(uuid.uuid4())}.jpg" + + # DALL-E + if CFG.image_provider == "dalle": + return generate_image_with_dalle(prompt, filename) + elif CFG.image_provider == "sd": + return generate_image_with_hf(prompt, filename) + else: + return "No Image Provider Set" + + +def generate_image_with_hf(prompt: str, filename: str) -> str: + """Generate an image with HuggingFace's API. + + Args: + prompt (str): The prompt to use + filename (str): The filename to save the image to + + Returns: + str: The filename of the image + """ + API_URL = ( + "https://api-inference.huggingface.co/models/CompVis/stable-diffusion-v1-4" + ) + if CFG.huggingface_api_token is None: + raise ValueError( + "You need to set your Hugging Face API token in the config file." + ) + headers = {"Authorization": f"Bearer {CFG.huggingface_api_token}"} + + response = requests.post( + API_URL, + headers=headers, + json={ + "inputs": prompt, + }, + ) + + image = Image.open(io.BytesIO(response.content)) + print(f"Image Generated for prompt:{prompt}") + + image.save(os.path.join(WORKING_DIRECTORY, filename)) + + return f"Saved to disk:{filename}" + + +def generate_image_with_dalle(prompt: str, filename: str) -> str: + """Generate an image with DALL-E. + + Args: + prompt (str): The prompt to use + filename (str): The filename to save the image to + + Returns: + str: The filename of the image + """ + openai.api_key = CFG.openai_api_key + + response = openai.Image.create( + prompt=prompt, + n=1, + size="256x256", + response_format="b64_json", + ) + + print(f"Image Generated for prompt:{prompt}") + + image_data = b64decode(response["data"][0]["b64_json"]) + + with open(f"{WORKING_DIRECTORY}/{filename}", mode="wb") as png: + png.write(image_data) + + return f"Saved to disk:{filename}" diff --git a/autogpt/commands/improve_code.py b/autogpt/commands/improve_code.py new file mode 100644 index 00000000..05fe89e9 --- /dev/null +++ b/autogpt/commands/improve_code.py @@ -0,0 +1,28 @@ +import json +from typing import List + +from autogpt.llm_utils import call_ai_function + + +def improve_code(suggestions: List[str], code: str) -> str: + """ + A function that takes in code and suggestions and returns a response from create + chat completion api call. + + Parameters: + suggestions (List): A list of suggestions around what needs to be improved. + code (str): Code to be improved. + Returns: + A result string from create chat completion. Improved code in response. + """ + + function_string = ( + "def generate_improved_code(suggestions: List[str], code: str) -> str:" + ) + args = [json.dumps(suggestions), code] + description_string = ( + "Improves the provided code based on the suggestions" + " provided, making no other changes." + ) + + return call_ai_function(function_string, args, description_string) diff --git a/autogpt/commands/times.py b/autogpt/commands/times.py new file mode 100644 index 00000000..3c9b8a4f --- /dev/null +++ b/autogpt/commands/times.py @@ -0,0 +1,10 @@ +from datetime import datetime + + +def get_datetime() -> str: + """Return the current date and time + + Returns: + str: The current date and time + """ + return "Current date and time: " + datetime.now().strftime("%Y-%m-%d %H:%M:%S") diff --git a/autogpt/browse.py b/autogpt/commands/web_requests.py similarity index 51% rename from autogpt/browse.py rename to autogpt/commands/web_requests.py index 60d33744..59c3e522 100644 --- a/autogpt/browse.py +++ b/autogpt/commands/web_requests.py @@ -1,21 +1,30 @@ +"""Browse a webpage and summarize it using the LLM model""" +from typing import List, Tuple, Union from urllib.parse import urljoin, urlparse import requests +from requests import Response from bs4 import BeautifulSoup from autogpt.config import Config -from autogpt.llm_utils import create_chat_completion from autogpt.memory import get_memory -cfg = Config() -memory = get_memory(cfg) +CFG = Config() +memory = get_memory(CFG) session = requests.Session() -session.headers.update({"User-Agent": cfg.user_agent}) +session.headers.update({"User-Agent": CFG.user_agent}) -# Function to check if the URL is valid -def is_valid_url(url): +def is_valid_url(url: str) -> bool: + """Check if the URL is valid + + Args: + url (str): The URL to check + + Returns: + bool: True if the URL is valid, False otherwise + """ try: result = urlparse(url) return all([result.scheme, result.netloc]) @@ -23,13 +32,27 @@ def is_valid_url(url): return False -# Function to sanitize the URL -def sanitize_url(url): +def sanitize_url(url: str) -> str: + """Sanitize the URL + + Args: + url (str): The URL to sanitize + + Returns: + str: The sanitized URL + """ return urljoin(url, urlparse(url).path) -# Define and check for local file address prefixes -def check_local_file_access(url): +def check_local_file_access(url: str) -> bool: + """Check if the URL is a local file + + Args: + url (str): The URL to check + + Returns: + bool: True if the URL is a local file, False otherwise + """ local_prefixes = [ "file:///", "file://localhost", @@ -39,7 +62,22 @@ def check_local_file_access(url): return any(url.startswith(prefix) for prefix in local_prefixes) -def get_response(url, timeout=10): +def get_response( + url: str, timeout: int = 10 +) -> Union[Tuple[None, str], Tuple[Response, None]]: + """Get the response from a URL + + Args: + url (str): The URL to get the response from + timeout (int): The timeout for the HTTP request + + Returns: + tuple[None, str] | tuple[Response, None]: The response and error message + + Raises: + ValueError: If the URL is invalid + requests.exceptions.RequestException: If the HTTP request fails + """ try: # Restrict access to local files if check_local_file_access(url): @@ -55,21 +93,28 @@ def get_response(url, timeout=10): # Check if the response contains an HTTP error if response.status_code >= 400: - return None, "Error: HTTP " + str(response.status_code) + " error" + return None, f"Error: HTTP {str(response.status_code)} error" return response, None except ValueError as ve: # Handle invalid URL format - return None, "Error: " + str(ve) + return None, f"Error: {str(ve)}" except requests.exceptions.RequestException as re: # Handle exceptions related to the HTTP request # (e.g., connection errors, timeouts, etc.) - return None, "Error: " + str(re) + return None, f"Error: {str(re)}" -def scrape_text(url): - """Scrape text from a webpage""" +def scrape_text(url: str) -> str: + """Scrape text from a webpage + + Args: + url (str): The URL to scrape text from + + Returns: + str: The scraped text + """ response, error_message = get_response(url) if error_message: return error_message @@ -89,24 +134,45 @@ def scrape_text(url): return text -def extract_hyperlinks(soup): - """Extract hyperlinks from a BeautifulSoup object""" +def extract_hyperlinks(soup: BeautifulSoup) -> List[Tuple[str, str]]: + """Extract hyperlinks from a BeautifulSoup object + + Args: + soup (BeautifulSoup): The BeautifulSoup object + + Returns: + List[Tuple[str, str]]: The extracted hyperlinks + """ hyperlinks = [] for link in soup.find_all("a", href=True): hyperlinks.append((link.text, link["href"])) return hyperlinks -def format_hyperlinks(hyperlinks): - """Format hyperlinks into a list of strings""" +def format_hyperlinks(hyperlinks: List[Tuple[str, str]]) -> List[str]: + """Format hyperlinks into a list of strings + + Args: + hyperlinks (List[Tuple[str, str]]): The hyperlinks to format + + Returns: + List[str]: The formatted hyperlinks + """ formatted_links = [] for link_text, link_url in hyperlinks: formatted_links.append(f"{link_text} ({link_url})") return formatted_links -def scrape_links(url): - """Scrape links from a webpage""" +def scrape_links(url: str) -> Union[str, List[str]]: + """Scrape links from a webpage + + Args: + url (str): The URL to scrape links from + + Returns: + Union[str, List[str]]: The scraped links + """ response, error_message = get_response(url) if error_message: return error_message @@ -122,25 +188,6 @@ def scrape_links(url): return format_hyperlinks(hyperlinks) -def split_text(text, max_length=cfg.browse_chunk_max_length): - """Split text into chunks of a maximum length""" - paragraphs = text.split("\n") - current_length = 0 - current_chunk = [] - - for paragraph in paragraphs: - if current_length + len(paragraph) + 1 <= max_length: - current_chunk.append(paragraph) - current_length += len(paragraph) + 1 - else: - yield "\n".join(current_chunk) - current_chunk = [paragraph] - current_length = len(paragraph) + 1 - - if current_chunk: - yield "\n".join(current_chunk) - - def create_message(chunk, question): """Create a message for the user to summarize a chunk of text""" return { @@ -149,50 +196,3 @@ def create_message(chunk, question): f' question: "{question}" -- if the question cannot be answered using the' " text, please summarize the text.", } - - -def summarize_text(url, text, question): - """Summarize text using the LLM model""" - if not text: - return "Error: No text to summarize" - - text_length = len(text) - print(f"Text length: {text_length} characters") - - summaries = [] - chunks = list(split_text(text)) - - for i, chunk in enumerate(chunks): - print(f"Adding chunk {i + 1} / {len(chunks)} to memory") - - memory_to_add = f"Source: {url}\n" f"Raw content part#{i + 1}: {chunk}" - - memory.add(memory_to_add) - - print(f"Summarizing chunk {i + 1} / {len(chunks)}") - messages = [create_message(chunk, question)] - - summary = create_chat_completion( - model=cfg.fast_llm_model, - messages=messages, - max_tokens=cfg.browse_summary_max_token, - ) - summaries.append(summary) - print(f"Added chunk {i + 1} summary to memory") - - memory_to_add = f"Source: {url}\n" f"Content summary part#{i + 1}: {summary}" - - memory.add(memory_to_add) - - print(f"Summarized {len(chunks)} chunks.") - - combined_summary = "\n".join(summaries) - messages = [create_message(combined_summary, question)] - - final_summary = create_chat_completion( - model=cfg.fast_llm_model, - messages=messages, - max_tokens=cfg.browse_summary_max_token, - ) - - return final_summary diff --git a/autogpt/commands/web_selenium.py b/autogpt/commands/web_selenium.py new file mode 100644 index 00000000..4d5703aa --- /dev/null +++ b/autogpt/commands/web_selenium.py @@ -0,0 +1,145 @@ +"""Selenium web scraping module.""" +from selenium import webdriver +import autogpt.processing.text as summary +from bs4 import BeautifulSoup +from selenium.webdriver.remote.webdriver import WebDriver +from selenium.webdriver.common.by import By +from selenium.webdriver.support.wait import WebDriverWait +from selenium.webdriver.support import expected_conditions as EC +from webdriver_manager.chrome import ChromeDriverManager +from selenium.webdriver.chrome.options import Options +import logging +from pathlib import Path +from autogpt.config import Config + +FILE_DIR = Path(__file__).parent.parent +CFG = Config() + + +def browse_website(url: str, question: str) -> tuple[str, WebDriver]: + """Browse a website and return the answer and links to the user + + Args: + url (str): The url of the website to browse + question (str): The question asked by the user + + Returns: + tuple[str, WebDriver]: The answer and links to the user and the webdriver + """ + driver, text = scrape_text_with_selenium(url) + add_header(driver) + summary_text = summary.summarize_text(url, text, question, driver) + links = scrape_links_with_selenium(driver) + + # Limit links to 5 + if len(links) > 5: + links = links[:5] + close_browser(driver) + return f"Answer gathered from website: {summary_text} \n \n Links: {links}", driver + + +def scrape_text_with_selenium(url: str) -> tuple[WebDriver, str]: + """Scrape text from a website using selenium + + Args: + url (str): The url of the website to scrape + + Returns: + tuple[WebDriver, str]: The webdriver and the text scraped from the website + """ + logging.getLogger("selenium").setLevel(logging.CRITICAL) + + options = Options() + options.add_argument( + "user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" + " (KHTML, like Gecko) Chrome/112.0.5615.49 Safari/537.36" + ) + driver = webdriver.Chrome( + executable_path=ChromeDriverManager().install(), options=options + ) + driver.get(url) + + WebDriverWait(driver, 10).until( + EC.presence_of_element_located((By.TAG_NAME, "body")) + ) + + # Get the HTML content directly from the browser's DOM + page_source = driver.execute_script("return document.body.outerHTML;") + soup = BeautifulSoup(page_source, "html.parser") + + for script in soup(["script", "style"]): + script.extract() + + text = soup.get_text() + lines = (line.strip() for line in text.splitlines()) + chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) + text = "\n".join(chunk for chunk in chunks if chunk) + return driver, text + + +def scrape_links_with_selenium(driver: WebDriver) -> list[str]: + """Scrape links from a website using selenium + + Args: + driver (WebDriver): The webdriver to use to scrape the links + + Returns: + list[str]: The links scraped from the website + """ + page_source = driver.page_source + soup = BeautifulSoup(page_source, "html.parser") + + for script in soup(["script", "style"]): + script.extract() + + hyperlinks = extract_hyperlinks(soup) + + return format_hyperlinks(hyperlinks) + + +def close_browser(driver: WebDriver) -> None: + """Close the browser + + Args: + driver (WebDriver): The webdriver to close + + Returns: + None + """ + driver.quit() + + +def extract_hyperlinks(soup: BeautifulSoup) -> list[tuple[str, str]]: + """Extract hyperlinks from a BeautifulSoup object + + Args: + soup (BeautifulSoup): The BeautifulSoup object to extract the hyperlinks from + + Returns: + list[tuple[str, str]]: The hyperlinks extracted from the BeautifulSoup object + """ + return [(link.text, link["href"]) for link in soup.find_all("a", href=True)] + + +def format_hyperlinks(hyperlinks: list[tuple[str, str]]) -> list[str]: + """Format hyperlinks to be displayed to the user + + Args: + hyperlinks (list[tuple[str, str]]): The hyperlinks to format + + Returns: + list[str]: The formatted hyperlinks + """ + return [f"{link_text} ({link_url})" for link_text, link_url in hyperlinks] + + +def add_header(driver: WebDriver) -> None: + """Add a header to the website + + Args: + driver (WebDriver): The webdriver to use to add the header + + Returns: + None + """ + driver.execute_script(open(f"{FILE_DIR}/js/overlay.js", "r").read()) diff --git a/autogpt/commands/write_tests.py b/autogpt/commands/write_tests.py new file mode 100644 index 00000000..f1d6c9b2 --- /dev/null +++ b/autogpt/commands/write_tests.py @@ -0,0 +1,29 @@ +"""A module that contains a function to generate test cases for the submitted code.""" +import json +from typing import List +from autogpt.llm_utils import call_ai_function + + +def write_tests(code: str, focus: List[str]) -> str: + """ + A function that takes in code and focus topics and returns a response from create + chat completion api call. + + Parameters: + focus (List): A list of suggestions around what needs to be improved. + code (str): Code for test cases to be generated against. + Returns: + A result string from create chat completion. Test cases for the submitted code + in response. + """ + + function_string = ( + "def create_test_cases(code: str, focus: Optional[str] = None) -> str:" + ) + args = [code, json.dumps(focus)] + description_string = ( + "Generates test cases for the existing code, focusing on" + " specific areas if required." + ) + + return call_ai_function(function_string, args, description_string) diff --git a/autogpt/config/__init__.py b/autogpt/config/__init__.py new file mode 100644 index 00000000..ceb5566c --- /dev/null +++ b/autogpt/config/__init__.py @@ -0,0 +1,14 @@ +""" +This module contains the configuration classes for AutoGPT. +""" +from autogpt.config.ai_config import AIConfig +from autogpt.config.config import check_openai_api_key, Config +from autogpt.config.singleton import AbstractSingleton, Singleton + +__all__ = [ + "check_openai_api_key", + "AbstractSingleton", + "AIConfig", + "Config", + "Singleton", +] diff --git a/autogpt/ai_config.py b/autogpt/config/ai_config.py similarity index 87% rename from autogpt/ai_config.py rename to autogpt/config/ai_config.py index 0957b886..c72b088b 100644 --- a/autogpt/ai_config.py +++ b/autogpt/config/ai_config.py @@ -1,9 +1,11 @@ +# sourcery skip: do-not-use-staticmethod +""" +A module that contains the AIConfig class object that contains the configuration +""" import os -from typing import Type +from typing import List, Optional, Type import yaml -from autogpt.prompt import get_prompt - class AIConfig: """ @@ -16,7 +18,7 @@ class AIConfig: """ def __init__( - self, ai_name: str = "", ai_role: str = "", ai_goals: list = [] + self, ai_name: str = "", ai_role: str = "", ai_goals: Optional[List] = None ) -> None: """ Initialize a class instance @@ -28,7 +30,8 @@ class AIConfig: Returns: None """ - + if ai_goals is None: + ai_goals = [] self.ai_name = ai_name self.ai_role = ai_role self.ai_goals = ai_goals @@ -36,15 +39,14 @@ class AIConfig: # Soon this will go in a folder where it remembers more stuff about the run(s) SAVE_FILE = os.path.join(os.path.dirname(__file__), "..", "ai_settings.yaml") - @classmethod - def load(cls: "Type[AIConfig]", config_file: str = SAVE_FILE) -> "Type[AIConfig]": + @staticmethod + def load(config_file: str = SAVE_FILE) -> "AIConfig": """ Returns class object with parameters (ai_name, ai_role, ai_goals) loaded from yaml file if yaml file exists, else returns class with no parameters. Parameters: - cls (class object): An AIConfig Class object. config_file (int): The path to the config yaml file. DEFAULT: "../ai_settings.yaml" @@ -62,7 +64,7 @@ class AIConfig: ai_role = config_params.get("ai_role", "") ai_goals = config_params.get("ai_goals", []) # type: Type[AIConfig] - return cls(ai_name, ai_role, ai_goals) + return AIConfig(ai_name, ai_role, ai_goals) def save(self, config_file: str = SAVE_FILE) -> None: """ @@ -103,6 +105,8 @@ class AIConfig: "" ) + from autogpt.prompt import get_prompt + # Construct full prompt full_prompt = ( f"You are {self.ai_name}, {self.ai_role}\n{prompt_start}\n\nGOALS:\n\n" diff --git a/autogpt/config.py b/autogpt/config/config.py similarity index 76% rename from autogpt/config.py rename to autogpt/config/config.py index 26132a5a..46764b9c 100644 --- a/autogpt/config.py +++ b/autogpt/config/config.py @@ -1,30 +1,15 @@ -import abc +"""Configuration class to store the state of bools for different scripts access.""" import os +from colorama import Fore + +from autogpt.config.singleton import Singleton import openai import yaml + from dotenv import load_dotenv -# Load environment variables from .env file -load_dotenv() - - -class Singleton(abc.ABCMeta, type): - """ - Singleton metaclass for ensuring only one instance of a class. - """ - - _instances = {} - - def __call__(cls, *args, **kwargs): - """Call method for the singleton metaclass.""" - if cls not in cls._instances: - cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) - return cls._instances[cls] - - -class AbstractSingleton(abc.ABC, metaclass=Singleton): - pass +load_dotenv(verbose=True) class Config(metaclass=Singleton): @@ -32,7 +17,7 @@ class Config(metaclass=Singleton): Configuration class to store the state of bools for different scripts access. """ - def __init__(self): + def __init__(self) -> None: """Initialize the Config class""" self.debug_mode = False self.continuous_mode = False @@ -81,10 +66,12 @@ class Config(metaclass=Singleton): self.huggingface_api_token = os.getenv("HUGGINGFACE_API_TOKEN") # User agent headers to use when browsing web - # Some websites might just completely deny request with an error code if no user agent was found. + # Some websites might just completely deny request with an error code if + # no user agent was found. self.user_agent = os.getenv( "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", + "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", ) self.redis_host = os.getenv("REDIS_HOST", "localhost") self.redis_port = os.getenv("REDIS_PORT", "6379") @@ -108,15 +95,17 @@ class Config(metaclass=Singleton): The matching deployment id if found, otherwise an empty string. """ if model == self.fast_llm_model: - return self.azure_model_to_deployment_id_map["fast_llm_model_deployment_id"] + return self.azure_model_to_deployment_id_map[ + "fast_llm_model_deployment_id" + ] # type: ignore elif model == self.smart_llm_model: return self.azure_model_to_deployment_id_map[ "smart_llm_model_deployment_id" - ] + ] # type: ignore elif model == "text-embedding-ada-002": return self.azure_model_to_deployment_id_map[ "embedding_model_deployment_id" - ] + ] # type: ignore else: return "" @@ -124,7 +113,8 @@ class Config(metaclass=Singleton): def load_azure_config(self, config_file: str = AZURE_CONFIG_FILE) -> None: """ - Loads the configuration parameters for Azure hosting from the specified file path as a yaml file. + Loads the configuration parameters for Azure hosting from the specified file + path as a yaml file. Parameters: config_file(str): The path to the config yaml file. DEFAULT: "../azure.yaml" @@ -148,74 +138,86 @@ class Config(metaclass=Singleton): ) self.azure_model_to_deployment_id_map = config_params.get("azure_model_map", []) - def set_continuous_mode(self, value: bool): + def set_continuous_mode(self, value: bool) -> None: """Set the continuous mode value.""" self.continuous_mode = value - def set_continuous_limit(self, value: int): + def set_continuous_limit(self, value: int) -> None: """Set the continuous limit value.""" self.continuous_limit = value - def set_speak_mode(self, value: bool): + def set_speak_mode(self, value: bool) -> None: """Set the speak mode value.""" self.speak_mode = value - def set_fast_llm_model(self, value: str): + def set_fast_llm_model(self, value: str) -> None: """Set the fast LLM model value.""" self.fast_llm_model = value - def set_smart_llm_model(self, value: str): + def set_smart_llm_model(self, value: str) -> None: """Set the smart LLM model value.""" self.smart_llm_model = value - def set_fast_token_limit(self, value: int): + def set_fast_token_limit(self, value: int) -> None: """Set the fast token limit value.""" self.fast_token_limit = value - def set_smart_token_limit(self, value: int): + def set_smart_token_limit(self, value: int) -> None: """Set the smart token limit value.""" self.smart_token_limit = value - def set_browse_chunk_max_length(self, value: int): + def set_browse_chunk_max_length(self, value: int) -> None: """Set the browse_website command chunk max length value.""" self.browse_chunk_max_length = value - def set_browse_summary_max_token(self, value: int): + def set_browse_summary_max_token(self, value: int) -> None: """Set the browse_website command summary max token value.""" self.browse_summary_max_token = value - def set_openai_api_key(self, value: str): + def set_openai_api_key(self, value: str) -> None: """Set the OpenAI API key value.""" self.openai_api_key = value - def set_elevenlabs_api_key(self, value: str): + def set_elevenlabs_api_key(self, value: str) -> None: """Set the ElevenLabs API key value.""" self.elevenlabs_api_key = value - def set_elevenlabs_voice_1_id(self, value: str): + def set_elevenlabs_voice_1_id(self, value: str) -> None: """Set the ElevenLabs Voice 1 ID value.""" self.elevenlabs_voice_1_id = value - def set_elevenlabs_voice_2_id(self, value: str): + def set_elevenlabs_voice_2_id(self, value: str) -> None: """Set the ElevenLabs Voice 2 ID value.""" self.elevenlabs_voice_2_id = value - def set_google_api_key(self, value: str): + def set_google_api_key(self, value: str) -> None: """Set the Google API key value.""" self.google_api_key = value - def set_custom_search_engine_id(self, value: str): + def set_custom_search_engine_id(self, value: str) -> None: """Set the custom search engine id value.""" self.custom_search_engine_id = value - def set_pinecone_api_key(self, value: str): + def set_pinecone_api_key(self, value: str) -> None: """Set the Pinecone API key value.""" self.pinecone_api_key = value - def set_pinecone_region(self, value: str): + def set_pinecone_region(self, value: str) -> None: """Set the Pinecone region value.""" self.pinecone_region = value - def set_debug_mode(self, value: bool): + def set_debug_mode(self, value: bool) -> None: """Set the debug mode value.""" self.debug_mode = value + + +def check_openai_api_key() -> None: + """Check if the OpenAI API key is set in config.py or as an environment variable.""" + cfg = Config() + if not cfg.openai_api_key: + print( + Fore.RED + + "Please set your OpenAI API key in .env or as an environment variable." + ) + print("You can get your key from https://beta.openai.com/account/api-keys") + exit(1) diff --git a/autogpt/config/singleton.py b/autogpt/config/singleton.py new file mode 100644 index 00000000..55b2aeea --- /dev/null +++ b/autogpt/config/singleton.py @@ -0,0 +1,24 @@ +"""The singleton metaclass for ensuring only one instance of a class.""" +import abc + + +class Singleton(abc.ABCMeta, type): + """ + Singleton metaclass for ensuring only one instance of a class. + """ + + _instances = {} + + def __call__(cls, *args, **kwargs): + """Call method for the singleton metaclass.""" + if cls not in cls._instances: + cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) + return cls._instances[cls] + + +class AbstractSingleton(abc.ABC, metaclass=Singleton): + """ + Abstract singleton class for ensuring only one instance of a class. + """ + + pass diff --git a/autogpt/data_ingestion.py b/autogpt/data_ingestion.py index 9df2b9e6..01bafc2a 100644 --- a/autogpt/data_ingestion.py +++ b/autogpt/data_ingestion.py @@ -2,7 +2,7 @@ import argparse import logging from autogpt.config import Config -from autogpt.file_operations import ingest_file, search_files +from autogpt.commands.file_operations import ingest_file, search_files from autogpt.memory import get_memory cfg = Config() @@ -87,7 +87,8 @@ def main() -> None: print(f"Error while ingesting directory '{args.dir}': {str(e)}") else: print( - "Please provide either a file path (--file) or a directory name (--dir) inside the auto_gpt_workspace directory as input." + "Please provide either a file path (--file) or a directory name (--dir)" + " inside the auto_gpt_workspace directory as input." ) diff --git a/autogpt/execute_code.py b/autogpt/execute_code.py deleted file mode 100644 index c5f85a04..00000000 --- a/autogpt/execute_code.py +++ /dev/null @@ -1,105 +0,0 @@ -import os -import subprocess - -import docker -from docker.errors import ImageNotFound - -WORKSPACE_FOLDER = "auto_gpt_workspace" - - -def execute_python_file(file): - """Execute a Python file in a Docker container and return the output""" - - print(f"Executing file '{file}' in workspace '{WORKSPACE_FOLDER}'") - - if not file.endswith(".py"): - return "Error: Invalid file type. Only .py files are allowed." - - file_path = os.path.join(WORKSPACE_FOLDER, file) - - if not os.path.isfile(file_path): - return f"Error: File '{file}' does not exist." - - if we_are_running_in_a_docker_container(): - result = subprocess.run( - f"python {file_path}", capture_output=True, encoding="utf8", shell=True - ) - if result.returncode == 0: - return result.stdout - else: - return f"Error: {result.stderr}" - else: - try: - client = docker.from_env() - - image_name = "python:3.10" - try: - client.images.get(image_name) - print(f"Image '{image_name}' found locally") - except ImageNotFound: - print( - f"Image '{image_name}' not found locally, pulling from Docker Hub" - ) - # Use the low-level API to stream the pull response - low_level_client = docker.APIClient() - for line in low_level_client.pull(image_name, stream=True, decode=True): - # Print the status and progress, if available - status = line.get("status") - progress = line.get("progress") - if status and progress: - print(f"{status}: {progress}") - elif status: - print(status) - - # You can replace 'python:3.8' with the desired Python image/version - # You can find available Python images on Docker Hub: - # https://hub.docker.com/_/python - container = client.containers.run( - image_name, - f"python {file}", - volumes={ - os.path.abspath(WORKSPACE_FOLDER): { - "bind": "/workspace", - "mode": "ro", - } - }, - working_dir="/workspace", - stderr=True, - stdout=True, - detach=True, - ) - - container.wait() - logs = container.logs().decode("utf-8") - container.remove() - - # print(f"Execution complete. Output: {output}") - # print(f"Logs: {logs}") - - return logs - - except Exception as e: - return f"Error: {str(e)}" - - -def execute_shell(command_line): - current_dir = os.getcwd() - - if WORKSPACE_FOLDER not in current_dir: # Change dir into workspace if necessary - work_dir = os.path.join(os.getcwd(), WORKSPACE_FOLDER) - os.chdir(work_dir) - - print(f"Executing command '{command_line}' in working directory '{os.getcwd()}'") - - result = subprocess.run(command_line, capture_output=True, shell=True) - output = f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}" - - # Change back to whatever the prior working dir was - - os.chdir(current_dir) - - return output - - -def we_are_running_in_a_docker_container(): - os.path.exists("/.dockerenv") diff --git a/autogpt/image_gen.py b/autogpt/image_gen.py deleted file mode 100644 index 9d5694e4..00000000 --- a/autogpt/image_gen.py +++ /dev/null @@ -1,67 +0,0 @@ -import io -import os.path -import uuid -from base64 import b64decode - -import openai -import requests -from PIL import Image - -from autogpt.config import Config - -cfg = Config() - -working_directory = "auto_gpt_workspace" - - -def generate_image(prompt): - filename = str(uuid.uuid4()) + ".jpg" - - # DALL-E - if cfg.image_provider == "dalle": - openai.api_key = cfg.openai_api_key - - response = openai.Image.create( - prompt=prompt, - n=1, - size="256x256", - response_format="b64_json", - ) - - print("Image Generated for prompt:" + prompt) - - image_data = b64decode(response["data"][0]["b64_json"]) - - with open(working_directory + "/" + filename, mode="wb") as png: - png.write(image_data) - - return "Saved to disk:" + filename - - # STABLE DIFFUSION - elif cfg.image_provider == "sd": - API_URL = ( - "https://api-inference.huggingface.co/models/CompVis/stable-diffusion-v1-4" - ) - if cfg.huggingface_api_token is None: - raise ValueError( - "You need to set your Hugging Face API token in the config file." - ) - headers = {"Authorization": "Bearer " + cfg.huggingface_api_token} - - response = requests.post( - API_URL, - headers=headers, - json={ - "inputs": prompt, - }, - ) - - image = Image.open(io.BytesIO(response.content)) - print("Image Generated for prompt:" + prompt) - - image.save(os.path.join(working_directory, filename)) - - return "Saved to disk:" + filename - - else: - return "No Image Provider Set" diff --git a/autogpt/json_fixes/__init__.py b/autogpt/json_fixes/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/autogpt/json_fixes/auto_fix.py b/autogpt/json_fixes/auto_fix.py new file mode 100644 index 00000000..60c089a2 --- /dev/null +++ b/autogpt/json_fixes/auto_fix.py @@ -0,0 +1,40 @@ +"""This module contains the function to fix JSON strings using GPT-3.""" +import json +from autogpt.llm_utils import call_ai_function +from autogpt.logs import logger + + +def fix_json(json_str: str, schema: str) -> str: + """Fix the given JSON string to make it parseable and fully compliant with the provided schema.""" + # Try to fix the JSON using GPT: + function_string = "def fix_json(json_str: str, schema:str=None) -> str:" + args = [f"'''{json_str}'''", f"'''{schema}'''"] + description_string = ( + "Fixes the provided JSON string to make it parseable" + " and fully compliant with the provided schema.\n If an object or" + " field specified in the schema isn't contained within the correct" + " JSON, it is omitted.\n This function is brilliant at guessing" + " when the format is incorrect." + ) + + # If it doesn't already start with a "`", add one: + if not json_str.startswith("`"): + json_str = "```json\n" + json_str + "\n```" + result_string = call_ai_function( + function_string, args, description_string, model=cfg.fast_llm_model + ) + logger.debug("------------ JSON FIX ATTEMPT ---------------") + logger.debug(f"Original JSON: {json_str}") + logger.debug("-----------") + logger.debug(f"Fixed JSON: {result_string}") + logger.debug("----------- END OF FIX ATTEMPT ----------------") + + try: + json.loads(result_string) # just check the validity + return result_string + except: # noqa: E722 + # Get the call stack: + # import traceback + # call_stack = traceback.format_exc() + # print(f"Failed to fix JSON: '{json_str}' "+call_stack) + return "failed" diff --git a/autogpt/json_fixes/bracket_termination.py b/autogpt/json_fixes/bracket_termination.py new file mode 100644 index 00000000..13c2ccfd --- /dev/null +++ b/autogpt/json_fixes/bracket_termination.py @@ -0,0 +1,73 @@ +"""Fix JSON brackets.""" +import contextlib +import json +from typing import Optional +import regex +from colorama import Fore + +from autogpt.logs import logger +from autogpt.config import Config +from autogpt.speech import say_text + +CFG = Config() + + +def attempt_to_fix_json_by_finding_outermost_brackets(json_string: str): + if CFG.speak_mode and CFG.debug_mode: + say_text( + "I have received an invalid JSON response from the OpenAI API. " + "Trying to fix it now." + ) + logger.typewriter_log("Attempting to fix JSON by finding outermost brackets\n") + + try: + json_pattern = regex.compile(r"\{(?:[^{}]|(?R))*\}") + json_match = json_pattern.search(json_string) + + if json_match: + # Extract the valid JSON object from the string + json_string = json_match.group(0) + logger.typewriter_log( + title="Apparently json was fixed.", title_color=Fore.GREEN + ) + if CFG.speak_mode and CFG.debug_mode: + say_text("Apparently json was fixed.") + else: + raise ValueError("No valid JSON object found") + + except (json.JSONDecodeError, ValueError): + if CFG.debug_mode: + logger.error("Error: Invalid JSON: %s\n", json_string) + if CFG.speak_mode: + say_text("Didn't work. I will have to ignore this response then.") + logger.error("Error: Invalid JSON, setting it to empty JSON now.\n") + json_string = {} + + return json_string + + +def balance_braces(json_string: str) -> Optional[str]: + """ + Balance the braces in a JSON string. + + Args: + json_string (str): The JSON string. + + Returns: + str: The JSON string with braces balanced. + """ + + open_braces_count = json_string.count("{") + close_braces_count = json_string.count("}") + + while open_braces_count > close_braces_count: + json_string += "}" + close_braces_count += 1 + + while close_braces_count > open_braces_count: + json_string = json_string.rstrip("}") + close_braces_count -= 1 + + with contextlib.suppress(json.JSONDecodeError): + json.loads(json_string) + return json_string diff --git a/autogpt/json_fixes/escaping.py b/autogpt/json_fixes/escaping.py new file mode 100644 index 00000000..68eb1714 --- /dev/null +++ b/autogpt/json_fixes/escaping.py @@ -0,0 +1,33 @@ +""" Fix invalid escape sequences in JSON strings. """ +import json + +from autogpt.config import Config +from autogpt.json_fixes.utilities import extract_char_position + +CFG = Config() + + +def fix_invalid_escape(json_to_load: str, error_message: str) -> str: + """Fix invalid escape sequences in JSON strings. + + Args: + json_to_load (str): The JSON string. + error_message (str): The error message from the JSONDecodeError + exception. + + Returns: + str: The JSON string with invalid escape sequences fixed. + """ + while error_message.startswith("Invalid \\escape"): + bad_escape_location = extract_char_position(error_message) + json_to_load = ( + json_to_load[:bad_escape_location] + json_to_load[bad_escape_location + 1 :] + ) + try: + json.loads(json_to_load) + return json_to_load + except json.JSONDecodeError as e: + if CFG.debug_mode: + print("json loads error - fix invalid escape", e) + error_message = str(e) + return json_to_load diff --git a/autogpt/json_fixes/missing_quotes.py b/autogpt/json_fixes/missing_quotes.py new file mode 100644 index 00000000..552a1517 --- /dev/null +++ b/autogpt/json_fixes/missing_quotes.py @@ -0,0 +1,27 @@ +"""Fix quotes in a JSON string.""" +import json +import re + + +def add_quotes_to_property_names(json_string: str) -> str: + """ + Add quotes to property names in a JSON string. + + Args: + json_string (str): The JSON string. + + Returns: + str: The JSON string with quotes added to property names. + """ + + def replace_func(match: re.Match) -> str: + return f'"{match[1]}":' + + property_name_pattern = re.compile(r"(\w+):") + corrected_json_string = property_name_pattern.sub(replace_func, json_string) + + try: + json.loads(corrected_json_string) + return corrected_json_string + except json.JSONDecodeError as e: + raise e diff --git a/autogpt/json_fixes/parsing.py b/autogpt/json_fixes/parsing.py new file mode 100644 index 00000000..26d06793 --- /dev/null +++ b/autogpt/json_fixes/parsing.py @@ -0,0 +1,143 @@ +"""Fix and parse JSON strings.""" + +import contextlib +import json +from typing import Any, Dict, Union + +from autogpt.config import Config +from autogpt.json_fixes.auto_fix import fix_json +from autogpt.json_fixes.bracket_termination import balance_braces +from autogpt.json_fixes.escaping import fix_invalid_escape +from autogpt.json_fixes.missing_quotes import add_quotes_to_property_names +from autogpt.logs import logger + +CFG = Config() + + +JSON_SCHEMA = """ +{ + "command": { + "name": "command name", + "args": { + "arg name": "value" + } + }, + "thoughts": + { + "text": "thought", + "reasoning": "reasoning", + "plan": "- short bulleted\n- list that conveys\n- long-term plan", + "criticism": "constructive self-criticism", + "speak": "thoughts summary to say to user" + } +} +""" + + +def correct_json(json_to_load: str) -> str: + """ + Correct common JSON errors. + + Args: + json_to_load (str): The JSON string. + """ + + try: + if CFG.debug_mode: + print("json", json_to_load) + json.loads(json_to_load) + return json_to_load + except json.JSONDecodeError as e: + if CFG.debug_mode: + print("json loads error", e) + error_message = str(e) + if error_message.startswith("Invalid \\escape"): + json_to_load = fix_invalid_escape(json_to_load, error_message) + if error_message.startswith( + "Expecting property name enclosed in double quotes" + ): + json_to_load = add_quotes_to_property_names(json_to_load) + try: + json.loads(json_to_load) + return json_to_load + except json.JSONDecodeError as e: + if CFG.debug_mode: + print("json loads error - add quotes", e) + error_message = str(e) + if balanced_str := balance_braces(json_to_load): + return balanced_str + return json_to_load + + +def fix_and_parse_json( + json_to_load: str, try_to_fix_with_gpt: bool = True +) -> Union[str, Dict[Any, Any]]: + """Fix and parse JSON string + + Args: + json_to_load (str): The JSON string. + try_to_fix_with_gpt (bool, optional): Try to fix the JSON with GPT. + Defaults to True. + + Returns: + Union[str, Dict[Any, Any]]: The parsed JSON. + """ + + with contextlib.suppress(json.JSONDecodeError): + json_to_load = json_to_load.replace("\t", "") + return json.loads(json_to_load) + + with contextlib.suppress(json.JSONDecodeError): + json_to_load = correct_json(json_to_load) + return json.loads(json_to_load) + # Let's do something manually: + # sometimes GPT responds with something BEFORE the braces: + # "I'm sorry, I don't understand. Please try again." + # {"text": "I'm sorry, I don't understand. Please try again.", + # "confidence": 0.0} + # So let's try to find the first brace and then parse the rest + # of the string + try: + brace_index = json_to_load.index("{") + maybe_fixed_json = json_to_load[brace_index:] + last_brace_index = maybe_fixed_json.rindex("}") + maybe_fixed_json = maybe_fixed_json[: last_brace_index + 1] + return json.loads(maybe_fixed_json) + except (json.JSONDecodeError, ValueError) as e: + return try_ai_fix(try_to_fix_with_gpt, e, json_to_load) + + +def try_ai_fix( + try_to_fix_with_gpt: bool, exception: Exception, json_to_load: str +) -> Union[str, Dict[Any, Any]]: + """Try to fix the JSON with the AI + + Args: + try_to_fix_with_gpt (bool): Whether to try to fix the JSON with the AI. + exception (Exception): The exception that was raised. + json_to_load (str): The JSON string to load. + + Raises: + exception: If try_to_fix_with_gpt is False. + + Returns: + Union[str, Dict[Any, Any]]: The JSON string or dictionary. + """ + if not try_to_fix_with_gpt: + raise exception + + logger.warn( + "Warning: Failed to parse AI output, attempting to fix." + "\n If you see this warning frequently, it's likely that" + " your prompt is confusing the AI. Try changing it up" + " slightly." + ) + # Now try to fix this up using the ai_functions + ai_fixed_json = fix_json(json_to_load, JSON_SCHEMA) + + if ai_fixed_json != "failed": + return json.loads(ai_fixed_json) + # This allows the AI to react to the error message, + # which usually results in it correcting its ways. + logger.error("Failed to fix AI output, telling the AI.") + return json_to_load diff --git a/autogpt/json_fixes/utilities.py b/autogpt/json_fixes/utilities.py new file mode 100644 index 00000000..0852b18a --- /dev/null +++ b/autogpt/json_fixes/utilities.py @@ -0,0 +1,20 @@ +"""Utilities for the json_fixes package.""" +import re + + +def extract_char_position(error_message: str) -> int: + """Extract the character position from the JSONDecodeError message. + + Args: + error_message (str): The error message from the JSONDecodeError + exception. + + Returns: + int: The character position. + """ + + char_pattern = re.compile(r"\(char (\d+)\)") + if match := char_pattern.search(error_message): + return int(match[1]) + else: + raise ValueError("Character position not found in the error message.") diff --git a/autogpt/json_parser.py b/autogpt/json_parser.py deleted file mode 100644 index b32146da..00000000 --- a/autogpt/json_parser.py +++ /dev/null @@ -1,113 +0,0 @@ -import json -from typing import Any, Dict, Union - -from autogpt.call_ai_function import call_ai_function -from autogpt.config import Config -from autogpt.json_utils import correct_json -from autogpt.logger import logger - -cfg = Config() - -JSON_SCHEMA = """ -{ - "command": { - "name": "command name", - "args": { - "arg name": "value" - } - }, - "thoughts": - { - "text": "thought", - "reasoning": "reasoning", - "plan": "- short bulleted\n- list that conveys\n- long-term plan", - "criticism": "constructive self-criticism", - "speak": "thoughts summary to say to user" - } -} -""" - - -def fix_and_parse_json( - json_str: str, try_to_fix_with_gpt: bool = True -) -> Union[str, Dict[Any, Any]]: - """Fix and parse JSON string""" - try: - json_str = json_str.replace("\t", "") - return json.loads(json_str) - except json.JSONDecodeError as _: # noqa: F841 - try: - json_str = correct_json(json_str) - return json.loads(json_str) - except json.JSONDecodeError as _: # noqa: F841 - pass - # Let's do something manually: - # sometimes GPT responds with something BEFORE the braces: - # "I'm sorry, I don't understand. Please try again." - # {"text": "I'm sorry, I don't understand. Please try again.", - # "confidence": 0.0} - # So let's try to find the first brace and then parse the rest - # of the string - try: - brace_index = json_str.index("{") - json_str = json_str[brace_index:] - last_brace_index = json_str.rindex("}") - json_str = json_str[: last_brace_index + 1] - return json.loads(json_str) - # Can throw a ValueError if there is no "{" or "}" in the json_str - except (json.JSONDecodeError, ValueError) as e: # noqa: F841 - if try_to_fix_with_gpt: - logger.warn( - "Warning: Failed to parse AI output, attempting to fix." - "\n If you see this warning frequently, it's likely that" - " your prompt is confusing the AI. Try changing it up" - " slightly." - ) - # Now try to fix this up using the ai_functions - ai_fixed_json = fix_json(json_str, JSON_SCHEMA) - - if ai_fixed_json != "failed": - return json.loads(ai_fixed_json) - else: - # This allows the AI to react to the error message, - # which usually results in it correcting its ways. - logger.error("Failed to fix AI output, telling the AI.") - return json_str - else: - raise e - - -def fix_json(json_str: str, schema: str) -> str: - """Fix the given JSON string to make it parseable and fully compliant with the provided schema.""" - # Try to fix the JSON using GPT: - function_string = "def fix_json(json_str: str, schema:str=None) -> str:" - args = [f"'''{json_str}'''", f"'''{schema}'''"] - description_string = ( - "Fixes the provided JSON string to make it parseable" - " and fully compliant with the provided schema.\n If an object or" - " field specified in the schema isn't contained within the correct" - " JSON, it is omitted.\n This function is brilliant at guessing" - " when the format is incorrect." - ) - - # If it doesn't already start with a "`", add one: - if not json_str.startswith("`"): - json_str = "```json\n" + json_str + "\n```" - result_string = call_ai_function( - function_string, args, description_string, model=cfg.fast_llm_model - ) - logger.debug("------------ JSON FIX ATTEMPT ---------------") - logger.debug(f"Original JSON: {json_str}") - logger.debug("-----------") - logger.debug(f"Fixed JSON: {result_string}") - logger.debug("----------- END OF FIX ATTEMPT ----------------") - - try: - json.loads(result_string) # just check the validity - return result_string - except: # noqa: E722 - # Get the call stack: - # import traceback - # call_stack = traceback.format_exc() - # print(f"Failed to fix JSON: '{json_str}' "+call_stack) - return "failed" diff --git a/autogpt/json_utils.py b/autogpt/json_utils.py deleted file mode 100644 index 848f9fff..00000000 --- a/autogpt/json_utils.py +++ /dev/null @@ -1,128 +0,0 @@ -import json -import re -from typing import Optional - -from autogpt.config import Config - -cfg = Config() - - -def extract_char_position(error_message: str) -> int: - """Extract the character position from the JSONDecodeError message. - - Args: - error_message (str): The error message from the JSONDecodeError - exception. - - Returns: - int: The character position. - """ - import re - - char_pattern = re.compile(r"\(char (\d+)\)") - if match := char_pattern.search(error_message): - return int(match[1]) - else: - raise ValueError("Character position not found in the error message.") - - -def add_quotes_to_property_names(json_string: str) -> str: - """ - Add quotes to property names in a JSON string. - - Args: - json_string (str): The JSON string. - - Returns: - str: The JSON string with quotes added to property names. - """ - - def replace_func(match): - return f'"{match.group(1)}":' - - property_name_pattern = re.compile(r"(\w+):") - corrected_json_string = property_name_pattern.sub(replace_func, json_string) - - try: - json.loads(corrected_json_string) - return corrected_json_string - except json.JSONDecodeError as e: - raise e - - -def balance_braces(json_string: str) -> Optional[str]: - """ - Balance the braces in a JSON string. - - Args: - json_string (str): The JSON string. - - Returns: - str: The JSON string with braces balanced. - """ - - open_braces_count = json_string.count("{") - close_braces_count = json_string.count("}") - - while open_braces_count > close_braces_count: - json_string += "}" - close_braces_count += 1 - - while close_braces_count > open_braces_count: - json_string = json_string.rstrip("}") - close_braces_count -= 1 - - try: - json.loads(json_string) - return json_string - except json.JSONDecodeError: - pass - - -def fix_invalid_escape(json_str: str, error_message: str) -> str: - while error_message.startswith("Invalid \\escape"): - bad_escape_location = extract_char_position(error_message) - json_str = json_str[:bad_escape_location] + json_str[bad_escape_location + 1 :] - try: - json.loads(json_str) - return json_str - except json.JSONDecodeError as e: - if cfg.debug_mode: - print("json loads error - fix invalid escape", e) - error_message = str(e) - return json_str - - -def correct_json(json_str: str) -> str: - """ - Correct common JSON errors. - - Args: - json_str (str): The JSON string. - """ - - try: - if cfg.debug_mode: - print("json", json_str) - json.loads(json_str) - return json_str - except json.JSONDecodeError as e: - if cfg.debug_mode: - print("json loads error", e) - error_message = str(e) - if error_message.startswith("Invalid \\escape"): - json_str = fix_invalid_escape(json_str, error_message) - if error_message.startswith( - "Expecting property name enclosed in double quotes" - ): - json_str = add_quotes_to_property_names(json_str) - try: - json.loads(json_str) - return json_str - except json.JSONDecodeError as e: - if cfg.debug_mode: - print("json loads error - add quotes", e) - error_message = str(e) - if balanced_str := balance_braces(json_str): - return balanced_str - return json_str diff --git a/autogpt/llm_utils.py b/autogpt/llm_utils.py index 7503dc44..f2418b65 100644 --- a/autogpt/llm_utils.py +++ b/autogpt/llm_utils.py @@ -1,4 +1,6 @@ +from ast import List import time +from typing import Dict, Optional import openai from openai.error import APIError, RateLimitError @@ -6,30 +8,79 @@ from colorama import Fore from autogpt.config import Config -cfg = Config() +CFG = Config() -openai.api_key = cfg.openai_api_key +openai.api_key = CFG.openai_api_key + + +def call_ai_function( + function: str, args: List, description: str, model: Optional[str] = None +) -> str: + """Call an AI function + + This is a magic function that can do anything with no-code. See + https://github.com/Torantulino/AI-Functions for more info. + + Args: + function (str): The function to call + args (list): The arguments to pass to the function + description (str): The description of the function + model (str, optional): The model to use. Defaults to None. + + Returns: + str: The response from the function + """ + if model is None: + model = CFG.smart_llm_model + # For each arg, if any are None, convert to "None": + args = [str(arg) if arg is not None else "None" for arg in args] + # parse args to comma separated string + args = ", ".join(args) + messages = [ + { + "role": "system", + "content": f"You are now the following python function: ```# {description}" + f"\n{function}```\n\nOnly respond with your `return` value.", + }, + {"role": "user", "content": args}, + ] + + return create_chat_completion(model=model, messages=messages, temperature=0) # Overly simple abstraction until we create something better # simple retry mechanism when getting a rate error or a bad gateway def create_chat_completion( - messages, model=None, temperature=cfg.temperature, max_tokens=None + messages: List, # type: ignore + model: Optional[str] = None, + temperature: float = CFG.temperature, + max_tokens: Optional[int] = None, ) -> str: - """Create a chat completion using the OpenAI API""" + """Create a chat completion using the OpenAI API + + Args: + messages (list[dict[str, str]]): The messages to send to the chat completion + model (str, optional): The model to use. Defaults to None. + temperature (float, optional): The temperature to use. Defaults to 0.9. + max_tokens (int, optional): The max tokens to use. Defaults to None. + + Returns: + str: The response from the chat completion + """ response = None - num_retries = 5 - if cfg.debug_mode: + num_retries = 10 + if CFG.debug_mode: print( Fore.GREEN + f"Creating chat completion with model {model}, temperature {temperature}," f" max_tokens {max_tokens}" + Fore.RESET ) for attempt in range(num_retries): + backoff = 2 ** (attempt + 2) try: - if cfg.use_azure: + if CFG.use_azure: response = openai.ChatCompletion.create( - deployment_id=cfg.get_azure_deployment_id_for_model(model), + deployment_id=CFG.get_azure_deployment_id_for_model(model), model=model, messages=messages, temperature=temperature, @@ -44,26 +95,21 @@ def create_chat_completion( ) break except RateLimitError: - if cfg.debug_mode: - print( - Fore.RED + "Error: ", - "API Rate Limit Reached. Waiting 20 seconds..." + Fore.RESET, - ) - time.sleep(20) + pass except APIError as e: if e.http_status == 502: - if cfg.debug_mode: - print( - Fore.RED + "Error: ", - "API Bad gateway. Waiting 20 seconds..." + Fore.RESET, - ) - time.sleep(20) + pass else: raise if attempt == num_retries - 1: raise - + if CFG.debug_mode: + print( + Fore.RED + "Error: ", + f"API Bad gateway. Waiting {backoff} seconds..." + Fore.RESET, + ) + time.sleep(backoff) if response is None: - raise RuntimeError("Failed to get response after 5 retries") + raise RuntimeError(f"Failed to get response after {num_retries} retries") return response.choices[0].message["content"] diff --git a/autogpt/logger.py b/autogpt/logs.py similarity index 59% rename from autogpt/logger.py rename to autogpt/logs.py index 1b58fdff..a34d89b1 100644 --- a/autogpt/logger.py +++ b/autogpt/logs.py @@ -1,25 +1,28 @@ +"""Logging module for Auto-GPT.""" +import json import logging import os import random import re import time from logging import LogRecord +import traceback from colorama import Fore, Style -from autogpt import speak +from autogpt.speech import say_text from autogpt.config import Config, Singleton -cfg = Config() - -""" -Logger that handle titles in different colors. -Outputs logs in console, activity.log, and errors.log -For console handler: simulates typing -""" +CFG = Config() class Logger(metaclass=Singleton): + """ + Logger that handle titles in different colors. + Outputs logs in console, activity.log, and errors.log + For console handler: simulates typing + """ + def __init__(self): # create log directory if it doesn't exist this_files_dir_path = os.path.dirname(__file__) @@ -74,8 +77,8 @@ class Logger(metaclass=Singleton): def typewriter_log( self, title="", title_color="", content="", speak_text=False, level=logging.INFO ): - if speak_text and cfg.speak_mode: - speak.say_text(f"{title}. {content}") + if speak_text and CFG.speak_mode: + say_text(f"{title}. {content}") if content: if isinstance(content, list): @@ -193,3 +196,93 @@ def remove_color_codes(s: str) -> str: logger = Logger() + + +def print_assistant_thoughts(ai_name, assistant_reply): + """Prints the assistant's thoughts to the console""" + from autogpt.json_fixes.bracket_termination import ( + attempt_to_fix_json_by_finding_outermost_brackets, + ) + from autogpt.json_fixes.parsing import fix_and_parse_json + + try: + try: + # Parse and print Assistant response + assistant_reply_json = fix_and_parse_json(assistant_reply) + except json.JSONDecodeError: + logger.error("Error: Invalid JSON in assistant thoughts\n", assistant_reply) + assistant_reply_json = attempt_to_fix_json_by_finding_outermost_brackets( + assistant_reply + ) + if isinstance(assistant_reply_json, str): + assistant_reply_json = fix_and_parse_json(assistant_reply_json) + + # Check if assistant_reply_json is a string and attempt to parse + # it into a JSON object + if isinstance(assistant_reply_json, str): + try: + assistant_reply_json = json.loads(assistant_reply_json) + except json.JSONDecodeError: + logger.error("Error: Invalid JSON\n", assistant_reply) + assistant_reply_json = ( + attempt_to_fix_json_by_finding_outermost_brackets( + assistant_reply_json + ) + ) + + assistant_thoughts_reasoning = None + assistant_thoughts_plan = None + assistant_thoughts_speak = None + assistant_thoughts_criticism = None + if not isinstance(assistant_reply_json, dict): + assistant_reply_json = {} + assistant_thoughts = assistant_reply_json.get("thoughts", {}) + assistant_thoughts_text = assistant_thoughts.get("text") + + if assistant_thoughts: + assistant_thoughts_reasoning = assistant_thoughts.get("reasoning") + assistant_thoughts_plan = assistant_thoughts.get("plan") + assistant_thoughts_criticism = assistant_thoughts.get("criticism") + assistant_thoughts_speak = assistant_thoughts.get("speak") + + logger.typewriter_log( + f"{ai_name.upper()} THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}" + ) + logger.typewriter_log( + "REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}" + ) + + if assistant_thoughts_plan: + logger.typewriter_log("PLAN:", Fore.YELLOW, "") + # If it's a list, join it into a string + if isinstance(assistant_thoughts_plan, list): + assistant_thoughts_plan = "\n".join(assistant_thoughts_plan) + elif isinstance(assistant_thoughts_plan, dict): + assistant_thoughts_plan = str(assistant_thoughts_plan) + + # Split the input_string using the newline character and dashes + lines = assistant_thoughts_plan.split("\n") + for line in lines: + line = line.lstrip("- ") + logger.typewriter_log("- ", Fore.GREEN, line.strip()) + + logger.typewriter_log( + "CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}" + ) + # Speak the assistant's thoughts + if CFG.speak_mode and assistant_thoughts_speak: + say_text(assistant_thoughts_speak) + + return assistant_reply_json + except json.decoder.JSONDecodeError: + logger.error("Error: Invalid JSON\n", assistant_reply) + if CFG.speak_mode: + say_text( + "I have received an invalid JSON response from the OpenAI API." + " I cannot ignore this response." + ) + + # All other errors, return "Error: + error message" + except Exception: + call_stack = traceback.format_exc() + logger.error("Error: \n", call_stack) diff --git a/autogpt/memory/local.py b/autogpt/memory/local.py index 67f040ae..a5f6076e 100644 --- a/autogpt/memory/local.py +++ b/autogpt/memory/local.py @@ -1,6 +1,6 @@ import dataclasses import os -from typing import Any, List, Optional +from typing import Any, List, Optional, Tuple import numpy as np import orjson @@ -24,8 +24,17 @@ class CacheContent: class LocalCache(MemoryProviderSingleton): - # on load, load our database + """A class that stores the memory in a local file""" + def __init__(self, cfg) -> None: + """Initialize a class instance + + Args: + cfg: Config object + + Returns: + None + """ self.filename = f"{cfg.memory_index}.json" if os.path.exists(self.filename): try: @@ -42,7 +51,8 @@ class LocalCache(MemoryProviderSingleton): self.data = CacheContent() else: print( - f"Warning: The file '{self.filename}' does not exist. Local memory would not be saved to a file." + f"Warning: The file '{self.filename}' does not exist." + "Local memory would not be saved to a file." ) self.data = CacheContent() @@ -116,7 +126,7 @@ class LocalCache(MemoryProviderSingleton): return [self.data.texts[i] for i in top_k_indices] - def get_stats(self): + def get_stats(self) -> Tuple[int, Tuple[int, ...]]: """ Returns: The stats of the local cache. """ diff --git a/autogpt/memory/no_memory.py b/autogpt/memory/no_memory.py index 37f00085..0a976690 100644 --- a/autogpt/memory/no_memory.py +++ b/autogpt/memory/no_memory.py @@ -1,9 +1,14 @@ +"""A class that does not store any data. This is the default memory provider.""" from typing import Optional, List, Any from autogpt.memory.base import MemoryProviderSingleton class NoMemory(MemoryProviderSingleton): + """ + A class that does not store any data. This is the default memory provider. + """ + def __init__(self, cfg): """ Initializes the NoMemory provider. diff --git a/autogpt/memory/pinecone.py b/autogpt/memory/pinecone.py index 4e302f6e..a7dbfa82 100644 --- a/autogpt/memory/pinecone.py +++ b/autogpt/memory/pinecone.py @@ -1,7 +1,7 @@ import pinecone from colorama import Fore, Style -from autogpt.logger import logger +from autogpt.logs import logger from autogpt.memory.base import MemoryProviderSingleton, get_ada_embedding @@ -16,7 +16,8 @@ class PineconeMemory(MemoryProviderSingleton): table_name = "auto-gpt" # this assumes we don't start with memory. # for now this works. - # we'll need a more complicated and robust system if we want to start with memory. + # we'll need a more complicated and robust system if we want to start with + # memory. self.vec_num = 0 try: @@ -28,8 +29,10 @@ class PineconeMemory(MemoryProviderSingleton): Style.BRIGHT + str(e) + Style.RESET_ALL, ) logger.double_check( - "Please ensure you have setup and configured Pinecone properly for use. " - + f"You can check out {Fore.CYAN + Style.BRIGHT}https://github.com/Torantulino/Auto-GPT#-pinecone-api-key-setup{Style.RESET_ALL} to ensure you've set up everything correctly." + "Please ensure you have setup and configured Pinecone properly for use." + + f"You can check out {Fore.CYAN + Style.BRIGHT}" + "https://github.com/Torantulino/Auto-GPT#-pinecone-api-key-setup" + f"{Style.RESET_ALL} to ensure you've set up everything correctly." ) exit(1) @@ -42,7 +45,7 @@ class PineconeMemory(MemoryProviderSingleton): def add(self, data): vector = get_ada_embedding(data) # no metadata here. We may wish to change that long term. - resp = self.index.upsert([(str(self.vec_num), vector, {"raw_text": data})]) + self.index.upsert([(str(self.vec_num), vector, {"raw_text": data})]) _text = f"Inserting data into memory at index: {self.vec_num}:\n data: {data}" self.vec_num += 1 return _text diff --git a/autogpt/memory/redismem.py b/autogpt/memory/redismem.py index d36594ba..df6d8fc0 100644 --- a/autogpt/memory/redismem.py +++ b/autogpt/memory/redismem.py @@ -8,7 +8,7 @@ from redis.commands.search.field import TextField, VectorField from redis.commands.search.indexDefinition import IndexDefinition, IndexType from redis.commands.search.query import Query -from autogpt.logger import logger +from autogpt.logs import logger from autogpt.memory.base import MemoryProviderSingleton, get_ada_embedding SCHEMA = [ @@ -54,7 +54,9 @@ class RedisMemory(MemoryProviderSingleton): ) logger.double_check( "Please ensure you have setup and configured Redis properly for use. " - + f"You can check out {Fore.CYAN + Style.BRIGHT}https://github.com/Torantulino/Auto-GPT#redis-setup{Style.RESET_ALL} to ensure you've set up everything correctly." + + f"You can check out {Fore.CYAN + Style.BRIGHT}" + f"https://github.com/Torantulino/Auto-GPT#redis-setup{Style.RESET_ALL}" + " to ensure you've set up everything correctly." ) exit(1) diff --git a/autogpt/processing/__init__.py b/autogpt/processing/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/autogpt/processing/text.py b/autogpt/processing/text.py new file mode 100644 index 00000000..24e3bb85 --- /dev/null +++ b/autogpt/processing/text.py @@ -0,0 +1,132 @@ +"""Text processing functions""" +from typing import Generator, Optional +from selenium.webdriver.remote.webdriver import WebDriver +from autogpt.memory import get_memory +from autogpt.config import Config +from autogpt.llm_utils import create_chat_completion + +CFG = Config() +MEMORY = get_memory(CFG) + + +def split_text(text: str, max_length: int = 8192) -> Generator[str, None, None]: + """Split text into chunks of a maximum length + + Args: + text (str): The text to split + max_length (int, optional): The maximum length of each chunk. Defaults to 8192. + + Yields: + str: The next chunk of text + + Raises: + ValueError: If the text is longer than the maximum length + """ + paragraphs = text.split("\n") + current_length = 0 + current_chunk = [] + + for paragraph in paragraphs: + if current_length + len(paragraph) + 1 <= max_length: + current_chunk.append(paragraph) + current_length += len(paragraph) + 1 + else: + yield "\n".join(current_chunk) + current_chunk = [paragraph] + current_length = len(paragraph) + 1 + + if current_chunk: + yield "\n".join(current_chunk) + + +def summarize_text( + url: str, text: str, question: str, driver: Optional[WebDriver] = None +) -> str: + """Summarize text using the OpenAI API + + Args: + url (str): The url of the text + text (str): The text to summarize + question (str): The question to ask the model + driver (WebDriver): The webdriver to use to scroll the page + + Returns: + str: The summary of the text + """ + if not text: + return "Error: No text to summarize" + + text_length = len(text) + print(f"Text length: {text_length} characters") + + summaries = [] + chunks = list(split_text(text)) + scroll_ratio = 1 / len(chunks) + + for i, chunk in enumerate(chunks): + if driver: + scroll_to_percentage(driver, scroll_ratio * i) + print(f"Adding chunk {i + 1} / {len(chunks)} to memory") + + memory_to_add = f"Source: {url}\n" f"Raw content part#{i + 1}: {chunk}" + + MEMORY.add(memory_to_add) + + print(f"Summarizing chunk {i + 1} / {len(chunks)}") + messages = [create_message(chunk, question)] + + summary = create_chat_completion( + model=CFG.fast_llm_model, + messages=messages, + max_tokens=CFG.browse_summary_max_token, + ) + summaries.append(summary) + print(f"Added chunk {i + 1} summary to memory") + + memory_to_add = f"Source: {url}\n" f"Content summary part#{i + 1}: {summary}" + + MEMORY.add(memory_to_add) + + print(f"Summarized {len(chunks)} chunks.") + + combined_summary = "\n".join(summaries) + messages = [create_message(combined_summary, question)] + + return create_chat_completion( + model=CFG.fast_llm_model, + messages=messages, + max_tokens=CFG.browse_summary_max_token, + ) + + +def scroll_to_percentage(driver: WebDriver, ratio: float) -> None: + """Scroll to a percentage of the page + + Args: + driver (WebDriver): The webdriver to use + ratio (float): The percentage to scroll to + + Raises: + ValueError: If the ratio is not between 0 and 1 + """ + if ratio < 0 or ratio > 1: + raise ValueError("Percentage should be between 0 and 1") + driver.execute_script(f"window.scrollTo(0, document.body.scrollHeight * {ratio});") + + +def create_message(chunk: str, question: str) -> dict[str, str]: + """Create a message for the chat completion + + Args: + chunk (str): The chunk of text to summarize + question (str): The question to answer + + Returns: + dict[str, str]: The message to send to the chat completion + """ + return { + "role": "user", + "content": f'"""{chunk}""" Using the above text, please answer the following' + f' question: "{question}" -- if the question cannot be answered using the text,' + " please summarize the text.", + } diff --git a/autogpt/prompt.py b/autogpt/prompt.py index e41312c7..050c2560 100644 --- a/autogpt/prompt.py +++ b/autogpt/prompt.py @@ -1,4 +1,12 @@ +from colorama import Fore +from autogpt.config.ai_config import AIConfig +from autogpt.config.config import Config +from autogpt.logs import logger from autogpt.promptgenerator import PromptGenerator +from autogpt.setup import prompt_user +from autogpt.utils import clean_input + +CFG = Config() def get_prompt() -> str: @@ -106,3 +114,42 @@ def get_prompt() -> str: # Generate the prompt string return prompt_generator.generate_prompt_string() + + +def construct_prompt() -> str: + """Construct the prompt for the AI to respond to + + Returns: + str: The prompt string + """ + config = AIConfig.load(CFG.ai_settings_file) + if CFG.skip_reprompt and config.ai_name: + logger.typewriter_log("Name :", Fore.GREEN, config.ai_name) + logger.typewriter_log("Role :", Fore.GREEN, config.ai_role) + logger.typewriter_log("Goals:", Fore.GREEN, f"{config.ai_goals}") + elif config.ai_name: + logger.typewriter_log( + "Welcome back! ", + Fore.GREEN, + f"Would you like me to return to being {config.ai_name}?", + speak_text=True, + ) + should_continue = clean_input( + f"""Continue with the last settings? +Name: {config.ai_name} +Role: {config.ai_role} +Goals: {config.ai_goals} +Continue (y/n): """ + ) + if should_continue.lower() == "n": + config = AIConfig() + + if not config.ai_name: + config = prompt_user() + config.save() + + # Get rid of this global: + global ai_name + ai_name = config.ai_name + + return config.construct_full_prompt() diff --git a/autogpt/promptgenerator.py b/autogpt/promptgenerator.py index d6802cec..82dba8e0 100644 --- a/autogpt/promptgenerator.py +++ b/autogpt/promptgenerator.py @@ -1,4 +1,6 @@ +""" A module for generating custom prompt strings.""" import json +from typing import Any, Dict, List class PromptGenerator: @@ -7,7 +9,7 @@ class PromptGenerator: resources, and performance evaluations. """ - def __init__(self): + def __init__(self) -> None: """ Initialize the PromptGenerator object with empty lists of constraints, commands, resources, and performance evaluations. @@ -27,7 +29,7 @@ class PromptGenerator: "command": {"name": "command name", "args": {"arg name": "value"}}, } - def add_constraint(self, constraint): + def add_constraint(self, constraint: str) -> None: """ Add a constraint to the constraints list. @@ -36,7 +38,7 @@ class PromptGenerator: """ self.constraints.append(constraint) - def add_command(self, command_label, command_name, args=None): + def add_command(self, command_label: str, command_name: str, args=None) -> None: """ Add a command to the commands list with a label, name, and optional arguments. @@ -59,7 +61,7 @@ class PromptGenerator: self.commands.append(command) - def _generate_command_string(self, command): + def _generate_command_string(self, command: Dict[str, Any]) -> str: """ Generate a formatted string representation of a command. @@ -92,7 +94,7 @@ class PromptGenerator: """ self.performance_evaluation.append(evaluation) - def _generate_numbered_list(self, items, item_type="list") -> str: + def _generate_numbered_list(self, items: List[Any], item_type="list") -> str: """ Generate a numbered list from given items based on the item_type. diff --git a/autogpt/setup.py b/autogpt/setup.py new file mode 100644 index 00000000..5315c01d --- /dev/null +++ b/autogpt/setup.py @@ -0,0 +1,69 @@ +"""Setup the AI and its goals""" +from colorama import Fore, Style +from autogpt import utils +from autogpt.config.ai_config import AIConfig +from autogpt.logs import logger + + +def prompt_user() -> AIConfig: + """Prompt the user for input + + Returns: + AIConfig: The AIConfig object containing the user's input + """ + ai_name = "" + # Construct the prompt + logger.typewriter_log( + "Welcome to Auto-GPT! ", + Fore.GREEN, + "Enter the name of your AI and its role below. Entering nothing will load" + " defaults.", + speak_text=True, + ) + + # Get AI Name from User + logger.typewriter_log( + "Name your AI: ", Fore.GREEN, "For example, 'Entrepreneur-GPT'" + ) + ai_name = utils.clean_input("AI Name: ") + if ai_name == "": + ai_name = "Entrepreneur-GPT" + + logger.typewriter_log( + f"{ai_name} here!", Fore.LIGHTBLUE_EX, "I am at your service.", speak_text=True + ) + + # Get AI Role from User + logger.typewriter_log( + "Describe your AI's role: ", + Fore.GREEN, + "For example, 'an AI designed to autonomously develop and run businesses with" + " the sole goal of increasing your net worth.'", + ) + ai_role = utils.clean_input(f"{ai_name} is: ") + if ai_role == "": + ai_role = "an AI designed to autonomously develop and run businesses with the" + " sole goal of increasing your net worth." + + # Enter up to 5 goals for the AI + logger.typewriter_log( + "Enter up to 5 goals for your AI: ", + Fore.GREEN, + "For example: \nIncrease net worth, Grow Twitter Account, Develop and manage" + " multiple businesses autonomously'", + ) + print("Enter nothing to load defaults, enter nothing when finished.", flush=True) + ai_goals = [] + for i in range(5): + ai_goal = utils.clean_input(f"{Fore.LIGHTBLUE_EX}Goal{Style.RESET_ALL} {i+1}: ") + if ai_goal == "": + break + ai_goals.append(ai_goal) + if not ai_goals: + ai_goals = [ + "Increase net worth", + "Grow Twitter Account", + "Develop and manage multiple businesses autonomously", + ] + + return AIConfig(ai_name, ai_role, ai_goals) diff --git a/autogpt/speak.py b/autogpt/speak.py deleted file mode 100644 index 41b3ac9f..00000000 --- a/autogpt/speak.py +++ /dev/null @@ -1,120 +0,0 @@ -import os - -import requests -from playsound import playsound - -from autogpt.config import Config - -import threading -from threading import Lock, Semaphore - -import gtts - -cfg = Config() - -# Default voice IDs -default_voices = ["ErXwobaYiN019PkySvjV", "EXAVITQu4vr4xnSDxMaL"] - -# Retrieve custom voice IDs from the Config class -custom_voice_1 = cfg.elevenlabs_voice_1_id -custom_voice_2 = cfg.elevenlabs_voice_2_id - -# Placeholder values that should be treated as empty -placeholders = {"your-voice-id"} - -# Use custom voice IDs if provided and not placeholders, otherwise use default voice IDs -voices = [ - custom_voice_1 - if custom_voice_1 and custom_voice_1 not in placeholders - else default_voices[0], - custom_voice_2 - if custom_voice_2 and custom_voice_2 not in placeholders - else default_voices[1], -] - -tts_headers = {"Content-Type": "application/json", "xi-api-key": cfg.elevenlabs_api_key} - -mutex_lock = Lock() # Ensure only one sound is played at a time -queue_semaphore = Semaphore( - 1 -) # The amount of sounds to queue before blocking the main thread - - -def eleven_labs_speech(text, voice_index=0): - """Speak text using elevenlabs.io's API""" - tts_url = "https://api.elevenlabs.io/v1/text-to-speech/{voice_id}".format( - voice_id=voices[voice_index] - ) - formatted_message = {"text": text} - response = requests.post(tts_url, headers=tts_headers, json=formatted_message) - - if response.status_code == 200: - with mutex_lock: - with open("speech.mpeg", "wb") as f: - f.write(response.content) - playsound("speech.mpeg", True) - os.remove("speech.mpeg") - return True - else: - print("Request failed with status code:", response.status_code) - print("Response content:", response.content) - return False - - -def brian_speech(text): - """Speak text using Brian with the streamelements API""" - tts_url = f"https://api.streamelements.com/kappa/v2/speech?voice=Brian&text={text}" - response = requests.get(tts_url) - - if response.status_code == 200: - with mutex_lock: - with open("speech.mp3", "wb") as f: - f.write(response.content) - playsound("speech.mp3") - os.remove("speech.mp3") - return True - else: - print("Request failed with status code:", response.status_code) - print("Response content:", response.content) - return False - - -def gtts_speech(text): - tts = gtts.gTTS(text) - with mutex_lock: - tts.save("speech.mp3") - playsound("speech.mp3", True) - os.remove("speech.mp3") - - -def macos_tts_speech(text, voice_index=0): - if voice_index == 0: - os.system(f'say "{text}"') - else: - if voice_index == 1: - os.system(f'say -v "Ava (Premium)" "{text}"') - else: - os.system(f'say -v Samantha "{text}"') - - -def say_text(text, voice_index=0): - def speak(): - if not cfg.elevenlabs_api_key: - if cfg.use_mac_os_tts == "True": - macos_tts_speech(text) - elif cfg.use_brian_tts == "True": - success = brian_speech(text) - if not success: - gtts_speech(text) - else: - gtts_speech(text) - else: - success = eleven_labs_speech(text, voice_index) - if not success: - gtts_speech(text) - - queue_semaphore.release() - - queue_semaphore.acquire(True) - thread = threading.Thread(target=speak) - thread.start() diff --git a/autogpt/speech/__init__.py b/autogpt/speech/__init__.py new file mode 100644 index 00000000..2ff0d2bf --- /dev/null +++ b/autogpt/speech/__init__.py @@ -0,0 +1,4 @@ +"""This module contains the speech recognition and speech synthesis functions.""" +from autogpt.speech.say import say_text + +__all__ = ["say_text"] diff --git a/autogpt/speech/base.py b/autogpt/speech/base.py new file mode 100644 index 00000000..d74fa51b --- /dev/null +++ b/autogpt/speech/base.py @@ -0,0 +1,50 @@ +"""Base class for all voice classes.""" +import abc +from threading import Lock + +from autogpt.config import AbstractSingleton + + +class VoiceBase(AbstractSingleton): + """ + Base class for all voice classes. + """ + + def __init__(self): + """ + Initialize the voice class. + """ + self._url = None + self._headers = None + self._api_key = None + self._voices = [] + self._mutex = Lock() + self._setup() + + def say(self, text: str, voice_index: int = 0) -> bool: + """ + Say the given text. + + Args: + text (str): The text to say. + voice_index (int): The index of the voice to use. + """ + with self._mutex: + return self._speech(text, voice_index) + + @abc.abstractmethod + def _setup(self) -> None: + """ + Setup the voices, API key, etc. + """ + pass + + @abc.abstractmethod + def _speech(self, text: str, voice_index: int = 0) -> bool: + """ + Play the given text. + + Args: + text (str): The text to play. + """ + pass diff --git a/autogpt/speech/brian.py b/autogpt/speech/brian.py new file mode 100644 index 00000000..e581bbcc --- /dev/null +++ b/autogpt/speech/brian.py @@ -0,0 +1,39 @@ +""" Brian speech module for autogpt """ +import os +import requests +from playsound import playsound + +from autogpt.speech.base import VoiceBase + + +class BrianSpeech(VoiceBase): + """Brian speech module for autogpt""" + + def _setup(self) -> None: + """Setup the voices, API key, etc.""" + pass + + def _speech(self, text: str) -> bool: + """Speak text using Brian with the streamelements API + + Args: + text (str): The text to speak + + Returns: + bool: True if the request was successful, False otherwise + """ + tts_url = ( + f"https://api.streamelements.com/kappa/v2/speech?voice=Brian&text={text}" + ) + response = requests.get(tts_url) + + if response.status_code == 200: + with open("speech.mp3", "wb") as f: + f.write(response.content) + playsound("speech.mp3") + os.remove("speech.mp3") + return True + else: + print("Request failed with status code:", response.status_code) + print("Response content:", response.content) + return False diff --git a/autogpt/speech/eleven_labs.py b/autogpt/speech/eleven_labs.py new file mode 100644 index 00000000..2c54ffad --- /dev/null +++ b/autogpt/speech/eleven_labs.py @@ -0,0 +1,71 @@ +"""ElevenLabs speech module""" +import os +from playsound import playsound + +import requests + +from autogpt.config import Config +from autogpt.speech.base import VoiceBase + +PLACEHOLDERS = {"your-voice-id"} + + +class ElevenLabsSpeech(VoiceBase): + """ElevenLabs speech class""" + + def _setup(self) -> None: + """Setup the voices, API key, etc. + + Returns: + None: None + """ + + cfg = Config() + default_voices = ["ErXwobaYiN019PkySvjV", "EXAVITQu4vr4xnSDxMaL"] + self._headers = { + "Content-Type": "application/json", + "xi-api-key": cfg.elevenlabs_api_key, + } + self._voices = default_voices.copy() + self._use_custom_voice(cfg.elevenlabs_voice_1_id, 0) + self._use_custom_voice(cfg.elevenlabs_voice_2_id, 1) + + def _use_custom_voice(self, voice, voice_index) -> None: + """Use a custom voice if provided and not a placeholder + + Args: + voice (str): The voice ID + voice_index (int): The voice index + + Returns: + None: None + """ + # Placeholder values that should be treated as empty + if voice and voice not in PLACEHOLDERS: + self._voices[voice_index] = voice + + def _speech(self, text: str, voice_index: int = 0) -> bool: + """Speak text using elevenlabs.io's API + + Args: + text (str): The text to speak + voice_index (int, optional): The voice to use. Defaults to 0. + + Returns: + bool: True if the request was successful, False otherwise + """ + tts_url = ( + f"https://api.elevenlabs.io/v1/text-to-speech/{self._voices[voice_index]}" + ) + response = requests.post(tts_url, headers=self._headers, json={"text": text}) + + if response.status_code == 200: + with open("speech.mpeg", "wb") as f: + f.write(response.content) + playsound("speech.mpeg", True) + os.remove("speech.mpeg") + return True + else: + print("Request failed with status code:", response.status_code) + print("Response content:", response.content) + return False diff --git a/autogpt/speech/gtts.py b/autogpt/speech/gtts.py new file mode 100644 index 00000000..37497075 --- /dev/null +++ b/autogpt/speech/gtts.py @@ -0,0 +1,21 @@ +""" GTTS Voice. """ +import os +from playsound import playsound +import gtts + +from autogpt.speech.base import VoiceBase + + +class GTTSVoice(VoiceBase): + """GTTS Voice.""" + + def _setup(self) -> None: + pass + + def _speech(self, text: str, _: int = 0) -> bool: + """Play the given text.""" + tts = gtts.gTTS(text) + tts.save("speech.mp3") + playsound("speech.mp3", True) + os.remove("speech.mp3") + return True diff --git a/autogpt/speech/macos_tts.py b/autogpt/speech/macos_tts.py new file mode 100644 index 00000000..4c072ce2 --- /dev/null +++ b/autogpt/speech/macos_tts.py @@ -0,0 +1,21 @@ +""" MacOS TTS Voice. """ +import os + +from autogpt.speech.base import VoiceBase + + +class MacOSTTS(VoiceBase): + """MacOS TTS Voice.""" + + def _setup(self) -> None: + pass + + def _speech(self, text: str, voice_index: int = 0) -> bool: + """Play the given text.""" + if voice_index == 0: + os.system(f'say "{text}"') + elif voice_index == 1: + os.system(f'say -v "Ava (Premium)" "{text}"') + else: + os.system(f'say -v Samantha "{text}"') + return True diff --git a/autogpt/speech/say.py b/autogpt/speech/say.py new file mode 100644 index 00000000..78b75b21 --- /dev/null +++ b/autogpt/speech/say.py @@ -0,0 +1,42 @@ +""" Text to speech module """ +from autogpt.config import Config + +import threading +from threading import Semaphore +from autogpt.speech.brian import BrianSpeech +from autogpt.speech.macos_tts import MacOSTTS +from autogpt.speech.gtts import GTTSVoice +from autogpt.speech.eleven_labs import ElevenLabsSpeech + + +CFG = Config() +DEFAULT_VOICE_ENGINE = GTTSVoice() +VOICE_ENGINE = None +if CFG.elevenlabs_api_key: + VOICE_ENGINE = ElevenLabsSpeech() +elif CFG.use_mac_os_tts == "True": + VOICE_ENGINE = MacOSTTS() +elif CFG.use_brian_tts == "True": + VOICE_ENGINE = BrianSpeech() +else: + VOICE_ENGINE = GTTSVoice() + + +QUEUE_SEMAPHORE = Semaphore( + 1 +) # The amount of sounds to queue before blocking the main thread + + +def say_text(text: str, voice_index: int = 0) -> None: + """Speak the given text using the given voice index""" + + def speak() -> None: + success = VOICE_ENGINE.say(text, voice_index) + if not success: + DEFAULT_VOICE_ENGINE.say(text) + + QUEUE_SEMAPHORE.release() + + QUEUE_SEMAPHORE.acquire(True) + thread = threading.Thread(target=speak) + thread.start() diff --git a/autogpt/spinner.py b/autogpt/spinner.py index 65679d56..56b4f20a 100644 --- a/autogpt/spinner.py +++ b/autogpt/spinner.py @@ -1,3 +1,4 @@ +"""A simple spinner module""" import itertools import sys import threading @@ -7,15 +8,20 @@ import time class Spinner: """A simple spinner class""" - def __init__(self, message="Loading...", delay=0.1): - """Initialize the spinner class""" + def __init__(self, message: str = "Loading...", delay: float = 0.1) -> None: + """Initialize the spinner class + + Args: + message (str): The message to display. + delay (float): The delay between each spinner update. + """ self.spinner = itertools.cycle(["-", "/", "|", "\\"]) self.delay = delay self.message = message self.running = False self.spinner_thread = None - def spin(self): + def spin(self) -> None: """Spin the spinner""" while self.running: sys.stdout.write(f"{next(self.spinner)} {self.message}\r") @@ -23,14 +29,20 @@ class Spinner: time.sleep(self.delay) sys.stdout.write(f"\r{' ' * (len(self.message) + 2)}\r") - def __enter__(self): + def __enter__(self) -> None: """Start the spinner""" self.running = True self.spinner_thread = threading.Thread(target=self.spin) self.spinner_thread.start() - def __exit__(self, exc_type, exc_value, exc_traceback): - """Stop the spinner""" + def __exit__(self, exc_type, exc_value, exc_traceback) -> None: + """Stop the spinner + + Args: + exc_type (Exception): The exception type. + exc_value (Exception): The exception value. + exc_traceback (Exception): The exception traceback. + """ self.running = False if self.spinner_thread is not None: self.spinner_thread.join() diff --git a/autogpt/summary.py b/autogpt/summary.py deleted file mode 100644 index 38f0aadc..00000000 --- a/autogpt/summary.py +++ /dev/null @@ -1,69 +0,0 @@ -from autogpt.llm_utils import create_chat_completion - - -def summarize_text(driver, text, question): - if not text: - return "Error: No text to summarize" - - text_length = len(text) - print(f"Text length: {text_length} characters") - - summaries = [] - chunks = list(split_text(text)) - - scroll_ratio = 1 / len(chunks) - for i, chunk in enumerate(chunks): - scroll_to_percentage(driver, scroll_ratio * i) - print(f"Summarizing chunk {i + 1} / {len(chunks)}") - messages = [create_message(chunk, question)] - - summary = create_chat_completion( - model="gpt-3.5-turbo", - messages=messages, - max_tokens=300, - ) - summaries.append(summary) - - print(f"Summarized {len(chunks)} chunks.") - - combined_summary = "\n".join(summaries) - messages = [create_message(combined_summary, question)] - - return create_chat_completion( - model="gpt-3.5-turbo", - messages=messages, - max_tokens=300, - ) - - -def split_text(text, max_length=8192): - paragraphs = text.split("\n") - current_length = 0 - current_chunk = [] - - for paragraph in paragraphs: - if current_length + len(paragraph) + 1 <= max_length: - current_chunk.append(paragraph) - current_length += len(paragraph) + 1 - else: - yield "\n".join(current_chunk) - current_chunk = [paragraph] - current_length = len(paragraph) + 1 - - if current_chunk: - yield "\n".join(current_chunk) - - -def create_message(chunk, question): - return { - "role": "user", - "content": f'"""{chunk}""" Using the above text, please answer the following' - f' question: "{question}" -- if the question cannot be answered using the text,' - " please summarize the text.", - } - - -def scroll_to_percentage(driver, ratio): - if ratio < 0 or ratio > 1: - raise ValueError("Percentage should be between 0 and 1") - driver.execute_script(f"window.scrollTo(0, document.body.scrollHeight * {ratio});") diff --git a/autogpt/token_counter.py b/autogpt/token_counter.py index 875e8d42..c1239722 100644 --- a/autogpt/token_counter.py +++ b/autogpt/token_counter.py @@ -1,8 +1,9 @@ +"""Functions for counting the number of tokens in a message or string.""" from typing import Dict, List import tiktoken -from autogpt.logger import logger +from autogpt.logs import logger def count_message_tokens( @@ -12,13 +13,13 @@ def count_message_tokens( Returns the number of tokens used by a list of messages. Args: - messages (list): A list of messages, each of which is a dictionary - containing the role and content of the message. - model (str): The name of the model to use for tokenization. - Defaults to "gpt-3.5-turbo-0301". + messages (list): A list of messages, each of which is a dictionary + containing the role and content of the message. + model (str): The name of the model to use for tokenization. + Defaults to "gpt-3.5-turbo-0301". Returns: - int: The number of tokens used by the list of messages. + int: The number of tokens used by the list of messages. """ try: encoding = tiktoken.encoding_for_model(model) @@ -62,11 +63,11 @@ def count_string_tokens(string: str, model_name: str) -> int: Returns the number of tokens in a text string. Args: - string (str): The text string. - model_name (str): The name of the encoding to use. (e.g., "gpt-3.5-turbo") + string (str): The text string. + model_name (str): The name of the encoding to use. (e.g., "gpt-3.5-turbo") Returns: - int: The number of tokens in the text string. + int: The number of tokens in the text string. """ encoding = tiktoken.encoding_for_model(model_name) return len(encoding.encode(string)) diff --git a/autogpt/web.py b/autogpt/web.py deleted file mode 100644 index 355f7fd3..00000000 --- a/autogpt/web.py +++ /dev/null @@ -1,85 +0,0 @@ -from selenium import webdriver -import autogpt.summary as summary -from bs4 import BeautifulSoup -from selenium.webdriver.common.by import By -from selenium.webdriver.support.wait import WebDriverWait -from selenium.webdriver.support import expected_conditions as EC -from webdriver_manager.chrome import ChromeDriverManager -from selenium.webdriver.chrome.options import Options -import logging -from pathlib import Path -from autogpt.config import Config - -file_dir = Path(__file__).parent -cfg = Config() - - -def browse_website(url, question): - driver, text = scrape_text_with_selenium(url) - add_header(driver) - summary_text = summary.summarize_text(driver, text, question) - links = scrape_links_with_selenium(driver) - - # Limit links to 5 - if len(links) > 5: - links = links[:5] - close_browser(driver) - return f"Answer gathered from website: {summary_text} \n \n Links: {links}", driver - - -def scrape_text_with_selenium(url): - logging.getLogger("selenium").setLevel(logging.CRITICAL) - - options = Options() - options.add_argument( - "user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.5615.49 Safari/537.36" - ) - driver = webdriver.Chrome( - executable_path=ChromeDriverManager().install(), options=options - ) - driver.get(url) - - WebDriverWait(driver, 10).until( - EC.presence_of_element_located((By.TAG_NAME, "body")) - ) - - # Get the HTML content directly from the browser's DOM - page_source = driver.execute_script("return document.body.outerHTML;") - soup = BeautifulSoup(page_source, "html.parser") - - for script in soup(["script", "style"]): - script.extract() - - text = soup.get_text() - lines = (line.strip() for line in text.splitlines()) - chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) - text = "\n".join(chunk for chunk in chunks if chunk) - return driver, text - - -def scrape_links_with_selenium(driver): - page_source = driver.page_source - soup = BeautifulSoup(page_source, "html.parser") - - for script in soup(["script", "style"]): - script.extract() - - hyperlinks = extract_hyperlinks(soup) - - return format_hyperlinks(hyperlinks) - - -def close_browser(driver): - driver.quit() - - -def extract_hyperlinks(soup): - return [(link.text, link["href"]) for link in soup.find_all("a", href=True)] - - -def format_hyperlinks(hyperlinks): - return [f"{link_text} ({link_url})" for link_text, link_url in hyperlinks] - - -def add_header(driver): - driver.execute_script(open(f"{file_dir}/js/overlay.js", "r").read()) diff --git a/scripts/main.py b/scripts/main.py deleted file mode 100644 index b6871d1c..00000000 --- a/scripts/main.py +++ /dev/null @@ -1,11 +0,0 @@ -from colorama import Style, init - -# Initialize colorama -init(autoreset=True) - -# Use the bold ANSI style -print( - f"""{Style.BRIGHT}Please run: -python -m autogpt -""" -) diff --git a/tests/test_json_parser.py b/tests/test_json_parser.py index 7e3d4f51..2862034b 100644 --- a/tests/test_json_parser.py +++ b/tests/test_json_parser.py @@ -1,7 +1,7 @@ import unittest import tests.context -from autogpt.json_parser import fix_and_parse_json +from autogpt.json_fixes.parsing import fix_and_parse_json class TestParseJson(unittest.TestCase): diff --git a/tests/unit/test_browse_scrape_text.py b/tests/unit/test_browse_scrape_text.py index be075ad7..98f5f558 100644 --- a/tests/unit/test_browse_scrape_text.py +++ b/tests/unit/test_browse_scrape_text.py @@ -2,7 +2,7 @@ import requests -from autogpt.browse import scrape_text +from autogpt.commands.web_requests import scrape_text """ Code Analysis