🤖 自动格式化代码 [skip ci]

This commit is contained in:
github-actions[bot]
2025-06-10 11:19:48 +00:00
parent 3434c2ad27
commit e4ee5ac4c7
9 changed files with 283 additions and 296 deletions

View File

@@ -22,14 +22,13 @@ class PluginActionWrapper(BaseAction):
将新插件系统的Action组件包装为旧系统兼容的BaseAction接口
"""
def __init__(self, plugin_action, action_name: str, action_data: dict, reasoning: str, cycle_timers: dict, thinking_id: str):
def __init__(
self, plugin_action, action_name: str, action_data: dict, reasoning: str, cycle_timers: dict, thinking_id: str
):
"""初始化包装器"""
# 调用旧系统BaseAction初始化只传递它能接受的参数
super().__init__(
action_data=action_data,
reasoning=reasoning,
cycle_timers=cycle_timers,
thinking_id=thinking_id
action_data=action_data, reasoning=reasoning, cycle_timers=cycle_timers, thinking_id=thinking_id
)
# 存储插件Action实例它已经包含了所有必要的服务对象
@@ -42,7 +41,7 @@ class PluginActionWrapper(BaseAction):
def _sync_attributes_from_plugin_action(self):
"""从插件Action实例同步属性到包装器"""
# 基本属性
self.action_name = getattr(self.plugin_action, 'action_name', self.action_name)
self.action_name = getattr(self.plugin_action, "action_name", self.action_name)
# 设置兼容的默认值
self.action_description = f"插件Action: {self.action_name}"
@@ -50,26 +49,30 @@ class PluginActionWrapper(BaseAction):
self.action_require = []
# 激活类型属性(从新插件系统转换)
plugin_focus_type = getattr(self.plugin_action, 'focus_activation_type', None)
plugin_normal_type = getattr(self.plugin_action, 'normal_activation_type', None)
plugin_focus_type = getattr(self.plugin_action, "focus_activation_type", None)
plugin_normal_type = getattr(self.plugin_action, "normal_activation_type", None)
if plugin_focus_type:
self.focus_activation_type = plugin_focus_type.value if hasattr(plugin_focus_type, 'value') else str(plugin_focus_type)
self.focus_activation_type = (
plugin_focus_type.value if hasattr(plugin_focus_type, "value") else str(plugin_focus_type)
)
if plugin_normal_type:
self.normal_activation_type = plugin_normal_type.value if hasattr(plugin_normal_type, 'value') else str(plugin_normal_type)
self.normal_activation_type = (
plugin_normal_type.value if hasattr(plugin_normal_type, "value") else str(plugin_normal_type)
)
# 其他属性
self.random_activation_probability = getattr(self.plugin_action, 'random_activation_probability', 0.0)
self.llm_judge_prompt = getattr(self.plugin_action, 'llm_judge_prompt', "")
self.activation_keywords = getattr(self.plugin_action, 'activation_keywords', [])
self.keyword_case_sensitive = getattr(self.plugin_action, 'keyword_case_sensitive', False)
self.random_activation_probability = getattr(self.plugin_action, "random_activation_probability", 0.0)
self.llm_judge_prompt = getattr(self.plugin_action, "llm_judge_prompt", "")
self.activation_keywords = getattr(self.plugin_action, "activation_keywords", [])
self.keyword_case_sensitive = getattr(self.plugin_action, "keyword_case_sensitive", False)
# 模式和并行设置
plugin_mode = getattr(self.plugin_action, 'mode_enable', None)
plugin_mode = getattr(self.plugin_action, "mode_enable", None)
if plugin_mode:
self.mode_enable = plugin_mode.value if hasattr(plugin_mode, 'value') else str(plugin_mode)
self.mode_enable = plugin_mode.value if hasattr(plugin_mode, "value") else str(plugin_mode)
self.parallel_action = getattr(self.plugin_action, 'parallel_action', True)
self.parallel_action = getattr(self.plugin_action, "parallel_action", True)
self.enable_plugin = True
async def handle_action(self) -> tuple[bool, str]:
@@ -215,11 +218,10 @@ class ActionManager:
# 将新插件系统的ActionInfo转换为旧系统格式
converted_action_info = {
"description": action_info.description,
"parameters": getattr(action_info, 'action_parameters', {}),
"require": getattr(action_info, 'action_require', []),
"associated_types": getattr(action_info, 'associated_types', []),
"parameters": getattr(action_info, "action_parameters", {}),
"require": getattr(action_info, "action_require", []),
"associated_types": getattr(action_info, "associated_types", []),
"enable_plugin": action_info.enabled,
# 激活类型相关
"focus_activation_type": action_info.focus_activation_type.value,
"normal_activation_type": action_info.normal_activation_type.value,
@@ -227,14 +229,12 @@ class ActionManager:
"llm_judge_prompt": action_info.llm_judge_prompt,
"activation_keywords": action_info.activation_keywords,
"keyword_case_sensitive": action_info.keyword_case_sensitive,
# 模式和并行设置
"mode_enable": action_info.mode_enable.value,
"parallel_action": action_info.parallel_action,
# 标记这是来自新插件系统的组件
"_plugin_system_component": True,
"_plugin_name": getattr(action_info, 'plugin_name', ''),
"_plugin_name": getattr(action_info, "plugin_name", ""),
}
self._registered_actions[action_name] = converted_action_info
@@ -243,13 +243,16 @@ class ActionManager:
if action_info.enabled:
self._default_actions[action_name] = converted_action_info
logger.debug(f"从插件系统加载Action组件: {action_name} (插件: {getattr(action_info, 'plugin_name', 'unknown')})")
logger.debug(
f"从插件系统加载Action组件: {action_name} (插件: {getattr(action_info, 'plugin_name', 'unknown')})"
)
logger.info(f"从新插件系统加载了 {len(action_components)} 个Action组件")
except Exception as e:
logger.error(f"从插件系统加载Action组件失败: {e}")
import traceback
logger.error(traceback.format_exc())
def create_action(
@@ -294,8 +297,17 @@ class ActionManager:
action_info = self._registered_actions.get(action_name)
if action_info and action_info.get("_plugin_system_component", False):
return self._create_plugin_system_action(
action_name, action_data, reasoning, cycle_timers, thinking_id,
observations, chat_stream, log_prefix, shutting_down, expressor, replyer
action_name,
action_data,
reasoning,
cycle_timers,
thinking_id,
observations,
chat_stream,
log_prefix,
shutting_down,
expressor,
replyer,
)
# 旧系统的动作创建逻辑
@@ -338,7 +350,7 @@ class ActionManager:
shutting_down: bool = False,
expressor: DefaultExpressor = None,
replyer: DefaultReplyer = None,
) -> Optional['PluginActionWrapper']:
) -> Optional["PluginActionWrapper"]:
"""
创建新插件系统的Action组件实例并包装为兼容旧系统的接口
@@ -364,7 +376,7 @@ class ActionManager:
expressor=expressor,
replyer=replyer,
observations=observations,
log_prefix=log_prefix
log_prefix=log_prefix,
)
# 创建兼容性包装器
@@ -374,7 +386,7 @@ class ActionManager:
action_data=action_data,
reasoning=reasoning,
cycle_timers=cycle_timers,
thinking_id=thinking_id
thinking_id=thinking_id,
)
logger.debug(f"创建插件Action实例成功: {action_name}")
@@ -383,6 +395,7 @@ class ActionManager:
except Exception as e:
logger.error(f"创建插件Action实例失败 {action_name}: {e}")
import traceback
logger.error(traceback.format_exc())
return None

View File

@@ -21,7 +21,7 @@ class DatabaseAPI:
action_prompt_display: str = "",
action_done: bool = True,
thinking_id: str = "",
action_data: dict = None
action_data: dict = None,
) -> None:
"""存储action信息到数据库

View File

@@ -23,7 +23,8 @@ class BaseAction(ABC):
- llm_judge_prompt: LLM判断提示词
"""
def __init__(self,
def __init__(
self,
action_data: dict,
reasoning: str,
cycle_timers: dict,
@@ -34,7 +35,8 @@ class BaseAction(ABC):
chat_stream=None,
log_prefix: str = "",
shutting_down: bool = False,
**kwargs):
**kwargs,
):
"""初始化Action组件
Args:
@@ -58,21 +60,21 @@ class BaseAction(ABC):
self.shutting_down = shutting_down
# 设置动作基本信息实例属性(兼容旧系统)
self.action_name: str = getattr(self, 'action_name', self.__class__.__name__.lower().replace('action', ''))
self.action_description: str = getattr(self, 'action_description', self.__doc__ or "Action组件")
self.action_parameters: dict = getattr(self.__class__, 'action_parameters', {}).copy()
self.action_require: list[str] = getattr(self.__class__, 'action_require', []).copy()
self.action_name: str = getattr(self, "action_name", self.__class__.__name__.lower().replace("action", ""))
self.action_description: str = getattr(self, "action_description", self.__doc__ or "Action组件")
self.action_parameters: dict = getattr(self.__class__, "action_parameters", {}).copy()
self.action_require: list[str] = getattr(self.__class__, "action_require", []).copy()
# 设置激活类型实例属性(从类属性复制,提供默认值)
self.focus_activation_type: str = self._get_activation_type_value('focus_activation_type', 'never')
self.normal_activation_type: str = self._get_activation_type_value('normal_activation_type', 'never')
self.random_activation_probability: float = getattr(self.__class__, 'random_activation_probability', 0.0)
self.llm_judge_prompt: str = getattr(self.__class__, 'llm_judge_prompt', "")
self.activation_keywords: list[str] = getattr(self.__class__, 'activation_keywords', []).copy()
self.keyword_case_sensitive: bool = getattr(self.__class__, 'keyword_case_sensitive', False)
self.mode_enable: str = self._get_mode_value('mode_enable', 'all')
self.parallel_action: bool = getattr(self.__class__, 'parallel_action', True)
self.associated_types: list[str] = getattr(self.__class__, 'associated_types', []).copy()
self.focus_activation_type: str = self._get_activation_type_value("focus_activation_type", "never")
self.normal_activation_type: str = self._get_activation_type_value("normal_activation_type", "never")
self.random_activation_probability: float = getattr(self.__class__, "random_activation_probability", 0.0)
self.llm_judge_prompt: str = getattr(self.__class__, "llm_judge_prompt", "")
self.activation_keywords: list[str] = getattr(self.__class__, "activation_keywords", []).copy()
self.keyword_case_sensitive: bool = getattr(self.__class__, "keyword_case_sensitive", False)
self.mode_enable: str = self._get_mode_value("mode_enable", "all")
self.parallel_action: bool = getattr(self.__class__, "parallel_action", True)
self.associated_types: list[str] = getattr(self.__class__, "associated_types", []).copy()
self.enable_plugin: bool = True # 默认启用
# 创建API实例传递所有服务对象
@@ -81,14 +83,11 @@ class BaseAction(ABC):
expressor=expressor or kwargs.get("expressor"),
replyer=replyer or kwargs.get("replyer"),
observations=observations or kwargs.get("observations", []),
log_prefix=log_prefix
log_prefix=log_prefix,
)
# 设置API的action上下文
self.api.set_action_context(
thinking_id=thinking_id,
shutting_down=shutting_down
)
self.api.set_action_context(thinking_id=thinking_id, shutting_down=shutting_down)
logger.debug(f"{self.log_prefix} Action组件初始化完成")
@@ -97,7 +96,7 @@ class BaseAction(ABC):
attr = getattr(self.__class__, attr_name, None)
if attr is None:
return default
if hasattr(attr, 'value'):
if hasattr(attr, "value"):
return attr.value
return str(attr)
@@ -106,7 +105,7 @@ class BaseAction(ABC):
attr = getattr(self.__class__, attr_name, None)
if attr is None:
return default
if hasattr(attr, 'value'):
if hasattr(attr, "value"):
return attr.value
return str(attr)
@@ -138,7 +137,7 @@ class BaseAction(ABC):
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] # 取第一行作为描述
# 安全获取激活类型值
def get_enum_value(attr_name, default):
@@ -158,18 +157,18 @@ class BaseAction(ABC):
name=name,
component_type=ComponentType.ACTION,
description=description,
focus_activation_type=get_enum_value('focus_activation_type', 'never'),
normal_activation_type=get_enum_value('normal_activation_type', 'never'),
activation_keywords=getattr(cls, 'activation_keywords', []).copy(),
keyword_case_sensitive=getattr(cls, 'keyword_case_sensitive', False),
mode_enable=get_mode_value('mode_enable', 'all'),
parallel_action=getattr(cls, 'parallel_action', True),
random_activation_probability=getattr(cls, 'random_activation_probability', 0.0),
llm_judge_prompt=getattr(cls, 'llm_judge_prompt', ""),
focus_activation_type=get_enum_value("focus_activation_type", "never"),
normal_activation_type=get_enum_value("normal_activation_type", "never"),
activation_keywords=getattr(cls, "activation_keywords", []).copy(),
keyword_case_sensitive=getattr(cls, "keyword_case_sensitive", False),
mode_enable=get_mode_value("mode_enable", "all"),
parallel_action=getattr(cls, "parallel_action", True),
random_activation_probability=getattr(cls, "random_activation_probability", 0.0),
llm_judge_prompt=getattr(cls, "llm_judge_prompt", ""),
# 使用正确的字段名
action_parameters=getattr(cls, 'action_parameters', {}).copy(),
action_require=getattr(cls, 'action_require', []).copy(),
associated_types=getattr(cls, 'associated_types', []).copy()
action_parameters=getattr(cls, "action_parameters", {}).copy(),
action_require=getattr(cls, "action_require", []).copy(),
associated_types=getattr(cls, "associated_types", []).copy(),
)
@abstractmethod

View File

@@ -22,7 +22,7 @@ class PluginManager:
def __init__(self):
self.plugin_directories: List[str] = []
self.loaded_plugins: Dict[str, 'BasePlugin'] = {}
self.loaded_plugins: Dict[str, "BasePlugin"] = {}
self.failed_plugins: Dict[str, str] = {}
self.plugin_paths: Dict[str, str] = {} # 记录插件名到目录路径的映射
@@ -85,7 +85,9 @@ class PluginManager:
component_types[comp_type] = component_types.get(comp_type, 0) + 1
components_str = ", ".join([f"{count}{ctype}" for ctype, count in component_types.items()])
logger.info(f"✅ 插件加载成功: {plugin_name} v{plugin_info.version} ({components_str}) - {plugin_info.description}")
logger.info(
f"✅ 插件加载成功: {plugin_name} v{plugin_info.version} ({components_str}) - {plugin_info.description}"
)
else:
logger.info(f"✅ 插件加载成功: {plugin_name}")
else:
@@ -98,12 +100,14 @@ class PluginManager:
# 📋 显示插件加载总览
if total_registered > 0:
action_count = stats.get('action_components', 0)
command_count = stats.get('command_components', 0)
total_components = stats.get('total_components', 0)
action_count = stats.get("action_components", 0)
command_count = stats.get("command_components", 0)
total_components = stats.get("total_components", 0)
logger.info("🎉 插件系统加载完成!")
logger.info(f"📊 总览: {total_registered}个插件, {total_components}个组件 (Action: {action_count}, Command: {command_count})")
logger.info(
f"📊 总览: {total_registered}个插件, {total_components}个组件 (Action: {action_count}, Command: {command_count})"
)
# 显示详细的插件列表
logger.info("📋 已加载插件详情:")
@@ -120,8 +124,8 @@ class PluginManager:
# 组件列表
if plugin_info.components:
action_components = [c for c in plugin_info.components if c.component_type.name == 'ACTION']
command_components = [c for c in plugin_info.components if c.component_type.name == 'COMMAND']
action_components = [c for c in plugin_info.components if c.component_type.name == "ACTION"]
command_components = [c for c in plugin_info.components if c.component_type.name == "COMMAND"]
if action_components:
action_names = [c.name for c in action_components]

View File

@@ -9,10 +9,7 @@ import re
from typing import List, Tuple, Type, Optional
# 导入新插件系统
from src.plugin_system import (
BasePlugin, register_plugin, BaseAction,
ComponentInfo, ActionActivationType, ChatMode
)
from src.plugin_system import BasePlugin, register_plugin, BaseAction, ComponentInfo, ActionActivationType, ChatMode
# 导入依赖的系统组件
from src.common.logger_manager import get_logger
@@ -40,11 +37,7 @@ class ReplyAction(BaseAction):
}
# 动作使用场景(旧系统字段名)
action_require = [
"你想要闲聊或者随便附和",
"有人提到你",
"如果你刚刚进行了回复,不要对同一个话题重复回应"
]
action_require = ["你想要闲聊或者随便附和", "有人提到你", "如果你刚刚进行了回复,不要对同一个话题重复回应"]
# 关联类型
associated_types = ["text"]
@@ -86,7 +79,7 @@ class ReplyAction(BaseAction):
action_prompt_display=reply_text,
action_done=True,
thinking_id=self.thinking_id,
action_data=self.action_data
action_data=self.action_data,
)
return success, reply_text
@@ -123,11 +116,7 @@ class ReplyAction(BaseAction):
logger.info(f"{self.log_prefix} 未找到锚点消息,创建占位符")
chat_stream = self.api.get_service("chat_stream")
if chat_stream:
return await create_empty_anchor_message(
chat_stream.platform,
chat_stream.group_info,
chat_stream
)
return await create_empty_anchor_message(chat_stream.platform, chat_stream.group_info, chat_stream)
return None
def _build_reply_text(self, reply_set) -> str:
@@ -144,6 +133,7 @@ class ReplyAction(BaseAction):
class NoReplyAction(BaseAction):
"""不回复动作,继承时会等待新消息或超时"""
focus_activation_type = ActionActivationType.ALWAYS
normal_activation_type = ActionActivationType.NEVER
mode_enable = ChatMode.FOCUS
@@ -156,10 +146,7 @@ class NoReplyAction(BaseAction):
action_parameters = {}
# 动作使用场景
action_require = [
"你连续发送了太多消息,且无人回复",
"想要暂时不回复"
]
action_require = ["你连续发送了太多消息,且无人回复", "想要暂时不回复"]
# 关联类型
associated_types = []
@@ -201,15 +188,10 @@ class EmojiAction(BaseAction):
"""
# 动作参数定义
action_parameters = {
"description": "文字描述你想要发送的表情包内容"
}
action_parameters = {"description": "文字描述你想要发送的表情包内容"}
# 动作使用场景
action_require = [
"表达情绪时可以选择使用",
"重点:不要连续发,如果你已经发过[表情包],就不要选择此动作"
]
action_require = ["表达情绪时可以选择使用", "重点:不要连续发,如果你已经发过[表情包],就不要选择此动作"]
# 关联类型
associated_types = ["emoji"]
@@ -252,11 +234,7 @@ class EmojiAction(BaseAction):
chat_stream = self.api.get_service("chat_stream")
if chat_stream:
logger.info(f"{self.log_prefix} 为表情包创建占位符")
return await create_empty_anchor_message(
chat_stream.platform,
chat_stream.group_info,
chat_stream
)
return await create_empty_anchor_message(chat_stream.platform, chat_stream.group_info, chat_stream)
return None
def _build_reply_text(self, reply_set) -> str:
@@ -297,7 +275,7 @@ class ExitFocusChatAction(BaseAction):
action_require = [
"很长时间没有回复,你决定退出专注聊天",
"当前内容不需要持续专注关注,你决定退出专注聊天",
"聊天内容已经完成,你决定退出专注聊天"
"聊天内容已经完成,你决定退出专注聊天",
]
# 关联类型
@@ -363,26 +341,19 @@ class CoreActionsPlugin(BasePlugin):
return [
# 回复动作
(ReplyAction.get_action_info(
name="reply",
description="参与聊天回复,处理文本和表情的发送"
), ReplyAction),
(ReplyAction.get_action_info(name="reply", description="参与聊天回复,处理文本和表情的发送"), ReplyAction),
# 不回复动作
(NoReplyAction.get_action_info(
name="no_reply",
description="暂时不回复消息,等待新消息或超时"
), NoReplyAction),
(
NoReplyAction.get_action_info(name="no_reply", description="暂时不回复消息,等待新消息或超时"),
NoReplyAction,
),
# 表情动作
(EmojiAction.get_action_info(
name="emoji",
description="发送表情包辅助表达情绪"
), EmojiAction),
(EmojiAction.get_action_info(name="emoji", description="发送表情包辅助表达情绪"), EmojiAction),
# 退出专注聊天动作
(ExitFocusChatAction.get_action_info(
name="exit_focus_chat",
description="退出专注聊天,从专注模式切换到普通模式"
), ExitFocusChatAction)
(
ExitFocusChatAction.get_action_info(
name="exit_focus_chat", description="退出专注聊天,从专注模式切换到普通模式"
),
ExitFocusChatAction,
),
]