Skip to content

[建议] 项目的思想不错, 需要提升代码规范 #220

@WalkerWang731

Description

@WalkerWang731

作者你好,
你的项目思想实现不错,但是需要提升一下代码规范,这些规范不光是代码更阅读,更可以避免一些潜在的bug
这里给项目组提出几个建议

PEP8 规范

需要遵循 PEP8 规范,代码中缩进、括号写的都比较随意
拿这个文件举例 https://github.com/AgentEra/Agently/blob/main/Agently/Agent/Agent.py
比如
这种括号和空格的使用

self.agent_request_prefix.update({ agent_component_name: component_export["prefix"] })

应该改为

self.agent_request_prefix.update({agent_component_name: component_export["prefix"]})

还有一些 if 的判断
比如

if agent_id == None or agent_id == "":

应该是

if agent_id is None or agent_id == ""

占用 Builtin 变量

这个比较容易产生bug
例如
这里使用了 input 内置变量

    def assign(self, input: Any, desc: Any = None) -> 'NamespaceOps':
        """智能分配值,根据输入类型自动选择合适的方法"""
        if desc is None:
            if isinstance(input, dict):
                return self.update(input)
            elif isinstance(input, list):
                return self.extend(input)
            else:
                return self.set(input)
        else:
            current_content = self.get(input)
            if isinstance(current_content, list):
                if isinstance(desc, list):
                    return self.extend(input, desc)
                else:
                    return self.append(input, desc)
            elif isinstance(desc, dict):
                return self.update(input, desc)
            else:
                return self.set(input, desc)

这里使用了 type 内置变量

    async def get_tools_info(self):
        tools = await self.session.list_tools()
        tools_info = []
        for tool in tools.tools:
            tools_info.append({
                "tool_name": tool.name,
                "desc": tool.description,
                "kwargs": {}
            })
            for key, value in tool.inputSchema["properties"].items():
                type = self._transform_schema_to_type(value)
                desc = (
                    value["description"]
                    if "description" in value
                    else (
                        value["desc"]
                        if "desc" in value
                        else None
                    )
                )
                tools_info[-1]["kwargs"].update({
                    key: (type, desc),
                })
        return tools_info

默认参数避免指针类型对象

比如这个 schema_data 只有在程序启动的第一次初始化一次,一旦被修改,下次默认的参数就有之前的状态了

 def __init__(self, schema_data = { 'chunks': [], 'edges': [] }, workflow = None, logger: logging.Logger = None):
        self.logger = logger
        self._chunks = []
        self._edges = []
        # 依次调用添加方法添加
        (
            self
                .append_raw_chunk_list(schema_data.get('chunks', []))
                .connect_with_edges(schema_data.get('edges', []))
        )
        self.workflow = workflow
        # 辅助 id 命名
        self.chunk_id_cursor = 0

应该修改为

    def __init__(self, schema_data=None, workflow=None, logger: logging.Logger = None):
        if schema_data is None:
            schema_data = {'chunks': [], 'edges': []}
        self.logger = logger
        self._chunks = []
        self._edges = []
        # 依次调用添加方法添加
        (
            self
            .append_raw_chunk_list(schema_data.get('chunks', []))
            .connect_with_edges(schema_data.get('edges', []))
        )
        self.workflow = workflow
        # 辅助 id 命名
        self.chunk_id_cursor = 0

规范父类的抽象接口

不然会很困惑是否要执行super调用父类

比如

class OpenAI(RequestABC):
    def __init__(self, request):
        self.request = request
        self.use_assistant = False
        self.assistant_id = None
        self.model_name = "OpenAI"
        self.model_settings = RuntimeCtxNamespace(f"model.{ self.model_name }", self.request.settings)
        self.request_type = self.request.request_runtime_ctx.get("request_type", "chat")
        if self.request_type == None:
            self.request_type = "chat"

阅读代码上下文后,我知道这个其实无需调用父类了
如果 RequestABC 无需执行 __init__ 的话,应该写到 class 变量里

class RequestABC(ABC):
    request = None
    model_name = "<Model-Name>"

    # if you want to use RuntimeCtxNamespace to help you manage your settings
    # from Agently.utils import RuntimeCtxNamespace
    # self.model_settings = RuntimeCtxNamespace(f"model.{ self.model_name }", self.request.settings)

或者使用 @abstractmethod 声明

class RequestABC(ABC):

    @abstractmethod
    def __init__(self, request):
        self.request = request
        self.model_name = "<Model-Name>"
        # if you want to use RuntimeCtxNamespace to help you manage your settings
        # from Agently.utils import RuntimeCtxNamespace
        # self.model_settings = RuntimeCtxNamespace(f"model.{ self.model_name }", self.request.settings)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions