🤖 自动格式化代码 [skip ci]
This commit is contained in:
@@ -29,10 +29,11 @@ EMOJI_DIR = os.path.join(BASE_DIR, "emoji") # 表情包存储目录
|
||||
EMOJI_REGISTED_DIR = os.path.join(BASE_DIR, "emoji_registed") # 已注册的表情包注册目录
|
||||
|
||||
|
||||
'''
|
||||
"""
|
||||
还没经过测试,有些地方数据库和内存数据同步可能不完全
|
||||
|
||||
'''
|
||||
"""
|
||||
|
||||
|
||||
class MaiEmoji:
|
||||
"""定义一个表情包"""
|
||||
@@ -258,7 +259,7 @@ class EmojiManager:
|
||||
if emoji.hash == hash:
|
||||
emoji.usage_count += 1
|
||||
break
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"记录表情使用失败: {str(e)}")
|
||||
|
||||
@@ -316,7 +317,9 @@ class EmojiManager:
|
||||
|
||||
time_end = time.time()
|
||||
|
||||
logger.info(f"找到[{text_emotion}]表情包,用时:{time_end - time_start:.2f}秒: {selected_emoji.description} (相似度: {similarity:.4f})")
|
||||
logger.info(
|
||||
f"找到[{text_emotion}]表情包,用时:{time_end - time_start:.2f}秒: {selected_emoji.description} (相似度: {similarity:.4f})"
|
||||
)
|
||||
return selected_emoji.path, f"[ {selected_emoji.description} ]"
|
||||
|
||||
except Exception as e:
|
||||
@@ -784,16 +787,15 @@ class EmojiManager:
|
||||
logger.error(f"[错误] 注册表情包失败: {str(e)}")
|
||||
logger.error(traceback.format_exc())
|
||||
return False
|
||||
|
||||
|
||||
|
||||
async def clear_temp_emoji(self):
|
||||
"""每天清理临时表情包
|
||||
清理/data/emoji和/data/image目录下的所有文件
|
||||
当目录中文件数超过50时,会全部删除
|
||||
"""
|
||||
|
||||
|
||||
logger.info("[清理] 开始清理临时表情包...")
|
||||
|
||||
|
||||
# 清理emoji目录
|
||||
emoji_dir = os.path.join(BASE_DIR, "emoji")
|
||||
if os.path.exists(emoji_dir):
|
||||
@@ -805,7 +807,7 @@ class EmojiManager:
|
||||
if os.path.isfile(file_path):
|
||||
os.remove(file_path)
|
||||
logger.debug(f"[清理] 删除表情包文件: {filename}")
|
||||
|
||||
|
||||
# 清理image目录
|
||||
image_dir = os.path.join(BASE_DIR, "image")
|
||||
if os.path.exists(image_dir):
|
||||
@@ -817,10 +819,8 @@ class EmojiManager:
|
||||
if os.path.isfile(file_path):
|
||||
os.remove(file_path)
|
||||
logger.debug(f"[清理] 删除图片文件: {filename}")
|
||||
|
||||
|
||||
logger.success("[清理] 临时文件清理完成")
|
||||
|
||||
|
||||
|
||||
|
||||
# 创建全局单例
|
||||
|
||||
@@ -38,31 +38,28 @@ logger = get_module_logger("HeartFCLoop", config=interest_log_config) # Logger
|
||||
|
||||
|
||||
# 默认动作定义
|
||||
DEFAULT_ACTIONS = {
|
||||
"no_reply": "不回复",
|
||||
"text_reply": "文本回复, 可选附带表情",
|
||||
"emoji_reply": "仅表情回复"
|
||||
}
|
||||
DEFAULT_ACTIONS = {"no_reply": "不回复", "text_reply": "文本回复, 可选附带表情", "emoji_reply": "仅表情回复"}
|
||||
|
||||
|
||||
class ActionManager:
|
||||
"""动作管理器:控制每次决策可以使用的动作"""
|
||||
|
||||
|
||||
def __init__(self):
|
||||
# 初始化为默认动作集
|
||||
self._available_actions: Dict[str, str] = DEFAULT_ACTIONS.copy()
|
||||
|
||||
|
||||
def get_available_actions(self) -> Dict[str, str]:
|
||||
"""获取当前可用的动作集"""
|
||||
return self._available_actions
|
||||
|
||||
|
||||
def add_action(self, action_name: str, description: str) -> bool:
|
||||
"""
|
||||
添加新的动作
|
||||
|
||||
|
||||
参数:
|
||||
action_name: 动作名称
|
||||
description: 动作描述
|
||||
|
||||
|
||||
返回:
|
||||
bool: 是否添加成功
|
||||
"""
|
||||
@@ -70,14 +67,14 @@ class ActionManager:
|
||||
return False
|
||||
self._available_actions[action_name] = description
|
||||
return True
|
||||
|
||||
|
||||
def remove_action(self, action_name: str) -> bool:
|
||||
"""
|
||||
移除指定动作
|
||||
|
||||
|
||||
参数:
|
||||
action_name: 动作名称
|
||||
|
||||
|
||||
返回:
|
||||
bool: 是否移除成功
|
||||
"""
|
||||
@@ -85,63 +82,73 @@ class ActionManager:
|
||||
return False
|
||||
del self._available_actions[action_name]
|
||||
return True
|
||||
|
||||
|
||||
def clear_actions(self):
|
||||
"""清空所有动作"""
|
||||
self._available_actions.clear()
|
||||
|
||||
|
||||
def reset_to_default(self):
|
||||
"""重置为默认动作集"""
|
||||
self._available_actions = DEFAULT_ACTIONS.copy()
|
||||
|
||||
|
||||
def get_planner_tool_definition(self) -> List[Dict[str, Any]]:
|
||||
"""获取当前动作集对应的规划器工具定义"""
|
||||
return [{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "decide_reply_action",
|
||||
"description": "根据当前聊天内容和上下文,决定机器人是否应该回复以及如何回复。",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": list(self._available_actions.keys()),
|
||||
"description": "决定采取的行动:" +
|
||||
", ".join([f"'{k}'({v})" for k, v in self._available_actions.items()]),
|
||||
},
|
||||
"reasoning": {"type": "string", "description": "做出此决定的简要理由。"},
|
||||
"emoji_query": {
|
||||
"type": "string",
|
||||
"description": "如果行动是'emoji_reply',指定表情的主题或概念。如果行动是'text_reply'且希望在文本后追加表情,也在此指定表情主题。",
|
||||
return [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "decide_reply_action",
|
||||
"description": "根据当前聊天内容和上下文,决定机器人是否应该回复以及如何回复。",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": list(self._available_actions.keys()),
|
||||
"description": "决定采取的行动:"
|
||||
+ ", ".join([f"'{k}'({v})" for k, v in self._available_actions.items()]),
|
||||
},
|
||||
"reasoning": {"type": "string", "description": "做出此决定的简要理由。"},
|
||||
"emoji_query": {
|
||||
"type": "string",
|
||||
"description": "如果行动是'emoji_reply',指定表情的主题或概念。如果行动是'text_reply'且希望在文本后追加表情,也在此指定表情主题。",
|
||||
},
|
||||
},
|
||||
"required": ["action", "reasoning"],
|
||||
},
|
||||
"required": ["action", "reasoning"],
|
||||
},
|
||||
},
|
||||
}]
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
# 在文件开头添加自定义异常类
|
||||
class HeartFCError(Exception):
|
||||
"""麦麦聊天系统基础异常类"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class PlannerError(HeartFCError):
|
||||
"""规划器异常"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class ReplierError(HeartFCError):
|
||||
"""回复器异常"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class SenderError(HeartFCError):
|
||||
"""发送器异常"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class CycleInfo:
|
||||
"""循环信息记录类"""
|
||||
|
||||
def __init__(self, cycle_id: int):
|
||||
self.cycle_id = cycle_id
|
||||
self.start_time = time.time()
|
||||
@@ -151,16 +158,16 @@ class CycleInfo:
|
||||
self.reasoning = ""
|
||||
self.timers: Dict[str, float] = {}
|
||||
self.thinking_id = ""
|
||||
|
||||
|
||||
# 添加响应信息相关字段
|
||||
self.response_info: Dict[str, Any] = {
|
||||
"response_text": [], # 回复的文本列表
|
||||
"emoji_info": "", # 表情信息
|
||||
"emoji_info": "", # 表情信息
|
||||
"anchor_message_id": "", # 锚点消息ID
|
||||
"reply_message_ids": [], # 回复消息ID列表
|
||||
"sub_mind_thinking": "", # 子思维思考内容
|
||||
}
|
||||
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""将循环信息转换为字典格式"""
|
||||
return {
|
||||
@@ -172,29 +179,31 @@ class CycleInfo:
|
||||
"reasoning": self.reasoning,
|
||||
"timers": self.timers,
|
||||
"thinking_id": self.thinking_id,
|
||||
"response_info": self.response_info
|
||||
"response_info": self.response_info,
|
||||
}
|
||||
|
||||
|
||||
def complete_cycle(self):
|
||||
"""完成循环,记录结束时间"""
|
||||
self.end_time = time.time()
|
||||
|
||||
|
||||
def set_action_info(self, action_type: str, reasoning: str, action_taken: bool):
|
||||
"""设置动作信息"""
|
||||
self.action_type = action_type
|
||||
self.reasoning = reasoning
|
||||
self.action_taken = action_taken
|
||||
|
||||
|
||||
def set_thinking_id(self, thinking_id: str):
|
||||
"""设置思考消息ID"""
|
||||
self.thinking_id = thinking_id
|
||||
|
||||
def set_response_info(self,
|
||||
response_text: Optional[List[str]] = None,
|
||||
emoji_info: Optional[str] = None,
|
||||
anchor_message_id: Optional[str] = None,
|
||||
reply_message_ids: Optional[List[str]] = None,
|
||||
sub_mind_thinking: Optional[str] = None):
|
||||
def set_response_info(
|
||||
self,
|
||||
response_text: Optional[List[str]] = None,
|
||||
emoji_info: Optional[str] = None,
|
||||
anchor_message_id: Optional[str] = None,
|
||||
reply_message_ids: Optional[List[str]] = None,
|
||||
sub_mind_thinking: Optional[str] = None,
|
||||
):
|
||||
"""设置响应信息"""
|
||||
if response_text is not None:
|
||||
self.response_info["response_text"] = response_text
|
||||
@@ -227,7 +236,7 @@ class HeartFChatting:
|
||||
self.chat_stream: Optional[ChatStream] = None # 关联的聊天流
|
||||
self.sub_mind: SubMind = sub_mind # 关联的子思维
|
||||
self.observations: List[Observation] = observations # 关联的观察列表,用于监控聊天流状态
|
||||
|
||||
|
||||
# 日志前缀
|
||||
self.log_prefix: str = f"[{chat_manager.get_stream_name(chat_id) or chat_id}]"
|
||||
|
||||
@@ -274,7 +283,7 @@ class HeartFChatting:
|
||||
|
||||
# 更新日志前缀(以防流名称发生变化)
|
||||
self.log_prefix = f"[{chat_manager.get_stream_name(self.stream_id) or self.stream_id}]"
|
||||
|
||||
|
||||
self._initialized = True
|
||||
logger.info(f"麦麦感觉到了,可以开始激情水群{self.log_prefix} ")
|
||||
return True
|
||||
@@ -333,52 +342,50 @@ class HeartFChatting:
|
||||
self._processing_lock.release()
|
||||
|
||||
async def _hfc_loop(self):
|
||||
"""主循环,持续进行计划并可能回复消息,直到被外部取消。"""
|
||||
"""主循环,持续进行计划并可能回复消息,直到被外部取消。"""
|
||||
try:
|
||||
while True: # 主循环
|
||||
# 创建新的循环信息
|
||||
self._cycle_counter += 1
|
||||
self._current_cycle = CycleInfo(self._cycle_counter)
|
||||
|
||||
|
||||
# 初始化周期状态
|
||||
cycle_timers = {}
|
||||
loop_cycle_start_time = time.monotonic()
|
||||
|
||||
|
||||
# 执行规划和处理阶段
|
||||
async with self._get_cycle_context() as acquired_lock:
|
||||
if not acquired_lock:
|
||||
continue
|
||||
|
||||
|
||||
# 记录规划开始时间点
|
||||
planner_start_db_time = time.time()
|
||||
|
||||
# 执行规划阶段
|
||||
action_taken, thinking_id = await self._think_plan_execute_loop(
|
||||
cycle_timers, planner_start_db_time
|
||||
)
|
||||
|
||||
|
||||
# 执行规划阶段
|
||||
action_taken, thinking_id = await self._think_plan_execute_loop(cycle_timers, planner_start_db_time)
|
||||
|
||||
# 更新循环信息
|
||||
self._current_cycle.set_thinking_id(thinking_id)
|
||||
self._current_cycle.timers = cycle_timers
|
||||
|
||||
# 防止循环过快消耗资源
|
||||
await self._handle_cycle_delay(action_taken, loop_cycle_start_time, self.log_prefix)
|
||||
|
||||
|
||||
# 等待直到所有消息都发送完成
|
||||
with Timer("发送消息", cycle_timers):
|
||||
while await self._should_skip_cycle(thinking_id):
|
||||
await asyncio.sleep(0.2)
|
||||
|
||||
|
||||
# 完成当前循环并保存历史
|
||||
self._current_cycle.complete_cycle()
|
||||
self._cycle_history.append(self._current_cycle)
|
||||
|
||||
|
||||
# 记录循环信息和计时器结果
|
||||
timer_strings = []
|
||||
for name, elapsed in cycle_timers.items():
|
||||
formatted_time = f"{elapsed * 1000:.2f}毫秒" if elapsed < 1 else f"{elapsed:.2f}秒"
|
||||
timer_strings.append(f"{name}: {formatted_time}")
|
||||
|
||||
|
||||
logger.debug(
|
||||
f"{self.log_prefix} 第 #{self._current_cycle.cycle_id}次思考完成,"
|
||||
f"耗时: {self._current_cycle.end_time - self._current_cycle.start_time:.2f}秒, "
|
||||
@@ -396,7 +403,7 @@ class HeartFChatting:
|
||||
async def _get_cycle_context(self):
|
||||
"""
|
||||
循环周期的上下文管理器
|
||||
|
||||
|
||||
用于确保资源的正确获取和释放:
|
||||
1. 获取处理锁
|
||||
2. 执行操作
|
||||
@@ -414,10 +421,10 @@ class HeartFChatting:
|
||||
async def _check_new_messages(self, start_time: float) -> bool:
|
||||
"""
|
||||
检查从指定时间点后是否有新消息
|
||||
|
||||
|
||||
参数:
|
||||
start_time: 开始检查的时间点
|
||||
|
||||
|
||||
返回:
|
||||
bool: 是否有新消息
|
||||
"""
|
||||
@@ -431,9 +438,7 @@ class HeartFChatting:
|
||||
logger.error(f"{self.log_prefix} 检查新消息时出错: {e}")
|
||||
return False
|
||||
|
||||
async def _think_plan_execute_loop(
|
||||
self, cycle_timers: dict, planner_start_db_time: float
|
||||
) -> tuple[bool, str]:
|
||||
async def _think_plan_execute_loop(self, cycle_timers: dict, planner_start_db_time: float) -> tuple[bool, str]:
|
||||
"""执行规划阶段"""
|
||||
try:
|
||||
# 获取子思维思考结果
|
||||
@@ -443,34 +448,36 @@ class HeartFChatting:
|
||||
# 记录子思维思考内容
|
||||
if self._current_cycle:
|
||||
self._current_cycle.set_response_info(sub_mind_thinking=current_mind)
|
||||
|
||||
|
||||
# 执行规划
|
||||
with Timer("决策", cycle_timers):
|
||||
planner_result = await self._planner(current_mind, cycle_timers)
|
||||
|
||||
|
||||
# 在获取规划结果后检查新消息
|
||||
if await self._check_new_messages(planner_start_db_time):
|
||||
# 更新循环信息
|
||||
logger.info(f"{self.log_prefix} 思考到一半,检测到新消息,重新思考")
|
||||
self._current_cycle.set_action_info("new_messages", "检测到新消息", False)
|
||||
return False, "new_messages"
|
||||
|
||||
|
||||
# 解析规划结果
|
||||
action = planner_result.get("action", "error")
|
||||
reasoning = planner_result.get("reasoning", "未提供理由")
|
||||
|
||||
|
||||
# 更新循环信息
|
||||
self._current_cycle.set_action_info(action, reasoning, True)
|
||||
|
||||
|
||||
# 处理LLM错误
|
||||
if planner_result.get("llm_error"):
|
||||
logger.error(f"{self.log_prefix} LLM失败: {reasoning}")
|
||||
return False, ""
|
||||
|
||||
|
||||
# 根据动作类型执行对应处理
|
||||
with Timer("执行", cycle_timers):
|
||||
return await self._handle_action(action, reasoning, planner_result.get("emoji_query", ""), cycle_timers, planner_start_db_time)
|
||||
|
||||
return await self._handle_action(
|
||||
action, reasoning, planner_result.get("emoji_query", ""), cycle_timers, planner_start_db_time
|
||||
)
|
||||
|
||||
except PlannerError as e:
|
||||
logger.error(f"{self.log_prefix} 规划错误: {e}")
|
||||
# 更新循环信息
|
||||
@@ -478,37 +485,32 @@ class HeartFChatting:
|
||||
return False, ""
|
||||
|
||||
async def _handle_action(
|
||||
self,
|
||||
action: str,
|
||||
reasoning: str,
|
||||
emoji_query: str,
|
||||
cycle_timers: dict,
|
||||
planner_start_db_time: float
|
||||
self, action: str, reasoning: str, emoji_query: str, cycle_timers: dict, planner_start_db_time: float
|
||||
) -> tuple[bool, str]:
|
||||
"""
|
||||
处理规划动作
|
||||
|
||||
|
||||
参数:
|
||||
action: 动作类型
|
||||
reasoning: 决策理由
|
||||
emoji_query: 表情查询
|
||||
cycle_timers: 计时器字典
|
||||
planner_start_db_time: 规划开始时间
|
||||
|
||||
|
||||
返回:
|
||||
tuple[bool, str]: (是否执行了动作, 思考消息ID)
|
||||
"""
|
||||
action_handlers = {
|
||||
"text_reply": self._handle_text_reply,
|
||||
"emoji_reply": self._handle_emoji_reply,
|
||||
"no_reply": self._handle_no_reply
|
||||
"no_reply": self._handle_no_reply,
|
||||
}
|
||||
|
||||
|
||||
handler = action_handlers.get(action)
|
||||
if not handler:
|
||||
logger.warning(f"{self.log_prefix} 未知动作: {action}, 原因: {reasoning}")
|
||||
return False, ""
|
||||
|
||||
|
||||
try:
|
||||
if action == "text_reply":
|
||||
return await handler(reasoning, emoji_query, cycle_timers)
|
||||
@@ -520,37 +522,35 @@ class HeartFChatting:
|
||||
logger.error(f"{self.log_prefix} 处理{action}时出错: {e}")
|
||||
return False, ""
|
||||
|
||||
async def _handle_text_reply(
|
||||
self, reasoning: str, emoji_query: str, cycle_timers: dict
|
||||
) -> tuple[bool, str]:
|
||||
async def _handle_text_reply(self, reasoning: str, emoji_query: str, cycle_timers: dict) -> tuple[bool, str]:
|
||||
"""
|
||||
处理文本回复
|
||||
|
||||
|
||||
工作流程:
|
||||
1. 获取锚点消息
|
||||
2. 创建思考消息
|
||||
3. 生成回复
|
||||
4. 发送消息
|
||||
|
||||
|
||||
参数:
|
||||
reasoning: 回复原因
|
||||
emoji_query: 表情查询
|
||||
cycle_timers: 计时器字典
|
||||
|
||||
|
||||
返回:
|
||||
tuple[bool, str]: (是否回复成功, 思考消息ID)
|
||||
"""
|
||||
|
||||
|
||||
# 获取锚点消息
|
||||
anchor_message = await self._get_anchor_message()
|
||||
if not anchor_message:
|
||||
raise PlannerError("无法获取锚点消息")
|
||||
|
||||
|
||||
# 创建思考消息
|
||||
thinking_id = await self._create_thinking_message(anchor_message)
|
||||
if not thinking_id:
|
||||
raise PlannerError("无法创建思考消息")
|
||||
|
||||
|
||||
try:
|
||||
# 生成回复
|
||||
with Timer("Replier", cycle_timers):
|
||||
@@ -559,10 +559,10 @@ class HeartFChatting:
|
||||
thinking_id=thinking_id,
|
||||
reason=reasoning,
|
||||
)
|
||||
|
||||
|
||||
if not reply:
|
||||
raise ReplierError("回复生成失败")
|
||||
|
||||
|
||||
# 发送消息
|
||||
with Timer("Sender", cycle_timers):
|
||||
await self._sender(
|
||||
@@ -571,9 +571,9 @@ class HeartFChatting:
|
||||
response_set=reply,
|
||||
send_emoji=emoji_query,
|
||||
)
|
||||
|
||||
|
||||
return True, thinking_id
|
||||
|
||||
|
||||
except (ReplierError, SenderError) as e:
|
||||
logger.error(f"{self.log_prefix} 回复失败: {e}")
|
||||
return True, thinking_id # 仍然返回thinking_id以便跟踪
|
||||
@@ -581,72 +581,68 @@ class HeartFChatting:
|
||||
async def _handle_emoji_reply(self, reasoning: str, emoji_query: str) -> bool:
|
||||
"""
|
||||
处理表情回复
|
||||
|
||||
|
||||
工作流程:
|
||||
1. 获取锚点消息
|
||||
2. 发送表情
|
||||
|
||||
|
||||
参数:
|
||||
reasoning: 回复原因
|
||||
emoji_query: 表情查询
|
||||
|
||||
|
||||
返回:
|
||||
bool: 是否发送成功
|
||||
"""
|
||||
logger.info(f"{self.log_prefix} 决定回复表情({emoji_query}): {reasoning}")
|
||||
|
||||
|
||||
try:
|
||||
anchor = await self._get_anchor_message()
|
||||
if not anchor:
|
||||
raise PlannerError("无法获取锚点消息")
|
||||
|
||||
|
||||
await self._handle_emoji(anchor, [], emoji_query)
|
||||
return True
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"{self.log_prefix} 表情发送失败: {e}")
|
||||
return False
|
||||
|
||||
async def _handle_no_reply(
|
||||
self, reasoning: str, planner_start_db_time: float, cycle_timers: dict
|
||||
) -> bool:
|
||||
async def _handle_no_reply(self, reasoning: str, planner_start_db_time: float, cycle_timers: dict) -> bool:
|
||||
"""
|
||||
处理不回复的情况
|
||||
|
||||
|
||||
工作流程:
|
||||
1. 等待新消息
|
||||
2. 超时或收到新消息时返回
|
||||
|
||||
|
||||
参数:
|
||||
reasoning: 不回复的原因
|
||||
planner_start_db_time: 规划开始时间
|
||||
cycle_timers: 计时器字典
|
||||
|
||||
|
||||
返回:
|
||||
bool: 是否成功处理
|
||||
"""
|
||||
logger.info(f"{self.log_prefix} 决定不回复: {reasoning}")
|
||||
|
||||
|
||||
observation = self.observations[0] if self.observations else None
|
||||
|
||||
|
||||
try:
|
||||
with Timer("Wait New Msg", cycle_timers):
|
||||
return await self._wait_for_new_message(observation, planner_start_db_time, self.log_prefix)
|
||||
except asyncio.CancelledError:
|
||||
logger.info(f"{self.log_prefix} 等待被中断")
|
||||
raise
|
||||
|
||||
async def _wait_for_new_message(
|
||||
self, observation, planner_start_db_time: float, log_prefix: str
|
||||
) -> bool:
|
||||
|
||||
async def _wait_for_new_message(self, observation, planner_start_db_time: float, log_prefix: str) -> bool:
|
||||
"""
|
||||
等待新消息
|
||||
|
||||
|
||||
参数:
|
||||
observation: 观察实例
|
||||
planner_start_db_time: 开始等待的时间
|
||||
log_prefix: 日志前缀
|
||||
|
||||
|
||||
返回:
|
||||
bool: 是否检测到新消息
|
||||
"""
|
||||
@@ -655,11 +651,11 @@ class HeartFChatting:
|
||||
if await observation.has_new_messages_since(planner_start_db_time):
|
||||
logger.info(f"{log_prefix} 检测到新消息")
|
||||
return True
|
||||
|
||||
|
||||
if time.monotonic() - wait_start_time > 60:
|
||||
logger.warning(f"{log_prefix} 等待超时(60秒)")
|
||||
return False
|
||||
|
||||
|
||||
await asyncio.sleep(1.5)
|
||||
|
||||
async def _should_skip_cycle(self, thinking_id: str) -> bool:
|
||||
@@ -677,13 +673,11 @@ class HeartFChatting:
|
||||
if timer_strings:
|
||||
logger.debug(f"{log_prefix} 该次决策耗时: {'; '.join(timer_strings)}")
|
||||
|
||||
async def _handle_cycle_delay(
|
||||
self, action_taken_this_cycle: bool, cycle_start_time: float, log_prefix: str
|
||||
):
|
||||
async def _handle_cycle_delay(self, action_taken_this_cycle: bool, cycle_start_time: float, log_prefix: str):
|
||||
"""处理循环延迟"""
|
||||
cycle_duration = time.monotonic() - cycle_start_time
|
||||
# if cycle_duration > 0.1:
|
||||
# logger.debug(f"{log_prefix} HeartFChatting: 周期耗时 {cycle_duration:.2f}s.")
|
||||
# logger.debug(f"{log_prefix} HeartFChatting: 周期耗时 {cycle_duration:.2f}s.")
|
||||
|
||||
try:
|
||||
sleep_duration = 0.0
|
||||
@@ -702,7 +696,7 @@ class HeartFChatting:
|
||||
async def _get_submind_thinking(self) -> str:
|
||||
"""
|
||||
获取子思维的思考结果
|
||||
|
||||
|
||||
返回:
|
||||
str: 思考结果,如果思考失败则返回错误信息
|
||||
"""
|
||||
@@ -719,7 +713,7 @@ class HeartFChatting:
|
||||
async def _planner(self, current_mind: str, cycle_timers: dict) -> Dict[str, Any]:
|
||||
"""
|
||||
规划器 (Planner): 使用LLM根据上下文决定是否和如何回复。
|
||||
|
||||
|
||||
参数:
|
||||
current_mind: 子思维的当前思考结果
|
||||
"""
|
||||
@@ -779,7 +773,9 @@ class HeartFChatting:
|
||||
action = arguments.get("action", "no_reply")
|
||||
# 验证动作是否在可用动作集中
|
||||
if action not in self.action_manager.get_available_actions():
|
||||
logger.warning(f"{self.log_prefix}[Planner] LLM返回了未授权的动作: {action},使用默认动作no_reply")
|
||||
logger.warning(
|
||||
f"{self.log_prefix}[Planner] LLM返回了未授权的动作: {action},使用默认动作no_reply"
|
||||
)
|
||||
action = "no_reply"
|
||||
reasoning = f"LLM返回了未授权的动作: {action}"
|
||||
else:
|
||||
@@ -787,7 +783,9 @@ class HeartFChatting:
|
||||
emoji_query = arguments.get("emoji_query", "")
|
||||
|
||||
# 记录决策结果
|
||||
logger.debug(f"{self.log_prefix}[要做什么]\nPrompt:\n{prompt}\n\n决策结果: {action}, 理由: {reasoning}, 表情查询: '{emoji_query}'")
|
||||
logger.debug(
|
||||
f"{self.log_prefix}[要做什么]\nPrompt:\n{prompt}\n\n决策结果: {action}, 理由: {reasoning}, 表情查询: '{emoji_query}'"
|
||||
)
|
||||
else:
|
||||
# 处理工具调用失败
|
||||
logger.warning(f"{self.log_prefix}[Planner] {error_msg}")
|
||||
@@ -960,9 +958,6 @@ class HeartFChatting:
|
||||
message=anchor_message, # Pass anchor_message positionally (matches 'message' parameter)
|
||||
thinking_id=thinking_id, # Pass thinking_id positionally
|
||||
)
|
||||
|
||||
|
||||
|
||||
|
||||
if not response_set:
|
||||
logger.warning(f"{self.log_prefix}[Replier-{thinking_id}] LLM生成了一个空回复集。")
|
||||
@@ -1014,8 +1009,7 @@ class HeartFChatting:
|
||||
# 记录锚点消息ID
|
||||
if self._current_cycle and anchor_message:
|
||||
self._current_cycle.set_response_info(
|
||||
response_text=response_set,
|
||||
anchor_message_id=anchor_message.message_info.message_id
|
||||
response_text=response_set, anchor_message_id=anchor_message.message_info.message_id
|
||||
)
|
||||
|
||||
chat = anchor_message.chat_stream
|
||||
@@ -1090,9 +1084,7 @@ class HeartFChatting:
|
||||
emoji_path, description = emoji_raw
|
||||
# 记录表情信息
|
||||
if self._current_cycle:
|
||||
self._current_cycle.set_response_info(
|
||||
emoji_info=f"表情: {description}, 路径: {emoji_path}"
|
||||
)
|
||||
self._current_cycle.set_response_info(emoji_info=f"表情: {description}, 路径: {emoji_path}")
|
||||
|
||||
emoji_cq = image_path_to_base64(emoji_path)
|
||||
thinking_time_point = round(time.time(), 2)
|
||||
@@ -1117,10 +1109,10 @@ class HeartFChatting:
|
||||
|
||||
def get_cycle_history(self, last_n: Optional[int] = None) -> List[Dict[str, Any]]:
|
||||
"""获取循环历史记录
|
||||
|
||||
|
||||
参数:
|
||||
last_n: 获取最近n个循环的信息,如果为None则获取所有历史记录
|
||||
|
||||
|
||||
返回:
|
||||
List[Dict[str, Any]]: 循环历史记录列表
|
||||
"""
|
||||
@@ -1134,4 +1126,3 @@ class HeartFChatting:
|
||||
if self._cycle_history:
|
||||
return self._cycle_history[-1].to_dict()
|
||||
return None
|
||||
|
||||
|
||||
@@ -24,14 +24,14 @@ logger = get_module_logger("heartflow_processor", config=processor_config)
|
||||
|
||||
class HeartFCProcessor:
|
||||
"""心流处理器,负责处理接收到的消息并计算兴趣度"""
|
||||
|
||||
|
||||
def __init__(self):
|
||||
"""初始化心流处理器,创建消息存储实例"""
|
||||
self.storage = MessageStorage()
|
||||
|
||||
async def _handle_error(self, error: Exception, context: str, message: Optional[MessageRecv] = None) -> None:
|
||||
"""统一的错误处理函数
|
||||
|
||||
|
||||
Args:
|
||||
error: 捕获到的异常
|
||||
context: 错误发生的上下文描述
|
||||
@@ -39,12 +39,12 @@ class HeartFCProcessor:
|
||||
"""
|
||||
logger.error(f"{context}: {error}")
|
||||
logger.error(traceback.format_exc())
|
||||
if message and hasattr(message, 'raw_message'):
|
||||
if message and hasattr(message, "raw_message"):
|
||||
logger.error(f"相关消息原始内容: {message.raw_message}")
|
||||
|
||||
async def _process_relationship(self, message: MessageRecv) -> None:
|
||||
"""处理用户关系逻辑
|
||||
|
||||
|
||||
Args:
|
||||
message: 消息对象,包含用户信息
|
||||
"""
|
||||
@@ -54,24 +54,20 @@ class HeartFCProcessor:
|
||||
cardname = message.message_info.user_info.user_cardname or nickname
|
||||
|
||||
is_known = await relationship_manager.is_known_some_one(platform, user_id)
|
||||
|
||||
|
||||
if not is_known:
|
||||
logger.info(f"首次认识用户: {nickname}")
|
||||
await relationship_manager.first_knowing_some_one(
|
||||
platform, user_id, nickname, cardname, ""
|
||||
)
|
||||
await relationship_manager.first_knowing_some_one(platform, user_id, nickname, cardname, "")
|
||||
elif not await relationship_manager.is_qved_name(platform, user_id):
|
||||
logger.info(f"给用户({nickname},{cardname})取名: {nickname}")
|
||||
await relationship_manager.first_knowing_some_one(
|
||||
platform, user_id, nickname, cardname, ""
|
||||
)
|
||||
await relationship_manager.first_knowing_some_one(platform, user_id, nickname, cardname, "")
|
||||
|
||||
async def _calculate_interest(self, message: MessageRecv) -> Tuple[float, bool]:
|
||||
"""计算消息的兴趣度
|
||||
|
||||
|
||||
Args:
|
||||
message: 待处理的消息对象
|
||||
|
||||
|
||||
Returns:
|
||||
Tuple[float, bool]: (兴趣度, 是否被提及)
|
||||
"""
|
||||
@@ -93,33 +89,35 @@ class HeartFCProcessor:
|
||||
|
||||
def _get_message_type(self, message: MessageRecv) -> str:
|
||||
"""获取消息类型
|
||||
|
||||
|
||||
Args:
|
||||
message: 消息对象
|
||||
|
||||
|
||||
Returns:
|
||||
str: 消息类型
|
||||
"""
|
||||
if message.message_segment.type != "seglist":
|
||||
return message.message_segment.type
|
||||
|
||||
if (isinstance(message.message_segment.data, list)
|
||||
|
||||
if (
|
||||
isinstance(message.message_segment.data, list)
|
||||
and all(isinstance(x, Seg) for x in message.message_segment.data)
|
||||
and len(message.message_segment.data) == 1):
|
||||
and len(message.message_segment.data) == 1
|
||||
):
|
||||
return message.message_segment.data[0].type
|
||||
|
||||
|
||||
return "seglist"
|
||||
|
||||
async def process_message(self, message_data: str) -> None:
|
||||
"""处理接收到的原始消息数据
|
||||
|
||||
|
||||
主要流程:
|
||||
1. 消息解析与初始化
|
||||
2. 消息缓冲处理
|
||||
3. 过滤检查
|
||||
4. 兴趣度计算
|
||||
5. 关系处理
|
||||
|
||||
|
||||
Args:
|
||||
message_data: 原始消息字符串
|
||||
"""
|
||||
@@ -133,20 +131,21 @@ class HeartFCProcessor:
|
||||
|
||||
# 2. 消息缓冲与流程序化
|
||||
await message_buffer.start_caching_messages(message)
|
||||
|
||||
|
||||
chat = await chat_manager.get_or_create_stream(
|
||||
platform=messageinfo.platform,
|
||||
user_info=userinfo,
|
||||
group_info=groupinfo,
|
||||
)
|
||||
|
||||
|
||||
subheartflow = await heartflow.create_subheartflow(chat.stream_id)
|
||||
message.update_chat_stream(chat)
|
||||
await message.process()
|
||||
|
||||
|
||||
# 3. 过滤检查
|
||||
if self._check_ban_words(message.processed_plain_text, chat, userinfo) or \
|
||||
self._check_ban_regex(message.raw_message, chat, userinfo):
|
||||
if self._check_ban_words(message.processed_plain_text, chat, userinfo) or self._check_ban_regex(
|
||||
message.raw_message, chat, userinfo
|
||||
):
|
||||
return
|
||||
|
||||
# 4. 缓冲检查
|
||||
@@ -156,7 +155,7 @@ class HeartFCProcessor:
|
||||
type_messages = {
|
||||
"text": f"触发缓冲,消息:{message.processed_plain_text}",
|
||||
"image": "触发缓冲,表情包/图片等待中",
|
||||
"seglist": "触发缓冲,消息列表等待中"
|
||||
"seglist": "触发缓冲,消息列表等待中",
|
||||
}
|
||||
logger.debug(type_messages.get(msg_type, "触发未知类型缓冲"))
|
||||
return
|
||||
@@ -189,12 +188,12 @@ class HeartFCProcessor:
|
||||
|
||||
def _check_ban_words(self, text: str, chat, userinfo) -> bool:
|
||||
"""检查消息是否包含过滤词
|
||||
|
||||
|
||||
Args:
|
||||
text: 待检查的文本
|
||||
chat: 聊天对象
|
||||
userinfo: 用户信息
|
||||
|
||||
|
||||
Returns:
|
||||
bool: 是否包含过滤词
|
||||
"""
|
||||
@@ -208,12 +207,12 @@ class HeartFCProcessor:
|
||||
|
||||
def _check_ban_regex(self, text: str, chat, userinfo) -> bool:
|
||||
"""检查消息是否匹配过滤正则表达式
|
||||
|
||||
|
||||
Args:
|
||||
text: 待检查的文本
|
||||
chat: 聊天对象
|
||||
userinfo: 用户信息
|
||||
|
||||
|
||||
Returns:
|
||||
bool: 是否匹配过滤正则
|
||||
"""
|
||||
|
||||
@@ -37,12 +37,15 @@ def init_prompt():
|
||||
{moderation_prompt}。注意:回复不要输出多余内容(包括前后缀,冒号和引号,括号,表情包,at或 @等 )。""",
|
||||
"heart_flow_prompt",
|
||||
)
|
||||
|
||||
Prompt("""
|
||||
|
||||
Prompt(
|
||||
"""
|
||||
你有以下信息可供参考:
|
||||
{structured_info}
|
||||
以上的消息是你获取到的消息,或许可以帮助你更好地回复。
|
||||
""", "info_from_tools")
|
||||
""",
|
||||
"info_from_tools",
|
||||
)
|
||||
|
||||
# Planner提示词
|
||||
Prompt(
|
||||
@@ -163,11 +166,11 @@ class PromptBuilder:
|
||||
prompt_ger += "你喜欢用倒装句"
|
||||
if random.random() < 0.02:
|
||||
prompt_ger += "你喜欢用反问句"
|
||||
|
||||
|
||||
if structured_info:
|
||||
structured_info_prompt = await global_prompt_manager.format_prompt(
|
||||
"info_from_tools",
|
||||
structured_info = structured_info)
|
||||
"info_from_tools", structured_info=structured_info
|
||||
)
|
||||
else:
|
||||
structured_info_prompt = ""
|
||||
|
||||
|
||||
@@ -303,9 +303,7 @@ async def build_readable_messages(
|
||||
)
|
||||
|
||||
readable_read_mark = translate_timestamp_to_human_readable(read_mark, mode=timestamp_mode)
|
||||
read_mark_line = (
|
||||
f"\n\n--- 以上消息已读 (标记时间: {readable_read_mark}) ---\n--- 以下新消息未读---\n"
|
||||
)
|
||||
read_mark_line = f"\n\n--- 以上消息已读 (标记时间: {readable_read_mark}) ---\n--- 以下新消息未读---\n"
|
||||
|
||||
# 组合结果,确保空部分不引入多余的标记或换行
|
||||
if formatted_before and formatted_after:
|
||||
|
||||
Reference in New Issue
Block a user