From c76c67a69c897be822335bedce59eb47f0f77e1d Mon Sep 17 00:00:00 2001 From: Richard Beales Date: Wed, 14 Jun 2023 10:03:11 +0100 Subject: [PATCH] Introduce method to ignore unexpected command params (#3570) Co-authored-by: Nicholas Tindle Co-authored-by: Reinier van der Leer Co-authored-by: Luke K <2609441+lc0rp@users.noreply.github.com> --- autogpt/commands/command.py | 30 +++++++++++++++++++++++++++++ autogpt/commands/file_operations.py | 4 +++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/autogpt/commands/command.py b/autogpt/commands/command.py index 742cc8df..ed93589f 100644 --- a/autogpt/commands/command.py +++ b/autogpt/commands/command.py @@ -1,6 +1,7 @@ import functools import importlib import inspect +from inspect import Parameter from typing import Any, Callable, Optional from autogpt.config import Config @@ -175,3 +176,32 @@ def command( return wrapper return decorator + + +def ignore_unexpected_kwargs(func: Callable[..., Any]) -> Callable[..., Any]: + def filter_kwargs(kwargs: dict) -> dict: + sig = inspect.signature(func) + # Parameter.VAR_KEYWORD - a dict of keyword arguments that aren't bound to any other + if any(map(lambda p: p.kind == Parameter.VAR_KEYWORD, sig.parameters.values())): + # if **kwargs exist, return directly + return kwargs + + _params = list( + filter( + lambda p: p.kind + in {Parameter.KEYWORD_ONLY, Parameter.POSITIONAL_OR_KEYWORD}, + sig.parameters.values(), + ) + ) + + res_kwargs = { + param.name: kwargs[param.name] for param in _params if param.name in kwargs + } + return res_kwargs + + @functools.wraps(func) + def wrapper(*args, **kwargs) -> Any: + kwargs = filter_kwargs(kwargs) + return func(*args, **kwargs) + + return wrapper diff --git a/autogpt/commands/file_operations.py b/autogpt/commands/file_operations.py index a0a61539..b851d662 100644 --- a/autogpt/commands/file_operations.py +++ b/autogpt/commands/file_operations.py @@ -13,8 +13,9 @@ from confection import Config from requests.adapters import HTTPAdapter, Retry from autogpt.agent.agent import Agent -from autogpt.commands.command import command +from autogpt.commands.command import command, ignore_unexpected_kwargs from autogpt.commands.file_operations_utils import read_textual_file +from autogpt.config import Config from autogpt.logs import logger from autogpt.memory.vector import MemoryItem, VectorMemory from autogpt.spinner import Spinner @@ -308,6 +309,7 @@ def delete_file(filename: str, agent: Agent) -> str: @command("list_files", "List Files in Directory", '"directory": ""') +@ignore_unexpected_kwargs def list_files(directory: str, agent: Agent) -> list[str]: """lists files in a directory recursively