AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
Merge branch 'master' into dev
Andres Caicedo26abb3067402
diff --cc scripts/ai_config.pyindex de214463b5,8cfa183a9b..14b4588781--- a/scripts/ai_config.py+++ b/scripts/ai_config.py@@@ -1,11 -1,9 +1,11 @@@import yamlimport data-+ import osclass AIConfig:+ """Class to store the AI's name, role, and goals."""def __init__(self, ai_name="", ai_role="", ai_goals=[]):+ """Initialize the AIConfig class"""self.ai_name = ai_nameself.ai_role = ai_roleself.ai_goals = ai_goalsdiff --cc scripts/browse.pyindex 89e41af496,0fda3d7b06..214ccadb02--- a/scripts/browse.py+++ b/scripts/browse.py@@@ -6,8 -6,7 +6,8 @@@ from llm_utils import create_chat_complcfg = Config()def scrape_text(url):+ """Scrape text from a webpage"""- response = requests.get(url)+ response = requests.get(url, headers=cfg.user_agent_header)# Check if the response contains an HTTP errorif response.status_code >= 400:@@@ -43,8 -40,7 +43,8 @@@ def format_hyperlinks(hyperlinks)def scrape_links(url):- """Scrape hyperlinks from a webpage"""- response = requests.get(url)++ """Scrape links from a webpage"""+ response = requests.get(url, headers=cfg.user_agent_header)# Check if the response contains an HTTP errorif response.status_code >= 400:diff --cc scripts/chat.pyindex 89a0350990,a27fbfd7ef..f4cf22991b--- a/scripts/chat.py+++ b/scripts/chat.py@@@ -49,21 -66,23 +65,23 @@@ def chat_with_aimodel = cfg.fast_llm_model # TODO: Change model from hardcode to argument# Reserve 1000 tokens for the responseif debug:- print(f"Token limit: {token_limit}")+ print(f"Token limit: {token_limit}")send_token_limit = token_limit - 1000- current_context = [- create_chat_message(- "system", prompt), create_chat_message(- "system", f"Permanent memory: {permanent_memory}")]+ relevant_memory = permanent_memory.get_relevant(str(full_message_history[-5:]), 10)++ if debug:+ print('Memory Stats: ', permanent_memory.get_stats())- # Add messages from the full message history until we reach the token limit- next_message_to_add_index = len(full_message_history) - 1- current_tokens_used = 0- insertion_index = len(current_context)+ 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)- # Count the currently used tokens- current_tokens_used = token_counter.count_message_tokens(current_context, model)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:diff --cc scripts/commands.pyindex 38912b4860,ba5383957a..6d264d548a--- a/scripts/commands.py+++ b/scripts/commands.py@@@ -16,8 -17,14 +17,15 @@@ from googleapiclient.errors import Httpcfg = Config()+ def is_valid_int(value):+ try:+ int(value)+ return True+ except ValueError:+ return False+def get_command(response):+ """Parse the response and return the command name and arguments"""try:response_json = fix_and_parse_json(response)@@@ -46,10 -53,11 +54,12 @@@def execute_command(command_name, arguments):- """Execute the command and return the response"""++ """Execute the command and return the result"""+ 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 methodif cfg.google_api_key and (cfg.google_api_key.strip() if cfg.google_api_key else None):@@@ -204,10 -204,23 +214,24 @@@ def delete_memory(key)def overwrite_memory(key, string):+ """Overwrite a memory with a given key and string"""- if int(key) >= 0 and key < len(mem.permanent_memory):- _text = "Overwriting memory with key " + \- str(key) + " and string " + 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 stringmem.permanent_memory[key] = stringprint(_text)return _text@@@ -247,9 -258,16 +271,17 @@@ def start_agent(name, task, prompt, moddef message_agent(key, message):+ """Message an agent with a given key and message"""global cfg- agent_response = agents.message_agent(key, message)++ # Check if the key is a valid integer+ if is_valid_int(key):+ agent_response = agents.message_agent(int(key), message)+ # Check if the key is a valid string+ elif isinstance(key, str):+ agent_response = agents.message_agent(key, message)+ else:+ return "Invalid key, must be an integer or a string."# Speak responseif cfg.speak_mode:diff --cc scripts/config.pyindex cf8fe7e7ee,4d7adec1c0..03f1d5df27--- a/scripts/config.py+++ b/scripts/config.py@@@ -26,7 -31,7 +32,8 @@@ class Config(metaclass=Singleton)"""def __init__(self):- """Initialize the configuration class."""++ """Initialize the Config class"""+ self.debug = Falseself.continuous_mode = Falseself.speak_mode = False# TODO - make these models be self-contained, using langchain, so we can configure them once and call it good@@@ -69,17 -95,22 +103,29 @@@self.smart_token_limit = valuedef set_openai_api_key(self, value: str):+ """Set the OpenAI API key value."""self.openai_api_key = value-+def set_elevenlabs_api_key(self, value: str):+ """Set the ElevenLabs API key value."""self.elevenlabs_api_key = value-+def set_google_api_key(self, value: str):+ """Set the Google API key value."""self.google_api_key = value-+def set_custom_search_engine_id(self, value: str):- """Set the custom search engine ID value."""- self.custom_search_engine_id = value++ """Set the custom search engine id value."""+ self.custom_search_engine_id = value++ def set_pinecone_api_key(self, value: str):++ """Set the Pinecone API key value."""+ self.pinecone_api_key = value++ def set_pinecone_region(self, value: str):++ """Set the Pinecone region value."""+ self.pinecone_region = value++ def set_debug_mode(self, value: bool):++ """Set the debug mode value."""+ self.debug = valuediff --cc scripts/data.pyindex e0840dd9f7,8d8a7b4acd..cd41f31373--- a/scripts/data.py+++ b/scripts/data.py@@@ -1,16 -1,14 +1,15 @@@import osfrom pathlib import Path- SRC_DIR = Path(__file__).parentdef load_prompt():+ """Load the prompt from data/prompt.txt"""try:# get directory of this file:- file_dir = Path(os.path.dirname(os.path.realpath(__file__)))- data_dir = file_dir / "data"- prompt_file = data_dir / "prompt.txt"- # Load the promt from data/prompt.txt- with open(SRC_DIR/ "data/prompt.txt", "r") as prompt_file:+ file_dir = Path(__file__).parent+ prompt_file_path = file_dir / "data" / "prompt.txt"++ # Load the prompt from data/prompt.txt+ with open(prompt_file_path, "r") as prompt_file:prompt = prompt_file.read()return promptdiff --cc scripts/json_parser.pyindex e46161ac21,c863ccdbb0..38df107c27--- a/scripts/json_parser.py+++ b/scripts/json_parser.py@@@ -50,10 -50,9 +51,10 @@@ def fix_and_parse_json(json_str: str, traise edef fix_json(json_str: str, schema: str, debug=False) -> str:+ """Fix the given JSON string to make it parseable and fully complient with the provided schema."""# Try to fix the JSON using gpt:function_string = "def fix_json(json_str: str, schema:str=None) -> str:"- args = [json_str, schema]+ args = [f"'''{json_str}'''", f"'''{schema}'''"]description_string = """Fixes the provided JSON string to make it parseable and fully complient with the provided schema.\n If an object or field specifed in the schema isn't contained within the correct JSON, it is ommited.\n This function is brilliant at guessing when the format is incorrect."""# If it doesn't already start with a "`", add one:@@@ -68,9 -67,9 +69,10 @@@print("-----------")print(f"Fixed JSON: {result_string}")print("----------- END OF FIX ATTEMPT ----------------")+try:- return json.loads(result_string)+ json.loads(result_string) # just check the validity+ return result_stringexcept:# Get the call stack:# import tracebackdiff --cc scripts/llm_utils.pyindex c512e99733,5a471ab7a1..94ba5f1316--- a/scripts/llm_utils.py+++ b/scripts/llm_utils.py@@@ -6,12 -6,20 +6,21 @@@ openai.api_key = cfg.openai_api_ke# Overly simple abstraction until we create something betterdef create_chat_completion(messages, model=None, temperature=None, max_tokens=None)->str:- """Create a chat completion using the OpenAI API."""- response = openai.ChatCompletion.create(- model=model,- messages=messages,- temperature=temperature,- max_tokens=max_tokens- )++ """Create a chat completion using the OpenAI API"""+ if cfg.use_azure:+ response = openai.ChatCompletion.create(+ deployment_id=cfg.openai_deployment_id,+ model=model,+ messages=messages,+ temperature=temperature,+ max_tokens=max_tokens+ )+ else:+ response = openai.ChatCompletion.create(+ model=model,+ messages=messages,+ temperature=temperature,+ max_tokens=max_tokens+ )return response.choices[0].message["content"]diff --cc scripts/main.pyindex 9b93855958,f96afeb163..0c2a94e062--- a/scripts/main.py+++ b/scripts/main.py@@@ -316,10 -320,10 +325,10 @@@ while TrueFore.CYAN,f"COMMAND = {Fore.CYAN}{command_name}{Style.RESET_ALL} ARGUMENTS = {Fore.CYAN}{arguments}{Style.RESET_ALL}")print(- f"Enter 'y' to authorise command or 'n' to exit program, or enter feedback for {ai_name}...",+ f"Enter 'y' to authorise command, 'y -N' to run N continuous commands, 'n' to exit program, or enter feedback for {ai_name}...",flush=True)while True:- console_input = input(Fore.MAGENTA + "Input:" + Style.RESET_ALL)+ console_input = input(Fore.MAGENTA + "Input:" + Style.RESET_ALL)if console_input.lower() == "y":user_input = "GENERATE NEXT COMMAND JSON"break