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.
Refactor module layout of command classes (#4706)
Erik Peterson195a7fcad8ad
diff --git a/autogpt/agent/agent.py b/autogpt/agent/agent.pyindex 5a236f673e..2fed0d4bc6 100644--- a/autogpt/agent/agent.py+++ b/autogpt/agent/agent.py@@ -5,7 +5,6 @@ from datetime import datetimefrom colorama import Fore, Style-from autogpt.commands.command import CommandRegistryfrom autogpt.config import Configfrom autogpt.config.ai_config import AIConfigfrom autogpt.json_utils.utilities import extract_json_from_response, validate_json@@ -24,6 +23,7 @@ from autogpt.log_cycle.log_cycle import (from autogpt.logs import logger, print_assistant_thoughtsfrom autogpt.memory.message_history import MessageHistoryfrom autogpt.memory.vector import VectorMemory+from autogpt.models.command_registry import CommandRegistryfrom autogpt.speech import say_textfrom autogpt.spinner import Spinnerfrom autogpt.utils import clean_inputdiff --git a/autogpt/app.py b/autogpt/app.pyindex c081835cf6..fee3413a17 100644--- a/autogpt/app.py+++ b/autogpt/app.py@@ -4,8 +4,9 @@ from typing import Dict, List, Unionfrom autogpt.agent.agent import Agentfrom autogpt.agent.agent_manager import AgentManager-from autogpt.commands.command import CommandRegistry, command+from autogpt.command_decorator import commandfrom autogpt.commands.web_requests import scrape_links, scrape_text+from autogpt.models.command_registry import CommandRegistryfrom autogpt.processing.text import summarize_textfrom autogpt.speech import say_textfrom autogpt.url_utils.validators import validate_urldiff --git a/autogpt/command_decorator.py b/autogpt/command_decorator.pynew file mode 100644index 0000000000..3f8279e4d6--- /dev/null+++ b/autogpt/command_decorator.py@@ -0,0 +1,51 @@+import functools+from typing import Any, Callable, Optional++from autogpt.config import Config+from autogpt.logs import logger+from autogpt.models.command import Command++# Unique identifier for auto-gpt commands+AUTO_GPT_COMMAND_IDENTIFIER = "auto_gpt_command"+++def command(+ name: str,+ description: str,+ signature: str,+ enabled: bool | Callable[[Config], bool] = True,+ disabled_reason: Optional[str] = None,+) -> Callable[..., Any]:+ """The command decorator is used to create Command objects from ordinary functions."""++ # TODO: Remove this in favor of better command management+ CFG = Config()++ if callable(enabled):+ enabled = enabled(CFG)+ if not enabled:+ if disabled_reason is not None:+ logger.debug(f"Command '{name}' is disabled: {disabled_reason}")+ return lambda func: func++ def decorator(func: Callable[..., Any]) -> Command:+ cmd = Command(+ name=name,+ description=description,+ method=func,+ signature=signature,+ enabled=enabled,+ disabled_reason=disabled_reason,+ )++ @functools.wraps(func)+ def wrapper(*args, **kwargs) -> Any:+ return func(*args, **kwargs)++ wrapper.command = cmd++ setattr(wrapper, AUTO_GPT_COMMAND_IDENTIFIER, True)++ return wrapper++ return decoratordiff --git a/autogpt/commands/analyze_code.py b/autogpt/commands/analyze_code.pyindex ca7fcb015f..cd176a9aa5 100644--- a/autogpt/commands/analyze_code.py+++ b/autogpt/commands/analyze_code.py@@ -2,7 +2,7 @@from __future__ import annotationsfrom autogpt.agent.agent import Agent-from autogpt.commands.command import command+from autogpt.command_decorator import commandfrom autogpt.llm.utils import call_ai_functiondiff --git a/autogpt/commands/audio_text.py b/autogpt/commands/audio_text.pyindex 2991fff32c..e77e37cc35 100644--- a/autogpt/commands/audio_text.py+++ b/autogpt/commands/audio_text.py@@ -4,7 +4,7 @@ import jsonimport requestsfrom autogpt.agent.agent import Agent-from autogpt.commands.command import command+from autogpt.command_decorator import command@command(diff --git a/autogpt/commands/execute_code.py b/autogpt/commands/execute_code.pyindex 109caa3aa6..c422d652f9 100644--- a/autogpt/commands/execute_code.py+++ b/autogpt/commands/execute_code.py@@ -7,7 +7,7 @@ import dockerfrom docker.errors import ImageNotFoundfrom autogpt.agent.agent import Agent-from autogpt.commands.command import command+from autogpt.command_decorator import commandfrom autogpt.config import Configfrom autogpt.logs import loggerfrom autogpt.setup import CFGdiff --git a/autogpt/commands/file_operations.py b/autogpt/commands/file_operations.pyindex 2ff1484474..d74fee9610 100644--- a/autogpt/commands/file_operations.py+++ b/autogpt/commands/file_operations.py@@ -13,7 +13,7 @@ from confection import Configfrom requests.adapters import HTTPAdapter, Retryfrom autogpt.agent.agent import Agent-from autogpt.commands.command import command+from autogpt.command_decorator import commandfrom autogpt.commands.file_operations_utils import read_textual_filefrom autogpt.logs import loggerfrom autogpt.memory.vector import MemoryItem, VectorMemorydiff --git a/autogpt/commands/git_operations.py b/autogpt/commands/git_operations.pyindex e844fd4151..8dfe213cdf 100644--- a/autogpt/commands/git_operations.py+++ b/autogpt/commands/git_operations.py@@ -3,7 +3,7 @@from git.repo import Repofrom autogpt.agent.agent import Agent-from autogpt.commands.command import command+from autogpt.command_decorator import commandfrom autogpt.url_utils.validators import validate_urldiff --git a/autogpt/commands/google_search.py b/autogpt/commands/google_search.pyindex b9d243f978..e6a1fc0588 100644--- a/autogpt/commands/google_search.py+++ b/autogpt/commands/google_search.py@@ -8,7 +8,7 @@ from itertools import islicefrom duckduckgo_search import DDGSfrom autogpt.agent.agent import Agent-from autogpt.commands.command import command+from autogpt.command_decorator import commandDUCKDUCKGO_MAX_ATTEMPTS = 3diff --git a/autogpt/commands/image_gen.py b/autogpt/commands/image_gen.pyindex b2dc9ea480..5bed8e00bb 100644--- a/autogpt/commands/image_gen.py+++ b/autogpt/commands/image_gen.py@@ -10,7 +10,7 @@ import requestsfrom PIL import Imagefrom autogpt.agent.agent import Agent-from autogpt.commands.command import command+from autogpt.command_decorator import commandfrom autogpt.logs import loggerdiff --git a/autogpt/commands/improve_code.py b/autogpt/commands/improve_code.pyindex 05e9b51c1c..d4f87782ce 100644--- a/autogpt/commands/improve_code.py+++ b/autogpt/commands/improve_code.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport jsonfrom autogpt.agent.agent import Agent-from autogpt.commands.command import command+from autogpt.command_decorator import commandfrom autogpt.llm.utils import call_ai_functiondiff --git a/autogpt/commands/task_statuses.py b/autogpt/commands/task_statuses.pyindex 283328a366..d5718fd359 100644--- a/autogpt/commands/task_statuses.py+++ b/autogpt/commands/task_statuses.py@@ -4,7 +4,7 @@ from __future__ import annotationsfrom typing import NoReturnfrom autogpt.agent.agent import Agent-from autogpt.commands.command import command+from autogpt.command_decorator import commandfrom autogpt.logs import loggerdiff --git a/autogpt/commands/web_selenium.py b/autogpt/commands/web_selenium.pyindex 14036c85e0..bdc5e61375 100644--- a/autogpt/commands/web_selenium.py+++ b/autogpt/commands/web_selenium.py@@ -28,7 +28,7 @@ from webdriver_manager.firefox import GeckoDriverManagerfrom webdriver_manager.microsoft import EdgeChromiumDriverManager as EdgeDriverManagerfrom autogpt.agent.agent import Agent-from autogpt.commands.command import command+from autogpt.command_decorator import commandfrom autogpt.logs import loggerfrom autogpt.memory.vector import MemoryItem, get_memoryfrom autogpt.processing.html import extract_hyperlinks, format_hyperlinksdiff --git a/autogpt/commands/write_tests.py b/autogpt/commands/write_tests.pyindex c09930b9f3..881b6ac4f1 100644--- a/autogpt/commands/write_tests.py+++ b/autogpt/commands/write_tests.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport jsonfrom autogpt.agent.agent import Agent-from autogpt.commands.command import command+from autogpt.command_decorator import commandfrom autogpt.llm.utils import call_ai_functiondiff --git a/autogpt/config/ai_config.py b/autogpt/config/ai_config.pyindex 1a52683234..d118be3f41 100644--- a/autogpt/config/ai_config.py+++ b/autogpt/config/ai_config.py@@ -13,7 +13,7 @@ import distroimport yamlif TYPE_CHECKING:- from autogpt.commands.command import CommandRegistry+ from autogpt.models.command_registry import CommandRegistryfrom autogpt.prompts.generator import PromptGenerator# Soon this will go in a folder where it remembers more stuff about the run(s)diff --git a/autogpt/main.py b/autogpt/main.pyindex ce6a983dc4..97baa7b28b 100644--- a/autogpt/main.py+++ b/autogpt/main.py@@ -6,11 +6,11 @@ from pathlib import Pathfrom colorama import Fore, Stylefrom autogpt.agent import Agent-from autogpt.commands.command import CommandRegistryfrom autogpt.config import Config, check_openai_api_keyfrom autogpt.configurator import create_configfrom autogpt.logs import loggerfrom autogpt.memory.vector import get_memory+from autogpt.models.command_registry import CommandRegistryfrom autogpt.plugins import scan_pluginsfrom autogpt.prompts.prompt import DEFAULT_TRIGGERING_PROMPT, construct_main_ai_configfrom autogpt.utils import (diff --git a/autogpt/models/__init__.py b/autogpt/models/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/autogpt/models/command.py b/autogpt/models/command.pynew file mode 100644index 0000000000..a925ca0436--- /dev/null+++ b/autogpt/models/command.py@@ -0,0 +1,41 @@+from typing import Any, Callable, Optional++from autogpt.config import Config+++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 = "",+ enabled: bool | Callable[[Config], bool] = True,+ disabled_reason: Optional[str] = None,+ ):+ self.name = name+ self.description = description+ self.method = method+ self.signature = signature+ self.enabled = enabled+ self.disabled_reason = disabled_reason++ def __call__(self, *args, **kwargs) -> Any:+ if hasattr(kwargs, "config") and callable(self.enabled):+ self.enabled = self.enabled(kwargs["config"])+ if not self.enabled:+ if self.disabled_reason:+ return f"Command '{self.name}' is disabled: {self.disabled_reason}"+ return f"Command '{self.name}' is disabled"+ return self.method(*args, **kwargs)++ def __str__(self) -> str:+ return f"{self.name}: {self.description}, args: {self.signature}"diff --git a/autogpt/commands/command.py b/autogpt/models/command_registry.pysimilarity index 56%rename from autogpt/commands/command.pyrename to autogpt/models/command_registry.pyindex 742cc8df64..29d0143d91 100644--- a/autogpt/commands/command.py+++ b/autogpt/models/command_registry.py@@ -1,51 +1,10 @@-import functoolsimport importlibimport inspect-from typing import Any, Callable, Optional+from typing import Any, Callable-from autogpt.config import Config+from autogpt.command_decorator import AUTO_GPT_COMMAND_IDENTIFIERfrom autogpt.logs import logger--# 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 = "",- enabled: bool | Callable[[Config], bool] = True,- disabled_reason: Optional[str] = None,- ):- self.name = name- self.description = description- self.method = method- self.signature = signature- self.enabled = enabled- self.disabled_reason = disabled_reason-- def __call__(self, *args, **kwargs) -> Any:- if hasattr(kwargs, "config") and callable(self.enabled):- self.enabled = self.enabled(kwargs["config"])- if not self.enabled:- if self.disabled_reason:- return f"Command '{self.name}' is disabled: {self.disabled_reason}"- return f"Command '{self.name}' is disabled"- return self.method(*args, **kwargs)-- def __str__(self) -> str:- return f"{self.name}: {self.description}, args: {self.signature}"+from autogpt.models.command import Commandclass CommandRegistry:@@ -133,45 +92,3 @@ class CommandRegistry:):cmd_instance = attr()self.register(cmd_instance)---def command(- name: str,- description: str,- signature: str,- enabled: bool | Callable[[Config], bool] = True,- disabled_reason: Optional[str] = None,-) -> Callable[..., Any]:- """The command decorator is used to create Command objects from ordinary functions."""-- # TODO: Remove this in favor of better command management- CFG = Config()-- if callable(enabled):- enabled = enabled(CFG)- if not enabled:- if disabled_reason is not None:- logger.debug(f"Command '{name}' is disabled: {disabled_reason}")- return lambda func: func-- def decorator(func: Callable[..., Any]) -> Command:- cmd = Command(- name=name,- description=description,- method=func,- signature=signature,- enabled=enabled,- disabled_reason=disabled_reason,- )-- @functools.wraps(func)- def wrapper(*args, **kwargs) -> Any:- return func(*args, **kwargs)-- wrapper.command = cmd-- setattr(wrapper, AUTO_GPT_COMMAND_IDENTIFIER, True)-- return wrapper-- return decoratordiff --git a/autogpt/prompts/generator.py b/autogpt/prompts/generator.pyindex 7101acfea1..2a0334bf45 100644--- a/autogpt/prompts/generator.py+++ b/autogpt/prompts/generator.py@@ -4,7 +4,7 @@ from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optionalfrom autogpt.json_utils.utilities import llm_response_schemaif TYPE_CHECKING:- from autogpt.commands.command import CommandRegistry+ from autogpt.models.command_registry import CommandRegistryclass PromptGenerator:diff --git a/tests/conftest.py b/tests/conftest.pyindex 671096fdc2..97620e2173 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -7,12 +7,12 @@ import yamlfrom pytest_mock import MockerFixturefrom autogpt.agent.agent import Agent-from autogpt.commands.command import CommandRegistryfrom autogpt.config.ai_config import AIConfigfrom autogpt.config.config import Configfrom autogpt.llm.api_manager import ApiManagerfrom autogpt.logs import TypingConsoleHandlerfrom autogpt.memory.vector import get_memory+from autogpt.models.command_registry import CommandRegistryfrom autogpt.prompts.prompt import DEFAULT_TRIGGERING_PROMPTfrom autogpt.workspace import Workspacediff --git a/tests/integration/agent_factory.py b/tests/integration/agent_factory.pyindex c9b99f50f7..9078a8434d 100644--- a/tests/integration/agent_factory.py+++ b/tests/integration/agent_factory.py@@ -1,10 +1,10 @@import pytestfrom autogpt.agent import Agent-from autogpt.commands.command import CommandRegistryfrom autogpt.config import AIConfig, Configfrom autogpt.main import COMMAND_CATEGORIESfrom autogpt.memory.vector import NoMemory, get_memory+from autogpt.models.command_registry import CommandRegistryfrom autogpt.prompts.prompt import DEFAULT_TRIGGERING_PROMPTfrom autogpt.workspace import Workspacediff --git a/tests/mocks/mock_commands.py b/tests/mocks/mock_commands.pyindex 42b0ea1134..7b16f1d150 100644--- a/tests/mocks/mock_commands.py+++ b/tests/mocks/mock_commands.py@@ -1,4 +1,4 @@-from autogpt.commands.command import command+from autogpt.command_decorator import command@command(diff --git a/tests/unit/test_commands.py b/tests/unit/test_commands.pyindex 5779a8a3f0..f02cb620e4 100644--- a/tests/unit/test_commands.py+++ b/tests/unit/test_commands.py@@ -5,7 +5,8 @@ from pathlib import Pathimport pytest-from autogpt.commands.command import Command, CommandRegistry+from autogpt.models.command import Command+from autogpt.models.command_registry import CommandRegistrySIGNATURE = "(arg1: int, arg2: str) -> str"