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 BillSchumacher/plugin-support, conflicts
Evgeny Vakhteevc62c8c6e7135
diff --cc autogpt/__main__.pyindex f8d2048756,c2e2e5c168..956cf10a3d--- a/autogpt/__main__.py+++ b/autogpt/__main__.py@@@ -1,8 -1,10 +1,8 @@@"""Main script for the autogpt package."""import logging--import os--from pathlib import Path+from colorama import Fore+from autogpt.agent.agent import Agentfrom autogpt.args import parse_argumentsfrom autogpt.commands.command import CommandRegistry@@@ -24,16 -24,43 +24,23 @@@ def main() -> Nonecheck_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)+ cfg.set_plugins(scan_plugins(cfg, cfg.debug_mode))# Create a CommandRegistry instance and scan default foldercommand_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")+ command_registry.import_commands("autogpt.commands.audio_text")+ command_registry.import_commands("autogpt.commands.evaluate_code")+ command_registry.import_commands("autogpt.commands.execute_code")+ command_registry.import_commands("autogpt.commands.file_operations")+ command_registry.import_commands("autogpt.commands.git_operations")+ command_registry.import_commands("autogpt.commands.google_search")+ command_registry.import_commands("autogpt.commands.image_gen")+ command_registry.import_commands("autogpt.commands.twitter")+ command_registry.import_commands("autogpt.commands.web_selenium")+ command_registry.import_commands("autogpt.commands.write_tests")+ command_registry.import_commands("autogpt.app")ai_name = ""ai_config = construct_main_ai_config()+ ai_config.command_registry = command_registry# print(prompt)# Initialize variablesfull_message_history = []diff --cc autogpt/plugins.pyindex 974adddc51,a00b989eae..a28ddbe534--- a/autogpt/plugins.py+++ b/autogpt/plugins.py@@@ -1,21 -1,11 +1,21 @@@"""Handles loading of plugins."""++import importlib+import json+import osimport zipfile-from ast import Module++import openapi_python_client++import requests++from pathlib import Path-from typing import List, Optional, Tuple+from typing import List, Tuple, Optional+from urllib.parse import urlparsefrom zipimport import zipimporter- import openapi_python_client- import requests- from abstract_singleton import AbstractSingleton+from openapi_python_client.cli import Config as OpenAPIConfig-+from autogpt.config import Config+from autogpt.models.base_open_ai_plugin import BaseOpenAIPlugin+def inspect_zip_for_module(zip_path: str, debug: bool = False) -> Optional[str]:"""@@@ -39,206 -29,45 +39,207 @@@return None- def write_dict_to_json_file(data: dict, file_path: str):-def scan_plugins(plugins_path: Path, debug: bool = False) -> List[Tuple[str, Path]]:- """Scan the plugins directory for plugins.++def write_dict_to_json_file(data: dict, file_path: str) -> None:+ """+ Write a dictionary to a JSON file.+ Args:+ data (dict): Dictionary to write.+ file_path (str): Path to the file.+ """+ with open(file_path, 'w') as file:+ json.dump(data, file, indent=4)+++def fetch_openai_plugins_manifest_and_spec(cfg: Config) -> dict:+ """+ Fetch the manifest for a list of OpenAI plugins.+ Args:+ urls (List): List of URLs to fetch.+ Returns:+ dict: per url dictionary of manifest and spec.+ """+ # TODO add directory scan+ manifests = {}+ for url in cfg.plugins_openai:+ openai_plugin_client_dir = f"{cfg.plugins_dir}/openai/{urlparse(url).netloc}"+ create_directory_if_not_exists(openai_plugin_client_dir)+ if not os.path.exists(f'{openai_plugin_client_dir}/ai-plugin.json'):+ try:+ response = requests.get(f"{url}/.well-known/ai-plugin.json")+ if response.status_code == 200:+ manifest = response.json()+ if manifest["schema_version"] != "v1":+ print(f"Unsupported manifest version: {manifest['schem_version']} for {url}")+ continue+ if manifest["api"]["type"] != "openapi":+ print(f"Unsupported API type: {manifest['api']['type']} for {url}")+ continue+ write_dict_to_json_file(manifest, f'{openai_plugin_client_dir}/ai-plugin.json')+ else:+ print(f"Failed to fetch manifest for {url}: {response.status_code}")+ except requests.exceptions.RequestException as e:+ print(f"Error while requesting manifest from {url}: {e}")+ else:+ print(f"Manifest for {url} already exists")+ manifest = json.load(open(f'{openai_plugin_client_dir}/ai-plugin.json'))+ if not os.path.exists(f'{openai_plugin_client_dir}/openapi.json'):+ openapi_spec = openapi_python_client._get_document(url=manifest["api"]["url"], path=None, timeout=5)+ write_dict_to_json_file(openapi_spec, f'{openai_plugin_client_dir}/openapi.json')+ else:+ print(f"OpenAPI spec for {url} already exists")+ openapi_spec = json.load(open(f'{openai_plugin_client_dir}/openapi.json'))+ manifests[url] = {+ 'manifest': manifest,+ 'openapi_spec': openapi_spec+ }+ return manifests++def create_directory_if_not_exists(directory_path: str) -> bool:+ """+ Create a directory if it does not exist.Args:- plugins_path (Path): Path to the plugins directory.+ directory_path (str): Path to the directory.+ Returns:+ bool: True if the directory was created, else False.+ """+ if not os.path.exists(directory_path):+ try:+ os.makedirs(directory_path)+ print(f"Created directory: {directory_path}")+ return True+ except OSError as e:+ print(f"Error creating directory {directory_path}: {e}")+ return False+ else:+ print(f"Directory {directory_path} already exists")+ return True++def initialize_openai_plugins(manifests_specs: dict, cfg: Config, debug: bool = False) -> dict:+ """+ Initialize OpenAI plugins.+ Args:+ manifests_specs (dict): per url dictionary of manifest and spec.+ cfg (Config): Config instance including plugins config+ debug (bool, optional): Enable debug logging. Defaults to False.Returns:- List[Path]: List of plugins.+ dict: per url dictionary of manifest, spec and client."""- plugins = []- for plugin in plugins_path.glob("*.zip"):- if module := inspect_zip_for_module(str(plugin), debug):- plugins.append((module, plugin))+ openai_plugins_dir = f'{cfg.plugins_dir}/openai'+ if create_directory_if_not_exists(openai_plugins_dir):+ for url, manifest_spec in manifests_specs.items():+ openai_plugin_client_dir = f'{openai_plugins_dir}/{urlparse(url).hostname}'+ _meta_option = openapi_python_client.MetaType.SETUP,+ _config = OpenAPIConfig(**{+ 'project_name_override': 'client',+ 'package_name_override': 'client',+ })+ prev_cwd = Path.cwd()+ os.chdir(openai_plugin_client_dir)+ Path('ai-plugin.json')+ if not os.path.exists('client'):+ client_results = openapi_python_client.create_new_client(+ url=manifest_spec['manifest']['api']['url'],+ path=None,+ meta=_meta_option,+ config=_config,+ )+ if client_results:+ print(f"Error creating OpenAPI client: {client_results[0].header} \n"+ f" details: {client_results[0].detail}")+ continue+ spec = importlib.util.spec_from_file_location('client', 'client/client/client.py')+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ client = module.Client(base_url=url)+ os.chdir(prev_cwd)+ manifest_spec['client'] = client+ return manifests_specs+++def instantiate_openai_plugin_clients(manifests_specs_clients: dict, cfg: Config, debug: bool = False) -> dict:+ """+ Instantiates BaseOpenAIPlugin instances for each OpenAI plugin.+ Args:+ manifests_specs_clients (dict): per url dictionary of manifest, spec and client.+ cfg (Config): Config instance including plugins config+ debug (bool, optional): Enable debug logging. Defaults to False.+ Returns:+ plugins (dict): per url dictionary of BaseOpenAIPlugin instances.++ """+ plugins = {}+ for url, manifest_spec_client in manifests_specs_clients.items():+ plugins[url] = BaseOpenAIPlugin(manifest_spec_client)return plugins- def scan_plugins(cfg: Config, debug: bool = False) -> List[Tuple[str, Path]]:-def load_plugins(plugins_path: Path, debug: bool = False) -> List[Module]:- """Load plugins from the plugins directory.++def scan_plugins(cfg: Config, debug: bool = False) -> List[object]:+ """Scan the plugins directory for plugins and loads them.++ Args:+ cfg (Config): Config instance including plugins config+ debug (bool, optional): Enable debug logging. Defaults to False.++ Returns:+ List[Tuple[str, Path]]: List of plugins.+ """+ loaded_plugins = []+ # Generic plugins+ plugins_path_path = Path(cfg.plugins_dir)+ for plugin in plugins_path_path.glob("*.zip"):+ if module := inspect_zip_for_module(str(plugin), debug):+ plugin = Path(plugin)+ module = Path(module)+ if debug:+ print(f"Plugin: {plugin} Module: {module}")+ zipped_package = zipimporter(plugin)+ zipped_module = zipped_package.load_module(str(module.parent))+ for key in dir(zipped_module):+ if key.startswith("__"):+ continue+ a_module = getattr(zipped_module, key)+ a_keys = dir(a_module)+ if (- "_abc_impl" in a_keys- and a_module.__name__ != "AutoGPTPluginTemplate"- and blacklist_whitelist_check(a_module.__name__, cfg)++ "_abc_impl" in a_keys++ and a_module.__name__ != "AutoGPTPluginTemplate"++ and blacklist_whitelist_check(a_module.__name__, cfg)+ ):+ loaded_plugins.append(a_module())+ # OpenAI plugins+ if cfg.plugins_openai:+ manifests_specs = fetch_openai_plugins_manifest_and_spec(cfg)+ if manifests_specs.keys():+ manifests_specs_clients = initialize_openai_plugins(manifests_specs, cfg, debug)+ for url, openai_plugin_meta in manifests_specs_clients.items():+ if blacklist_whitelist_check(url, cfg):+ plugin = BaseOpenAIPlugin(openai_plugin_meta)+ 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}")+ return loaded_plugins++++def blacklist_whitelist_check(plugin_name: str, cfg: Config) -> bool:+ """Check if the plugin is in the whitelist or blacklist.Args:- plugins_path (Path): Path to the plugins directory.+ plugin_name (str): Name of the plugin.+ cfg (Config): Config object.Returns:- List[Path]: List of plugins.+ True or False"""- plugins = scan_plugins(plugins_path)- plugin_modules = []- for module, plugin in plugins:- plugin = Path(plugin)- module = Path(module)- if debug:- print(f"Plugin: {plugin} Module: {module}")- zipped_package = zipimporter(plugin)- zipped_module = zipped_package.load_module(str(module.parent))- for key in dir(zipped_module):- if key.startswith("__"):- continue- a_module = getattr(zipped_module, key)- a_keys = dir(a_module)- if "_abc_impl" in a_keys and a_module.__name__ != "AutoGPTPluginTemplate":- plugin_modules.append(a_module)- return plugin_modules+ if plugin_name in cfg.plugins_blacklist:+ return False+ if plugin_name in cfg.plugins_whitelist:+ return True+ ack = input(+ f"WARNNG Plugin {plugin_name} found. But not in the"+ " whitelist... Load? (y/n): "+ )+ return ack.lower() == "y"diff --cc docker/workspace/23dc7e07-db57-40d5-bb18-c75c6ff2cc0f.jpgindex 0000000000,0000000000..59be7609c3new file mode 100644Binary files differdiff --cc docker/workspace/34cdcc0e-1343-4f6c-a204-dc34d0e75f96.jpgindex 0000000000,0000000000..774cf51f60new file mode 100644Binary files differdiff --cc docker/workspace/analyze_trending_tokens.pyindex 0000000000,0000000000..7bd8673969new file mode 100644--- /dev/null+++ b/docker/workspace/analyze_trending_tokens.py@@@ -1,0 -1,0 +1,17 @@@++# Use the DexGuru API to retrieve top trending tokens data++import requests++++url = 'https://api-stage-lax.dex.guru/v2/tokens/trending'++headers = {'Content-type': 'application/json'}++++payload = {'ids': [], 'network': 'eth,optimism,bsc,gnosis,polygon,fantom,zksync,canto,arbitrum,nova,celo,avalanche'}++++response = requests.post(url, json=payload, headers=headers)++++if response.status_code == 200:++ data = response.json()++ # data contains list of dict objects describing the trending tokens++ # EXTRACT INFO YOU WILL NEED TO SUGGEST INVESTMENTS HERE++ print(data)++else:++ print(f"An error occurred with status code {response.status_code}")diff --cc docker/workspace/config.jsonindex 0000000000,0000000000..b468f76270new file mode 100644--- /dev/null+++ b/docker/workspace/config.json@@@ -1,0 -1,0 +1,3 @@@++{++ "EXECUTE_LOCAL_COMMANDS": "True"++}diff --cc docker/workspace/ethereum_price.jsonindex 0000000000,0000000000..e69de29bb2new file mode 100644--- /dev/null+++ b/docker/workspace/ethereum_price.jsondiff --cc docker/workspace/llm_risks.mdindex 0000000000,0000000000..aadb349ba9new file mode 100644--- /dev/null+++ b/docker/workspace/llm_risks.md@@@ -1,0 -1,0 +1,7 @@@++# Legal Risk Statement++++As an LLM, we would like to remind you of the risks associated with cryptocurrency investment. While cryptocurrencies have become an appealing investment choice, it is also a highly volatile market. As such, we advise that you carefully consider the risks before making any investments.++++We caution users that the crypto market is generally unregulated, meaning that it is not bound by any particular legal framework. Virtual currencies are also a new and rapidly evolving technology, and as such, new developments may affect their long-term ability to remain a viable investment option. Therefore, it is essential to understand that investing in cryptocurrency comes with inherent risks that are associated with any investment.++++Please note that this statement is for educational purposes only and does not constitute legal or financial advice. Before making any significant financial decisions, you should seek professional advice tailored to your needs and objectives.diff --cc requirements.txtindex 9f015f92dc,843b66bfe4..c10ca5c175--- a/requirements.txt+++ b/requirements.txt@@@ -25,12 -29,12 +29,18 @@@ blacsourceryisortgitpython==3.1.31++ # Testing dependenciespytest+ asynctest+ pytest-asyncio+ pytest-benchmark+ pytest-cov+ pytest-integrationpytest-mock- tweepy+++# OpenAI and Generic plugins import+openapi-python-client==0.13.4+abstract-singleton+auto-gpt-plugin-template