fix:优化离开focus模式的机制,完全移除Interest机制,
This commit is contained in:
@@ -92,28 +92,30 @@ class BackgroundTaskManager:
|
||||
|
||||
# 根据 chat_mode 条件添加其他任务
|
||||
if not (global_config.chat.chat_mode == "normal"):
|
||||
task_configs.extend([
|
||||
(
|
||||
self._run_cleanup_cycle,
|
||||
"info",
|
||||
f"清理任务已启动 间隔:{CLEANUP_INTERVAL_SECONDS}s",
|
||||
"_cleanup_task",
|
||||
),
|
||||
# 新增私聊激活任务配置
|
||||
(
|
||||
# Use lambda to pass the interval to the runner function
|
||||
lambda: self._run_private_chat_activation_cycle(PRIVATE_CHAT_ACTIVATION_CHECK_INTERVAL_SECONDS),
|
||||
"debug",
|
||||
f"私聊激活检查任务已启动 间隔:{PRIVATE_CHAT_ACTIVATION_CHECK_INTERVAL_SECONDS}s",
|
||||
"_private_chat_activation_task",
|
||||
),
|
||||
# (
|
||||
# self._run_into_focus_cycle,
|
||||
# "debug", # 设为debug,避免过多日志
|
||||
# f"专注评估任务已启动 间隔:{INTEREST_EVAL_INTERVAL_SECONDS}s",
|
||||
# "_into_focus_task",
|
||||
# )
|
||||
])
|
||||
task_configs.extend(
|
||||
[
|
||||
(
|
||||
self._run_cleanup_cycle,
|
||||
"info",
|
||||
f"清理任务已启动 间隔:{CLEANUP_INTERVAL_SECONDS}s",
|
||||
"_cleanup_task",
|
||||
),
|
||||
# 新增私聊激活任务配置
|
||||
(
|
||||
# Use lambda to pass the interval to the runner function
|
||||
lambda: self._run_private_chat_activation_cycle(PRIVATE_CHAT_ACTIVATION_CHECK_INTERVAL_SECONDS),
|
||||
"debug",
|
||||
f"私聊激活检查任务已启动 间隔:{PRIVATE_CHAT_ACTIVATION_CHECK_INTERVAL_SECONDS}s",
|
||||
"_private_chat_activation_task",
|
||||
),
|
||||
# (
|
||||
# self._run_into_focus_cycle,
|
||||
# "debug", # 设为debug,避免过多日志
|
||||
# f"专注评估任务已启动 间隔:{INTEREST_EVAL_INTERVAL_SECONDS}s",
|
||||
# "_into_focus_task",
|
||||
# )
|
||||
]
|
||||
)
|
||||
else:
|
||||
logger.info("聊天模式为 normal,跳过启动清理任务、私聊激活任务和专注评估任务")
|
||||
|
||||
|
||||
@@ -59,11 +59,11 @@ class Heartflow:
|
||||
|
||||
async def api_get_normal_chat_replies(self, subheartflow_id: str, limit: int = 10) -> Optional[List[dict]]:
|
||||
"""获取子心流的NormalChat回复记录
|
||||
|
||||
|
||||
Args:
|
||||
subheartflow_id: 子心流ID
|
||||
limit: 最大返回数量,默认10条
|
||||
|
||||
|
||||
Returns:
|
||||
Optional[List[dict]]: 回复记录列表,如果子心流不存在则返回None
|
||||
"""
|
||||
@@ -71,7 +71,7 @@ class Heartflow:
|
||||
if not subheartflow:
|
||||
logger.warning(f"尝试获取不存在的子心流 {subheartflow_id} 的NormalChat回复记录")
|
||||
return None
|
||||
|
||||
|
||||
return subheartflow.get_normal_chat_recent_replies(limit)
|
||||
|
||||
async def heartflow_start_working(self):
|
||||
|
||||
@@ -20,9 +20,9 @@ MAX_REPLY_PROBABILITY = 1
|
||||
class InterestChatting:
|
||||
def __init__(
|
||||
self,
|
||||
decay_rate=global_config.focus_chat.default_decay_rate_per_second,
|
||||
decay_rate=0.95,
|
||||
max_interest=MAX_INTEREST,
|
||||
trigger_threshold=global_config.focus_chat.reply_trigger_threshold,
|
||||
trigger_threshold=4,
|
||||
max_probability=MAX_REPLY_PROBABILITY,
|
||||
):
|
||||
# 基础属性初始化
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
from datetime import datetime
|
||||
from src.llm_models.utils_model import LLMRequest
|
||||
from src.config.config import global_config
|
||||
import traceback
|
||||
from src.chat.utils.chat_message_builder import (
|
||||
|
||||
@@ -12,7 +12,6 @@ from src.chat.normal_chat.normal_chat import NormalChat
|
||||
from src.chat.heart_flow.mai_state_manager import MaiStateInfo
|
||||
from src.chat.heart_flow.chat_state_info import ChatState, ChatStateInfo
|
||||
from .utils_chat import get_chat_type_and_target_info
|
||||
from .interest_chatting import InterestChatting
|
||||
from src.config.config import global_config
|
||||
|
||||
|
||||
@@ -51,7 +50,7 @@ class SubHeartflow:
|
||||
# --- End Initialization ---
|
||||
|
||||
# 兴趣检测器
|
||||
self.interest_chatting: InterestChatting = InterestChatting()
|
||||
self.interest_dict: Dict[str, tuple[MessageRecv, float, bool]] = {}
|
||||
|
||||
# 活动状态管理
|
||||
self.should_stop = False # 停止标志
|
||||
@@ -85,8 +84,8 @@ class SubHeartflow:
|
||||
# --- End using utility function ---
|
||||
|
||||
# Initialize interest system (existing logic)
|
||||
await self.interest_chatting.initialize()
|
||||
logger.debug(f"{self.log_prefix} InterestChatting 实例已初始化。")
|
||||
# await self.interest_chatting.initialize()
|
||||
# logger.debug(f"{self.log_prefix} InterestChatting 实例已初始化。")
|
||||
|
||||
# 根据配置决定初始状态
|
||||
if global_config.chat.chat_mode == "focus":
|
||||
@@ -131,9 +130,9 @@ class SubHeartflow:
|
||||
if rewind or not self.normal_chat_instance:
|
||||
# 提供回调函数,用于接收需要切换到focus模式的通知
|
||||
self.normal_chat_instance = NormalChat(
|
||||
chat_stream=chat_stream,
|
||||
interest_dict=self.get_interest_dict(),
|
||||
on_switch_to_focus_callback=self._handle_switch_to_focus_request
|
||||
chat_stream=chat_stream,
|
||||
interest_dict=self.interest_dict,
|
||||
on_switch_to_focus_callback=self._handle_switch_to_focus_request,
|
||||
)
|
||||
|
||||
# 进行异步初始化
|
||||
@@ -152,12 +151,12 @@ class SubHeartflow:
|
||||
async def _handle_switch_to_focus_request(self) -> None:
|
||||
"""
|
||||
处理来自NormalChat的切换到focus模式的请求
|
||||
|
||||
|
||||
Args:
|
||||
stream_id: 请求切换的stream_id
|
||||
"""
|
||||
logger.info(f"{self.log_prefix} 收到NormalChat请求切换到focus模式")
|
||||
|
||||
|
||||
# 切换到focus模式
|
||||
current_state = self.chat_state.chat_status
|
||||
if current_state == ChatState.NORMAL:
|
||||
@@ -166,6 +165,21 @@ class SubHeartflow:
|
||||
else:
|
||||
logger.warning(f"{self.log_prefix} 当前状态为{current_state.value},无法切换到FOCUSED状态")
|
||||
|
||||
async def _handle_stop_focus_chat_request(self) -> None:
|
||||
"""
|
||||
处理来自HeartFChatting的停止focus模式的请求
|
||||
当收到stop_focus_chat命令时被调用
|
||||
"""
|
||||
logger.info(f"{self.log_prefix} 收到HeartFChatting请求停止focus模式")
|
||||
|
||||
# 切换到normal模式
|
||||
current_state = self.chat_state.chat_status
|
||||
if current_state == ChatState.FOCUSED:
|
||||
await self.change_chat_state(ChatState.NORMAL)
|
||||
logger.info(f"{self.log_prefix} 已根据HeartFChatting请求从FOCUSED切换到NORMAL状态")
|
||||
else:
|
||||
logger.warning(f"{self.log_prefix} 当前状态为{current_state.value},无法切换到NORMAL状态")
|
||||
|
||||
async def _stop_heart_fc_chat(self):
|
||||
"""停止并清理 HeartFChatting 实例"""
|
||||
if self.heart_fc_instance:
|
||||
@@ -182,7 +196,7 @@ class SubHeartflow:
|
||||
async def _start_heart_fc_chat(self) -> bool:
|
||||
"""启动 HeartFChatting 实例,确保 NormalChat 已停止"""
|
||||
await self._stop_normal_chat() # 确保普通聊天监控已停止
|
||||
self.clear_interest_dict() # 清理兴趣字典,准备专注聊天
|
||||
self.interest_dict.clear()
|
||||
|
||||
log_prefix = self.log_prefix
|
||||
# 如果实例已存在,检查其循环任务状态
|
||||
@@ -211,6 +225,7 @@ class SubHeartflow:
|
||||
self.heart_fc_instance = HeartFChatting(
|
||||
chat_id=self.subheartflow_id,
|
||||
observations=self.observations,
|
||||
on_stop_focus_chat=self._handle_stop_focus_chat_request,
|
||||
)
|
||||
|
||||
# 初始化并启动 HeartFChatting
|
||||
@@ -259,7 +274,7 @@ class SubHeartflow:
|
||||
|
||||
elif new_state == ChatState.ABSENT:
|
||||
logger.info(f"{log_prefix} 进入 ABSENT 状态,停止所有聊天活动...")
|
||||
self.clear_interest_dict()
|
||||
self.interest_dict.clear()
|
||||
await self._stop_normal_chat()
|
||||
await self._stop_heart_fc_chat()
|
||||
state_changed = True
|
||||
@@ -300,38 +315,35 @@ class SubHeartflow:
|
||||
logger.warning(f"SubHeartflow {self.subheartflow_id} 没有找到有效的 ChattingObservation")
|
||||
return None
|
||||
|
||||
async def get_interest_state(self) -> dict:
|
||||
return await self.interest_chatting.get_state()
|
||||
|
||||
def get_normal_chat_last_speak_time(self) -> float:
|
||||
if self.normal_chat_instance:
|
||||
return self.normal_chat_instance.last_speak_time
|
||||
return 0
|
||||
|
||||
def get_interest_dict(self) -> Dict[str, tuple[MessageRecv, float, bool]]:
|
||||
return self.interest_chatting.interest_dict
|
||||
|
||||
def get_normal_chat_recent_replies(self, limit: int = 10) -> List[dict]:
|
||||
"""获取NormalChat实例的最近回复记录
|
||||
|
||||
|
||||
Args:
|
||||
limit: 最大返回数量,默认10条
|
||||
|
||||
|
||||
Returns:
|
||||
List[dict]: 最近的回复记录列表,如果没有NormalChat实例则返回空列表
|
||||
"""
|
||||
if self.normal_chat_instance:
|
||||
return self.normal_chat_instance.get_recent_replies(limit)
|
||||
return []
|
||||
|
||||
def clear_interest_dict(self):
|
||||
self.interest_chatting.interest_dict.clear()
|
||||
|
||||
def add_interest_message(self, message: MessageRecv, interest_value: float, is_mentioned: bool):
|
||||
self.interest_dict[message.message_info.message_id] = (message, interest_value, is_mentioned)
|
||||
# 如果字典长度超过10,删除最旧的消息
|
||||
if len(self.interest_dict) > 10:
|
||||
oldest_key = next(iter(self.interest_dict))
|
||||
self.interest_dict.pop(oldest_key)
|
||||
|
||||
async def get_full_state(self) -> dict:
|
||||
"""获取子心流的完整状态,包括兴趣、思维和聊天状态。"""
|
||||
interest_state = await self.get_interest_state()
|
||||
return {
|
||||
"interest_state": interest_state,
|
||||
"interest_state": "interest_state",
|
||||
"chat_state": self.chat_state.chat_status.value,
|
||||
"chat_state_changed_time": self.chat_state_changed_time,
|
||||
}
|
||||
@@ -349,10 +361,6 @@ class SubHeartflow:
|
||||
await self._stop_normal_chat()
|
||||
await self._stop_heart_fc_chat()
|
||||
|
||||
# 停止兴趣更新任务
|
||||
if self.interest_chatting:
|
||||
logger.info(f"{self.log_prefix} 停止兴趣系统后台任务...")
|
||||
await self.interest_chatting.stop_updates()
|
||||
|
||||
# 取消可能存在的旧后台任务 (self.task)
|
||||
if self.task and not self.task.done():
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import asyncio
|
||||
import time
|
||||
import random
|
||||
from typing import Dict, Any, Optional, List
|
||||
from src.common.logger_manager import get_logger
|
||||
from src.chat.message_receive.chat_stream import chat_manager
|
||||
@@ -187,40 +186,40 @@ class SubHeartflowManager:
|
||||
)
|
||||
|
||||
# async def sbhf_normal_into_focus(self):
|
||||
# """评估子心流兴趣度,满足条件则提升到FOCUSED状态(基于start_hfc_probability)"""
|
||||
# try:
|
||||
# for sub_hf in list(self.subheartflows.values()):
|
||||
# flow_id = sub_hf.subheartflow_id
|
||||
# stream_name = chat_manager.get_stream_name(flow_id) or flow_id
|
||||
# """评估子心流兴趣度,满足条件则提升到FOCUSED状态(基于start_hfc_probability)"""
|
||||
# try:
|
||||
# for sub_hf in list(self.subheartflows.values()):
|
||||
# flow_id = sub_hf.subheartflow_id
|
||||
# stream_name = chat_manager.get_stream_name(flow_id) or flow_id
|
||||
|
||||
# # 跳过已经是FOCUSED状态的子心流
|
||||
# if sub_hf.chat_state.chat_status == ChatState.FOCUSED:
|
||||
# continue
|
||||
# # 跳过已经是FOCUSED状态的子心流
|
||||
# if sub_hf.chat_state.chat_status == ChatState.FOCUSED:
|
||||
# continue
|
||||
|
||||
# if sub_hf.interest_chatting.start_hfc_probability == 0:
|
||||
# continue
|
||||
# else:
|
||||
# logger.debug(
|
||||
# f"{stream_name},现在状态: {sub_hf.chat_state.chat_status.value},进入专注概率: {sub_hf.interest_chatting.start_hfc_probability}"
|
||||
# )
|
||||
# if sub_hf.interest_chatting.start_hfc_probability == 0:
|
||||
# continue
|
||||
# else:
|
||||
# logger.debug(
|
||||
# f"{stream_name},现在状态: {sub_hf.chat_state.chat_status.value},进入专注概率: {sub_hf.interest_chatting.start_hfc_probability}"
|
||||
# )
|
||||
|
||||
# if random.random() >= sub_hf.interest_chatting.start_hfc_probability:
|
||||
# continue
|
||||
# if random.random() >= sub_hf.interest_chatting.start_hfc_probability:
|
||||
# continue
|
||||
|
||||
# # 获取最新状态并执行提升
|
||||
# current_subflow = self.subheartflows.get(flow_id)
|
||||
# if not current_subflow:
|
||||
# continue
|
||||
# # 获取最新状态并执行提升
|
||||
# current_subflow = self.subheartflows.get(flow_id)
|
||||
# if not current_subflow:
|
||||
# continue
|
||||
|
||||
# logger.info(
|
||||
# f"{stream_name} 触发 认真水群 (概率={current_subflow.interest_chatting.start_hfc_probability:.2f})"
|
||||
# )
|
||||
# logger.info(
|
||||
# f"{stream_name} 触发 认真水群 (概率={current_subflow.interest_chatting.start_hfc_probability:.2f})"
|
||||
# )
|
||||
|
||||
# # 执行状态提升
|
||||
# await current_subflow.change_chat_state(ChatState.FOCUSED)
|
||||
# # 执行状态提升
|
||||
# await current_subflow.change_chat_state(ChatState.FOCUSED)
|
||||
|
||||
# except Exception as e:
|
||||
# logger.error(f"启动HFC 兴趣评估失败: {e}", exc_info=True)
|
||||
# except Exception as e:
|
||||
# logger.error(f"启动HFC 兴趣评估失败: {e}", exc_info=True)
|
||||
|
||||
async def sbhf_focus_into_normal(self, subflow_id: Any):
|
||||
"""
|
||||
@@ -249,7 +248,7 @@ class SubHeartflowManager:
|
||||
)
|
||||
try:
|
||||
# 从HFC到CHAT时,清空兴趣字典
|
||||
subflow.clear_interest_dict()
|
||||
subflow.interest_dict.clear()
|
||||
await subflow.change_chat_state(target_state)
|
||||
final_state = subflow.chat_state.chat_status
|
||||
if final_state == target_state:
|
||||
|
||||
Reference in New Issue
Block a user