feat:继续重构插件api
This commit is contained in:
@@ -1,7 +0,0 @@
|
||||
# 导入所有动作模块以确保装饰器被执行
|
||||
from . import reply_action # noqa
|
||||
from . import no_reply_action # noqa
|
||||
from . import exit_focus_chat_action # noqa
|
||||
from . import emoji_action # noqa
|
||||
|
||||
# 在此处添加更多动作模块导入
|
||||
@@ -1,147 +0,0 @@
|
||||
from src.common.logger_manager import get_logger
|
||||
from src.chat.actions.base_action import BaseAction, register_action, ActionActivationType, ChatMode
|
||||
from typing import Tuple, List
|
||||
from src.chat.heart_flow.observation.observation import Observation
|
||||
from src.chat.focus_chat.replyer.default_replyer import DefaultReplyer
|
||||
from src.chat.message_receive.chat_stream import ChatStream
|
||||
from src.chat.focus_chat.hfc_utils import create_empty_anchor_message
|
||||
from src.config.config import global_config
|
||||
|
||||
logger = get_logger("action_taken")
|
||||
|
||||
|
||||
@register_action
|
||||
class EmojiAction(BaseAction):
|
||||
"""表情动作处理类
|
||||
|
||||
处理构建和发送消息表情的动作。
|
||||
"""
|
||||
|
||||
action_name: str = "emoji"
|
||||
action_description: str = "当你想单独发送一个表情包辅助你的回复表达"
|
||||
action_parameters: dict[str:str] = {
|
||||
"description": "文字描述你想要发送的表情包内容",
|
||||
}
|
||||
action_require: list[str] = ["表达情绪时可以选择使用", "重点:不要连续发,如果你已经发过[表情包],就不要选择此动作"]
|
||||
|
||||
associated_types: list[str] = ["emoji"]
|
||||
|
||||
enable_plugin = True
|
||||
|
||||
focus_activation_type = ActionActivationType.LLM_JUDGE
|
||||
normal_activation_type = ActionActivationType.RANDOM
|
||||
|
||||
random_activation_probability = global_config.normal_chat.emoji_chance
|
||||
|
||||
parallel_action = True
|
||||
|
||||
llm_judge_prompt = """
|
||||
判定是否需要使用表情动作的条件:
|
||||
1. 用户明确要求使用表情包
|
||||
2. 这是一个适合表达强烈情绪的场合
|
||||
3. 不要发送太多表情包,如果你已经发送过多个表情包
|
||||
"""
|
||||
|
||||
# 模式启用设置 - 表情动作只在Focus模式下使用
|
||||
mode_enable = ChatMode.ALL
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
action_data: dict,
|
||||
reasoning: str,
|
||||
cycle_timers: dict,
|
||||
thinking_id: str,
|
||||
observations: List[Observation],
|
||||
chat_stream: ChatStream,
|
||||
log_prefix: str,
|
||||
replyer: DefaultReplyer,
|
||||
**kwargs,
|
||||
):
|
||||
"""初始化回复动作处理器
|
||||
|
||||
Args:
|
||||
action_name: 动作名称
|
||||
action_data: 动作数据,包含 message, emojis, target 等
|
||||
reasoning: 执行该动作的理由
|
||||
cycle_timers: 计时器字典
|
||||
thinking_id: 思考ID
|
||||
observations: 观察列表
|
||||
replyer: 回复器
|
||||
chat_stream: 聊天流
|
||||
log_prefix: 日志前缀
|
||||
"""
|
||||
super().__init__(action_data, reasoning, cycle_timers, thinking_id)
|
||||
self.observations = observations
|
||||
self.replyer = replyer
|
||||
self.chat_stream = chat_stream
|
||||
self.log_prefix = log_prefix
|
||||
|
||||
async def handle_action(self) -> Tuple[bool, str]:
|
||||
"""
|
||||
处理回复动作
|
||||
|
||||
Returns:
|
||||
Tuple[bool, str]: (是否执行成功, 回复文本)
|
||||
"""
|
||||
# 注意: 此处可能会使用不同的expressor实现根据任务类型切换不同的回复策略
|
||||
return await self._handle_reply(
|
||||
reasoning=self.reasoning,
|
||||
reply_data=self.action_data,
|
||||
cycle_timers=self.cycle_timers,
|
||||
thinking_id=self.thinking_id,
|
||||
)
|
||||
|
||||
async def _handle_reply(
|
||||
self, reasoning: str, reply_data: dict, cycle_timers: dict, thinking_id: str
|
||||
) -> tuple[bool, str]:
|
||||
"""
|
||||
处理统一的回复动作 - 可包含文本和表情,顺序任意
|
||||
|
||||
reply_data格式:
|
||||
{
|
||||
"description": "描述你想要发送的表情"
|
||||
}
|
||||
"""
|
||||
logger.info(f"{self.log_prefix} 决定发送表情")
|
||||
# 从聊天观察获取锚定消息
|
||||
# chatting_observation: ChattingObservation = next(
|
||||
# obs for obs in self.observations if isinstance(obs, ChattingObservation)
|
||||
# )
|
||||
# if reply_data.get("target"):
|
||||
# anchor_message = chatting_observation.search_message_by_text(reply_data["target"])
|
||||
# else:
|
||||
# anchor_message = None
|
||||
|
||||
# 如果没有找到锚点消息,创建一个占位符
|
||||
# if not anchor_message:
|
||||
# logger.info(f"{self.log_prefix} 未找到锚点消息,创建占位符")
|
||||
# anchor_message = await create_empty_anchor_message(
|
||||
# self.chat_stream.platform, self.chat_stream.group_info, self.chat_stream
|
||||
# )
|
||||
# else:
|
||||
# anchor_message.update_chat_stream(self.chat_stream)
|
||||
|
||||
logger.info(f"{self.log_prefix} 为了表情包创建占位符")
|
||||
anchor_message = await create_empty_anchor_message(
|
||||
self.chat_stream.platform, self.chat_stream.group_info, self.chat_stream
|
||||
)
|
||||
|
||||
success, reply_set = await self.replyer.deal_emoji(
|
||||
cycle_timers=cycle_timers,
|
||||
action_data=reply_data,
|
||||
anchor_message=anchor_message,
|
||||
# reasoning=reasoning,
|
||||
thinking_id=thinking_id,
|
||||
)
|
||||
|
||||
reply_text = ""
|
||||
if reply_set:
|
||||
for reply in reply_set:
|
||||
type = reply[0]
|
||||
data = reply[1]
|
||||
if type == "text":
|
||||
reply_text += data
|
||||
elif type == "emoji":
|
||||
reply_text += data
|
||||
|
||||
return success, reply_text
|
||||
@@ -1,88 +0,0 @@
|
||||
import asyncio
|
||||
import traceback
|
||||
from src.common.logger_manager import get_logger
|
||||
from src.chat.actions.base_action import BaseAction, register_action, ChatMode
|
||||
from typing import Tuple, List
|
||||
from src.chat.heart_flow.observation.observation import Observation
|
||||
from src.chat.message_receive.chat_stream import ChatStream
|
||||
|
||||
logger = get_logger("action_taken")
|
||||
|
||||
|
||||
@register_action
|
||||
class ExitFocusChatAction(BaseAction):
|
||||
"""退出专注聊天动作处理类
|
||||
|
||||
处理决定退出专注聊天的动作。
|
||||
执行后会将所属的sub heartflow转变为normal_chat状态。
|
||||
"""
|
||||
|
||||
action_name = "exit_focus_chat"
|
||||
action_description = "退出专注聊天,转为普通聊天模式"
|
||||
action_parameters = {}
|
||||
action_require = [
|
||||
"很长时间没有回复,你决定退出专注聊天",
|
||||
"当前内容不需要持续专注关注,你决定退出专注聊天",
|
||||
"聊天内容已经完成,你决定退出专注聊天",
|
||||
]
|
||||
# 退出专注聊天是系统核心功能,不是插件,但默认不启用(需要特定条件触发)
|
||||
enable_plugin = False
|
||||
|
||||
# 模式启用设置 - 退出专注聊天动作只在Focus模式下使用
|
||||
mode_enable = ChatMode.FOCUS
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
action_data: dict,
|
||||
reasoning: str,
|
||||
cycle_timers: dict,
|
||||
thinking_id: str,
|
||||
observations: List[Observation],
|
||||
log_prefix: str,
|
||||
chat_stream: ChatStream,
|
||||
shutting_down: bool = False,
|
||||
**kwargs,
|
||||
):
|
||||
"""初始化退出专注聊天动作处理器
|
||||
|
||||
Args:
|
||||
action_data: 动作数据
|
||||
reasoning: 执行该动作的理由
|
||||
cycle_timers: 计时器字典
|
||||
thinking_id: 思考ID
|
||||
observations: 观察列表
|
||||
log_prefix: 日志前缀
|
||||
shutting_down: 是否正在关闭
|
||||
"""
|
||||
super().__init__(action_data, reasoning, cycle_timers, thinking_id)
|
||||
self.observations = observations
|
||||
self.log_prefix = log_prefix
|
||||
self._shutting_down = shutting_down
|
||||
|
||||
async def handle_action(self) -> Tuple[bool, str]:
|
||||
"""
|
||||
处理退出专注聊天的情况
|
||||
|
||||
工作流程:
|
||||
1. 将sub heartflow转换为normal_chat状态
|
||||
2. 等待新消息、超时或关闭信号
|
||||
3. 根据等待结果更新连续不回复计数
|
||||
4. 如果达到阈值,触发回调
|
||||
|
||||
Returns:
|
||||
Tuple[bool, str]: (是否执行成功, 状态转换消息)
|
||||
"""
|
||||
try:
|
||||
# 转换状态
|
||||
status_message = ""
|
||||
command = "stop_focus_chat"
|
||||
return True, status_message, command
|
||||
|
||||
except asyncio.CancelledError:
|
||||
logger.info(f"{self.log_prefix} 处理 'exit_focus_chat' 时等待被中断 (CancelledError)")
|
||||
raise
|
||||
except Exception as e:
|
||||
error_msg = f"处理 'exit_focus_chat' 时发生错误: {str(e)}"
|
||||
logger.error(f"{self.log_prefix} {error_msg}")
|
||||
logger.error(traceback.format_exc())
|
||||
return False, "", ""
|
||||
@@ -1,139 +0,0 @@
|
||||
import asyncio
|
||||
import traceback
|
||||
from src.common.logger_manager import get_logger
|
||||
from src.chat.utils.timer_calculator import Timer
|
||||
from src.chat.actions.base_action import BaseAction, register_action, ActionActivationType, ChatMode
|
||||
from typing import Tuple, List
|
||||
from src.chat.heart_flow.observation.observation import Observation
|
||||
from src.chat.heart_flow.observation.chatting_observation import ChattingObservation
|
||||
from src.chat.focus_chat.hfc_utils import parse_thinking_id_to_timestamp
|
||||
|
||||
logger = get_logger("action_taken")
|
||||
|
||||
# 常量定义
|
||||
WAITING_TIME_THRESHOLD = 1200 # 等待新消息时间阈值,单位秒
|
||||
|
||||
|
||||
@register_action
|
||||
class NoReplyAction(BaseAction):
|
||||
"""不回复动作处理类
|
||||
|
||||
处理决定不回复的动作。
|
||||
"""
|
||||
|
||||
action_name = "no_reply"
|
||||
action_description = "暂时不回复消息"
|
||||
action_parameters = {}
|
||||
action_require = [
|
||||
"你连续发送了太多消息,且无人回复",
|
||||
"想要休息一下",
|
||||
]
|
||||
enable_plugin = True
|
||||
|
||||
# 激活类型设置
|
||||
focus_activation_type = ActionActivationType.ALWAYS
|
||||
|
||||
# 模式启用设置 - no_reply动作只在Focus模式下使用
|
||||
mode_enable = ChatMode.FOCUS
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
action_data: dict,
|
||||
reasoning: str,
|
||||
cycle_timers: dict,
|
||||
thinking_id: str,
|
||||
observations: List[Observation],
|
||||
log_prefix: str,
|
||||
shutting_down: bool = False,
|
||||
**kwargs,
|
||||
):
|
||||
"""初始化不回复动作处理器
|
||||
|
||||
Args:
|
||||
action_name: 动作名称
|
||||
action_data: 动作数据
|
||||
reasoning: 执行该动作的理由
|
||||
cycle_timers: 计时器字典
|
||||
thinking_id: 思考ID
|
||||
observations: 观察列表
|
||||
log_prefix: 日志前缀
|
||||
shutting_down: 是否正在关闭
|
||||
"""
|
||||
super().__init__(action_data, reasoning, cycle_timers, thinking_id)
|
||||
self.observations = observations
|
||||
self.log_prefix = log_prefix
|
||||
self._shutting_down = shutting_down
|
||||
|
||||
async def handle_action(self) -> Tuple[bool, str]:
|
||||
"""
|
||||
处理不回复的情况
|
||||
|
||||
工作流程:
|
||||
1. 等待新消息、超时或关闭信号
|
||||
2. 根据等待结果更新连续不回复计数
|
||||
3. 如果达到阈值,触发回调
|
||||
|
||||
Returns:
|
||||
Tuple[bool, str]: (是否执行成功, 空字符串)
|
||||
"""
|
||||
logger.info(f"{self.log_prefix} 决定不回复: {self.reasoning}")
|
||||
|
||||
observation = self.observations[0] if self.observations else None
|
||||
|
||||
try:
|
||||
with Timer("等待新消息", self.cycle_timers):
|
||||
# 等待新消息、超时或关闭信号,并获取结果
|
||||
await self._wait_for_new_message(observation, self.thinking_id, self.log_prefix)
|
||||
|
||||
return True, "" # 不回复动作没有回复文本
|
||||
|
||||
except asyncio.CancelledError:
|
||||
logger.info(f"{self.log_prefix} 处理 'no_reply' 时等待被中断 (CancelledError)")
|
||||
raise
|
||||
except Exception as e: # 捕获调用管理器或其他地方可能发生的错误
|
||||
logger.error(f"{self.log_prefix} 处理 'no_reply' 时发生错误: {e}")
|
||||
logger.error(traceback.format_exc())
|
||||
return False, ""
|
||||
|
||||
async def _wait_for_new_message(self, observation: ChattingObservation, thinking_id: str, log_prefix: str) -> bool:
|
||||
"""
|
||||
等待新消息 或 检测到关闭信号
|
||||
|
||||
参数:
|
||||
observation: 观察实例
|
||||
thinking_id: 思考ID
|
||||
log_prefix: 日志前缀
|
||||
|
||||
返回:
|
||||
bool: 是否检测到新消息 (如果因关闭信号退出则返回 False)
|
||||
"""
|
||||
wait_start_time = asyncio.get_event_loop().time()
|
||||
while True:
|
||||
# --- 在每次循环开始时检查关闭标志 ---
|
||||
if self._shutting_down:
|
||||
logger.info(f"{log_prefix} 等待新消息时检测到关闭信号,中断等待。")
|
||||
return False # 表示因为关闭而退出
|
||||
# -----------------------------------
|
||||
|
||||
thinking_id_timestamp = parse_thinking_id_to_timestamp(thinking_id)
|
||||
|
||||
# 检查新消息
|
||||
if await observation.has_new_messages_since(thinking_id_timestamp):
|
||||
logger.info(f"{log_prefix} 检测到新消息")
|
||||
return True
|
||||
|
||||
# 检查超时 (放在检查新消息和关闭之后)
|
||||
if asyncio.get_event_loop().time() - wait_start_time > WAITING_TIME_THRESHOLD:
|
||||
logger.warning(f"{log_prefix} 等待新消息超时({WAITING_TIME_THRESHOLD}秒)")
|
||||
return False
|
||||
|
||||
try:
|
||||
# 短暂休眠,让其他任务有机会运行,并能更快响应取消或关闭
|
||||
await asyncio.sleep(0.5) # 缩短休眠时间
|
||||
except asyncio.CancelledError:
|
||||
# 如果在休眠时被取消,再次检查关闭标志
|
||||
# 如果是正常关闭,则不需要警告
|
||||
if not self._shutting_down:
|
||||
logger.warning(f"{log_prefix} _wait_for_new_message 的休眠被意外取消")
|
||||
# 无论如何,重新抛出异常,让上层处理
|
||||
raise
|
||||
@@ -1,193 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
from src.common.logger_manager import get_logger
|
||||
from src.chat.actions.base_action import BaseAction, register_action, ActionActivationType, ChatMode
|
||||
from typing import Tuple, List
|
||||
from src.chat.heart_flow.observation.observation import Observation
|
||||
from src.chat.focus_chat.replyer.default_replyer import DefaultReplyer
|
||||
from src.chat.message_receive.chat_stream import ChatStream
|
||||
from src.chat.heart_flow.observation.chatting_observation import ChattingObservation
|
||||
from src.chat.focus_chat.hfc_utils import create_empty_anchor_message
|
||||
import time
|
||||
import traceback
|
||||
from src.common.database.database_model import ActionRecords
|
||||
import re
|
||||
|
||||
logger = get_logger("action_taken")
|
||||
|
||||
|
||||
@register_action
|
||||
class ReplyAction(BaseAction):
|
||||
"""回复动作处理类
|
||||
|
||||
处理构建和发送消息回复的动作。
|
||||
"""
|
||||
|
||||
action_name: str = "reply"
|
||||
action_description: str = "当你想要参与回复或者聊天"
|
||||
action_parameters: dict[str:str] = {
|
||||
"reply_to": "如果是明确回复某个人的发言,请在reply_to参数中指定,格式:(用户名:发言内容),如果不是,reply_to的值设为none"
|
||||
}
|
||||
action_require: list[str] = [
|
||||
"你想要闲聊或者随便附和",
|
||||
"有人提到你",
|
||||
"如果你刚刚进行了回复,不要对同一个话题重复回应",
|
||||
]
|
||||
|
||||
associated_types: list[str] = ["text"]
|
||||
|
||||
enable_plugin = True
|
||||
|
||||
# 激活类型设置
|
||||
focus_activation_type = ActionActivationType.ALWAYS
|
||||
|
||||
# 模式启用设置 - 回复动作只在Focus模式下使用
|
||||
mode_enable = ChatMode.FOCUS
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
action_data: dict,
|
||||
reasoning: str,
|
||||
cycle_timers: dict,
|
||||
thinking_id: str,
|
||||
observations: List[Observation],
|
||||
chat_stream: ChatStream,
|
||||
log_prefix: str,
|
||||
replyer: DefaultReplyer,
|
||||
**kwargs,
|
||||
):
|
||||
"""初始化回复动作处理器
|
||||
|
||||
Args:
|
||||
action_name: 动作名称
|
||||
action_data: 动作数据,包含 message, emojis, target 等
|
||||
reasoning: 执行该动作的理由
|
||||
cycle_timers: 计时器字典
|
||||
thinking_id: 思考ID
|
||||
observations: 观察列表
|
||||
replyer: 回复器
|
||||
chat_stream: 聊天流
|
||||
log_prefix: 日志前缀
|
||||
"""
|
||||
super().__init__(action_data, reasoning, cycle_timers, thinking_id)
|
||||
self.observations = observations
|
||||
self.replyer = replyer
|
||||
self.chat_stream = chat_stream
|
||||
self.log_prefix = log_prefix
|
||||
|
||||
async def handle_action(self) -> Tuple[bool, str]:
|
||||
"""
|
||||
处理回复动作
|
||||
|
||||
Returns:
|
||||
Tuple[bool, str]: (是否执行成功, 回复文本)
|
||||
"""
|
||||
# 注意: 此处可能会使用不同的expressor实现根据任务类型切换不同的回复策略
|
||||
success, reply_text = await self._handle_reply(
|
||||
reasoning=self.reasoning,
|
||||
reply_data=self.action_data,
|
||||
cycle_timers=self.cycle_timers,
|
||||
thinking_id=self.thinking_id,
|
||||
)
|
||||
|
||||
await self.store_action_info(
|
||||
action_build_into_prompt=False,
|
||||
action_prompt_display=f"{reply_text}",
|
||||
)
|
||||
|
||||
return success, reply_text
|
||||
|
||||
async def _handle_reply(
|
||||
self, reasoning: str, reply_data: dict, cycle_timers: dict, thinking_id: str
|
||||
) -> tuple[bool, str]:
|
||||
"""
|
||||
处理统一的回复动作 - 可包含文本和表情,顺序任意
|
||||
|
||||
reply_data格式:
|
||||
{
|
||||
"text": "你好啊" # 文本内容列表(可选)
|
||||
"target": "锚定消息", # 锚定消息的文本内容
|
||||
}
|
||||
"""
|
||||
logger.info(f"{self.log_prefix} 决定回复: {self.reasoning}")
|
||||
|
||||
# 从聊天观察获取锚定消息
|
||||
chatting_observation: ChattingObservation = next(
|
||||
obs for obs in self.observations if isinstance(obs, ChattingObservation)
|
||||
)
|
||||
|
||||
reply_to = reply_data.get("reply_to", "none")
|
||||
|
||||
if ":" in reply_to or ":" in reply_to:
|
||||
# 使用正则表达式匹配中文或英文冒号
|
||||
parts = re.split(pattern=r"[::]", string=reply_to, maxsplit=1)
|
||||
if len(parts) == 2:
|
||||
target = parts[1].strip()
|
||||
anchor_message = chatting_observation.search_message_by_text(target)
|
||||
else:
|
||||
anchor_message = None
|
||||
|
||||
if anchor_message:
|
||||
anchor_message.update_chat_stream(self.chat_stream)
|
||||
else:
|
||||
logger.info(f"{self.log_prefix} 未找到锚点消息,创建占位符")
|
||||
anchor_message = await create_empty_anchor_message(
|
||||
self.chat_stream.platform, self.chat_stream.group_info, self.chat_stream
|
||||
)
|
||||
|
||||
success, reply_set = await self.replyer.deal_reply(
|
||||
cycle_timers=cycle_timers,
|
||||
action_data=reply_data,
|
||||
anchor_message=anchor_message,
|
||||
reasoning=reasoning,
|
||||
thinking_id=thinking_id,
|
||||
)
|
||||
|
||||
reply_text = ""
|
||||
for reply in reply_set:
|
||||
type = reply[0]
|
||||
data = reply[1]
|
||||
if type == "text":
|
||||
reply_text += data
|
||||
elif type == "emoji":
|
||||
reply_text += data
|
||||
|
||||
return success, reply_text
|
||||
|
||||
async def store_action_info(
|
||||
self, action_build_into_prompt: bool = False, action_prompt_display: str = "", action_done: bool = True
|
||||
) -> None:
|
||||
"""存储action执行信息到数据库
|
||||
|
||||
Args:
|
||||
action_build_into_prompt: 是否构建到提示中
|
||||
action_prompt_display: 动作显示内容
|
||||
"""
|
||||
try:
|
||||
chat_stream = self.chat_stream
|
||||
if not chat_stream:
|
||||
logger.error(f"{self.log_prefix} 无法存储action信息:缺少chat_stream服务")
|
||||
return
|
||||
|
||||
action_time = time.time()
|
||||
action_id = f"{action_time}_{self.thinking_id}"
|
||||
|
||||
ActionRecords.create(
|
||||
action_id=action_id,
|
||||
time=action_time,
|
||||
action_name=self.__class__.__name__,
|
||||
action_data=str(self.action_data),
|
||||
action_done=action_done,
|
||||
action_build_into_prompt=action_build_into_prompt,
|
||||
action_prompt_display=action_prompt_display,
|
||||
chat_id=chat_stream.stream_id,
|
||||
chat_info_stream_id=chat_stream.stream_id,
|
||||
chat_info_platform=chat_stream.platform,
|
||||
user_id=chat_stream.user_info.user_id if chat_stream.user_info else "",
|
||||
user_nickname=chat_stream.user_info.user_nickname if chat_stream.user_info else "",
|
||||
user_cardname=chat_stream.user_info.user_cardname if chat_stream.user_info else "",
|
||||
)
|
||||
logger.debug(f"{self.log_prefix} 已存储action信息: {action_prompt_display}")
|
||||
except Exception as e:
|
||||
logger.error(f"{self.log_prefix} 存储action信息时出错: {e}")
|
||||
traceback.print_exc()
|
||||
@@ -15,6 +15,77 @@ logger = get_logger("action_manager")
|
||||
ActionInfo = Dict[str, Any]
|
||||
|
||||
|
||||
class PluginActionWrapper(BaseAction):
|
||||
"""
|
||||
新插件系统Action组件的兼容性包装器
|
||||
|
||||
将新插件系统的Action组件包装为旧系统兼容的BaseAction接口
|
||||
"""
|
||||
|
||||
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实例(它已经包含了所有必要的服务对象)
|
||||
self.plugin_action = plugin_action
|
||||
self.action_name = action_name
|
||||
|
||||
# 从插件Action实例复制属性到包装器
|
||||
self._sync_attributes_from_plugin_action()
|
||||
|
||||
def _sync_attributes_from_plugin_action(self):
|
||||
"""从插件Action实例同步属性到包装器"""
|
||||
# 基本属性
|
||||
self.action_name = getattr(self.plugin_action, 'action_name', self.action_name)
|
||||
|
||||
# 设置兼容的默认值
|
||||
self.action_description = f"插件Action: {self.action_name}"
|
||||
self.action_parameters = {}
|
||||
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)
|
||||
|
||||
if 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.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)
|
||||
if 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.enable_plugin = True
|
||||
|
||||
async def handle_action(self) -> tuple[bool, str]:
|
||||
"""兼容旧系统的动作处理接口,委托给插件Action的execute方法"""
|
||||
try:
|
||||
# 调用插件Action的execute方法
|
||||
success, response = await self.plugin_action.execute()
|
||||
|
||||
logger.debug(f"插件Action {self.action_name} 执行{'成功' if success else '失败'}: {response}")
|
||||
return success, response
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"插件Action {self.action_name} 执行异常: {e}")
|
||||
return False, f"插件Action执行失败: {str(e)}"
|
||||
|
||||
|
||||
class ActionManager:
|
||||
"""
|
||||
动作管理器,用于管理各种类型的动作
|
||||
@@ -113,13 +184,73 @@ class ActionManager:
|
||||
加载所有插件目录中的动作
|
||||
|
||||
注意:插件动作的实际导入已经在main.py中完成,这里只需要从_ACTION_REGISTRY获取
|
||||
同时也从新插件系统的component_registry获取Action组件
|
||||
"""
|
||||
try:
|
||||
# 插件动作已在main.py中加载,这里只需要从_ACTION_REGISTRY获取
|
||||
# 从旧的_ACTION_REGISTRY获取插件动作
|
||||
self._load_registered_actions()
|
||||
logger.info("从注册表加载插件动作成功")
|
||||
logger.debug("从旧注册表加载插件动作成功")
|
||||
|
||||
# 从新插件系统获取Action组件
|
||||
self._load_plugin_system_actions()
|
||||
logger.debug("从新插件系统加载Action组件成功")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"加载插件动作失败: {e}")
|
||||
|
||||
def _load_plugin_system_actions(self) -> None:
|
||||
"""从新插件系统的component_registry加载Action组件"""
|
||||
try:
|
||||
from src.plugin_system.core.component_registry import component_registry
|
||||
from src.plugin_system.base.component_types import ComponentType
|
||||
|
||||
# 获取所有Action组件
|
||||
action_components = component_registry.get_components_by_type(ComponentType.ACTION)
|
||||
|
||||
for action_name, action_info in action_components.items():
|
||||
if action_name in self._registered_actions:
|
||||
logger.debug(f"Action组件 {action_name} 已存在,跳过")
|
||||
continue
|
||||
|
||||
# 将新插件系统的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', []),
|
||||
"enable_plugin": action_info.enabled,
|
||||
|
||||
# 激活类型相关
|
||||
"focus_activation_type": action_info.focus_activation_type.value,
|
||||
"normal_activation_type": action_info.normal_activation_type.value,
|
||||
"random_activation_probability": action_info.random_activation_probability,
|
||||
"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', ''),
|
||||
}
|
||||
|
||||
self._registered_actions[action_name] = converted_action_info
|
||||
|
||||
# 如果启用,也添加到默认动作集
|
||||
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.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(
|
||||
self,
|
||||
@@ -158,7 +289,16 @@ class ActionManager:
|
||||
# if action_name not in self._using_actions:
|
||||
# logger.warning(f"当前不可用的动作类型: {action_name}")
|
||||
# return None
|
||||
|
||||
# 检查是否是新插件系统的Action组件
|
||||
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
|
||||
)
|
||||
|
||||
# 旧系统的动作创建逻辑
|
||||
handler_class = _ACTION_REGISTRY.get(action_name)
|
||||
if not handler_class:
|
||||
logger.warning(f"未注册的动作类型: {action_name}")
|
||||
@@ -184,6 +324,67 @@ class ActionManager:
|
||||
except Exception as e:
|
||||
logger.error(f"创建动作处理器实例失败: {e}")
|
||||
return None
|
||||
|
||||
def _create_plugin_system_action(
|
||||
self,
|
||||
action_name: str,
|
||||
action_data: dict,
|
||||
reasoning: str,
|
||||
cycle_timers: dict,
|
||||
thinking_id: str,
|
||||
observations: List[Observation],
|
||||
chat_stream: ChatStream,
|
||||
log_prefix: str,
|
||||
shutting_down: bool = False,
|
||||
expressor: DefaultExpressor = None,
|
||||
replyer: DefaultReplyer = None,
|
||||
) -> Optional['PluginActionWrapper']:
|
||||
"""
|
||||
创建新插件系统的Action组件实例,并包装为兼容旧系统的接口
|
||||
|
||||
Returns:
|
||||
Optional[PluginActionWrapper]: 包装后的Action实例
|
||||
"""
|
||||
try:
|
||||
from src.plugin_system.core.component_registry import component_registry
|
||||
|
||||
# 获取组件类
|
||||
component_class = component_registry.get_component_class(action_name)
|
||||
if not component_class:
|
||||
logger.error(f"未找到插件Action组件类: {action_name}")
|
||||
return None
|
||||
|
||||
# 创建插件Action实例
|
||||
plugin_action_instance = component_class(
|
||||
action_data=action_data,
|
||||
reasoning=reasoning,
|
||||
cycle_timers=cycle_timers,
|
||||
thinking_id=thinking_id,
|
||||
chat_stream=chat_stream,
|
||||
expressor=expressor,
|
||||
replyer=replyer,
|
||||
observations=observations,
|
||||
log_prefix=log_prefix
|
||||
)
|
||||
|
||||
# 创建兼容性包装器
|
||||
wrapper = PluginActionWrapper(
|
||||
plugin_action=plugin_action_instance,
|
||||
action_name=action_name,
|
||||
action_data=action_data,
|
||||
reasoning=reasoning,
|
||||
cycle_timers=cycle_timers,
|
||||
thinking_id=thinking_id
|
||||
)
|
||||
|
||||
logger.debug(f"创建插件Action实例成功: {action_name}")
|
||||
return wrapper
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"创建插件Action实例失败 {action_name}: {e}")
|
||||
import traceback
|
||||
logger.error(traceback.format_exc())
|
||||
return None
|
||||
|
||||
def get_registered_actions(self) -> Dict[str, ActionInfo]:
|
||||
"""获取所有已注册的动作集"""
|
||||
|
||||
Reference in New Issue
Block a user