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' of https://github.com/Significant-Gravitas/Auto-GPT into pr/1436
BillSchumacher0d1fd4fcf0ce
diff --cc autogpt/app.pyindex 0000000000,e7b16adc0b..fa5cab6201mode 000000,100644..100644--- a/autogpt/app.py+++ b/autogpt/app.py@@@ -1,0 -1,304 +1,304 @@@+ """ Command and Control """+ import json+ 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.commands.image_gen import generate_image+ from autogpt.commands.audio_text import read_audio_from_file+ 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.processing.text import summarize_text+ from autogpt.speech import say_text+ from autogpt.commands.web_selenium import browse_website+ from autogpt.commands.git_operations import clone_repository+ from autogpt.commands.twitter import send_tweet+++ CFG = Config()+ AGENT_MANAGER = AgentManager()+++ 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+ except ValueError:+ return False+++ 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)++ 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"++ command_name = command["name"]++ # Use an empty dictionary if 'args' field is not present in 'command' object+ arguments = command.get("args", {})++ return command_name, arguments+ except json.decoder.JSONDecodeError:+ return "Error:", "Invalid JSON"+ # All other errors, return "Error: + error message"+ except Exception as e:+ return "Error:", str(e)+++ def map_command_synonyms(command_name: str):+ """Takes the original command name given by the AI, and checks if the+ string matches a list of common/known hallucinations+ """+ synonyms = [+ ("write_file", "write_to_file"),+ ("create_file", "write_to_file"),+ ("search", "google"),+ ]+ for seen_command, actual_command_name in synonyms:+ if command_name == seen_command:+ return actual_command_name+ return command_name+++ 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:+ command_name = map_command_synonyms(command_name)+ 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+ if key and key.strip() and key != "your-google-api-key":+ google_result = google_official_search(arguments["input"])+ else:+ google_result = google_search(arguments["input"])+ safe_message = google_result.encode("utf-8", "ignore")+ return str(safe_message)+ elif command_name == "memory_add":+ return memory.add(arguments["string"])+ elif command_name == "start_agent":+ return start_agent(+ arguments["name"], arguments["task"], arguments["prompt"]+ )+ elif command_name == "message_agent":+ return message_agent(arguments["key"], arguments["message"])+ elif command_name == "list_agents":+ return list_agents()+ elif command_name == "delete_agent":+ return delete_agent(arguments["key"])+ elif command_name == "get_text_summary":+ return get_text_summary(arguments["url"], arguments["question"])+ elif command_name == "get_hyperlinks":+ return get_hyperlinks(arguments["url"])+ elif command_name == "clone_repository":+ return clone_repository(+ arguments["repository_url"], arguments["clone_path"]+ )+ elif command_name == "read_file":+ return read_file(arguments["file"])+ elif command_name == "write_to_file":+ return write_to_file(arguments["file"], arguments["text"])+ elif command_name == "append_to_file":+ return append_to_file(arguments["file"], arguments["text"])+ elif command_name == "delete_file":+ return delete_file(arguments["file"])+ elif command_name == "search_files":+ return search_files(arguments["directory"])+ elif command_name == "browse_website":+ return browse_website(arguments["url"], arguments["question"])+ # TODO: Change these to take in a file rather than pasted code, if+ # 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 evaluate_code(arguments["code"])+ elif command_name == "improve_code":+ return improve_code(arguments["suggestions"], arguments["code"])+ elif command_name == "write_tests":+ 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."+ )+ elif command_name == "read_audio_from_file":+ return read_audio_from_file(arguments["file"])+ elif command_name == "generate_image":+ return generate_image(arguments["prompt"])+ elif command_name == "send_tweet":- return send_tweet(arguments['text'])++ return send_tweet(arguments["text"])+ elif command_name == "do_nothing":+ return "No action performed."+ 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."+ )+ except Exception as e:+ return f"Error: {str(e)}"+++ 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++ Returns:+ str: The summary of the text+ """+ text = scrape_text(url)+ summary = summarize_text(url, text, question)+ return f""" "Result" : {summary}"""+++ 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() -> NoReturn:+ """Shut down the program"""+ print("Shutting down...")+ quit()+++ 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("_", " ")++ first_message = f"""You are {name}. Respond with: "Acknowledged"."""+ agent_intro = f"{voice_name} here, Reporting for duty!"++ # Create agent+ if CFG.speak_mode:+ say_text(agent_intro, 1)+ key, ack = AGENT_MANAGER.create_agent(task, first_message, model)++ if CFG.speak_mode:+ say_text(f"Hello {voice_name}. Your task is as follows. {task}.")++ # Assign task (prompt), get response+ agent_response = AGENT_MANAGER.message_agent(key, prompt)++ return f"Agent {name} created with key {key}. First response: {agent_response}"+++ 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 = AGENT_MANAGER.message_agent(int(key), message)+ else:+ return "Invalid key, must be an integer."++ # Speak response+ if CFG.speak_mode:+ say_text(agent_response, 1)+ return agent_response+++ def list_agents():+ """List all agents++ Returns:+ str: A list of all agents+ """+ return "List of agents:\n" + "\n".join(+ [str(x[0]) + ": " + x[1] for x in AGENT_MANAGER.list_agents()]+ )+++ 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 --cc autogpt/commands/audio_text.pyindex 0000000000,bf9c3640d8..b9ca988c64mode 000000,100644..100644--- a/autogpt/commands/audio_text.py+++ b/autogpt/commands/audio_text.py@@@ -1,0 -1,35 +1,37 @@@+ import requests+ import json++ from autogpt.config import Config+ from autogpt.commands.file_operations import safe_join++ cfg = Config()++ working_directory = "auto_gpt_workspace"+++ def read_audio_from_file(audio_path):+ audio_path = safe_join(working_directory, audio_path)+ with open(audio_path, "rb") as audio_file:+ audio = audio_file.read()+ return read_audio(audio)+++ def read_audio(audio):+ model = cfg.huggingface_audio_to_text_model+ api_url = f"https://api-inference.huggingface.co/models/{model}"+ api_token = cfg.huggingface_api_token+ headers = {"Authorization": f"Bearer {api_token}"}++ if api_token is None:- raise ValueError("You need to set your Hugging Face API token in the config file.")++ raise ValueError(++ "You need to set your Hugging Face API token in the config file."++ )++ response = requests.post(+ api_url,+ headers=headers,+ data=audio,+ )+- text = json.loads(response.content.decode("utf-8"))['text']++ text = json.loads(response.content.decode("utf-8"))["text"]+ return "The audio says: " + textdiff --cc autogpt/commands/file_operations.pyindex 9f0697ff5a,47a04dce44..d02b125a79--- a/autogpt/commands/file_operations.py+++ b/autogpt/commands/file_operations.py@@@ -1,40 -1,29 +1,63 @@@+ """File operations for AutoGPT"""import osimport 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"++WORKING_DIRECTORY = Path(os.getcwd()) / "auto_gpt_workspace"- log_file = "file_logger.txt"+ # Create the directory if it doesn't exist+ if not os.path.exists(WORKING_DIRECTORY):+ os.makedirs(WORKING_DIRECTORY)++LOG_FILE = "file_logger.txt"++LOG_FILE_PATH = WORKING_DIRECTORY / LOG_FILE+ WORKING_DIRECTORY = str(WORKING_DIRECTORY)- # Create the directory if it doesn't exist- if not os.path.exists(working_directory):- os.makedirs(working_directory)++def check_duplicate_operation(operation: str, filename: str) -> bool:++ """Check if the operation has already been performed on the given file+++ Args:++ operation (str): The operation to check for++ filename (str): The name of the file to check for+- def log_operation(operation, filename):- """Log the file operation to the file_logger.txt"""++ Returns:++ bool: True if the operation has already been performed on the file++ """++ log_content = read_file(LOG_FILE)++ log_entry = f"{operation}: {filename}\n"++ return log_entry in log_content++++++def log_operation(operation: str, filename: str) -> None:++ """Log the file operation to the file_logger.txt++++ Args:++ operation (str): The operation to log++ filename (str): The name of the file the operation was performed on++ """+ log_entry = f"{operation}: {filename}\n"+- log_filepath = safe_join(working_directory, log_file)-+ # Create the log file if it doesn't exist- if not os.path.exists(log_filepath):- with open(log_filepath, "w", encoding="utf-8") as f:++ if not os.path.exists(LOG_FILE_PATH):++ with open(LOG_FILE_PATH, "w", encoding="utf-8") as f:+ f.write("File Operation Logger ")+- append_to_file(log_file, log_entry)++ append_to_file(LOG_FILE, log_entry)++- def check_duplicate_operation(operation, filename):- """Check if the operation has already been performed on the given file"""- log_content = read_file(log_file)- log_entry = f"{operation}: {filename}\n"- return log_entry in log_content+ 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- def safe_join(base, *paths):- """Join one or more path components intelligently."""+ Returns:+ str: The joined path+ """new_path = os.path.join(base, *paths)norm_new_path = os.path.normpath(new_path)@@@ -110,56 -112,79 +146,86 @@@ def ingest_fileprint(f"Error while ingesting file '{filename}': {str(e)}")- def write_to_file(filename, text):- """Write text to a file and log the operation"""+ 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+ """+ if check_duplicate_operation("write", filename):+ return "Error: File has already been updated."-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)with open(filepath, "w", encoding="utf-8") as f:f.write(text)+ log_operation("write", filename)return "File written to successfully."except Exception as e:- return "Error: " + str(e)+ return f"Error: {str(e)}"++ def append_to_file(filename: str, text: str) -> str:+ """Append text to a file- def append_to_file(filename, text):- """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)++ log_operation("append", filename)return "Text appended successfully."except Exception as e:- return "Error: " + str(e)+ return f"Error: {str(e)}"- def delete_file(filename):- """Delete a file and log the operation"""+ 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+ """+ if check_duplicate_operation("delete", filename):+ return "Error: File has already been deleted."-try:- filepath = safe_join(working_directory, filename)+ filepath = safe_join(WORKING_DIRECTORY, filename)os.remove(filepath)+ log_operation("delete", filename)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_DIRECTORYelse:- 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:diff --cc autogpt/commands/twitter.pyindex 0000000000,1774bfb943..dc4d450c1fmode 000000,100644..100644--- a/autogpt/commands/twitter.py+++ b/autogpt/commands/twitter.py@@@ -1,0 -1,25 +1,25 @@@+ import tweepy+ import os+ from dotenv import load_dotenv++ load_dotenv()+++ def send_tweet(tweet_text):+ consumer_key = os.environ.get("TW_CONSUMER_KEY")- consumer_secret= os.environ.get("TW_CONSUMER_SECRET")- access_token= os.environ.get("TW_ACCESS_TOKEN")- access_token_secret= os.environ.get("TW_ACCESS_TOKEN_SECRET")++ consumer_secret = os.environ.get("TW_CONSUMER_SECRET")++ access_token = os.environ.get("TW_ACCESS_TOKEN")++ access_token_secret = os.environ.get("TW_ACCESS_TOKEN_SECRET")+ # Authenticate to Twitter+ auth = tweepy.OAuthHandler(consumer_key, consumer_secret)+ auth.set_access_token(access_token, access_token_secret)++ # Create API object+ api = tweepy.API(auth)++ # Send tweet+ try:+ api.update_status(tweet_text)+ print("Tweet sent successfully!")+ except tweepy.TweepyException as e:+ print("Error sending tweet: {}".format(e.reason))diff --cc autogpt/logs.pyindex 0ae84704ab,c644c5eae6..22ce23f4aa--- a/autogpt/logs.py+++ b/autogpt/logs.py@@@ -187,3 -196,97 +196,95 @@@ def remove_color_codes(s: str) -> strlogger = 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)+ else:- logger.typewriter_log(- "SPEAK:", Fore.YELLOW, f"{assistant_thoughts_speak}"- )++ logger.typewriter_log("SPEAK:", Fore.YELLOW, f"{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 --cc autogpt/prompt.pyindex 8e65388d1c,9f79d42052..97bacb711d--- a/autogpt/prompt.py+++ b/autogpt/prompt.py@@@ -61,16 -81,30 +81,29 @@@ def get_prompt() -> str{"code": "<full_code_string>", "focus": "<list_of_focus_areas>"},),("Execute Python File", "execute_python_file", {"file": "<file>"}),- (- "Execute Shell Command, non-interactive commands only",- "execute_shell",- {"command_line": "<command_line>"},- ),- ("Task Complete (Shutdown)", "task_complete", {"reason": "<reason>"}),("Generate Image", "generate_image", {"prompt": "<prompt>"}),- ("Do Nothing", "do_nothing", {}),+ ("Convert Audio to text", "read_audio_from_file", {"file": "<file>"}),+ ("Send Tweet", "send_tweet", {"text": "<text>"}),-]+ # Only add shell command to the prompt if the AI is allowed to execute it+ if cfg.execute_local_commands:+ commands.append(+ (+ "Execute Shell Command, non-interactive commands only",+ "execute_shell",+ {"command_line": "<command_line>"},+ ),+ )++ # Add these command last.+ commands.append(+ ("Do Nothing", "do_nothing", {}),+ )+ commands.append(+ ("Task Complete (Shutdown)", "task_complete", {"reason": "<reason>"}),+ )+# Add commands to the PromptGenerator objectfor command_label, command_name, args in commands:prompt_generator.add_command(command_label, command_name, args)diff --cc tests/unit/test_browse_scrape_text.pyindex be075ad745,61c19b058d..fea5ebfc05--- a/tests/unit/test_browse_scrape_text.py+++ b/tests/unit/test_browse_scrape_text.py@@@ -50,7 -50,7 +50,9 @@@ class TestScrapeText# Tests that the function returns an error message when an invalid or unreachable url is provided.def test_invalid_url(self, mocker):# Mock the requests.get() method to raise an exception- mocker.patch("requests.get", side_effect=requests.exceptions.RequestException)- mocker.patch("requests.Session.get", side_effect=requests.exceptions.RequestException)++ mocker.patch(++ "requests.Session.get", side_effect=requests.exceptions.RequestException++ )# Call the function with an invalid URL and assert that it returns an error messageurl = "http://www.invalidurl.com"diff --cc tests/unit/test_chat.pyindex 0000000000,258ed62bf2..55a44492a0mode 000000,100644..100644--- a/tests/unit/test_chat.py+++ b/tests/unit/test_chat.py@@@ -1,0 -1,70 +1,86 @@@-+ # Generated by CodiumAI+ import unittest+ import time+ from unittest.mock import patch++ from autogpt.chat import create_chat_message, generate_context+++ class TestChat(unittest.TestCase):-+ # Tests that the function returns a dictionary with the correct keys and values when valid strings are provided for role and content.+ def test_happy_path_role_content(self):+ result = create_chat_message("system", "Hello, world!")+ self.assertEqual(result, {"role": "system", "content": "Hello, world!"})++ # Tests that the function returns a dictionary with the correct keys and values when empty strings are provided for role and content.+ def test_empty_role_content(self):+ result = create_chat_message("", "")+ self.assertEqual(result, {"role": "", "content": ""})++ # Tests the behavior of the generate_context function when all input parameters are empty.+ @patch("time.strftime")+ def test_generate_context_empty_inputs(self, mock_strftime):+ # Mock the time.strftime function to return a fixed value+ mock_strftime.return_value = "Sat Apr 15 00:00:00 2023"+ # Arrange+ prompt = ""+ relevant_memory = ""+ full_message_history = []+ model = "gpt-3.5-turbo-0301"++ # Act+ result = generate_context(prompt, relevant_memory, full_message_history, model)++ # Assert- expected_result = (-1, 47, 3, [- {"role": "system", "content": ""},- {"role": "system", "content": f"The current time and date is {time.strftime('%c')}"},- {"role": "system", "content": f"This reminds you of these events from your past:\n\n\n"},- ])++ expected_result = (++ -1,++ 47,++ 3,++ [++ {"role": "system", "content": ""},++ {++ "role": "system",++ "content": f"The current time and date is {time.strftime('%c')}",++ },++ {++ "role": "system",++ "content": f"This reminds you of these events from your past:\n\n\n",++ },++ ],++ )+ self.assertEqual(result, expected_result)++ # Tests that the function successfully generates a current_context given valid inputs.+ def test_generate_context_valid_inputs(self):+ # Given+ prompt = "What is your favorite color?"+ relevant_memory = "You once painted your room blue."+ full_message_history = [+ create_chat_message("user", "Hi there!"),+ create_chat_message("assistant", "Hello! How can I assist you today?"),+ create_chat_message("user", "Can you tell me a joke?"),- create_chat_message("assistant", "Why did the tomato turn red? Because it saw the salad dressing!"),++ create_chat_message(++ "assistant",++ "Why did the tomato turn red? Because it saw the salad dressing!",++ ),+ create_chat_message("user", "Haha, that's funny."),+ ]+ model = "gpt-3.5-turbo-0301"++ # When+ result = generate_context(prompt, relevant_memory, full_message_history, model)++ # Then+ self.assertIsInstance(result[0], int)+ self.assertIsInstance(result[1], int)+ self.assertIsInstance(result[2], int)+ self.assertIsInstance(result[3], list)+ self.assertGreaterEqual(result[0], 0)+ self.assertGreaterEqual(result[1], 0)+ self.assertGreaterEqual(result[2], 0)- self.assertGreaterEqual(len(result[3]), 3) # current_context should have at least 3 messages- self.assertLessEqual(result[1], 2048) # token limit for GPT-3.5-turbo-0301 is 2048 tokens++ self.assertGreaterEqual(++ len(result[3]), 3++ ) # current_context should have at least 3 messages++ self.assertLessEqual(++ result[1], 2048++ ) # token limit for GPT-3.5-turbo-0301 is 2048 tokens