🌟 The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming
refine utils code
geekan8f649252900a
diff --git a/metagpt/utils/common.py b/metagpt/utils/common.pyindex 6301cd6a3..08df480ee 100644--- a/metagpt/utils/common.py+++ b/metagpt/utils/common.py@@ -301,9 +301,6 @@ class NoMoneyException(Exception):def print_members(module, indent=0):"""https://stackoverflow.com/questions/1796180/how-can-i-get-a-list-of-all-classes-within-current-module-in-python- :param module:- :param indent:- :return:"""prefix = " " * indentfor name, obj in inspect.getmembers(module):@@ -321,6 +318,7 @@ def print_members(module, indent=0):def parse_recipient(text):+ # FIXME: use ActionNode instead.pattern = r"## Send To:\s*([A-Za-z]+)\s*?" # hard code for nowrecipient = re.search(pattern, text)if recipient:@@ -337,18 +335,12 @@ def get_class_name(cls) -> str:return f"{cls.__module__}.{cls.__name__}"-def get_object_name(obj) -> str:- """Return class name of the object"""- cls = type(obj)- return f"{cls.__module__}.{cls.__name__}"---def any_to_str(val) -> str:+def any_to_str(val: str | typing.Callable) -> str:"""Return the class name or the class name of the object, or 'val' if it's a string type."""if isinstance(val, str):return valif not callable(val):- return get_object_name(val)+ return get_class_name(type(val))return get_class_name(val)@@ -356,32 +348,57 @@ def any_to_str(val) -> str:def any_to_str_set(val) -> set:"""Convert any type to string set."""res = set()- if isinstance(val, dict) or isinstance(val, list) or isinstance(val, set) or isinstance(val, tuple):++ # Check if the value is iterable, but not a string (since strings are technically iterable)+ if isinstance(val, (dict, list, set, tuple)):+ # Special handling for dictionaries to iterate over values+ if isinstance(val, dict):+ val = val.values()+for i in val:res.add(any_to_str(i))else:res.add(any_to_str(val))+return res-def is_subscribed(message, tags):+def is_subscribed(message: "Message", tags: set):"""Return whether it's consumer"""if MESSAGE_ROUTE_TO_ALL in message.send_to:return True- for t in tags:- if t in message.send_to:+ for i in tags:+ if i in message.send_to:return Truereturn False-def general_after_log(logger: "loguru.Logger", sec_format: str = "%0.3f") -> typing.Callable[["RetryCallState"], None]:+def general_after_log(i: "loguru.Logger", sec_format: str = "%0.3f") -> typing.Callable[["RetryCallState"], None]:+ """+ Generates a logging function to be used after a call is retried.++ This generated function logs an error message with the outcome of the retried function call. It includes+ the name of the function, the time taken for the call in seconds (formatted according to `sec_format`),+ the number of attempts made, and the exception raised, if any.++ :param i: A Logger instance from the loguru library used to log the error message.+ :param sec_format: A string format specifier for how to format the number of seconds since the start of the call.+ Defaults to three decimal places.+ :return: A callable that accepts a RetryCallState object and returns None. This callable logs the details+ of the retried call.+ """+def log_it(retry_state: "RetryCallState") -> None:+ # If the function name is not known, default to "<unknown>"if retry_state.fn is None:fn_name = "<unknown>"else:+ # Retrieve the callable's name using a utility functionfn_name = _utils.get_callback_name(retry_state.fn)- logger.error(++ # Log an error message with the function name, time since start, attempt number, and the exception+ i.error(f"Finished call to '{fn_name}' after {sec_format % retry_state.seconds_since_start}(s), "f"this was the {_utils.to_ordinal(retry_state.attempt_number)} time calling it. "f"exp: {retry_state.outcome.exception()}"diff --git a/tests/metagpt/test_role.py b/tests/metagpt/test_role.pyindex 611d321fc..dbe45130d 100644--- a/tests/metagpt/test_role.py+++ b/tests/metagpt/test_role.py@@ -18,7 +18,7 @@ from metagpt.actions import Action, ActionOutput, UserRequirementfrom metagpt.environment import Environmentfrom metagpt.roles import Rolefrom metagpt.schema import Message-from metagpt.utils.common import any_to_str, get_class_name+from metagpt.utils.common import any_to_strclass MockAction(Action):@@ -88,13 +88,13 @@ async def test_react():@pytest.mark.asyncioasync def test_msg_to():m = Message(content="a", send_to=["a", MockRole, Message])- assert m.send_to == set({"a", get_class_name(MockRole), get_class_name(Message)})+ assert m.send_to == {"a", any_to_str(MockRole), any_to_str(Message)}m = Message(content="a", cause_by=MockAction, send_to={"a", MockRole, Message})- assert m.send_to == set({"a", get_class_name(MockRole), get_class_name(Message)})+ assert m.send_to == {"a", any_to_str(MockRole), any_to_str(Message)}m = Message(content="a", send_to=("a", MockRole, Message))- assert m.send_to == set({"a", get_class_name(MockRole), get_class_name(Message)})+ assert m.send_to == {"a", any_to_str(MockRole), any_to_str(Message)}if __name__ == "__main__":diff --git a/tests/metagpt/test_schema.py b/tests/metagpt/test_schema.pyindex 10343c192..c8602d953 100644--- a/tests/metagpt/test_schema.py+++ b/tests/metagpt/test_schema.py@@ -16,8 +16,7 @@ from metagpt.schema import AIMessage, Message, SystemMessage, UserMessagefrom metagpt.actions.action_output import ActionOutputfrom metagpt.actions.write_code import WriteCodefrom metagpt.utils.serialize import serialize_general_message, deserialize_general_message--from metagpt.utils.common import get_class_name+from metagpt.utils.common import any_to_str@pytest.mark.asyncio@@ -58,9 +57,9 @@ def test_message():m.cause_by = "Message"assert m.cause_by == "Message"m.cause_by = Action- assert m.cause_by == get_class_name(Action)+ assert m.cause_by == any_to_str(Action)m.cause_by = Action()- assert m.cause_by == get_class_name(Action)+ assert m.cause_by == any_to_str(Action)m.content = "b"assert m.content == "b"@@ -71,7 +70,7 @@ def test_routes():m.send_to = "b"assert m.send_to == {"b"}m.send_to = {"e", Action}- assert m.send_to == {"e", get_class_name(Action)}+ assert m.send_to == {"e", any_to_str(Action)}def test_message_serdeser():