feat:优化了auto切换聊天模式机制,修改取名prompt,不再处理temp

This commit is contained in:
SengokuCola
2025-05-27 21:45:03 +08:00
parent 7e59382603
commit 369de9d137
14 changed files with 237 additions and 70 deletions

View File

@@ -107,12 +107,12 @@ class BackgroundTaskManager:
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",
)
# (
# self._run_into_focus_cycle,
# "debug", # 设为debug避免过多日志
# f"专注评估任务已启动 间隔:{INTEREST_EVAL_INTERVAL_SECONDS}s",
# "_into_focus_task",
# )
])
else:
logger.info("聊天模式为 normal跳过启动清理任务、私聊激活任务和专注评估任务")
@@ -215,10 +215,10 @@ class BackgroundTaskManager:
logger.info(f"[清理任务] 清理完成, 共停止 {stopped_count}/{len(flows_to_stop)} 个子心流")
# --- 新增兴趣评估工作函数 ---
async def _perform_into_focus_work(self):
"""执行一轮子心流兴趣评估与提升检查。"""
# 直接调用 subheartflow_manager 的方法,并传递当前状态信息
await self.subheartflow_manager.sbhf_normal_into_focus()
# async def _perform_into_focus_work(self):
# """执行一轮子心流兴趣评估与提升检查。"""
# # 直接调用 subheartflow_manager 的方法,并传递当前状态信息
# await self.subheartflow_manager.sbhf_normal_into_focus()
async def _run_state_update_cycle(self, interval: int):
await _run_periodic_loop(task_name="State Update", interval=interval, task_func=self._perform_state_update_work)
@@ -229,12 +229,12 @@ class BackgroundTaskManager:
)
# --- 新增兴趣评估任务运行器 ---
async def _run_into_focus_cycle(self):
await _run_periodic_loop(
task_name="Into Focus",
interval=INTEREST_EVAL_INTERVAL_SECONDS,
task_func=self._perform_into_focus_work,
)
# async def _run_into_focus_cycle(self):
# await _run_periodic_loop(
# task_name="Into Focus",
# interval=INTEREST_EVAL_INTERVAL_SECONDS,
# task_func=self._perform_into_focus_work,
# )
# 新增私聊激活任务运行器
async def _run_private_chat_activation_cycle(self, interval: int):

View File

@@ -1,6 +1,6 @@
from src.chat.heart_flow.sub_heartflow import SubHeartflow, ChatState
from src.common.logger_manager import get_logger
from typing import Any, Optional
from typing import Any, Optional, List
from src.chat.heart_flow.mai_state_manager import MaiStateInfo, MaiStateManager
from src.chat.heart_flow.subheartflow_manager import SubHeartflowManager
from src.chat.heart_flow.background_tasks import BackgroundTaskManager # Import BackgroundTaskManager
@@ -57,6 +57,23 @@ class Heartflow:
return heartfc_instance.get_cycle_history(last_n=history_len)
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
"""
subheartflow = await self.subheartflow_manager.get_or_create_subheartflow(subheartflow_id)
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):
"""启动后台任务"""
await self.background_task_manager.start_tasks()

View File

@@ -129,7 +129,12 @@ class SubHeartflow:
return False
# 在 rewind 为 True 或 NormalChat 实例尚未创建时,创建新实例
if rewind or not self.normal_chat_instance:
self.normal_chat_instance = NormalChat(chat_stream=chat_stream, interest_dict=self.get_interest_dict())
# 提供回调函数用于接收需要切换到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
)
# 进行异步初始化
await self.normal_chat_instance.initialize()
@@ -144,6 +149,23 @@ class SubHeartflow:
self.normal_chat_instance = None # 启动/初始化失败,清理实例
return False
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:
await self.change_chat_state(ChatState.FOCUSED)
logger.info(f"{self.log_prefix} 已根据NormalChat请求从NORMAL切换到FOCUSED状态")
else:
logger.warning(f"{self.log_prefix} 当前状态为{current_state.value}无法切换到FOCUSED状态")
async def _stop_heart_fc_chat(self):
"""停止并清理 HeartFChatting 实例"""
if self.heart_fc_instance:
@@ -289,6 +311,19 @@ class SubHeartflow:
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()

View File

@@ -186,41 +186,41 @@ class SubHeartflowManager:
f"{log_prefix} 完成,共处理 {processed_count} 个子心流,成功将 {changed_count} 个非 ABSENT 子心流的状态更改为 ABSENT。"
)
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
# 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状态的子心流
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):
"""