🤖 自动格式化代码 [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

@@ -18,69 +18,72 @@ ActionInfo = Dict[str, Any]
class PluginActionWrapper(BaseAction): class PluginActionWrapper(BaseAction):
""" """
新插件系统Action组件的兼容性包装器 新插件系统Action组件的兼容性包装器
将新插件系统的Action组件包装为旧系统兼容的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初始化只传递它能接受的参数 # 调用旧系统BaseAction初始化只传递它能接受的参数
super().__init__( super().__init__(
action_data=action_data, action_data=action_data, reasoning=reasoning, cycle_timers=cycle_timers, thinking_id=thinking_id
reasoning=reasoning,
cycle_timers=cycle_timers,
thinking_id=thinking_id
) )
# 存储插件Action实例它已经包含了所有必要的服务对象 # 存储插件Action实例它已经包含了所有必要的服务对象
self.plugin_action = plugin_action self.plugin_action = plugin_action
self.action_name = action_name self.action_name = action_name
# 从插件Action实例复制属性到包装器 # 从插件Action实例复制属性到包装器
self._sync_attributes_from_plugin_action() self._sync_attributes_from_plugin_action()
def _sync_attributes_from_plugin_action(self): def _sync_attributes_from_plugin_action(self):
"""从插件Action实例同步属性到包装器""" """从插件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}" self.action_description = f"插件Action: {self.action_name}"
self.action_parameters = {} self.action_parameters = {}
self.action_require = [] self.action_require = []
# 激活类型属性(从新插件系统转换) # 激活类型属性(从新插件系统转换)
plugin_focus_type = getattr(self.plugin_action, 'focus_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) plugin_normal_type = getattr(self.plugin_action, "normal_activation_type", None)
if plugin_focus_type: 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: 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.random_activation_probability = getattr(self.plugin_action, "random_activation_probability", 0.0)
self.llm_judge_prompt = getattr(self.plugin_action, 'llm_judge_prompt', "") self.llm_judge_prompt = getattr(self.plugin_action, "llm_judge_prompt", "")
self.activation_keywords = getattr(self.plugin_action, 'activation_keywords', []) self.activation_keywords = getattr(self.plugin_action, "activation_keywords", [])
self.keyword_case_sensitive = getattr(self.plugin_action, 'keyword_case_sensitive', False) 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: 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 self.enable_plugin = True
async def handle_action(self) -> tuple[bool, str]: async def handle_action(self) -> tuple[bool, str]:
"""兼容旧系统的动作处理接口委托给插件Action的execute方法""" """兼容旧系统的动作处理接口委托给插件Action的execute方法"""
try: try:
# 调用插件Action的execute方法 # 调用插件Action的execute方法
success, response = await self.plugin_action.execute() success, response = await self.plugin_action.execute()
logger.debug(f"插件Action {self.action_name} 执行{'成功' if success else '失败'}: {response}") logger.debug(f"插件Action {self.action_name} 执行{'成功' if success else '失败'}: {response}")
return success, response return success, response
except Exception as e: except Exception as e:
logger.error(f"插件Action {self.action_name} 执行异常: {e}") logger.error(f"插件Action {self.action_name} 执行异常: {e}")
return False, f"插件Action执行失败: {str(e)}" return False, f"插件Action执行失败: {str(e)}"
@@ -190,36 +193,35 @@ class ActionManager:
# 从旧的_ACTION_REGISTRY获取插件动作 # 从旧的_ACTION_REGISTRY获取插件动作
self._load_registered_actions() self._load_registered_actions()
logger.debug("从旧注册表加载插件动作成功") logger.debug("从旧注册表加载插件动作成功")
# 从新插件系统获取Action组件 # 从新插件系统获取Action组件
self._load_plugin_system_actions() self._load_plugin_system_actions()
logger.debug("从新插件系统加载Action组件成功") logger.debug("从新插件系统加载Action组件成功")
except Exception as e: except Exception as e:
logger.error(f"加载插件动作失败: {e}") logger.error(f"加载插件动作失败: {e}")
def _load_plugin_system_actions(self) -> None: def _load_plugin_system_actions(self) -> None:
"""从新插件系统的component_registry加载Action组件""" """从新插件系统的component_registry加载Action组件"""
try: try:
from src.plugin_system.core.component_registry import component_registry from src.plugin_system.core.component_registry import component_registry
from src.plugin_system.base.component_types import ComponentType from src.plugin_system.base.component_types import ComponentType
# 获取所有Action组件 # 获取所有Action组件
action_components = component_registry.get_components_by_type(ComponentType.ACTION) action_components = component_registry.get_components_by_type(ComponentType.ACTION)
for action_name, action_info in action_components.items(): for action_name, action_info in action_components.items():
if action_name in self._registered_actions: if action_name in self._registered_actions:
logger.debug(f"Action组件 {action_name} 已存在,跳过") logger.debug(f"Action组件 {action_name} 已存在,跳过")
continue continue
# 将新插件系统的ActionInfo转换为旧系统格式 # 将新插件系统的ActionInfo转换为旧系统格式
converted_action_info = { converted_action_info = {
"description": action_info.description, "description": action_info.description,
"parameters": getattr(action_info, 'action_parameters', {}), "parameters": getattr(action_info, "action_parameters", {}),
"require": getattr(action_info, 'action_require', []), "require": getattr(action_info, "action_require", []),
"associated_types": getattr(action_info, 'associated_types', []), "associated_types": getattr(action_info, "associated_types", []),
"enable_plugin": action_info.enabled, "enable_plugin": action_info.enabled,
# 激活类型相关 # 激活类型相关
"focus_activation_type": action_info.focus_activation_type.value, "focus_activation_type": action_info.focus_activation_type.value,
"normal_activation_type": action_info.normal_activation_type.value, "normal_activation_type": action_info.normal_activation_type.value,
@@ -227,29 +229,30 @@ class ActionManager:
"llm_judge_prompt": action_info.llm_judge_prompt, "llm_judge_prompt": action_info.llm_judge_prompt,
"activation_keywords": action_info.activation_keywords, "activation_keywords": action_info.activation_keywords,
"keyword_case_sensitive": action_info.keyword_case_sensitive, "keyword_case_sensitive": action_info.keyword_case_sensitive,
# 模式和并行设置 # 模式和并行设置
"mode_enable": action_info.mode_enable.value, "mode_enable": action_info.mode_enable.value,
"parallel_action": action_info.parallel_action, "parallel_action": action_info.parallel_action,
# 标记这是来自新插件系统的组件 # 标记这是来自新插件系统的组件
"_plugin_system_component": True, "_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 self._registered_actions[action_name] = converted_action_info
# 如果启用,也添加到默认动作集 # 如果启用,也添加到默认动作集
if action_info.enabled: if action_info.enabled:
self._default_actions[action_name] = converted_action_info 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组件") logger.info(f"从新插件系统加载了 {len(action_components)} 个Action组件")
except Exception as e: except Exception as e:
logger.error(f"从插件系统加载Action组件失败: {e}") logger.error(f"从插件系统加载Action组件失败: {e}")
import traceback import traceback
logger.error(traceback.format_exc()) logger.error(traceback.format_exc())
def create_action( def create_action(
@@ -289,13 +292,22 @@ class ActionManager:
# if action_name not in self._using_actions: # if action_name not in self._using_actions:
# logger.warning(f"当前不可用的动作类型: {action_name}") # logger.warning(f"当前不可用的动作类型: {action_name}")
# return None # return None
# 检查是否是新插件系统的Action组件 # 检查是否是新插件系统的Action组件
action_info = self._registered_actions.get(action_name) action_info = self._registered_actions.get(action_name)
if action_info and action_info.get("_plugin_system_component", False): if action_info and action_info.get("_plugin_system_component", False):
return self._create_plugin_system_action( return self._create_plugin_system_action(
action_name, action_data, reasoning, cycle_timers, thinking_id, action_name,
observations, chat_stream, log_prefix, shutting_down, expressor, replyer action_data,
reasoning,
cycle_timers,
thinking_id,
observations,
chat_stream,
log_prefix,
shutting_down,
expressor,
replyer,
) )
# 旧系统的动作创建逻辑 # 旧系统的动作创建逻辑
@@ -324,7 +336,7 @@ class ActionManager:
except Exception as e: except Exception as e:
logger.error(f"创建动作处理器实例失败: {e}") logger.error(f"创建动作处理器实例失败: {e}")
return None return None
def _create_plugin_system_action( def _create_plugin_system_action(
self, self,
action_name: str, action_name: str,
@@ -338,7 +350,7 @@ class ActionManager:
shutting_down: bool = False, shutting_down: bool = False,
expressor: DefaultExpressor = None, expressor: DefaultExpressor = None,
replyer: DefaultReplyer = None, replyer: DefaultReplyer = None,
) -> Optional['PluginActionWrapper']: ) -> Optional["PluginActionWrapper"]:
""" """
创建新插件系统的Action组件实例并包装为兼容旧系统的接口 创建新插件系统的Action组件实例并包装为兼容旧系统的接口
@@ -347,13 +359,13 @@ class ActionManager:
""" """
try: try:
from src.plugin_system.core.component_registry import component_registry from src.plugin_system.core.component_registry import component_registry
# 获取组件类 # 获取组件类
component_class = component_registry.get_component_class(action_name) component_class = component_registry.get_component_class(action_name)
if not component_class: if not component_class:
logger.error(f"未找到插件Action组件类: {action_name}") logger.error(f"未找到插件Action组件类: {action_name}")
return None return None
# 创建插件Action实例 # 创建插件Action实例
plugin_action_instance = component_class( plugin_action_instance = component_class(
action_data=action_data, action_data=action_data,
@@ -364,9 +376,9 @@ class ActionManager:
expressor=expressor, expressor=expressor,
replyer=replyer, replyer=replyer,
observations=observations, observations=observations,
log_prefix=log_prefix log_prefix=log_prefix,
) )
# 创建兼容性包装器 # 创建兼容性包装器
wrapper = PluginActionWrapper( wrapper = PluginActionWrapper(
plugin_action=plugin_action_instance, plugin_action=plugin_action_instance,
@@ -374,15 +386,16 @@ class ActionManager:
action_data=action_data, action_data=action_data,
reasoning=reasoning, reasoning=reasoning,
cycle_timers=cycle_timers, cycle_timers=cycle_timers,
thinking_id=thinking_id thinking_id=thinking_id,
) )
logger.debug(f"创建插件Action实例成功: {action_name}") logger.debug(f"创建插件Action实例成功: {action_name}")
return wrapper return wrapper
except Exception as e: except Exception as e:
logger.error(f"创建插件Action实例失败 {action_name}: {e}") logger.error(f"创建插件Action实例失败 {action_name}: {e}")
import traceback import traceback
logger.error(traceback.format_exc()) logger.error(traceback.format_exc())
return None return None

View File

@@ -16,15 +16,15 @@ class DatabaseAPI:
""" """
async def store_action_info( async def store_action_info(
self, self,
action_build_into_prompt: bool = False, action_build_into_prompt: bool = False,
action_prompt_display: str = "", action_prompt_display: str = "",
action_done: bool = True, action_done: bool = True,
thinking_id: str = "", thinking_id: str = "",
action_data: dict = None action_data: dict = None,
) -> None: ) -> None:
"""存储action信息到数据库 """存储action信息到数据库
Args: Args:
action_build_into_prompt: 是否构建到提示中 action_build_into_prompt: 是否构建到提示中
action_prompt_display: 显示的action提示信息 action_prompt_display: 显示的action提示信息

View File

@@ -54,10 +54,10 @@ class PluginAPI(MessageAPI, LLMAPI, DatabaseAPI, ConfigAPI, UtilsAPI, StreamAPI,
} }
self.log_prefix = log_prefix self.log_prefix = log_prefix
# 存储action上下文信息 # 存储action上下文信息
self._action_context = {} self._action_context = {}
# 调用所有父类的初始化 # 调用所有父类的初始化
super().__init__() super().__init__()
@@ -97,7 +97,7 @@ class PluginAPI(MessageAPI, LLMAPI, DatabaseAPI, ConfigAPI, UtilsAPI, StreamAPI,
self._action_context["thinking_id"] = thinking_id self._action_context["thinking_id"] = thinking_id
self._action_context["shutting_down"] = shutting_down self._action_context["shutting_down"] = shutting_down
self._action_context.update(kwargs) self._action_context.update(kwargs)
def get_action_context(self, key: str, default=None): def get_action_context(self, key: str, default=None):
"""获取action上下文信息""" """获取action上下文信息"""
return self._action_context.get(key, default) return self._action_context.get(key, default)

View File

@@ -162,10 +162,10 @@ class StreamAPI:
async def wait_for_new_message(self, timeout: int = 1200) -> Tuple[bool, str]: async def wait_for_new_message(self, timeout: int = 1200) -> Tuple[bool, str]:
"""等待新消息或超时 """等待新消息或超时
Args: Args:
timeout: 超时时间默认1200秒 timeout: 超时时间默认1200秒
Returns: Returns:
Tuple[bool, str]: (是否收到新消息, 空字符串) Tuple[bool, str]: (是否收到新消息, 空字符串)
""" """
@@ -175,21 +175,21 @@ class StreamAPI:
if not observations: if not observations:
logger.warning(f"{self.log_prefix} 无法获取observations服务无法等待新消息") logger.warning(f"{self.log_prefix} 无法获取observations服务无法等待新消息")
return False, "" return False, ""
# 获取第一个观察对象通常是ChattingObservation # 获取第一个观察对象通常是ChattingObservation
observation = observations[0] if observations else None observation = observations[0] if observations else None
if not observation: if not observation:
logger.warning(f"{self.log_prefix} 无观察对象,无法等待新消息") logger.warning(f"{self.log_prefix} 无观察对象,无法等待新消息")
return False, "" return False, ""
# 从action上下文获取thinking_id # 从action上下文获取thinking_id
thinking_id = self.get_action_context("thinking_id") thinking_id = self.get_action_context("thinking_id")
if not thinking_id: if not thinking_id:
logger.warning(f"{self.log_prefix} 无thinking_id无法等待新消息") logger.warning(f"{self.log_prefix} 无thinking_id无法等待新消息")
return False, "" return False, ""
logger.info(f"{self.log_prefix} 开始等待新消息... (超时: {timeout}秒)") logger.info(f"{self.log_prefix} 开始等待新消息... (超时: {timeout}秒)")
wait_start_time = asyncio.get_event_loop().time() wait_start_time = asyncio.get_event_loop().time()
while True: while True:
# 检查关闭标志 # 检查关闭标志
@@ -197,21 +197,21 @@ class StreamAPI:
if shutting_down: if shutting_down:
logger.info(f"{self.log_prefix} 等待新消息时检测到关闭信号,中断等待") logger.info(f"{self.log_prefix} 等待新消息时检测到关闭信号,中断等待")
return False, "" return False, ""
# 检查新消息 # 检查新消息
thinking_id_timestamp = parse_thinking_id_to_timestamp(thinking_id) thinking_id_timestamp = parse_thinking_id_to_timestamp(thinking_id)
if await observation.has_new_messages_since(thinking_id_timestamp): if await observation.has_new_messages_since(thinking_id_timestamp):
logger.info(f"{self.log_prefix} 检测到新消息") logger.info(f"{self.log_prefix} 检测到新消息")
return True, "" return True, ""
# 检查超时 # 检查超时
if asyncio.get_event_loop().time() - wait_start_time > timeout: if asyncio.get_event_loop().time() - wait_start_time > timeout:
logger.warning(f"{self.log_prefix} 等待新消息超时({timeout}秒)") logger.warning(f"{self.log_prefix} 等待新消息超时({timeout}秒)")
return False, "" return False, ""
# 短暂休眠 # 短暂休眠
await asyncio.sleep(0.5) await asyncio.sleep(0.5)
except asyncio.CancelledError: except asyncio.CancelledError:
logger.info(f"{self.log_prefix} 等待新消息被中断 (CancelledError)") logger.info(f"{self.log_prefix} 等待新消息被中断 (CancelledError)")
return False, "" return False, ""

View File

@@ -11,7 +11,7 @@ class BaseAction(ABC):
"""Action组件基类 """Action组件基类
Action是插件的一种组件类型用于处理聊天中的动作逻辑 Action是插件的一种组件类型用于处理聊天中的动作逻辑
子类可以通过类属性定义激活条件,这些会在实例化时转换为实例属性: 子类可以通过类属性定义激活条件,这些会在实例化时转换为实例属性:
- focus_activation_type: 专注模式激活类型 - focus_activation_type: 专注模式激活类型
- normal_activation_type: 普通模式激活类型 - normal_activation_type: 普通模式激活类型
@@ -22,19 +22,21 @@ class BaseAction(ABC):
- random_activation_probability: 随机激活概率 - random_activation_probability: 随机激活概率
- llm_judge_prompt: LLM判断提示词 - llm_judge_prompt: LLM判断提示词
""" """
def __init__(self, def __init__(
action_data: dict, self,
reasoning: str, action_data: dict,
cycle_timers: dict, reasoning: str,
thinking_id: str, cycle_timers: dict,
observations: list = None, thinking_id: str,
expressor = None, observations: list = None,
replyer = None, expressor=None,
chat_stream = None, replyer=None,
log_prefix: str = "", chat_stream=None,
shutting_down: bool = False, log_prefix: str = "",
**kwargs): shutting_down: bool = False,
**kwargs,
):
"""初始化Action组件 """初始化Action组件
Args: Args:
@@ -56,60 +58,57 @@ class BaseAction(ABC):
self.thinking_id = thinking_id self.thinking_id = thinking_id
self.log_prefix = log_prefix self.log_prefix = log_prefix
self.shutting_down = shutting_down self.shutting_down = shutting_down
# 设置动作基本信息实例属性(兼容旧系统) # 设置动作基本信息实例属性(兼容旧系统)
self.action_name: str = getattr(self, 'action_name', self.__class__.__name__.lower().replace('action', '')) 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_description: str = getattr(self, "action_description", self.__doc__ or "Action组件")
self.action_parameters: dict = getattr(self.__class__, 'action_parameters', {}).copy() self.action_parameters: dict = getattr(self.__class__, "action_parameters", {}).copy()
self.action_require: list[str] = getattr(self.__class__, 'action_require', []).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.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.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.random_activation_probability: float = getattr(self.__class__, "random_activation_probability", 0.0)
self.llm_judge_prompt: str = getattr(self.__class__, 'llm_judge_prompt', "") self.llm_judge_prompt: str = getattr(self.__class__, "llm_judge_prompt", "")
self.activation_keywords: list[str] = getattr(self.__class__, 'activation_keywords', []).copy() self.activation_keywords: list[str] = getattr(self.__class__, "activation_keywords", []).copy()
self.keyword_case_sensitive: bool = getattr(self.__class__, 'keyword_case_sensitive', False) self.keyword_case_sensitive: bool = getattr(self.__class__, "keyword_case_sensitive", False)
self.mode_enable: str = self._get_mode_value('mode_enable', 'all') self.mode_enable: str = self._get_mode_value("mode_enable", "all")
self.parallel_action: bool = getattr(self.__class__, 'parallel_action', True) self.parallel_action: bool = getattr(self.__class__, "parallel_action", True)
self.associated_types: list[str] = getattr(self.__class__, 'associated_types', []).copy() self.associated_types: list[str] = getattr(self.__class__, "associated_types", []).copy()
self.enable_plugin: bool = True # 默认启用 self.enable_plugin: bool = True # 默认启用
# 创建API实例传递所有服务对象 # 创建API实例传递所有服务对象
self.api = PluginAPI( self.api = PluginAPI(
chat_stream=chat_stream or kwargs.get("chat_stream"), chat_stream=chat_stream or kwargs.get("chat_stream"),
expressor=expressor or kwargs.get("expressor"), expressor=expressor or kwargs.get("expressor"),
replyer=replyer or kwargs.get("replyer"), replyer=replyer or kwargs.get("replyer"),
observations=observations or kwargs.get("observations", []), observations=observations or kwargs.get("observations", []),
log_prefix=log_prefix log_prefix=log_prefix,
) )
# 设置API的action上下文 # 设置API的action上下文
self.api.set_action_context( self.api.set_action_context(thinking_id=thinking_id, shutting_down=shutting_down)
thinking_id=thinking_id,
shutting_down=shutting_down
)
logger.debug(f"{self.log_prefix} Action组件初始化完成") logger.debug(f"{self.log_prefix} Action组件初始化完成")
def _get_activation_type_value(self, attr_name: str, default: str) -> str: def _get_activation_type_value(self, attr_name: str, default: str) -> str:
"""获取激活类型的字符串值""" """获取激活类型的字符串值"""
attr = getattr(self.__class__, attr_name, None) attr = getattr(self.__class__, attr_name, None)
if attr is None: if attr is None:
return default return default
if hasattr(attr, 'value'): if hasattr(attr, "value"):
return attr.value return attr.value
return str(attr) return str(attr)
def _get_mode_value(self, attr_name: str, default: str) -> str: def _get_mode_value(self, attr_name: str, default: str) -> str:
"""获取模式的字符串值""" """获取模式的字符串值"""
attr = getattr(self.__class__, attr_name, None) attr = getattr(self.__class__, attr_name, None)
if attr is None: if attr is None:
return default return default
if hasattr(attr, 'value'): if hasattr(attr, "value"):
return attr.value return attr.value
return str(attr) return str(attr)
async def send_reply(self, content: str) -> bool: async def send_reply(self, content: str) -> bool:
"""发送回复消息 """发送回复消息
@@ -138,8 +137,8 @@ class BaseAction(ABC):
name = cls.__name__.lower().replace("action", "") name = cls.__name__.lower().replace("action", "")
if description is None: if description is None:
description = cls.__doc__ or f"{cls.__name__} Action组件" 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): def get_enum_value(attr_name, default):
attr = getattr(cls, attr_name, None) attr = getattr(cls, attr_name, None)
@@ -147,29 +146,29 @@ class BaseAction(ABC):
# 如果没有定义,返回默认的枚举值 # 如果没有定义,返回默认的枚举值
return getattr(ActionActivationType, default.upper(), ActionActivationType.NEVER) return getattr(ActionActivationType, default.upper(), ActionActivationType.NEVER)
return attr return attr
def get_mode_value(attr_name, default): def get_mode_value(attr_name, default):
attr = getattr(cls, attr_name, None) attr = getattr(cls, attr_name, None)
if attr is None: if attr is None:
return getattr(ChatMode, default.upper(), ChatMode.ALL) return getattr(ChatMode, default.upper(), ChatMode.ALL)
return attr return attr
return ActionInfo( return ActionInfo(
name=name, name=name,
component_type=ComponentType.ACTION, component_type=ComponentType.ACTION,
description=description, description=description,
focus_activation_type=get_enum_value('focus_activation_type', 'never'), focus_activation_type=get_enum_value("focus_activation_type", "never"),
normal_activation_type=get_enum_value('normal_activation_type', 'never'), normal_activation_type=get_enum_value("normal_activation_type", "never"),
activation_keywords=getattr(cls, 'activation_keywords', []).copy(), activation_keywords=getattr(cls, "activation_keywords", []).copy(),
keyword_case_sensitive=getattr(cls, 'keyword_case_sensitive', False), keyword_case_sensitive=getattr(cls, "keyword_case_sensitive", False),
mode_enable=get_mode_value('mode_enable', 'all'), mode_enable=get_mode_value("mode_enable", "all"),
parallel_action=getattr(cls, 'parallel_action', True), parallel_action=getattr(cls, "parallel_action", True),
random_activation_probability=getattr(cls, 'random_activation_probability', 0.0), random_activation_probability=getattr(cls, "random_activation_probability", 0.0),
llm_judge_prompt=getattr(cls, 'llm_judge_prompt', ""), llm_judge_prompt=getattr(cls, "llm_judge_prompt", ""),
# 使用正确的字段名 # 使用正确的字段名
action_parameters=getattr(cls, 'action_parameters', {}).copy(), action_parameters=getattr(cls, "action_parameters", {}).copy(),
action_require=getattr(cls, 'action_require', []).copy(), action_require=getattr(cls, "action_require", []).copy(),
associated_types=getattr(cls, 'associated_types', []).copy() associated_types=getattr(cls, "associated_types", []).copy(),
) )
@abstractmethod @abstractmethod
@@ -180,14 +179,14 @@ class BaseAction(ABC):
Tuple[bool, str]: (是否执行成功, 回复文本) Tuple[bool, str]: (是否执行成功, 回复文本)
""" """
pass pass
async def handle_action(self) -> Tuple[bool, str]: async def handle_action(self) -> Tuple[bool, str]:
"""兼容旧系统的handle_action接口委托给execute方法 """兼容旧系统的handle_action接口委托给execute方法
为了保持向后兼容性旧系统的代码可能会调用handle_action方法。 为了保持向后兼容性旧系统的代码可能会调用handle_action方法。
此方法将调用委托给新的execute方法。 此方法将调用委托给新的execute方法。
Returns: Returns:
Tuple[bool, str]: (是否执行成功, 回复文本) Tuple[bool, str]: (是否执行成功, 回复文本)
""" """
return await self.execute() return await self.execute()

View File

@@ -69,7 +69,7 @@ class ComponentRegistry:
self._register_action_component(component_info, component_class) self._register_action_component(component_info, component_class)
elif component_type == ComponentType.COMMAND: elif component_type == ComponentType.COMMAND:
self._register_command_component(component_info, component_class) self._register_command_component(component_info, component_class)
logger.debug(f"已注册{component_type.value}组件: {component_name} ({component_class.__name__})") logger.debug(f"已注册{component_type.value}组件: {component_name} ({component_class.__name__})")
return True return True

View File

@@ -22,10 +22,10 @@ class PluginManager:
def __init__(self): def __init__(self):
self.plugin_directories: List[str] = [] self.plugin_directories: List[str] = []
self.loaded_plugins: Dict[str, 'BasePlugin'] = {} self.loaded_plugins: Dict[str, "BasePlugin"] = {}
self.failed_plugins: Dict[str, str] = {} self.failed_plugins: Dict[str, str] = {}
self.plugin_paths: Dict[str, str] = {} # 记录插件名到目录路径的映射 self.plugin_paths: Dict[str, str] = {} # 记录插件名到目录路径的映射
logger.info("插件管理器初始化完成") logger.info("插件管理器初始化完成")
def add_plugin_directory(self, directory: str): def add_plugin_directory(self, directory: str):
@@ -43,7 +43,7 @@ class PluginManager:
tuple[int, int]: (插件数量, 组件数量) tuple[int, int]: (插件数量, 组件数量)
""" """
logger.debug("开始加载所有插件...") logger.debug("开始加载所有插件...")
# 第一阶段:加载所有插件模块(注册插件类) # 第一阶段:加载所有插件模块(注册插件类)
total_loaded_modules = 0 total_loaded_modules = 0
total_failed_modules = 0 total_failed_modules = 0
@@ -52,9 +52,9 @@ class PluginManager:
loaded, failed = self._load_plugin_modules_from_directory(directory) loaded, failed = self._load_plugin_modules_from_directory(directory)
total_loaded_modules += loaded total_loaded_modules += loaded
total_failed_modules += failed total_failed_modules += failed
logger.debug(f"插件模块加载完成 - 成功: {total_loaded_modules}, 失败: {total_failed_modules}") logger.debug(f"插件模块加载完成 - 成功: {total_loaded_modules}, 失败: {total_failed_modules}")
# 第二阶段:实例化所有已注册的插件类 # 第二阶段:实例化所有已注册的插件类
from src.plugin_system.base.base_plugin import get_registered_plugin_classes, instantiate_and_register_plugin from src.plugin_system.base.base_plugin import get_registered_plugin_classes, instantiate_and_register_plugin
@@ -65,17 +65,17 @@ class PluginManager:
for plugin_name, plugin_class in plugin_classes.items(): for plugin_name, plugin_class in plugin_classes.items():
# 使用记录的插件目录路径 # 使用记录的插件目录路径
plugin_dir = self.plugin_paths.get(plugin_name) plugin_dir = self.plugin_paths.get(plugin_name)
# 如果没有记录则尝试查找fallback # 如果没有记录则尝试查找fallback
if not plugin_dir: if not plugin_dir:
plugin_dir = self._find_plugin_directory(plugin_class) plugin_dir = self._find_plugin_directory(plugin_class)
if plugin_dir: if plugin_dir:
self.plugin_paths[plugin_name] = plugin_dir self.plugin_paths[plugin_name] = plugin_dir
if instantiate_and_register_plugin(plugin_class, plugin_dir): if instantiate_and_register_plugin(plugin_class, plugin_dir):
total_registered += 1 total_registered += 1
self.loaded_plugins[plugin_name] = plugin_class self.loaded_plugins[plugin_name] = plugin_class
# 📊 显示插件详细信息 # 📊 显示插件详细信息
plugin_info = component_registry.get_plugin_info(plugin_name) plugin_info = component_registry.get_plugin_info(plugin_name)
if plugin_info: if plugin_info:
@@ -83,28 +83,32 @@ class PluginManager:
for comp in plugin_info.components: for comp in plugin_info.components:
comp_type = comp.component_type.name comp_type = comp.component_type.name
component_types[comp_type] = component_types.get(comp_type, 0) + 1 component_types[comp_type] = component_types.get(comp_type, 0) + 1
components_str = ", ".join([f"{count}{ctype}" for ctype, count in component_types.items()]) 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: else:
logger.info(f"✅ 插件加载成功: {plugin_name}") logger.info(f"✅ 插件加载成功: {plugin_name}")
else: else:
total_failed_registration += 1 total_failed_registration += 1
self.failed_plugins[plugin_name] = "插件注册失败" self.failed_plugins[plugin_name] = "插件注册失败"
logger.error(f"❌ 插件加载失败: {plugin_name}") logger.error(f"❌ 插件加载失败: {plugin_name}")
# 获取组件统计信息 # 获取组件统计信息
stats = component_registry.get_registry_stats() stats = component_registry.get_registry_stats()
# 📋 显示插件加载总览 # 📋 显示插件加载总览
if total_registered > 0: if total_registered > 0:
action_count = stats.get('action_components', 0) action_count = stats.get("action_components", 0)
command_count = stats.get('command_components', 0) command_count = stats.get("command_components", 0)
total_components = stats.get('total_components', 0) total_components = stats.get("total_components", 0)
logger.info("🎉 插件系统加载完成!") 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("📋 已加载插件详情:") logger.info("📋 已加载插件详情:")
for plugin_name, _plugin_class in self.loaded_plugins.items(): for plugin_name, _plugin_class in self.loaded_plugins.items():
@@ -115,31 +119,31 @@ class PluginManager:
author_info = f"by {plugin_info.author}" if plugin_info.author else "" author_info = f"by {plugin_info.author}" if plugin_info.author else ""
info_parts = [part for part in [version_info, author_info] if part] info_parts = [part for part in [version_info, author_info] if part]
extra_info = f" ({', '.join(info_parts)})" if info_parts else "" extra_info = f" ({', '.join(info_parts)})" if info_parts else ""
logger.info(f" 📦 {plugin_name}{extra_info}") logger.info(f" 📦 {plugin_name}{extra_info}")
# 组件列表 # 组件列表
if plugin_info.components: if plugin_info.components:
action_components = [c for c in plugin_info.components if c.component_type.name == 'ACTION'] 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'] command_components = [c for c in plugin_info.components if c.component_type.name == "COMMAND"]
if action_components: if action_components:
action_names = [c.name for c in action_components] action_names = [c.name for c in action_components]
logger.info(f" 🎯 Action组件: {', '.join(action_names)}") logger.info(f" 🎯 Action组件: {', '.join(action_names)}")
if command_components: if command_components:
command_names = [c.name for c in command_components] command_names = [c.name for c in command_components]
logger.info(f" ⚡ Command组件: {', '.join(command_names)}") logger.info(f" ⚡ Command组件: {', '.join(command_names)}")
# 依赖信息 # 依赖信息
if plugin_info.dependencies: if plugin_info.dependencies:
logger.info(f" 🔗 依赖: {', '.join(plugin_info.dependencies)}") logger.info(f" 🔗 依赖: {', '.join(plugin_info.dependencies)}")
# 配置文件信息 # 配置文件信息
if plugin_info.config_file: if plugin_info.config_file:
config_status = "" if self.plugin_paths.get(plugin_name) else "" config_status = "" if self.plugin_paths.get(plugin_name) else ""
logger.info(f" ⚙️ 配置: {plugin_info.config_file} {config_status}") logger.info(f" ⚙️ 配置: {plugin_info.config_file} {config_status}")
# 显示目录统计 # 显示目录统计
logger.info("📂 加载目录统计:") logger.info("📂 加载目录统计:")
for directory in self.plugin_directories: for directory in self.plugin_directories:
@@ -149,12 +153,12 @@ class PluginManager:
plugin_path = self.plugin_paths.get(plugin_name, "") plugin_path = self.plugin_paths.get(plugin_name, "")
if plugin_path.startswith(directory): if plugin_path.startswith(directory):
plugins_in_dir.append(plugin_name) plugins_in_dir.append(plugin_name)
if plugins_in_dir: if plugins_in_dir:
logger.info(f" 📁 {directory}: {len(plugins_in_dir)}个插件 ({', '.join(plugins_in_dir)})") logger.info(f" 📁 {directory}: {len(plugins_in_dir)}个插件 ({', '.join(plugins_in_dir)})")
else: else:
logger.info(f" 📁 {directory}: 0个插件") logger.info(f" 📁 {directory}: 0个插件")
# 失败信息 # 失败信息
if total_failed_registration > 0: if total_failed_registration > 0:
logger.info(f"⚠️ 失败统计: {total_failed_registration}个插件加载失败") logger.info(f"⚠️ 失败统计: {total_failed_registration}个插件加载失败")
@@ -162,10 +166,10 @@ class PluginManager:
logger.info(f"{failed_plugin}: {error}") logger.info(f"{failed_plugin}: {error}")
else: else:
logger.warning("😕 没有成功加载任何插件") logger.warning("😕 没有成功加载任何插件")
# 返回插件数量和组件数量 # 返回插件数量和组件数量
return total_registered, total_components return total_registered, total_components
def _find_plugin_directory(self, plugin_class) -> Optional[str]: def _find_plugin_directory(self, plugin_class) -> Optional[str]:
"""查找插件类对应的目录路径""" """查找插件类对应的目录路径"""
try: try:
@@ -186,9 +190,9 @@ class PluginManager:
if not os.path.exists(directory): if not os.path.exists(directory):
logger.warning(f"插件目录不存在: {directory}") logger.warning(f"插件目录不存在: {directory}")
return loaded_count, failed_count return loaded_count, failed_count
logger.debug(f"正在扫描插件目录: {directory}") logger.debug(f"正在扫描插件目录: {directory}")
# 遍历目录中的所有Python文件和包 # 遍历目录中的所有Python文件和包
for item in os.listdir(directory): for item in os.listdir(directory):
item_path = os.path.join(directory, item) item_path = os.path.join(directory, item)
@@ -212,10 +216,10 @@ class PluginManager:
failed_count += 1 failed_count += 1
return loaded_count, failed_count return loaded_count, failed_count
def _load_plugin_module_file(self, plugin_file: str, plugin_name: str, plugin_dir: str) -> bool: def _load_plugin_module_file(self, plugin_file: str, plugin_name: str, plugin_dir: str) -> bool:
"""加载单个插件模块文件 """加载单个插件模块文件
Args: Args:
plugin_file: 插件文件路径 plugin_file: 插件文件路径
plugin_name: 插件名称 plugin_name: 插件名称
@@ -239,10 +243,10 @@ class PluginManager:
module = importlib.util.module_from_spec(spec) module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module) spec.loader.exec_module(module)
# 记录插件名和目录路径的映射 # 记录插件名和目录路径的映射
self.plugin_paths[plugin_name] = plugin_dir self.plugin_paths[plugin_name] = plugin_dir
logger.debug(f"插件模块加载成功: {plugin_file}") logger.debug(f"插件模块加载成功: {plugin_file}")
return True return True

View File

@@ -9,10 +9,7 @@ import re
from typing import List, Tuple, Type, Optional from typing import List, Tuple, Type, Optional
# 导入新插件系统 # 导入新插件系统
from src.plugin_system import ( from src.plugin_system import BasePlugin, register_plugin, BaseAction, ComponentInfo, ActionActivationType, ChatMode
BasePlugin, register_plugin, BaseAction,
ComponentInfo, ActionActivationType, ChatMode
)
# 导入依赖的系统组件 # 导入依赖的系统组件
from src.common.logger_manager import get_logger from src.common.logger_manager import get_logger
@@ -27,47 +24,43 @@ WAITING_TIME_THRESHOLD = 1200 # 等待新消息时间阈值,单位秒
class ReplyAction(BaseAction): class ReplyAction(BaseAction):
"""回复动作 - 参与聊天回复""" """回复动作 - 参与聊天回复"""
# 激活设置 # 激活设置
focus_activation_type = ActionActivationType.ALWAYS focus_activation_type = ActionActivationType.ALWAYS
normal_activation_type = ActionActivationType.NEVER normal_activation_type = ActionActivationType.NEVER
mode_enable = ChatMode.FOCUS mode_enable = ChatMode.FOCUS
parallel_action = False parallel_action = False
# 动作参数定义(旧系统格式) # 动作参数定义(旧系统格式)
action_parameters = { action_parameters = {
"reply_to": "如果是明确回复某个人的发言请在reply_to参数中指定格式用户名:发言内容如果不是reply_to的值设为none" "reply_to": "如果是明确回复某个人的发言请在reply_to参数中指定格式用户名:发言内容如果不是reply_to的值设为none"
} }
# 动作使用场景(旧系统字段名) # 动作使用场景(旧系统字段名)
action_require = [ action_require = ["你想要闲聊或者随便附和", "有人提到你", "如果你刚刚进行了回复,不要对同一个话题重复回应"]
"你想要闲聊或者随便附和",
"有人提到你",
"如果你刚刚进行了回复,不要对同一个话题重复回应"
]
# 关联类型 # 关联类型
associated_types = ["text"] associated_types = ["text"]
async def execute(self) -> Tuple[bool, str]: async def execute(self) -> Tuple[bool, str]:
"""执行回复动作""" """执行回复动作"""
logger.info(f"{self.log_prefix} 决定回复: {self.reasoning}") logger.info(f"{self.log_prefix} 决定回复: {self.reasoning}")
try: try:
# 获取聊天观察 # 获取聊天观察
chatting_observation = self._get_chatting_observation() chatting_observation = self._get_chatting_observation()
if not chatting_observation: if not chatting_observation:
return False, "未找到聊天观察" return False, "未找到聊天观察"
# 处理回复目标 # 处理回复目标
anchor_message = await self._resolve_reply_target(chatting_observation) anchor_message = await self._resolve_reply_target(chatting_observation)
# 获取回复器服务 # 获取回复器服务
replyer = self.api.get_service("replyer") replyer = self.api.get_service("replyer")
if not replyer: if not replyer:
logger.error(f"{self.log_prefix} 未找到回复器服务") logger.error(f"{self.log_prefix} 未找到回复器服务")
return False, "回复器服务不可用" return False, "回复器服务不可用"
# 执行回复 # 执行回复
success, reply_set = await replyer.deal_reply( success, reply_set = await replyer.deal_reply(
cycle_timers=self.cycle_timers, cycle_timers=self.cycle_timers,
@@ -76,25 +69,25 @@ class ReplyAction(BaseAction):
reasoning=self.reasoning, reasoning=self.reasoning,
thinking_id=self.thinking_id, thinking_id=self.thinking_id,
) )
# 构建回复文本 # 构建回复文本
reply_text = self._build_reply_text(reply_set) reply_text = self._build_reply_text(reply_set)
# 存储动作记录 # 存储动作记录
await self.api.store_action_info( await self.api.store_action_info(
action_build_into_prompt=False, action_build_into_prompt=False,
action_prompt_display=reply_text, action_prompt_display=reply_text,
action_done=True, action_done=True,
thinking_id=self.thinking_id, thinking_id=self.thinking_id,
action_data=self.action_data action_data=self.action_data,
) )
return success, reply_text return success, reply_text
except Exception as e: except Exception as e:
logger.error(f"{self.log_prefix} 回复动作执行失败: {e}") logger.error(f"{self.log_prefix} 回复动作执行失败: {e}")
return False, f"回复失败: {str(e)}" return False, f"回复失败: {str(e)}"
def _get_chatting_observation(self) -> Optional[ChattingObservation]: def _get_chatting_observation(self) -> Optional[ChattingObservation]:
"""获取聊天观察对象""" """获取聊天观察对象"""
observations = self.api.get_service("observations") or [] observations = self.api.get_service("observations") or []
@@ -102,11 +95,11 @@ class ReplyAction(BaseAction):
if isinstance(obs, ChattingObservation): if isinstance(obs, ChattingObservation):
return obs return obs
return None return None
async def _resolve_reply_target(self, chatting_observation: ChattingObservation): async def _resolve_reply_target(self, chatting_observation: ChattingObservation):
"""解析回复目标消息""" """解析回复目标消息"""
reply_to = self.action_data.get("reply_to", "none") reply_to = self.action_data.get("reply_to", "none")
if ":" in reply_to or "" in reply_to: if ":" in reply_to or "" in reply_to:
# 解析回复目标格式:用户名:消息内容 # 解析回复目标格式:用户名:消息内容
parts = re.split(pattern=r"[:]", string=reply_to, maxsplit=1) parts = re.split(pattern=r"[:]", string=reply_to, maxsplit=1)
@@ -118,18 +111,14 @@ class ReplyAction(BaseAction):
if chat_stream: if chat_stream:
anchor_message.update_chat_stream(chat_stream) anchor_message.update_chat_stream(chat_stream)
return anchor_message return anchor_message
# 创建空锚点消息 # 创建空锚点消息
logger.info(f"{self.log_prefix} 未找到锚点消息,创建占位符") logger.info(f"{self.log_prefix} 未找到锚点消息,创建占位符")
chat_stream = self.api.get_service("chat_stream") chat_stream = self.api.get_service("chat_stream")
if chat_stream: if chat_stream:
return await create_empty_anchor_message( return await create_empty_anchor_message(chat_stream.platform, chat_stream.group_info, chat_stream)
chat_stream.platform,
chat_stream.group_info,
chat_stream
)
return None return None
def _build_reply_text(self, reply_set) -> str: def _build_reply_text(self, reply_set) -> str:
"""构建回复文本""" """构建回复文本"""
reply_text = "" reply_text = ""
@@ -144,37 +133,35 @@ class ReplyAction(BaseAction):
class NoReplyAction(BaseAction): class NoReplyAction(BaseAction):
"""不回复动作,继承时会等待新消息或超时""" """不回复动作,继承时会等待新消息或超时"""
focus_activation_type = ActionActivationType.ALWAYS focus_activation_type = ActionActivationType.ALWAYS
normal_activation_type = ActionActivationType.NEVER normal_activation_type = ActionActivationType.NEVER
mode_enable = ChatMode.FOCUS mode_enable = ChatMode.FOCUS
parallel_action = False parallel_action = False
# 默认超时时间,将由插件在注册时设置 # 默认超时时间,将由插件在注册时设置
waiting_timeout = 1200 waiting_timeout = 1200
# 动作参数定义 # 动作参数定义
action_parameters = {} action_parameters = {}
# 动作使用场景 # 动作使用场景
action_require = [ action_require = ["你连续发送了太多消息,且无人回复", "想要暂时不回复"]
"你连续发送了太多消息,且无人回复",
"想要暂时不回复"
]
# 关联类型 # 关联类型
associated_types = [] associated_types = []
async def execute(self) -> Tuple[bool, str]: async def execute(self) -> Tuple[bool, str]:
"""执行不回复动作,等待新消息或超时""" """执行不回复动作,等待新消息或超时"""
try: try:
# 使用类属性中的超时时间 # 使用类属性中的超时时间
timeout = self.waiting_timeout timeout = self.waiting_timeout
logger.info(f"{self.log_prefix} 选择不回复,等待新消息中... (超时: {timeout}秒)") logger.info(f"{self.log_prefix} 选择不回复,等待新消息中... (超时: {timeout}秒)")
# 等待新消息或达到时间上限 # 等待新消息或达到时间上限
return await self.api.wait_for_new_message(timeout) return await self.api.wait_for_new_message(timeout)
except Exception as e: except Exception as e:
logger.error(f"{self.log_prefix} 不回复动作执行失败: {e}") logger.error(f"{self.log_prefix} 不回复动作执行失败: {e}")
return False, f"不回复动作执行失败: {e}" return False, f"不回复动作执行失败: {e}"
@@ -182,14 +169,14 @@ class NoReplyAction(BaseAction):
class EmojiAction(BaseAction): class EmojiAction(BaseAction):
"""表情动作 - 发送表情包""" """表情动作 - 发送表情包"""
# 激活设置 # 激活设置
focus_activation_type = ActionActivationType.LLM_JUDGE focus_activation_type = ActionActivationType.LLM_JUDGE
normal_activation_type = ActionActivationType.RANDOM normal_activation_type = ActionActivationType.RANDOM
mode_enable = ChatMode.ALL mode_enable = ChatMode.ALL
parallel_action = True parallel_action = True
random_activation_probability = 0.1 # 默认值,可通过配置覆盖 random_activation_probability = 0.1 # 默认值,可通过配置覆盖
# LLM判断提示词 # LLM判断提示词
llm_judge_prompt = """ llm_judge_prompt = """
判定是否需要使用表情动作的条件: 判定是否需要使用表情动作的条件:
@@ -199,37 +186,32 @@ class EmojiAction(BaseAction):
请回答"""" 请回答""""
""" """
# 动作参数定义 # 动作参数定义
action_parameters = { action_parameters = {"description": "文字描述你想要发送的表情包内容"}
"description": "文字描述你想要发送的表情包内容"
}
# 动作使用场景 # 动作使用场景
action_require = [ action_require = ["表达情绪时可以选择使用", "重点:不要连续发,如果你已经发过[表情包],就不要选择此动作"]
"表达情绪时可以选择使用",
"重点:不要连续发,如果你已经发过[表情包],就不要选择此动作"
]
# 关联类型 # 关联类型
associated_types = ["emoji"] associated_types = ["emoji"]
async def execute(self) -> Tuple[bool, str]: async def execute(self) -> Tuple[bool, str]:
"""执行表情动作""" """执行表情动作"""
logger.info(f"{self.log_prefix} 决定发送表情") logger.info(f"{self.log_prefix} 决定发送表情")
try: try:
# 创建空锚点消息 # 创建空锚点消息
anchor_message = await self._create_anchor_message() anchor_message = await self._create_anchor_message()
if not anchor_message: if not anchor_message:
return False, "无法创建锚点消息" return False, "无法创建锚点消息"
# 获取回复器服务 # 获取回复器服务
replyer = self.api.get_service("replyer") replyer = self.api.get_service("replyer")
if not replyer: if not replyer:
logger.error(f"{self.log_prefix} 未找到回复器服务") logger.error(f"{self.log_prefix} 未找到回复器服务")
return False, "回复器服务不可用" return False, "回复器服务不可用"
# 执行表情处理 # 执行表情处理
success, reply_set = await replyer.deal_emoji( success, reply_set = await replyer.deal_emoji(
cycle_timers=self.cycle_timers, cycle_timers=self.cycle_timers,
@@ -237,28 +219,24 @@ class EmojiAction(BaseAction):
anchor_message=anchor_message, anchor_message=anchor_message,
thinking_id=self.thinking_id, thinking_id=self.thinking_id,
) )
# 构建回复文本 # 构建回复文本
reply_text = self._build_reply_text(reply_set) reply_text = self._build_reply_text(reply_set)
return success, reply_text return success, reply_text
except Exception as e: except Exception as e:
logger.error(f"{self.log_prefix} 表情动作执行失败: {e}") logger.error(f"{self.log_prefix} 表情动作执行失败: {e}")
return False, f"表情发送失败: {str(e)}" return False, f"表情发送失败: {str(e)}"
async def _create_anchor_message(self): async def _create_anchor_message(self):
"""创建锚点消息""" """创建锚点消息"""
chat_stream = self.api.get_service("chat_stream") chat_stream = self.api.get_service("chat_stream")
if chat_stream: if chat_stream:
logger.info(f"{self.log_prefix} 为表情包创建占位符") logger.info(f"{self.log_prefix} 为表情包创建占位符")
return await create_empty_anchor_message( return await create_empty_anchor_message(chat_stream.platform, chat_stream.group_info, chat_stream)
chat_stream.platform,
chat_stream.group_info,
chat_stream
)
return None return None
def _build_reply_text(self, reply_set) -> str: def _build_reply_text(self, reply_set) -> str:
"""构建回复文本""" """构建回复文本"""
reply_text = "" reply_text = ""
@@ -273,13 +251,13 @@ class EmojiAction(BaseAction):
class ExitFocusChatAction(BaseAction): class ExitFocusChatAction(BaseAction):
"""退出专注聊天动作 - 从专注模式切换到普通模式""" """退出专注聊天动作 - 从专注模式切换到普通模式"""
# 激活设置 # 激活设置
focus_activation_type = ActionActivationType.LLM_JUDGE focus_activation_type = ActionActivationType.LLM_JUDGE
normal_activation_type = ActionActivationType.NEVER normal_activation_type = ActionActivationType.NEVER
mode_enable = ChatMode.FOCUS mode_enable = ChatMode.FOCUS
parallel_action = False parallel_action = False
# LLM判断提示词 # LLM判断提示词
llm_judge_prompt = """ llm_judge_prompt = """
判定是否需要退出专注聊天的条件: 判定是否需要退出专注聊天的条件:
@@ -289,38 +267,38 @@ class ExitFocusChatAction(BaseAction):
请回答"""" 请回答""""
""" """
# 动作参数定义 # 动作参数定义
action_parameters = {} action_parameters = {}
# 动作使用场景 # 动作使用场景
action_require = [ action_require = [
"很长时间没有回复,你决定退出专注聊天", "很长时间没有回复,你决定退出专注聊天",
"当前内容不需要持续专注关注,你决定退出专注聊天", "当前内容不需要持续专注关注,你决定退出专注聊天",
"聊天内容已经完成,你决定退出专注聊天" "聊天内容已经完成,你决定退出专注聊天",
] ]
# 关联类型 # 关联类型
associated_types = [] associated_types = []
async def execute(self) -> Tuple[bool, str]: async def execute(self) -> Tuple[bool, str]:
"""执行退出专注聊天动作""" """执行退出专注聊天动作"""
logger.info(f"{self.log_prefix} 决定退出专注聊天: {self.reasoning}") logger.info(f"{self.log_prefix} 决定退出专注聊天: {self.reasoning}")
try: try:
# 转换状态 - 这里返回特殊的命令标识 # 转换状态 - 这里返回特殊的命令标识
status_message = "" status_message = ""
# 通过返回值中的特殊标识来通知系统执行状态切换 # 通过返回值中的特殊标识来通知系统执行状态切换
# 系统会识别这个返回值并执行相应的状态切换逻辑 # 系统会识别这个返回值并执行相应的状态切换逻辑
self._mark_state_change() self._mark_state_change()
return True, status_message return True, status_message
except Exception as e: except Exception as e:
logger.error(f"{self.log_prefix} 退出专注聊天动作执行失败: {e}") logger.error(f"{self.log_prefix} 退出专注聊天动作执行失败: {e}")
return False, f"退出专注聊天失败: {str(e)}" return False, f"退出专注聊天失败: {str(e)}"
def _mark_state_change(self): def _mark_state_change(self):
"""标记状态切换请求""" """标记状态切换请求"""
# 通过action_data传递状态切换命令 # 通过action_data传递状态切换命令
@@ -331,13 +309,13 @@ class ExitFocusChatAction(BaseAction):
@register_plugin @register_plugin
class CoreActionsPlugin(BasePlugin): class CoreActionsPlugin(BasePlugin):
"""核心动作插件 """核心动作插件
系统内置插件,提供基础的聊天交互功能: 系统内置插件,提供基础的聊天交互功能:
- Reply: 回复动作 - Reply: 回复动作
- NoReply: 不回复动作 - NoReply: 不回复动作
- Emoji: 表情动作 - Emoji: 表情动作
""" """
# 插件基本信息 # 插件基本信息
plugin_name = "core_actions" plugin_name = "core_actions"
plugin_description = "系统核心动作插件,提供基础聊天交互功能" plugin_description = "系统核心动作插件,提供基础聊天交互功能"
@@ -345,44 +323,37 @@ class CoreActionsPlugin(BasePlugin):
plugin_author = "MaiBot团队" plugin_author = "MaiBot团队"
enable_plugin = True enable_plugin = True
config_file_name = "config.toml" config_file_name = "config.toml"
def get_plugin_components(self) -> List[Tuple[ComponentInfo, Type]]: def get_plugin_components(self) -> List[Tuple[ComponentInfo, Type]]:
"""返回插件包含的组件列表""" """返回插件包含的组件列表"""
# 从配置获取表情动作的随机概率 # 从配置获取表情动作的随机概率
emoji_chance = self.get_config("emoji.random_probability", 0.1) emoji_chance = self.get_config("emoji.random_probability", 0.1)
# 动态设置EmojiAction的随机概率 # 动态设置EmojiAction的随机概率
EmojiAction.random_activation_probability = emoji_chance EmojiAction.random_activation_probability = emoji_chance
# 从配置获取不回复动作的超时时间 # 从配置获取不回复动作的超时时间
no_reply_timeout = self.get_config("no_reply.waiting_timeout", 1200) no_reply_timeout = self.get_config("no_reply.waiting_timeout", 1200)
# 动态设置NoReplyAction的超时时间 # 动态设置NoReplyAction的超时时间
NoReplyAction.waiting_timeout = no_reply_timeout NoReplyAction.waiting_timeout = no_reply_timeout
return [ return [
# 回复动作 # 回复动作
(ReplyAction.get_action_info( (ReplyAction.get_action_info(name="reply", description="参与聊天回复,处理文本和表情的发送"), ReplyAction),
name="reply",
description="参与聊天回复,处理文本和表情的发送"
), ReplyAction),
# 不回复动作 # 不回复动作
(NoReplyAction.get_action_info( (
name="no_reply", NoReplyAction.get_action_info(name="no_reply", description="暂时不回复消息,等待新消息或超时"),
description="暂时不回复消息,等待新消息或超时" NoReplyAction,
), NoReplyAction), ),
# 表情动作 # 表情动作
(EmojiAction.get_action_info( (EmojiAction.get_action_info(name="emoji", description="发送表情包辅助表达情绪"), EmojiAction),
name="emoji",
description="发送表情包辅助表达情绪"
), EmojiAction),
# 退出专注聊天动作 # 退出专注聊天动作
(ExitFocusChatAction.get_action_info( (
name="exit_focus_chat", ExitFocusChatAction.get_action_info(
description="退出专注聊天,从专注模式切换到普通模式" name="exit_focus_chat", description="退出专注聊天,从专注模式切换到普通模式"
), ExitFocusChatAction) ),
] ExitFocusChatAction,
),
]

View File

@@ -40,12 +40,12 @@ class HelloAction(BaseAction):
async def execute(self) -> Tuple[bool, str]: async def execute(self) -> Tuple[bool, str]:
"""执行问候动作""" """执行问候动作"""
username = self.action_data.get("username", "朋友") username = self.action_data.get("username", "朋友")
# 使用默认配置值(避免创建新插件实例) # 使用默认配置值(避免创建新插件实例)
greeting_template = "你好,{username}" greeting_template = "你好,{username}"
enable_emoji = True enable_emoji = True
enable_llm = False enable_llm = False
# 如果启用LLM生成个性化问候 # 如果启用LLM生成个性化问候
if enable_llm: if enable_llm:
try: try:
@@ -116,11 +116,11 @@ class StatusCommand(BaseCommand):
"""执行状态查询命令""" """执行状态查询命令"""
# 获取匹配的参数 # 获取匹配的参数
query_type = self.matched_groups.get("type", "系统") query_type = self.matched_groups.get("type", "系统")
# 使用默认配置值(避免创建新插件实例) # 使用默认配置值(避免创建新插件实例)
show_detailed = True show_detailed = True
allowed_types = ["系统", "插件"] allowed_types = ["系统", "插件"]
if query_type not in allowed_types: if query_type not in allowed_types:
response = f"不支持的查询类型: {query_type}\n支持的类型: {', '.join(allowed_types)}" response = f"不支持的查询类型: {query_type}\n支持的类型: {', '.join(allowed_types)}"
elif show_detailed: elif show_detailed: