Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(web): update APIs to support web panel configuration #1393

Merged
merged 1 commit into from
Feb 9, 2025

Conversation

lss233
Copy link
Owner

@lss233 lss233 commented Feb 9, 2025

Summary by Sourcery

更新 API 以支持调度规则的 Web 面板配置。在规则创建和更新端点中添加规则类型和配置。添加端点以检索可用的规则类型及其配置架构。

新功能:

  • 添加了对调度规则 Web 面板配置的支持。

测试:

  • 更新了测试以反映内存和工作流管理的变更。
Original summary in English

Summary by Sourcery

Update APIs to support web panel configuration for dispatch rules. Add rule type and configuration to rule creation and update endpoints. Add endpoint to retrieve available rule types and their configuration schemas.

New Features:

  • Added support for web panel configuration of dispatch rules.

Tests:

  • Updated tests to reflect changes in memory and workflow management.

Copy link
Contributor

sourcery-ai bot commented Feb 9, 2025

审阅者指南 by Sourcery

这个拉取请求重构了框架的几个核心组件,以支持 Web 面板配置并改进整体 API 一致性。主要变更包括:使用虚拟持久化更新内存管理器测试,改进插件加载,对工作流构建器和块注册进行广泛重构(包括解耦构造函数中的容器依赖),为检索规则、LLM 和 IM 适配器的配置架构添加新的 API 端点,以及更新文档。此外,PR 还包括大量测试调整以及日志和错误处理方面的增强。

更新的 PluginLoader 和 WorkflowBuilder 类图(类图)

classDiagram
    class PluginLoader {
      - container: DependencyContainer
      - plugin_dir: str
      - logger: Logger
      - _loaded_entry_points: set
      - internal_plugins: List
      - config: GlobalConfig
      + register_plugin(plugin_class: Type[Plugin], plugin_name: str)
      + _load_external_plugin(plugin_name: str)
      + instantiate_plugin(plugin_class)
      + enable_plugin(plugin_name: str)
      + disable_plugin(plugin_name: str)
      + update_plugin(plugin_name: str)
      + discover_external_plugins()
    }

    class WorkflowBuilder {
      - name: str
      - head: Node
      - current: Node
      - blocks: List<Block>
      - nodes_by_name: Dict<string, Node>
      + __init__(name: str)
      + build(container: DependencyContainer): Workflow
      + save_to_yaml(file_path: str, container: DependencyContainer)
      + load_from_yaml(file_path: str, container: DependencyContainer): WorkflowBuilder
      + chain(block)
      + parallel(blocks: List)
    }

    class BlockSpec {
      - block_class: Type<Block>
      - name: string
      - kwargs: Dict<string, Any>
      - wire_from: Optional<List<string>>
      + __post_init__()
    }

    PluginLoader ..> GlobalConfig : uses
    WorkflowBuilder ..> Node : creates
    WorkflowBuilder ..> Block : manages
    BlockSpec ..> Block : specifies
Loading

文件级变更

变更 详情 文件
重构内存管理器及其测试,引入虚拟持久化并改进测试结构。
  • 添加 DummyMemoryPersistence 实现,用于测试内存管理器。
  • 将传统的 unittest 测试转换为使用 pytest 夹具和断言风格。
  • 更新 MemoryManager 的构造函数,允许可选的持久化覆盖。
  • 调整相关测试用例以使用新的虚拟持久化和更新的内存存储 API。
tests/memory/test_memory_manager.py
framework/memory/memory_manager.py
改进插件加载和外部插件注册。
  • 修改 plugin_loader.py 以使用 importlib.metadata 入口点加载外部插件。
  • 增强插件加载失败时的错误处理和日志记录。
  • 删除未使用的变量和冗余的模块重新加载代码。
framework/plugin_manager/plugin_loader.py
扩展 Web API 路由以支持 Web 面板配置变更。
  • 添加端点以检索可用的规则类型和配置架构(如 /types 和 /types/<rule_type>/config-schema)。
  • 更新规则创建和更新处理程序以验证规则类型并通过 model_dump 使用新的配置提取。
  • 调整 API 响应以包含新字段,如规则的"类型"和更新的配置格式。
framework/web/api/dispatch/routes.py
framework/web/api/workflow/routes.py
framework/web/api/llm/routes.py
framework/web/api/im/routes.py
重构工作流构建器、注册表和块基类。
  • 修改 WorkflowBuilder 以仅在实例化期间接受工作流名称,要求在 build() 期间提供容器。
  • 引入新的 BlockSpec 数据类和 builder.py 中节点创建的相关更改。
  • 重构 WorkflowRegistry 方法,包括工作流注册、注销和路径验证。
  • 将容器依赖解析从块构造函数移至执行时间,使用类属性注入。
  • 更新块基类(Block)以通过构造函数支持可选名称、输入和输出,并为先前的 init 参数添加弃用。
framework/workflow/core/workflow/builder.py
framework/workflow/core/block/base.py
framework/workflow/core/dispatch/dispatcher.py
framework/workflow/core/dispatch/registry.py
framework/workflow/core/workflow/registry.py
更新块实现和测试以适应新的 API。
  • 更改块实现(如 ChatMemoryQuery、ChatMemoryStore、ChatMessageConstructor)以使用类属性和延迟容器解析。
  • 更新工作流构建、块执行和执行器的测试以使用新的 API 签名。
  • 调整测试文件和块架构导入以匹配重构的模块结构。
framework/workflow/implementations/blocks/memory/chat_memory.py
framework/workflow/implementations/blocks/llm/chat.py
tests/test_workflow_builder.py
tests/test_workflow_factories.py
tests/workflow_executor/test_block.py
tests/workflow_executor/test_input_output.py
tests/workflow_executor/test_workflow_basic.py
添加适配器配置架构的 API 端点和文档更新。
  • 在 LLM 和 IM 路由中添加新端点以检索适配器配置的 JSON 架构。
  • 更新 API 文档(README 文件)以包含新配置架构端点的示例。
  • 重构适配器模型以包含新的配置架构模型定义。
framework/web/api/llm/README.md
framework/web/api/im/README.md
framework/web/api/llm/models.py
framework/web/api/im/models.py
引入其他项目配置和杂项改进。
  • 添加新的 pyproject.toml 文件以支持现代构建系统。
  • 创建新的块架构模块以存放 BlockInput、BlockOutput 和 BlockConfig 模型。
  • 使用 pydantic_validation_wrapper 增强 ConfigLoader 以获得更好的验证错误日志记录。
  • 对 Docker 启动脚本和 requirements.txt 进行微小更新。
pyproject.toml
framework/workflow/core/block/schema.py
framework/config/config_loader.py
docker/start.sh
requirements.txt
跨代码库的常规代码风格和依赖注入改进。
  • 在许多块和测试中将构造函数中的直接容器注入替换为属性赋值。
  • 在重构后的测试文件中更新了手动分配容器的位置。
  • 改进了多个模块中的日志记录和错误处理。
多个测试文件,如 tests/web/api/im/test_im.py, tests/web/api/llm/test_llm.py, tests/web/auth/test_auth.py 等

提示和命令

与 Sourcery 交互

  • 触发新的审阅: 在拉取请求上评论 @sourcery-ai review
  • 继续讨论: 直接回复 Sourcery 的审阅评论。
  • 从审阅评论生成 GitHub 问题: 通过回复审阅评论,要求 Sourcery 创建一个问题。您也可以通过回复审阅评论并写 @sourcery-ai issue 来创建问题。
  • 生成拉取请求标题: 在拉取请求标题的任何位置写 @sourcery-ai 以随时生成标题。您也可以在拉取请求上评论 @sourcery-ai title 以随时(重新)生成标题。
  • 生成拉取请求摘要: 在拉取请求正文的任何位置写 @sourcery-ai summary 以在您想要的确切位置生成 PR 摘要。您也可以在拉取请求上评论 @sourcery-ai summary 以随时(重新)生成摘要。
  • 生成审阅者指南: 在拉取请求上评论 @sourcery-ai guide 以随时(重新)生成审阅者指南。
  • 解决所有 Sourcery 评论: 在拉取请求上评论 @sourcery-ai resolve 以解决所有 Sourcery 评论。如果您已经处理了所有评论并且不想再看到它们,这很有用。
  • 取消所有 Sourcery 审阅: 在拉取请求上评论 @sourcery-ai dismiss 以取消所有现有的 Sourcery 审阅。特别是在您想要重新开始审阅时很有用 - 别忘了评论 @sourcery-ai review 以触发新的审阅!
  • 为问题生成行动计划: 在问题上评论 @sourcery-ai plan 以生成该问题的行动计划。

自定义您的体验

访问您的仪表板以:

  • 启用或禁用审阅功能,如 Sourcery 生成的拉取请求摘要、审阅者指南等。
  • 更改审阅语言。
  • 添加、删除或编辑自定义审阅说明。
  • 调整其他审阅设置。

获取帮助

Original review guide in English

Reviewer's Guide by Sourcery

This pull request refactors several core components of the framework to support web panel configuration and improve overall API consistency. Major changes include updates to memory manager testing with dummy persistence, improvements to plugin loading, extensive refactoring of workflow builders and block registration (including decoupling container dependency from constructors), addition of new API endpoints for retrieving configuration schemas for rules, LLM, and IM adapters, and documentation updates. Additionally, the PR includes numerous test adjustments and enhancements in logging and error handling.

Updated class diagram for PluginLoader and WorkflowBuilder (Class Diagram)

classDiagram
    class PluginLoader {
      - container: DependencyContainer
      - plugin_dir: str
      - logger: Logger
      - _loaded_entry_points: set
      - internal_plugins: List
      - config: GlobalConfig
      + register_plugin(plugin_class: Type[Plugin], plugin_name: str)
      + _load_external_plugin(plugin_name: str)
      + instantiate_plugin(plugin_class)
      + enable_plugin(plugin_name: str)
      + disable_plugin(plugin_name: str)
      + update_plugin(plugin_name: str)
      + discover_external_plugins()
    }

    class WorkflowBuilder {
      - name: str
      - head: Node
      - current: Node
      - blocks: List<Block>
      - nodes_by_name: Dict<string, Node>
      + __init__(name: str)
      + build(container: DependencyContainer): Workflow
      + save_to_yaml(file_path: str, container: DependencyContainer)
      + load_from_yaml(file_path: str, container: DependencyContainer): WorkflowBuilder
      + chain(block)
      + parallel(blocks: List)
    }

    class BlockSpec {
      - block_class: Type<Block>
      - name: string
      - kwargs: Dict<string, Any>
      - wire_from: Optional<List<string>>
      + __post_init__()
    }

    PluginLoader ..> GlobalConfig : uses
    WorkflowBuilder ..> Node : creates
    WorkflowBuilder ..> Block : manages
    BlockSpec ..> Block : specifies
Loading

File-Level Changes

Change Details Files
Refactored memory manager and its tests to introduce a dummy persistence and improve test structure.
  • Added a DummyMemoryPersistence implementation for use in testing the memory manager.
  • Converted legacy unittest tests to use pytest fixtures and assertion style.
  • Updated MemoryManager's constructor to allow an optional persistence override.
  • Adjusted related test cases to use the new dummy persistence and updated memory storage API.
tests/memory/test_memory_manager.py
framework/memory/memory_manager.py
Improved plugin loading and external plugin registration.
  • Modified plugin_loader.py to use importlib.metadata entry_points for loading external plugins.
  • Enhanced error handling and logging when a plugin fails to load.
  • Removed unused variables and redundant module reloading code.
framework/plugin_manager/plugin_loader.py
Extended web API routes to support web panel configuration changes.
  • Added endpoints to retrieve available rule types and configuration schemas (e.g., /types and /types/<rule_type>/config-schema).
  • Updated rule creation and updating handlers to validate rule types and use new configuration extraction via model_dump.
  • Adjusted API responses to include new fields such as 'type' for rules and updated config formats.
framework/web/api/dispatch/routes.py
framework/web/api/workflow/routes.py
framework/web/api/llm/routes.py
framework/web/api/im/routes.py
Refactored workflow builder, registry, and block base classes.
  • Modified WorkflowBuilder to accept only the workflow name during instantiation, requiring the container during build().
  • Introduced a new BlockSpec data class and associated changes in node creation within builder.py.
  • Refactored WorkflowRegistry methods including workflow registration, unregistration, and path validation.
  • Moved container dependency resolution from block constructors to execution time using class attribute injection.
  • Updated block base class (Block) to support optional name, inputs, and outputs via constructor, and added deprecation of previous init parameters.
framework/workflow/core/workflow/builder.py
framework/workflow/core/block/base.py
framework/workflow/core/dispatch/dispatcher.py
framework/workflow/core/dispatch/registry.py
framework/workflow/core/workflow/registry.py
Updated block implementations and tests to align with new APIs.
  • Changed block implementations (e.g., ChatMemoryQuery, ChatMemoryStore, ChatMessageConstructor) to use class attributes and delayed container resolution.
  • Updated tests for workflow building, block execution, and executor to use new API signatures.
  • Adjusted test files and block schema imports to match refactored module structure.
framework/workflow/implementations/blocks/memory/chat_memory.py
framework/workflow/implementations/blocks/llm/chat.py
tests/test_workflow_builder.py
tests/test_workflow_factories.py
tests/workflow_executor/test_block.py
tests/workflow_executor/test_input_output.py
tests/workflow_executor/test_workflow_basic.py
Added API endpoints and documentation updates for adapter configuration schemas.
  • Added new endpoints in both LLM and IM routes to retrieve JSON Schema for adapter configuration.
  • Updated API documentation (README files) to include examples for the new config schema endpoints.
  • Refactored the adapter models to include new config schema model definitions.
framework/web/api/llm/README.md
framework/web/api/im/README.md
framework/web/api/llm/models.py
framework/web/api/im/models.py
Introduced additional project configuration and miscellaneous improvements.
  • Added a new pyproject.toml file to support modern build systems.
  • Created a new block schema module to house BlockInput, BlockOutput, and BlockConfig models.
  • Enhanced the ConfigLoader with a pydantic_validation_wrapper for better validation error logging.
  • Minor updates to Docker startup script and requirements.txt.
pyproject.toml
framework/workflow/core/block/schema.py
framework/config/config_loader.py
docker/start.sh
requirements.txt
General code style and dependency injection improvements across the codebase.
  • Replaced direct container injection in constructors with attribute assignment in many blocks and tests.
  • Updated various test files to assign container manually where needed after refactoring.
  • Improved logging and error handling in several modules.
Multiple test files such as tests/web/api/im/test_im.py, tests/web/api/llm/test_llm.py, tests/web/auth/test_auth.py, and others

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@lss233 lss233 merged commit d3c4ae0 into refactoring-v3-mvp Feb 9, 2025
1 check passed
@lss233 lss233 deleted the feature/web_panel branch February 9, 2025 15:37
Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lss233 - 我已经审查了你的更改 - 以下是一些反馈:

整体评论

  • 考虑重构容器分配到块,以便容器注入能够统一处理,而不是在测试中需要手动分配。
  • 确保对 WorkflowBuilder 的构建方法和相关工厂方法的更改在所有使用处都一致反映,以避免容器注入方面的混淆。
  • 检查 WorkflowRegistry.get_workflow_path 中的新正则表达式检查边缘情况,确保它们匹配所有有效的工作流和组 ID。
以下是我在审查期间查看的内容
  • 🟡 一般性问题:发现 4 个问题
  • 🟢 安全性:一切看起来都很好
  • 🟡 测试:发现 2 个问题
  • 🟢 复杂性:一切看起来都很好
  • 🟢 文档:一切看起来都很好

Sourcery 对开源是免费的 - 如果你喜欢我们的评论,请考虑分享 ✨
帮助我变得更有用!请在每条评论上点击 👍 或 👎,我将使用这些反馈来改进你的评论。
Original comment in English

Hey @lss233 - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider refactoring container assignment to blocks so that container injection is handled uniformly rather than needing manual assignment in tests.
  • Ensure that the changes to WorkflowBuilder's build method and related factory methods are consistently reflected in all usages to avoid confusion around container injection.
  • Review the new regex checks in WorkflowRegistry.get_workflow_path for edge cases and ensure they match all valid workflow and group IDs.
Here's what I looked at during the review
  • 🟡 General issues: 4 issues found
  • 🟢 Security: all looks good
  • 🟡 Testing: 2 issues found
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

return list(self._blocks.values())

def extract_block_info(self, block_type: Type[Block]) -> Tuple[Dict[str, BlockInput], Dict[str, BlockOutput], Dict[str, BlockConfig]]:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

建议: 考虑改进 extract_block_info 中的 Optional 类型检测。

当前的检查使用 'hasattr(param_type, 'args') 和 param_type.name == 'Optional''。更健壮的方法可能涉及使用 'typing.get_origin' 和 'typing.get_args' 来正确解释 Optional[T] 和其他 Union 类型,这可以避免类型注解中的微妙错误。

建议的实现:

from typing import Dict, Tuple, List, Type, get_origin, get_args, Union
        for name, param_type in block_type.__annotations__.items():
            if get_origin(param_type) is Union and type(None) in get_args(param_type):
                inner_types = [arg for arg in get_args(param_type) if arg is not type(None)]
                inner_type = inner_types[0] if inner_types else param_type

注意:

  1. 此处假设 extract_block_info 中遍历 block_type.annotations 并对 Optional 类型做了检测,
    如果代码中 Optional 类型的检测部分不止这一处,请在其他地方也做类似修改。
  2. 根据项目整体代码风格,请确保导入调整不会与已有的内容冲突。
Original comment in English

suggestion: Consider improving Optional type detection in extract_block_info.

The current check uses 'hasattr(param_type, 'args') and param_type.name == 'Optional''. A more robust approach might involve using 'typing.get_origin' and 'typing.get_args' to correctly interpret Optional[T] and other Union types, which can avoid subtle bugs with type annotations.

Suggested implementation:

from typing import Dict, Tuple, List, Type, get_origin, get_args, Union
        for name, param_type in block_type.__annotations__.items():
            if get_origin(param_type) is Union and type(None) in get_args(param_type):
                inner_types = [arg for arg in get_args(param_type) if arg is not type(None)]
                inner_type = inner_types[0] if inner_types else param_type

注意:

  1. 此处假设 extract_block_info 中遍历 block_type.annotations 并对 Optional 类型做了检测,
    如果代码中 Optional 类型的检测部分不止这一处,请在其他地方也做类似修改。
  2. 根据项目整体代码风格,请确保导入调整不会与已有的内容冲突。

Comment on lines +107 to +108
# 查询
results = memory_manager.query(mock_scope, "user1")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

问题(测试): 缺少无匹配条目的查询测试。

添加一个测试用例,验证当没有内存条目匹配提供的发送者时 query 的行为。

Original comment in English

issue (testing): Missing test for query with no matching entries.

Add a test case to verify the behavior of query when no memory entries match the provided sender.

Comment on lines +133 to +142
def test_shutdown(self, memory_manager, test_entry):
"""测试关闭"""
# 添加一些测试数据
self.manager.memories = {
"scope1": [self.test_entry],
"scope2": [self.test_entry]
memory_manager.memories = {
"scope1": [test_entry],
"scope2": [test_entry]
}

# 测试关闭
self.manager.shutdown()
# 关闭
memory_manager.shutdown()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

问题(测试): 使用空内存测试 shutdown

添加一个 memories 为空字典的测试用例,以确保正确处理此边缘情况。

Original comment in English

issue (testing): Test shutdown with empty memories.

Add a test case where memories is an empty dictionary to ensure correct handling of this edge case.

@@ -129,6 +129,46 @@ DELETE/backend-api/api/llm/backends/{backend_name}

删除指定的后端。如果后端当前已启用,会先自动卸载。

### 获取适配器配置模式
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

建议: 请阐明 adapter_type 的类型和格式。提供一个示例值将会很有帮助。

Suggested change
### 获取适配器配置模式
### 获取适配器配置模式
注意:路径参数 adapter_type 必须为字符串,表示适配器类型,例如 "openai"。
Original comment in English

suggestion: Please clarify the type and format of adapter_type. Providing an example value would be helpful.

Suggested change
### 获取适配器配置模式
### 获取适配器配置模式
注意:路径参数 adapter_type 必须为字符串,表示适配器类型,例如 "openai"。

@@ -152,6 +192,10 @@ DELETE/backend-api/api/llm/backends/{backend_name}
### LLMAdapterTypes
- `types`: 可用的适配器类型列表

### LLMAdapterConfigSchema
- `error`: 错误信息(可选)
- `schema`: JSON Schema 格式的配置字段描述
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

建议: 请为 schema 字段本身添加描述,解释 schema 代表什么。

Suggested change
- `schema`: JSON Schema 格式的配置字段描述
- `schema`: JSON Schema 格式的配置字段描述。此 schema 定义了配置字段的结构、数据类型以及验证规则,确保适配器配置的有效性。
Original comment in English

suggestion: Please add a description for the schema field itself, explaining what the schema represents.

Suggested change
- `schema`: JSON Schema 格式的配置字段描述
- `schema`: JSON Schema 格式的配置字段描述。此 schema 定义了配置字段的结构、数据类型以及验证规则,确保适配器配置的有效性。

if possible_plugin_infos[0].version != old_version:
return possible_plugin_infos[0]
else:
raise Exception(f"Failed to update plugin: {plugin_info.package_name} is already up to date")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

问题(代码质量): 引发特定错误而不是通用的 ExceptionBaseExceptionraise-specific-error

解释如果一段代码引发特定的异常类型而不是通用的 [`BaseException`](https://docs.python.org/3/library/exceptions.html#BaseException) 或 [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception),调用代码可以:
  • 获取有关错误类型的更多信息
  • 为其定义特定的异常处理

这样,代码的调用者可以适当地处理错误。

如何解决?

所以,不是像这样引发 ExceptionBaseException

if incorrect_input(value):
    raise Exception("输入不正确")

你可以像这样引发特定错误

if incorrect_input(value):
    raise ValueError("输入不正确")

class IncorrectInputError(Exception):
    pass


if incorrect_input(value):
    raise IncorrectInputError("输入不正确")
Original comment in English

issue (code-quality): Raise a specific error instead of the general Exception or BaseException (raise-specific-error)

ExplanationIf a piece of code raises a specific exception type rather than the generic [`BaseException`](https://docs.python.org/3/library/exceptions.html#BaseException) or [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception), the calling code can:
  • get more information about what type of error it is
  • define specific exception handling for it

This way, callers of the code can handle the error appropriately.

How can you solve this?

So instead of having code raising Exception or BaseException like

if incorrect_input(value):
    raise Exception("The input is incorrect")

you can have code raising a specific error like

if incorrect_input(value):
    raise ValueError("The input is incorrect")

or

class IncorrectInputError(Exception):
    pass


if incorrect_input(value):
    raise IncorrectInputError("The input is incorrect")

metadata=builder.metadata if hasattr(builder, 'metadata') else None
))


return WorkflowList(workflows=workflows).model_dump()

@workflow_bp.route('/<group_id>/<workflow_id>', methods=['GET'])
@require_auth
async def get_workflow(group_id: str, workflow_id: str):
"""获取特定工作流的详细信息"""
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

问题(代码质量): 将 for 循环转换为列表推导式 [×2](list-comprehension

Original comment in English

issue (code-quality): Convert for loop into list comprehension [×2] (list-comprehension)

@@ -177,15 +176,18 @@ def _parse_block_spec(self, block_spec: Union[Type[Block], tuple]) -> BlockSpec:

def _create_node(self, spec: BlockSpec, is_parallel: bool = False) -> Node:
"""创建并初始化一个新的节点"""
block = spec.block_class(self.container, **spec.kwargs)
try:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

问题(代码质量): 我们发现了以下问题:

Original comment in English

issue (code-quality): We've found these issues:

Comment on lines +65 to +67
if builder and container:
return builder.build(container)
return builder
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

建议(代码质量): 我们发现了以下问题:

Suggested change
if builder and container:
return builder.build(container)
return builder
return builder.build(container) if builder and container else builder
Original comment in English

suggestion (code-quality): We've found these issues:

Suggested change
if builder and container:
return builder.build(container)
return builder
return builder.build(container) if builder and container else builder

Comment on lines +53 to +54
manager = MemoryManager(container, persistence=dummy_persistence)
return manager
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

建议(代码质量): 内联立即返回的变量(inline-immediately-returned-variable

Suggested change
manager = MemoryManager(container, persistence=dummy_persistence)
return manager
return MemoryManager(container, persistence=dummy_persistence)
Original comment in English

suggestion (code-quality): Inline variable that is immediately returned (inline-immediately-returned-variable)

Suggested change
manager = MemoryManager(container, persistence=dummy_persistence)
return manager
return MemoryManager(container, persistence=dummy_persistence)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant