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 'command_registry' of https://github.com/kreneskyp/Auto-GPT into plugin-support
BillSchumacherec8ff0fcde26
diff --cc autogpt/__main__.pyindex 3e3331548a,0000000000..60079f7511mode 100644,000000..100644--- a/autogpt/__main__.py+++ b/autogpt/__main__.py@@@ -1,80 -1,0 +1,87 @@@+"""Main script for the autogpt package."""+import logging+import os+from pathlib import Path+from colorama import Fore+from autogpt.agent.agent import Agent+from autogpt.args import parse_arguments-++from autogpt.commands.command import CommandRegistry+from autogpt.config import Config, check_openai_api_key+from autogpt.logs import logger+from autogpt.memory import get_memory++from autogpt.prompts.prompt import construct_main_ai_config+from autogpt.plugins import load_plugins+++# Load environment variables from .env file+++def main() -> None:+ """Main function for the script"""+ cfg = Config()+ # TODO: fill in llm values here+ check_openai_api_key()+ parse_arguments()+ logger.set_level(logging.DEBUG if cfg.debug_mode else logging.INFO)+ plugins_found = load_plugins(Path(os.getcwd()) / "plugins")+ loaded_plugins = []+ for plugin in plugins_found:+ if plugin.__name__ in cfg.plugins_blacklist:+ continue+ if plugin.__name__ in cfg.plugins_whitelist:+ loaded_plugins.append(plugin())+ else:+ ack = input(+ f"WARNNG Plugin {plugin.__name__} found. But not in the"+ " whitelist... Load? (y/n): "+ )+ if ack.lower() == "y":+ loaded_plugins.append(plugin())++ if loaded_plugins:+ print(f"\nPlugins found: {len(loaded_plugins)}\n" "--------------------")+ for plugin in loaded_plugins:+ print(f"{plugin._name}: {plugin._version} - {plugin._description}")++ cfg.set_plugins(loaded_plugins)-++ # Create a CommandRegistry instance and scan default folder++ command_registry = CommandRegistry()++ command_registry.import_commands('scripts.ai_functions')++ command_registry.import_commands('scripts.commands')++ command_registry.import_commands('scripts.execute_code')++ command_registry.import_commands('scripts.agent_manager')++ command_registry.import_commands('scripts.file_operations')+ ai_name = ""+ ai_config = construct_main_ai_config()+ # print(prompt)+ # Initialize variables+ full_message_history = []+ next_action_count = 0+ # Make a constant:+ 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)+ logger.typewriter_log(+ f"Using memory of type:", Fore.GREEN, f"{memory.__class__.__name__}"+ )+ logger.typewriter_log(f"Using Browser:", Fore.GREEN, cfg.selenium_web_browser)+ agent = Agent(+ ai_name=ai_name,+ memory=memory,+ full_message_history=full_message_history,+ next_action_count=next_action_count,++ command_registry=command_registry,+ config=ai_config,+ prompt=ai_config.construct_full_prompt(),+ user_input=user_input,+ )+ agent.start_interaction_loop()+++if __name__ == "__main__":+ main()diff --cc autogpt/agent/agent.pyindex a3a3729a4e,0000000000..513478b9d8mode 100644,000000..100644--- a/autogpt/agent/agent.py+++ b/autogpt/agent/agent.py@@@ -1,197 -1,0 +1,199 @@@+from colorama import Fore, Style+from autogpt.app import execute_command, get_command++from autogpt.chat import chat_with_ai, create_chat_message+from autogpt.config import Config+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+++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,++ command_registry,+ config,+ 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.command_registry = command_registry+ self.config = config+ self.prompt = prompt+ self.user_input = user_input++ def start_interaction_loop(self):+ # Interaction Loop+ cfg = Config()+ 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_with_ai(+ self,+ 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++ for plugin in cfg.plugins:+ assistant_reply = plugin.post_planning(self, assistant_reply)++ # Print Assistant thoughts+ print_assistant_thoughts(self.ai_name, assistant_reply)++ # Get command name and arguments+ try:+ command_name, arguments = get_command(+ attempt_to_fix_json_by_finding_outermost_brackets(assistant_reply)+ )+ if cfg.speak_mode:+ 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 = 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:+ for plugin in cfg.plugins:+ command_name, arguments = plugin.pre_command(+ command_name, arguments+ )+ result = (+ f"Command {command_name} returned: "- f"{execute_command(command_name, arguments, self.config.prompt_generator)}"++ f"{execute_command(self.command_registry, command_name, arguments, self.config.prompt_generator)}"+ )++ for plugin in cfg.plugins:+ result = plugin.post_command(command_name, result)+ 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(create_chat_message("system", result))+ logger.typewriter_log("SYSTEM: ", Fore.YELLOW, result)+ else:+ self.full_message_history.append(+ create_chat_message("system", "Unable to execute command")+ )+ logger.typewriter_log(+ "SYSTEM: ", Fore.YELLOW, "Unable to execute command"+ )diff --cc autogpt/app.pyindex aca97a7512,0000000000..9eb9d3ab67mode 100644,000000..100644--- a/autogpt/app.py+++ b/autogpt/app.py@@@ -1,318 -1,0 +1,330 @@@+""" Command and Control """+import json+from typing import List, NoReturn, Union+from autogpt.agent.agent_manager import AgentManager++from autogpt.commands.command import command, CommandRegistry+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.prompts.generator import PromptGenerator+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, prompt: PromptGenerator):++def execute_command(command_registry: CommandRegistry, command_name: str, arguments, prompt: PromptGenerator):+ """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:++ cmd = command_registry.commands.get(command_name)++++ # If the command is found, call it with the provided arguments++ if cmd:++ return cmd(**arguments)++++ # TODO: Remove commands below after they are moved to the command registry.+ 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"])+ return google_result+ else:+ google_result = google_search(arguments["input"])++ # google_result can be a list or a string depending on the search results+ if isinstance(google_result, list):+ safe_message = [+ google_result_single.encode("utf-8", "ignore")+ for google_result_single in google_result+ ]+ else:+ 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"])+ elif command_name == "do_nothing":+ return "No action performed."+ elif command_name == "task_complete":+ shutdown()+ else:+ for command in prompt.commands:+ if command_name == command["label"] or command_name == command["name"]:+ return command["function"](*arguments.values())+ 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()++++@command("start_agent", "Start GPT Agent", '"name": "<name>", "task": "<short_task_desc>", "prompt": "<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("_", " ")++ 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}"++++@command("message_agent", "Message GPT Agent", '"key": "<key>", "message": "<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 = 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++++@command("list_agents", "List GPT Agents", "")+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()]+ )++++@command("delete_agent", "Delete GPT Agent", '"key": "<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 --cc autogpt/commands/command.pyindex 0000000000,0000000000..84a5899008new file mode 100644--- /dev/null+++ b/autogpt/commands/command.py@@@ -1,0 -1,0 +1,123 @@@++import os++import sys++import importlib++import inspect++from typing import Callable, Any, List++++# Unique identifier for auto-gpt commands++AUTO_GPT_COMMAND_IDENTIFIER = "auto_gpt_command"++++++class Command:++ """A class representing a command.++++ Attributes:++ name (str): The name of the command.++ description (str): A brief description of what the command does.++ signature (str): The signature of the function that the command executes. Defaults to None.++ """++++ def __init__(self, name: str, description: str, method: Callable[..., Any], signature: str = None):++ self.name = name++ self.description = description++ self.method = method++ self.signature = signature if signature else str(inspect.signature(self.method))++++ def __call__(self, *args, **kwargs) -> Any:++ return self.method(*args, **kwargs)++++ def __str__(self) -> str:++ return f"{self.name}: {self.description}, args: {self.signature}"++++++class CommandRegistry:++ """++ The CommandRegistry class is a manager for a collection of Command objects.++ It allows the registration, modification, and retrieval of Command objects,++ as well as the scanning and loading of command plugins from a specified++ directory.++ """++++ def __init__(self):++ self.commands = {}++++ def _import_module(self, module_name: str) -> Any:++ return importlib.import_module(module_name)++++ def _reload_module(self, module: Any) -> Any:++ return importlib.reload(module)++++ def register(self, cmd: Command) -> None:++ self.commands[cmd.name] = cmd++++ def unregister(self, command_name: str):++ if command_name in self.commands:++ del self.commands[command_name]++ else:++ raise KeyError(f"Command '{command_name}' not found in registry.")++++ def reload_commands(self) -> None:++ """Reloads all loaded command plugins."""++ for cmd_name in self.commands:++ cmd = self.commands[cmd_name]++ module = self._import_module(cmd.__module__)++ reloaded_module = self._reload_module(module)++ if hasattr(reloaded_module, "register"):++ reloaded_module.register(self)++++ def get_command(self, name: str) -> Callable[..., Any]:++ return self.commands[name]++++ def call(self, command_name: str, **kwargs) -> Any:++ if command_name not in self.commands:++ raise KeyError(f"Command '{command_name}' not found in registry.")++ command = self.commands[command_name]++ return command(**kwargs)++++ def command_prompt(self) -> str:++ """++ Returns a string representation of all registered `Command` objects for use in a prompt++ """++ commands_list = [f"{idx + 1}. {str(cmd)}" for idx, cmd in enumerate(self.commands.values())]++ return "\n".join(commands_list)++++ def import_commands(self, module_name: str) -> None:++ """++ Imports the specified Python module containing command plugins.++++ This method imports the associated module and registers any functions or++ classes that are decorated with the `AUTO_GPT_COMMAND_IDENTIFIER` attribute++ as `Command` objects. The registered `Command` objects are then added to the++ `commands` dictionary of the `CommandRegistry` object.++++ Args:++ module_name (str): The name of the module to import for command plugins.++ """++++ module = importlib.import_module(module_name)++++ for attr_name in dir(module):++ attr = getattr(module, attr_name)++ # Register decorated functions++ if hasattr(attr, AUTO_GPT_COMMAND_IDENTIFIER) and getattr(attr, AUTO_GPT_COMMAND_IDENTIFIER):++ self.register(attr.command)++ # Register command classes++ elif inspect.isclass(attr) and issubclass(attr, Command) and attr != Command:++ cmd_instance = attr()++ self.register(cmd_instance)++++++def command(name: str, description: str, signature: str = None) -> Callable[..., Any]:++ """The command decorator is used to create Command objects from ordinary functions."""++ def decorator(func: Callable[..., Any]) -> Command:++ cmd = Command(name=name, description=description, method=func, signature=signature)++++ def wrapper(*args, **kwargs) -> Any:++ return func(*args, **kwargs)++++ wrapper.command = cmd++++ setattr(wrapper, AUTO_GPT_COMMAND_IDENTIFIER, True)++ return wrapper++++ return decoratordiff --cc autogpt/commands/evaluate_code.pyindex 8f7cbca9c1,0000000000..b3d1c87fe2mode 100644,000000..100644--- a/autogpt/commands/evaluate_code.py+++ b/autogpt/commands/evaluate_code.py@@@ -1,25 -1,0 +1,27 @@@+"""Code evaluation module."""+from __future__ import annotations+++from autogpt.commands import command+from autogpt.llm_utils import call_ai_function++++@command("evaluate_code", "Evaluate Code", '"code": "<full _code_string>"')+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 --cc autogpt/commands/execute_code.pyindex eaafa00a82,0000000000..61d95e36ebmode 100644,000000..100644--- a/autogpt/commands/execute_code.py+++ b/autogpt/commands/execute_code.py@@@ -1,123 -1,0 +1,124 @@@+"""Execute code in a Docker container"""+import os+import subprocess++import docker+from docker.errors import ImageNotFound-++from autogpt.commands.command import command+from autogpt.workspace import path_in_workspace, WORKSPACE_PATH++++@command("execute_python_file", "Execute Python File", '"file": "<file>"')+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 '{WORKSPACE_PATH}'")++ if not file.endswith(".py"):+ return "Error: Invalid file type. Only .py files are allowed."++ file_path = path_in_workspace(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(WORKSPACE_PATH): {+ "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()+ # Change dir into workspace if necessary+ if str(WORKSPACE_PATH) not in current_dir:+ os.chdir(WORKSPACE_PATH)++ 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 --cc autogpt/commands/file_operations.pyindex 60ede701ee,0000000000..fea62fad18mode 100644,000000..100644--- a/autogpt/commands/file_operations.py+++ b/autogpt/commands/file_operations.py@@@ -1,216 -1,0 +1,222 @@@+"""File operations for AutoGPT"""+from __future__ import annotations++import os+import os.path+from pathlib import Path+from typing import Generator++from autogpt.commands.command import command+from autogpt.workspace import path_in_workspace, WORKSPACE_PATH++LOG_FILE = "file_logger.txt"+LOG_FILE_PATH = WORKSPACE_PATH / LOG_FILE+++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++ 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"++ # Create the log file if it doesn't exist+ 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, shouldLog=False)+++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.++ :param content: 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+ if end + overlap < content_length:+ chunk = content[start : end + overlap]+ else:+ chunk = content[start:content_length]+ yield chunk+ start += max_length - overlap++++@command("read_file", "Read file", '"file": "<file>"')+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 = path_in_workspace(filename)+ with open(filepath, "r", encoding="utf-8") as f:+ content = f.read()+ return content+ except Exception as e:+ return f"Error: {str(e)}"+++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.++ :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)}")++++@command("write_to_file", "Write to file", '"file": "<file>", "text": "<text>"')+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 = path_in_workspace(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 f"Error: {str(e)}"++++@command("append_to_file", "Append to file", '"file": "<file>", "text": "<text>"')+def append_to_file(filename: str, text: str, shouldLog: bool = True) -> 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 = path_in_workspace(filename)+ with open(filepath, "a") as f:+ f.write(text)++ if shouldLog:+ log_operation("append", filename)++ return "Text appended successfully."+ except Exception as e:+ return f"Error: {str(e)}"++++@command("delete_file", "Delete file", '"file": "<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+ """+ if check_duplicate_operation("delete", filename):+ return "Error: File has already been deleted."+ try:+ filepath = path_in_workspace(filename)+ os.remove(filepath)+ log_operation("delete", filename)+ return "File deleted successfully."+ except Exception as e:+ return f"Error: {str(e)}"++++@command("search_files", "Search Files", '"directory": "<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 in {"", "/"}:+ search_directory = WORKSPACE_PATH+ else:+ search_directory = path_in_workspace(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), WORKSPACE_PATH)+ found_files.append(relative_path)++ return found_filesdiff --cc autogpt/commands/image_gen.pyindex 6243616ea8,0000000000..2b62aa354bmode 100644,000000..100644--- a/autogpt/commands/image_gen.py+++ b/autogpt/commands/image_gen.py@@@ -1,97 -1,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 autogpt.commands.command import command+from autogpt.config import Config+from autogpt.workspace import path_in_workspace++CFG = Config()++++@command("generate_image", "Generate Image", '"prompt": "<prompt>"')+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(path_in_workspace(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(path_in_workspace(filename), mode="wb") as png:+ png.write(image_data)++ return f"Saved to disk:{filename}"diff --cc autogpt/commands/improve_code.pyindex e3440d8b7c,0000000000..9d7dc2f0dcmode 100644,000000..100644--- a/autogpt/commands/improve_code.py+++ b/autogpt/commands/improve_code.py@@@ -1,29 -1,0 +1,31 @@@+from __future__ import annotations++import json+++from autogpt.commands import command+from autogpt.llm_utils import call_ai_function++++@command("improve_code", "Get Improved Code", '"suggestions": "<list_of_suggestions>", "code": "<full_code_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)diff --cc autogpt/commands/web_selenium.pyindex 1d078d76d7,0000000000..a5369ea2d6mode 100644,000000..100644--- a/autogpt/commands/web_selenium.py+++ b/autogpt/commands/web_selenium.py@@@ -1,142 -1,0 +1,143 @@@+"""Selenium web scraping module."""+from __future__ import annotations++from selenium import webdriver+from autogpt.processing.html import extract_hyperlinks, format_hyperlinks+import autogpt.processing.text as summary+from bs4 import BeautifulSoup+from selenium.webdriver.remote.webdriver import WebDriver+from selenium.webdriver.common.by import By+from selenium.webdriver.support.wait import WebDriverWait+from selenium.webdriver.support import expected_conditions as EC+from webdriver_manager.chrome import ChromeDriverManager+from webdriver_manager.firefox import GeckoDriverManager+from selenium.webdriver.chrome.options import Options as ChromeOptions+from selenium.webdriver.firefox.options import Options as FirefoxOptions+from selenium.webdriver.safari.options import Options as SafariOptions+import logging+from pathlib import Path+from autogpt.config import Config++FILE_DIR = Path(__file__).parent.parent+CFG = Config()++++@command("browse_website", "Browse Website", '"url": "<url>", "question": "<what_you_want_to_find_on_website>"')+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, url)++ # Limit links to 5+ if len(links) > 5:+ links = links[:5]+ close_browser(driver)+ return f"Answer gathered from website: {summary_text} \n \n Links: {links}", driver+++def scrape_text_with_selenium(url: str) -> tuple[WebDriver, str]:+ """Scrape text from a website using selenium++ Args:+ url (str): The url of the website to scrape++ Returns:+ Tuple[WebDriver, str]: The webdriver and the text scraped from the website+ """+ logging.getLogger("selenium").setLevel(logging.CRITICAL)++ options_available = {+ "chrome": ChromeOptions,+ "safari": SafariOptions,+ "firefox": FirefoxOptions,+ }++ options = options_available[CFG.selenium_web_browser]()+ options.add_argument(+ "user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.5615.49 Safari/537.36"+ )++ if CFG.selenium_web_browser == "firefox":+ driver = webdriver.Firefox(+ executable_path=GeckoDriverManager().install(), options=options+ )+ elif CFG.selenium_web_browser == "safari":+ # Requires a bit more setup on the users end+ # See https://developer.apple.com/documentation/webkit/testing_with_webdriver_in_safari+ driver = webdriver.Safari(options=options)+ else:+ driver = webdriver.Chrome(+ executable_path=ChromeDriverManager().install(), options=options+ )+ driver.get(url)++ WebDriverWait(driver, 10).until(+ EC.presence_of_element_located((By.TAG_NAME, "body"))+ )++ # Get the HTML content directly from the browser's DOM+ page_source = driver.execute_script("return document.body.outerHTML;")+ soup = BeautifulSoup(page_source, "html.parser")++ for script in soup(["script", "style"]):+ script.extract()++ text = soup.get_text()+ lines = (line.strip() for line in text.splitlines())+ chunks = (phrase.strip() for line in lines for phrase in line.split(" "))+ text = "\n".join(chunk for chunk in chunks if chunk)+ return driver, text+++def scrape_links_with_selenium(driver: WebDriver, url: str) -> list[str]:+ """Scrape links from a website using selenium++ Args:+ driver (WebDriver): The webdriver to use to scrape the links++ Returns:+ List[str]: The links scraped from the website+ """+ page_source = driver.page_source+ soup = BeautifulSoup(page_source, "html.parser")++ for script in soup(["script", "style"]):+ script.extract()++ hyperlinks = extract_hyperlinks(soup, url)++ return format_hyperlinks(hyperlinks)+++def close_browser(driver: WebDriver) -> None:+ """Close the browser++ Args:+ driver (WebDriver): The webdriver to close++ Returns:+ None+ """+ driver.quit()+++def add_header(driver: WebDriver) -> None:+ """Add a header to the website++ Args:+ driver (WebDriver): The webdriver to use to add the header++ Returns:+ None+ """+ driver.execute_script(open(f"{FILE_DIR}/js/overlay.js", "r").read())diff --cc autogpt/commands/write_tests.pyindex 138a1adb6f,0000000000..f73311787dmode 100644,000000..100644--- a/autogpt/commands/write_tests.py+++ b/autogpt/commands/write_tests.py@@@ -1,30 -1,0 +1,32 @@@+"""A module that contains a function to generate test cases for the submitted code."""+from __future__ import annotations++import json++from autogpt.commands import command+from autogpt.llm_utils import call_ai_function++++@command("write_tests", "Write Tests", '"code": "<full_code_string>", "focus": "<list_of_focus_areas>"')+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)