This commit is contained in:
春河晴
2025-06-10 16:43:45 +09:00
parent cf39f2fe84
commit b0c553703f
18 changed files with 500 additions and 489 deletions

View File

@@ -80,6 +80,7 @@ class ChatBot:
except Exception as e:
logger.error(f"执行命令时出错: {command_class.__name__} - {e}")
import traceback
logger.error(traceback.format_exc())
try:

View File

@@ -22,8 +22,10 @@ from .api.main import start_api_server
# 导入actions模块确保装饰器被执行
import src.chat.actions.default_actions # noqa
# 导入新的插件管理器
from src.plugin_system.core.plugin_manager import plugin_manager
# 导入消息API和traceback模块
from src.common.message import global_api
import traceback

View File

@@ -9,8 +9,13 @@ from src.plugin_system.base.base_plugin import BasePlugin, register_plugin
from src.plugin_system.base.base_action import BaseAction
from src.plugin_system.base.base_command import BaseCommand
from src.plugin_system.base.component_types import (
ComponentType, ActionActivationType, ChatMode,
ComponentInfo, ActionInfo, CommandInfo, PluginInfo
ComponentType,
ActionActivationType,
ChatMode,
ComponentInfo,
ActionInfo,
CommandInfo,
PluginInfo,
)
from src.plugin_system.apis.plugin_api import PluginAPI, create_plugin_api, create_command_api
from src.plugin_system.core.plugin_manager import plugin_manager
@@ -20,28 +25,24 @@ __version__ = "1.0.0"
__all__ = [
# 基础类
'BasePlugin',
'BaseAction',
'BaseCommand',
"BasePlugin",
"BaseAction",
"BaseCommand",
# 类型定义
'ComponentType',
'ActionActivationType',
'ChatMode',
'ComponentInfo',
'ActionInfo',
'CommandInfo',
'PluginInfo',
"ComponentType",
"ActionActivationType",
"ChatMode",
"ComponentInfo",
"ActionInfo",
"CommandInfo",
"PluginInfo",
# API接口
'PluginAPI',
'create_plugin_api',
'create_command_api',
"PluginAPI",
"create_plugin_api",
"create_command_api",
# 管理器
'plugin_manager',
'component_registry',
"plugin_manager",
"component_registry",
# 装饰器
'register_plugin',
"register_plugin",
]

View File

@@ -19,19 +19,19 @@ from src.plugin_system.apis.independent_apis import IndependentAPI, StaticAPI
__all__ = [
# 原有统一API
'PluginAPI',
'create_plugin_api',
'create_command_api',
"PluginAPI",
"create_plugin_api",
"create_command_api",
# 原有单独API
'MessageAPI',
'LLMAPI',
'DatabaseAPI',
'ConfigAPI',
'UtilsAPI',
'StreamAPI',
'HearflowAPI',
"MessageAPI",
"LLMAPI",
"DatabaseAPI",
"ConfigAPI",
"UtilsAPI",
"StreamAPI",
"HearflowAPI",
# 新增分类API
'ActionAPI', # 需要Action依赖的API
'IndependentAPI', # 独立API
'StaticAPI', # 静态API
"ActionAPI", # 需要Action依赖的API
"IndependentAPI", # 独立API
"StaticAPI", # 静态API
]

View File

@@ -11,6 +11,7 @@ from src.common.logger_manager import get_logger
logger = get_logger("action_apis")
class ActionAPI(MessageAPI, DatabaseAPI):
"""
Action相关API聚合类
@@ -27,7 +28,8 @@ class ActionAPI(MessageAPI, DatabaseAPI):
- 需要访问聊天上下文和执行环境的操作
"""
def __init__(self,
def __init__(
self,
chat_stream=None,
expressor=None,
replyer=None,
@@ -35,7 +37,8 @@ class ActionAPI(MessageAPI, DatabaseAPI):
log_prefix: str = "[ActionAPI]",
thinking_id: str = "",
cycle_timers: dict = None,
action_data: dict = None):
action_data: dict = None,
):
"""
初始化Action相关API
@@ -54,7 +57,7 @@ class ActionAPI(MessageAPI, DatabaseAPI):
"chat_stream": chat_stream,
"expressor": expressor,
"replyer": replyer,
"observations": observations or []
"observations": observations or [],
}
self.log_prefix = log_prefix

View File

@@ -14,6 +14,7 @@ from src.common.logger_manager import get_logger
logger = get_logger("independent_apis")
class IndependentAPI(LLMAPI, ConfigAPI, UtilsAPI, StreamAPI, HearflowAPI):
"""
独立API聚合类
@@ -47,6 +48,7 @@ class IndependentAPI(LLMAPI, ConfigAPI, UtilsAPI, StreamAPI, HearflowAPI):
logger.debug(f"{self.log_prefix} IndependentAPI 初始化完成")
# 提供便捷的静态访问方式
class StaticAPI:
"""

View File

@@ -174,8 +174,8 @@ class MessageAPI:
"""
try:
# 安全获取服务和日志前缀
services = getattr(self, '_services', {})
log_prefix = getattr(self, 'log_prefix', '[MessageAPI]')
services = getattr(self, "_services", {})
log_prefix = getattr(self, "log_prefix", "[MessageAPI]")
expressor: DefaultExpressor = services.get("expressor")
chat_stream: ChatStream = services.get("chat_stream")
@@ -221,7 +221,7 @@ class MessageAPI:
return success
except Exception as e:
log_prefix = getattr(self, 'log_prefix', '[MessageAPI]')
log_prefix = getattr(self, "log_prefix", "[MessageAPI]")
logger.error(f"{log_prefix} 发送消息时出错: {e}")
traceback.print_exc()
return False
@@ -237,8 +237,8 @@ class MessageAPI:
bool: 是否发送成功
"""
# 安全获取服务和日志前缀
services = getattr(self, '_services', {})
log_prefix = getattr(self, 'log_prefix', '[MessageAPI]')
services = getattr(self, "_services", {})
log_prefix = getattr(self, "log_prefix", "[MessageAPI]")
expressor: DefaultExpressor = services.get("expressor")
chat_stream: ChatStream = services.get("chat_stream")
@@ -276,9 +276,9 @@ class MessageAPI:
anchor_message.update_chat_stream(chat_stream)
# 调用内部方法发送消息
cycle_timers = getattr(self, 'cycle_timers', {})
reasoning = getattr(self, 'reasoning', '插件生成')
thinking_id = getattr(self, 'thinking_id', 'plugin_thinking')
cycle_timers = getattr(self, "cycle_timers", {})
reasoning = getattr(self, "reasoning", "插件生成")
thinking_id = getattr(self, "thinking_id", "plugin_thinking")
success, _ = await expressor.deal_reply(
cycle_timers=cycle_timers,
@@ -303,8 +303,8 @@ class MessageAPI:
bool: 是否发送成功
"""
# 安全获取服务和日志前缀
services = getattr(self, '_services', {})
log_prefix = getattr(self, 'log_prefix', '[MessageAPI]')
services = getattr(self, "_services", {})
log_prefix = getattr(self, "log_prefix", "[MessageAPI]")
replyer: DefaultReplyer = services.get("replyer")
chat_stream: ChatStream = services.get("chat_stream")
@@ -342,9 +342,9 @@ class MessageAPI:
anchor_message.update_chat_stream(chat_stream)
# 调用内部方法发送消息
cycle_timers = getattr(self, 'cycle_timers', {})
reasoning = getattr(self, 'reasoning', '插件生成')
thinking_id = getattr(self, 'thinking_id', 'plugin_thinking')
cycle_timers = getattr(self, "cycle_timers", {})
reasoning = getattr(self, "reasoning", "插件生成")
thinking_id = getattr(self, "thinking_id", "plugin_thinking")
success, _ = await replyer.deal_reply(
cycle_timers=cycle_timers,
@@ -362,7 +362,7 @@ class MessageAPI:
Returns:
str: 聊天类型 ("group""private")
"""
services = getattr(self, '_services', {})
services = getattr(self, "_services", {})
chat_stream: ChatStream = services.get("chat_stream")
if chat_stream and hasattr(chat_stream, "group_info"):
return "group" if chat_stream.group_info else "private"
@@ -378,7 +378,7 @@ class MessageAPI:
List[Dict]: 消息列表,每个消息包含发送者、内容等信息
"""
messages = []
services = getattr(self, '_services', {})
services = getattr(self, "_services", {})
observations = services.get("observations", [])
if observations and len(observations) > 0:

View File

@@ -5,7 +5,6 @@
提供所有插件API功能的统一访问入口
"""
from typing import Dict, Any, Optional
from src.common.logger_manager import get_logger
# 导入所有API模块
@@ -33,12 +32,9 @@ class PluginAPI(MessageAPI, LLMAPI, DatabaseAPI, ConfigAPI, UtilsAPI, StreamAPI,
- 提供统一的错误处理和日志记录
"""
def __init__(self,
chat_stream=None,
expressor=None,
replyer=None,
observations=None,
log_prefix: str = "[PluginAPI]"):
def __init__(
self, chat_stream=None, expressor=None, replyer=None, observations=None, log_prefix: str = "[PluginAPI]"
):
"""
初始化插件API
@@ -54,7 +50,7 @@ class PluginAPI(MessageAPI, LLMAPI, DatabaseAPI, ConfigAPI, UtilsAPI, StreamAPI,
"chat_stream": chat_stream,
"expressor": expressor,
"replyer": replyer,
"observations": observations or []
"observations": observations or [],
}
self.log_prefix = log_prefix
@@ -94,11 +90,9 @@ class PluginAPI(MessageAPI, LLMAPI, DatabaseAPI, ConfigAPI, UtilsAPI, StreamAPI,
# 便捷的工厂函数
def create_plugin_api(chat_stream=None,
expressor=None,
replyer=None,
observations=None,
log_prefix: str = "[Plugin]") -> PluginAPI:
def create_plugin_api(
chat_stream=None, expressor=None, replyer=None, observations=None, log_prefix: str = "[Plugin]"
) -> PluginAPI:
"""
创建插件API实例的便捷函数
@@ -113,11 +107,7 @@ def create_plugin_api(chat_stream=None,
PluginAPI: 配置好的插件API实例
"""
return PluginAPI(
chat_stream=chat_stream,
expressor=expressor,
replyer=replyer,
observations=observations,
log_prefix=log_prefix
chat_stream=chat_stream, expressor=expressor, replyer=replyer, observations=observations, log_prefix=log_prefix
)
@@ -132,27 +122,24 @@ def create_command_api(message, log_prefix: str = "[Command]") -> PluginAPI:
Returns:
PluginAPI: 配置好的插件API实例
"""
chat_stream = getattr(message, 'chat_stream', None)
chat_stream = getattr(message, "chat_stream", None)
api = PluginAPI(
chat_stream=chat_stream,
log_prefix=log_prefix
)
api = PluginAPI(chat_stream=chat_stream, log_prefix=log_prefix)
return api
# 导出主要接口
__all__ = [
'PluginAPI',
'create_plugin_api',
'create_command_api',
"PluginAPI",
"create_plugin_api",
"create_command_api",
# 也可以导出各个API类供单独使用
'MessageAPI',
'LLMAPI',
'DatabaseAPI',
'ConfigAPI',
'UtilsAPI',
'StreamAPI',
'HearflowAPI'
"MessageAPI",
"LLMAPI",
"DatabaseAPI",
"ConfigAPI",
"UtilsAPI",
"StreamAPI",
"HearflowAPI",
]

View File

@@ -8,20 +8,25 @@ from src.plugin_system.base.base_plugin import BasePlugin, register_plugin
from src.plugin_system.base.base_action import BaseAction
from src.plugin_system.base.base_command import BaseCommand
from src.plugin_system.base.component_types import (
ComponentType, ActionActivationType, ChatMode,
ComponentInfo, ActionInfo, CommandInfo, PluginInfo
ComponentType,
ActionActivationType,
ChatMode,
ComponentInfo,
ActionInfo,
CommandInfo,
PluginInfo,
)
__all__ = [
'BasePlugin',
'BaseAction',
'BaseCommand',
'register_plugin',
'ComponentType',
'ActionActivationType',
'ChatMode',
'ComponentInfo',
'ActionInfo',
'CommandInfo',
'PluginInfo',
"BasePlugin",
"BaseAction",
"BaseCommand",
"register_plugin",
"ComponentType",
"ActionActivationType",
"ChatMode",
"ComponentInfo",
"ActionInfo",
"CommandInfo",
"PluginInfo",
]

View File

@@ -1,11 +1,12 @@
from abc import ABC, abstractmethod
from typing import Tuple, Dict, Any, Optional
from typing import Tuple
from src.common.logger_manager import get_logger
from src.plugin_system.apis.plugin_api import PluginAPI
from src.plugin_system.base.component_types import ActionActivationType, ChatMode, ActionInfo, ComponentType
logger = get_logger("base_action")
class BaseAction(ABC):
"""Action组件基类
@@ -32,12 +33,7 @@ class BaseAction(ABC):
random_activation_probability: float = 0.0
llm_judge_prompt: str = ""
def __init__(self,
action_data: dict,
reasoning: str,
cycle_timers: dict,
thinking_id: str,
**kwargs):
def __init__(self, action_data: dict, reasoning: str, cycle_timers: dict, thinking_id: str, **kwargs):
"""初始化Action组件
Args:
@@ -58,7 +54,7 @@ class BaseAction(ABC):
expressor=kwargs.get("expressor"),
replyer=kwargs.get("replyer"),
observations=kwargs.get("observations"),
log_prefix=kwargs.get("log_prefix", "")
log_prefix=kwargs.get("log_prefix", ""),
)
self.log_prefix = kwargs.get("log_prefix", "")
@@ -77,7 +73,7 @@ class BaseAction(ABC):
return await self.api.send_message("text", content)
@classmethod
def get_action_info(cls, name: str = None, description: str = None) -> 'ActionInfo':
def get_action_info(cls, name: str = None, description: str = None) -> "ActionInfo":
"""从类属性生成ActionInfo
Args:
@@ -88,13 +84,12 @@ class BaseAction(ABC):
ActionInfo: 生成的Action信息对象
"""
# 自动生成名称和描述
if name is None:
name = cls.__name__.lower().replace('action', '')
name = cls.__name__.lower().replace("action", "")
if description is None:
description = cls.__doc__ or f"{cls.__name__} Action组件"
description = description.strip().split('\n')[0] # 取第一行作为描述
description = description.strip().split("\n")[0] # 取第一行作为描述
return ActionInfo(
name=name,
@@ -107,7 +102,7 @@ class BaseAction(ABC):
mode_enable=cls.mode_enable,
parallel_action=cls.parallel_action,
random_activation_probability=cls.random_activation_probability,
llm_judge_prompt=cls.llm_judge_prompt
llm_judge_prompt=cls.llm_judge_prompt,
)
@abstractmethod

View File

@@ -7,6 +7,7 @@ from src.chat.message_receive.message import MessageRecv
logger = get_logger("base_command")
class BaseCommand(ABC):
"""Command组件基类
@@ -33,12 +34,9 @@ class BaseCommand(ABC):
self.matched_groups: Dict[str, str] = {} # 存储正则表达式匹配的命名组
# 创建API实例
self.api = PluginAPI(
chat_stream=message.chat_stream,
log_prefix=f"[Command]"
)
self.api = PluginAPI(chat_stream=message.chat_stream, log_prefix="[Command]")
self.log_prefix = f"[Command]"
self.log_prefix = "[Command]"
logger.debug(f"{self.log_prefix} Command组件初始化完成")
@@ -71,20 +69,16 @@ class BaseCommand(ABC):
if chat_stream.group_info:
# 群聊
await self.api.send_text_to_group(
text=content,
group_id=str(chat_stream.group_info.group_id),
platform=chat_stream.platform
text=content, group_id=str(chat_stream.group_info.group_id), platform=chat_stream.platform
)
else:
# 私聊
await self.api.send_text_to_user(
text=content,
user_id=str(chat_stream.user_info.user_id),
platform=chat_stream.platform
text=content, user_id=str(chat_stream.user_info.user_id), platform=chat_stream.platform
)
@classmethod
def get_command_info(cls, name: str = None, description: str = None) -> 'CommandInfo':
def get_command_info(cls, name: str = None, description: str = None) -> "CommandInfo":
"""从类属性生成CommandInfo
Args:
@@ -95,13 +89,12 @@ class BaseCommand(ABC):
CommandInfo: 生成的Command信息对象
"""
# 自动生成名称和描述
if name is None:
name = cls.__name__.lower().replace('command', '')
name = cls.__name__.lower().replace("command", "")
if description is None:
description = cls.__doc__ or f"{cls.__name__} Command组件"
description = description.strip().split('\n')[0] # 取第一行作为描述
description = description.strip().split("\n")[0] # 取第一行作为描述
return CommandInfo(
name=name,
@@ -109,5 +102,5 @@ class BaseCommand(ABC):
description=description,
command_pattern=cls.command_pattern,
command_help=cls.command_help,
command_examples=cls.command_examples.copy() if cls.command_examples else []
command_examples=cls.command_examples.copy() if cls.command_examples else [],
)

View File

@@ -5,15 +5,16 @@ import inspect
import toml
from src.common.logger_manager import get_logger
from src.plugin_system.base.component_types import (
PluginInfo, ComponentInfo, ActionInfo, CommandInfo,
ComponentType, ActionActivationType, ChatMode
PluginInfo,
ComponentInfo,
)
from src.plugin_system.core.component_registry import component_registry
logger = get_logger("base_plugin")
# 全局插件类注册表
_plugin_classes: Dict[str, Type['BasePlugin']] = {}
_plugin_classes: Dict[str, Type["BasePlugin"]] = {}
class BasePlugin(ABC):
"""插件基类
@@ -58,7 +59,7 @@ class BasePlugin(ABC):
enabled=self.enable_plugin,
is_built_in=False,
config_file=self.config_file_name or "",
dependencies=self.dependencies.copy()
dependencies=self.dependencies.copy(),
)
logger.debug(f"{self.log_prefix} 插件基类初始化完成")
@@ -87,7 +88,7 @@ class BasePlugin(ABC):
except (TypeError, OSError):
# 最后的fallback从模块的__file__属性获取
module = inspect.getmodule(self.__class__)
if module and hasattr(module, '__file__') and module.__file__:
if module and hasattr(module, "__file__") and module.__file__:
plugin_dir = os.path.dirname(module.__file__)
else:
logger.warning(f"{self.log_prefix} 无法获取插件目录路径,跳过配置加载")
@@ -201,12 +202,12 @@ def register_plugin(cls):
return cls
def get_registered_plugin_classes() -> Dict[str, Type['BasePlugin']]:
def get_registered_plugin_classes() -> Dict[str, Type["BasePlugin"]]:
"""获取所有已注册的插件类"""
return _plugin_classes.copy()
def instantiate_and_register_plugin(plugin_class: Type['BasePlugin'], plugin_dir: str = None) -> bool:
def instantiate_and_register_plugin(plugin_class: Type["BasePlugin"], plugin_dir: str = None) -> bool:
"""实例化并注册插件
Args:
@@ -222,5 +223,6 @@ def instantiate_and_register_plugin(plugin_class: Type['BasePlugin'], plugin_dir
except Exception as e:
logger.error(f"注册插件 {plugin_class.__name__} 时出错: {e}")
import traceback
logger.error(traceback.format_exc())
return False

View File

@@ -2,33 +2,41 @@ from enum import Enum
from typing import Dict, Any, List
from dataclasses import dataclass
# 组件类型枚举
class ComponentType(Enum):
"""组件类型枚举"""
ACTION = "action" # 动作组件
COMMAND = "command" # 命令组件
SCHEDULER = "scheduler" # 定时任务组件(预留)
LISTENER = "listener" # 事件监听组件(预留)
# 动作激活类型枚举
class ActionActivationType(Enum):
"""动作激活类型枚举"""
NEVER = "never" # 从不激活(默认关闭)
ALWAYS = "always" # 默认参与到planner
LLM_JUDGE = "llm_judge" # LLM判定是否启动该action到planner
RANDOM = "random" # 随机启用action到planner
KEYWORD = "keyword" # 关键词触发启用action到planner
# 聊天模式枚举
class ChatMode(Enum):
"""聊天模式枚举"""
FOCUS = "focus" # Focus聊天模式
NORMAL = "normal" # Normal聊天模式
ALL = "all" # 所有聊天模式
@dataclass
class ComponentInfo:
"""组件信息"""
name: str # 组件名称
component_type: ComponentType # 组件类型
description: str # 组件描述
@@ -41,9 +49,11 @@ class ComponentInfo:
if self.metadata is None:
self.metadata = {}
@dataclass
class ActionInfo(ComponentInfo):
"""动作组件信息"""
focus_activation_type: ActionActivationType = ActionActivationType.ALWAYS
normal_activation_type: ActionActivationType = ActionActivationType.ALWAYS
random_activation_probability: float = 0.3
@@ -68,9 +78,11 @@ class ActionInfo(ComponentInfo):
self.associated_types = []
self.component_type = ComponentType.ACTION
@dataclass
class CommandInfo(ComponentInfo):
"""命令组件信息"""
command_pattern: str = "" # 命令匹配模式(正则表达式)
command_help: str = "" # 命令帮助信息
command_examples: List[str] = None # 命令使用示例
@@ -81,9 +93,11 @@ class CommandInfo(ComponentInfo):
self.command_examples = []
self.component_type = ComponentType.COMMAND
@dataclass
class PluginInfo:
"""插件信息"""
name: str # 插件名称
description: str # 插件描述
version: str = "1.0.0" # 插件版本

View File

@@ -8,6 +8,6 @@ from src.plugin_system.core.plugin_manager import plugin_manager
from src.plugin_system.core.component_registry import component_registry
__all__ = [
'plugin_manager',
'component_registry',
"plugin_manager",
"component_registry",
]

View File

@@ -1,14 +1,17 @@
from typing import Dict, List, Type, Optional, Any, Pattern
from abc import ABC
import re
from src.common.logger_manager import get_logger
from src.plugin_system.base.component_types import (
ComponentInfo, ActionInfo, CommandInfo, PluginInfo,
ComponentType, ActionActivationType, ChatMode
ComponentInfo,
ActionInfo,
CommandInfo,
PluginInfo,
ComponentType,
)
logger = get_logger("component_registry")
class ComponentRegistry:
"""统一的组件注册中心
@@ -233,8 +236,7 @@ class ComponentRegistry:
"total_components": len(self._components),
"total_plugins": len(self._plugins),
"components_by_type": {
component_type.value: len(components)
for component_type, components in self._components_by_type.items()
component_type.value: len(components) for component_type, components in self._components_by_type.items()
},
"enabled_components": len([c for c in self._components.values() if c.enabled]),
"enabled_plugins": len([p for p in self._plugins.values() if p.enabled]),

View File

@@ -9,6 +9,7 @@ from src.plugin_system.base.component_types import PluginInfo, ComponentType
logger = get_logger("plugin_manager")
class PluginManager:
"""插件管理器
@@ -74,14 +75,15 @@ class PluginManager:
logger.info(f"组件注册统计: {stats}")
# 返回插件数量和组件数量
return total_registered, stats.get('total_components', 0)
return total_registered, stats.get("total_components", 0)
def _find_plugin_directory(self, plugin_class) -> Optional[str]:
"""查找插件类对应的目录路径"""
try:
import inspect
module = inspect.getmodule(plugin_class)
if module and hasattr(module, '__file__') and module.__file__:
if module and hasattr(module, "__file__") and module.__file__:
return os.path.dirname(module.__file__)
except Exception:
pass
@@ -102,16 +104,16 @@ class PluginManager:
for item in os.listdir(directory):
item_path = os.path.join(directory, item)
if os.path.isfile(item_path) and item.endswith('.py') and item != '__init__.py':
if os.path.isfile(item_path) and item.endswith(".py") and item != "__init__.py":
# 单文件插件
if self._load_plugin_module_file(item_path):
loaded_count += 1
else:
failed_count += 1
elif os.path.isdir(item_path) and not item.startswith('.') and not item.startswith('__'):
elif os.path.isdir(item_path) and not item.startswith(".") and not item.startswith("__"):
# 插件包
plugin_file = os.path.join(item_path, 'plugin.py')
plugin_file = os.path.join(item_path, "plugin.py")
if os.path.exists(plugin_file):
if self._load_plugin_module_file(plugin_file):
loaded_count += 1
@@ -126,7 +128,7 @@ class PluginManager:
# 生成模块名
plugin_path = Path(plugin_file)
if plugin_path.parent.name != 'plugins':
if plugin_path.parent.name != "plugins":
# 插件包格式parent_dir.plugin
module_name = f"plugins.{plugin_path.parent.name}.plugin"
else:
@@ -144,7 +146,7 @@ class PluginManager:
spec.loader.exec_module(module)
# 模块加载成功,插件类会自动通过装饰器注册
plugin_name = plugin_path.parent.name if plugin_path.parent.name != 'plugins' else plugin_path.stem
plugin_name = plugin_path.parent.name if plugin_path.parent.name != "plugins" else plugin_path.stem
logger.debug(f"插件模块加载成功: {plugin_file}")
return True
@@ -204,7 +206,7 @@ class PluginManager:
"action_components": len(action_components),
"command_components": len(command_components),
"loaded_plugin_files": len(self.loaded_plugins),
"failed_plugin_details": self.failed_plugins.copy()
"failed_plugin_details": self.failed_plugins.copy(),
}
def reload_plugin(self, plugin_name: str) -> bool:

View File

@@ -13,8 +13,13 @@ from typing import List, Tuple, Type, Optional
# 使用简化的导入接口
from src.plugin_system import (
BasePlugin, register_plugin, BaseAction, BaseCommand,
ComponentInfo, ActionInfo, CommandInfo, ActionActivationType, ChatMode
BasePlugin,
register_plugin,
BaseAction,
BaseCommand,
ComponentInfo,
ActionActivationType,
ChatMode,
)
from src.common.logger_manager import get_logger
@@ -52,8 +57,7 @@ class HelloAction(BaseAction):
prompt = f"为用户名叫{username}的朋友生成一句温暖的个性化问候语不超过30字"
success, response, _, _ = await self.api.generate_with_model(
prompt=prompt,
model_config=first_model
prompt=prompt, model_config=first_model
)
if success:
@@ -69,9 +73,7 @@ class HelloAction(BaseAction):
# 演示存储Action执行记录到数据库
await self.api.store_action_info(
action_build_into_prompt=False,
action_prompt_display=f"问候了用户: {username}",
action_done=True
action_build_into_prompt=False, action_prompt_display=f"问候了用户: {username}", action_done=True
)
logger.info(f"{self.log_prefix} 执行问候动作: {username}")
@@ -191,5 +193,5 @@ class SimplePlugin(BasePlugin):
(HelloAction.get_action_info("hello_action", "智能问候动作,支持自定义消息和表情"), HelloAction),
(EchoCommand.get_command_info("echo_command", "回声命令,重复用户输入的消息"), EchoCommand),
(StatusCommand.get_command_info("status_command", "状态查询命令,支持多种查询类型"), StatusCommand),
(HelpCommand.get_command_info("help_command", "帮助命令,显示插件功能说明"), HelpCommand)
(HelpCommand.get_command_info("help_command", "帮助命令,显示插件功能说明"), HelpCommand),
]