remove:冗余的sbhf代码和focus代码

This commit is contained in:
SengokuCola
2025-07-06 20:14:09 +08:00
parent dc24a76413
commit 1365099fd4
44 changed files with 132 additions and 2210 deletions

View File

@@ -9,15 +9,7 @@ from rich.traceback import install
from src.chat.utils.prompt_builder import global_prompt_manager
from src.common.logger import get_logger
from src.chat.utils.timer_calculator import Timer
from src.chat.focus_chat.observation.observation import Observation
from src.chat.focus_chat.info.info_base import InfoBase
from src.chat.focus_chat.info_processors.chattinginfo_processor import ChattingInfoProcessor
from src.chat.focus_chat.info_processors.working_memory_processor import WorkingMemoryProcessor
from src.chat.focus_chat.observation.hfcloop_observation import HFCloopObservation
from src.chat.focus_chat.observation.working_observation import WorkingMemoryObservation
from src.chat.focus_chat.observation.chatting_observation import ChattingObservation
from src.chat.focus_chat.observation.actions_observation import ActionObservation
from src.chat.focus_chat.info_processors.base_processor import BaseProcessor
from src.chat.focus_chat.focus_loop_info import FocusLoopInfo
from src.chat.planner_actions.planner_focus import ActionPlanner
from src.chat.planner_actions.action_modifier import ActionModifier
from src.chat.planner_actions.action_manager import ActionManager
@@ -32,23 +24,8 @@ install(extra_lines=3)
# 注释:原来的动作修改超时常量已移除,因为改为顺序执行
# 定义观察器映射:键是观察器名称,值是 (观察器类, 初始化参数)
OBSERVATION_CLASSES = {
"ChattingObservation": (ChattingObservation, "chat_id"),
"WorkingMemoryObservation": (WorkingMemoryObservation, "observe_id"),
"HFCloopObservation": (HFCloopObservation, "observe_id"),
}
# 定义处理器映射:键是处理器名称,值是 (处理器类, 可选的配置键名)
PROCESSOR_CLASSES = {
"ChattingInfoProcessor": (ChattingInfoProcessor, None),
"WorkingMemoryProcessor": (WorkingMemoryProcessor, "working_memory_processor"),
}
logger = get_logger("hfc") # Logger Name Changed
class HeartFChatting:
"""
管理一个连续的Focus Chat循环
@@ -83,25 +60,14 @@ class HeartFChatting:
self._message_threshold = max(10, int(30 * global_config.chat.exit_focus_threshold))
self._fatigue_triggered = False # 是否已触发疲惫退出
# 初始化观察器
self.observations: List[Observation] = []
self._register_observations()
# 根据配置文件和默认规则确定启用的处理器
self.enabled_processor_names = ["ChattingInfoProcessor"]
if global_config.focus_chat.working_memory_processor:
self.enabled_processor_names.append("WorkingMemoryProcessor")
self.processors: List[BaseProcessor] = []
self._register_default_processors()
self.loop_info: FocusLoopInfo = FocusLoopInfo(observe_id=self.stream_id)
self.action_manager = ActionManager()
self.action_planner = ActionPlanner(
log_prefix=self.log_prefix, action_manager=self.action_manager
chat_id = self.stream_id,
action_manager=self.action_manager
)
self.action_modifier = ActionModifier(action_manager=self.action_manager, chat_id=self.stream_id)
self.action_observation = ActionObservation(observe_id=self.stream_id)
self.action_observation.set_action_manager(self.action_manager)
self._processing_lock = asyncio.Lock()
@@ -130,66 +96,8 @@ class HeartFChatting:
f"{self.log_prefix} HeartFChatting 初始化完成,消息疲惫阈值: {self._message_threshold}基于exit_focus_threshold={global_config.chat.exit_focus_threshold}计算仅在auto模式下生效"
)
def _register_observations(self):
"""注册所有观察器"""
self.observations = [] # 清空已有的
for name, (observation_class, param_name) in OBSERVATION_CLASSES.items():
try:
# 检查是否需要跳过WorkingMemoryObservation
if name == "WorkingMemoryObservation":
# 如果工作记忆处理器被禁用则跳过WorkingMemoryObservation
if not global_config.focus_chat.working_memory_processor:
logger.debug(f"{self.log_prefix} 工作记忆处理器已禁用,跳过注册观察器 {name}")
continue
# 根据参数名使用正确的参数
kwargs = {param_name: self.stream_id}
observation = observation_class(**kwargs)
self.observations.append(observation)
logger.debug(f"{self.log_prefix} 注册观察器 {name}")
except Exception as e:
logger.error(f"{self.log_prefix} 观察器 {name} 构造失败: {e}")
if self.observations:
logger.info(f"{self.log_prefix} 已注册观察器: {[o.__class__.__name__ for o in self.observations]}")
else:
logger.warning(f"{self.log_prefix} 没有注册任何观察器")
def _register_default_processors(self):
"""根据 self.enabled_processor_names 注册信息处理器"""
self.processors = [] # 清空已有的
for name in self.enabled_processor_names: # 'name' is "ChattingInfoProcessor", etc.
processor_info = PROCESSOR_CLASSES.get(name) # processor_info is (ProcessorClass, config_key)
if processor_info:
processor_actual_class = processor_info[0] # 获取实际的类定义
# 根据处理器类名判断构造参数
if name == "ChattingInfoProcessor":
self.processors.append(processor_actual_class())
elif name == "WorkingMemoryProcessor":
self.processors.append(processor_actual_class(subheartflow_id=self.stream_id))
else:
try:
self.processors.append(processor_actual_class()) # 尝试无参构造
logger.debug(f"{self.log_prefix} 注册处理器 {name} (尝试无参构造).")
except TypeError:
logger.error(
f"{self.log_prefix} 处理器 {name} 构造失败。它可能需要参数(如 subheartflow_id但未在注册逻辑中明确处理。"
)
else:
logger.warning(
f"{self.log_prefix} 在 PROCESSOR_CLASSES 中未找到名为 '{name}' 的处理器定义,将跳过注册。"
)
if self.processors:
logger.info(f"{self.log_prefix} 已注册处理器: {[p.__class__.__name__ for p in self.processors]}")
else:
logger.warning(f"{self.log_prefix} 没有注册任何处理器。这可能是由于配置错误或所有处理器都被禁用了。")
async def start(self):
"""检查是否需要启动主循环,如果未激活则启动。"""
logger.debug(f"{self.log_prefix} 开始启动 HeartFChatting")
# 如果循环已经激活,直接返回
if self._loop_active:
@@ -210,8 +118,6 @@ class HeartFChatting:
try:
# 等待旧任务确实被取消
await asyncio.wait_for(self._loop_task, timeout=5.0)
except (asyncio.CancelledError, asyncio.TimeoutError):
pass # 忽略取消或超时错误
except Exception as e:
logger.warning(f"{self.log_prefix} 等待旧任务取消时出错: {e}")
self._loop_task = None # 清理旧任务引用
@@ -310,14 +216,11 @@ class HeartFChatting:
logger.error(f"{self.log_prefix} 处理上下文时出错: {e}")
# 为当前循环设置错误状态,防止后续重复报错
error_loop_info = {
"loop_observation_info": {},
"loop_processor_info": {},
"loop_plan_info": {
"action_result": {
"action_type": "error",
"action_data": {},
},
"observed_messages": "",
},
"loop_action_info": {
"action_taken": False,
@@ -335,14 +238,8 @@ class HeartFChatting:
self._current_cycle_detail.set_loop_info(loop_info)
# 从observations列表中获取HFCloopObservation
hfcloop_observation = next(
(obs for obs in self.observations if isinstance(obs, HFCloopObservation)), None
)
if hfcloop_observation:
hfcloop_observation.add_loop_info(self._current_cycle_detail)
else:
logger.warning(f"{self.log_prefix} 未找到HFCloopObservation实例")
self.loop_info.add_loop_info(self._current_cycle_detail)
self._current_cycle_detail.timers = cycle_timers
@@ -391,15 +288,12 @@ class HeartFChatting:
# 如果_current_cycle_detail存在但未完成为其设置错误状态
if self._current_cycle_detail and not hasattr(self._current_cycle_detail, "end_time"):
error_loop_info = {
"loop_observation_info": {},
"loop_processor_info": {},
"loop_plan_info": {
"action_result": {
"action_type": "error",
"action_data": {},
"reasoning": f"循环处理失败: {e}",
},
"observed_messages": "",
},
"loop_action_info": {
"action_taken": False,
@@ -445,65 +339,10 @@ class HeartFChatting:
if acquired and self._processing_lock.locked():
self._processing_lock.release()
async def _process_processors(self, observations: List[Observation]) -> tuple[List[InfoBase], Dict[str, float]]:
# 记录并行任务开始时间
parallel_start_time = time.time()
logger.debug(f"{self.log_prefix} 开始信息处理器并行任务")
processor_tasks = []
task_to_name_map = {}
for processor in self.processors:
processor_name = processor.__class__.log_prefix
async def run_with_timeout(proc=processor):
return await proc.process_info(observations=observations)
task = asyncio.create_task(run_with_timeout())
processor_tasks.append(task)
task_to_name_map[task] = processor_name
logger.debug(f"{self.log_prefix} 启动处理器任务: {processor_name}")
pending_tasks = set(processor_tasks)
all_plan_info: List[InfoBase] = []
while pending_tasks:
done, pending_tasks = await asyncio.wait(pending_tasks, return_when=asyncio.FIRST_COMPLETED)
for task in done:
processor_name = task_to_name_map[task]
task_completed_time = time.time()
duration_since_parallel_start = task_completed_time - parallel_start_time
try:
result_list = await task
logger.debug(f"{self.log_prefix} 处理器 {processor_name} 已完成!")
if result_list is not None:
all_plan_info.extend(result_list)
else:
logger.warning(f"{self.log_prefix} 处理器 {processor_name} 返回了 None")
except Exception as e:
logger.error(
f"{self.log_prefix} 处理器 {processor_name} 执行失败,耗时 (自并行开始): {duration_since_parallel_start:.2f}秒. 错误: {e}",
exc_info=True,
)
traceback.print_exc()
return all_plan_info
async def _observe_process_plan_action_loop(self, cycle_timers: dict, thinking_id: str) -> dict:
try:
loop_start_time = time.time()
with Timer("观察", cycle_timers):
# 执行所有观察器的观察
for observation in self.observations:
await observation.observe()
loop_observation_info = {
"observations": self.observations,
}
await self.loop_info.observe()
await self.relationship_builder.build_relation()
@@ -513,37 +352,18 @@ class HeartFChatting:
try:
# 调用完整的动作修改流程
await self.action_modifier.modify_actions(
observations=self.observations,
loop_info = self.loop_info,
mode="focus",
)
await self.action_observation.observe()
self.observations.append(self.action_observation)
logger.debug(f"{self.log_prefix} 动作修改完成")
except Exception as e:
logger.error(f"{self.log_prefix} 动作修改失败: {e}")
# 继续执行,不中断流程
try:
all_plan_info = await self._process_processors(self.observations)
except Exception as e:
logger.error(f"{self.log_prefix} 信息处理器失败: {e}")
# 设置默认值以继续执行
all_plan_info = []
loop_processor_info = {
"all_plan_info": all_plan_info,
}
logger.debug(f"{self.log_prefix} 并行阶段完成准备进入规划器plan_info数量: {len(all_plan_info)}")
with Timer("规划器", cycle_timers):
plan_result = await self.action_planner.plan(all_plan_info, loop_start_time)
plan_result = await self.action_planner.plan()
loop_plan_info = {
"action_result": plan_result.get("action_result", {}),
"observed_messages": plan_result.get("observed_messages", ""),
}
action_type, action_data, reasoning = (
@@ -551,6 +371,8 @@ class HeartFChatting:
plan_result.get("action_result", {}).get("action_data", {}),
plan_result.get("action_result", {}).get("reasoning", "未提供理由"),
)
action_data["loop_start_time"] = loop_start_time
if action_type == "reply":
action_str = "回复"
@@ -559,7 +381,7 @@ class HeartFChatting:
else:
action_str = action_type
logger.debug(f"{self.log_prefix} 麦麦想要:'{action_str}'")
logger.debug(f"{self.log_prefix} 麦麦想要:'{action_str}',理由是:{reasoning}")
# 动作执行计时
with Timer("动作执行", cycle_timers):
@@ -575,8 +397,6 @@ class HeartFChatting:
}
loop_info = {
"loop_observation_info": loop_observation_info,
"loop_processor_info": loop_processor_info,
"loop_plan_info": loop_plan_info,
"loop_action_info": loop_action_info,
}
@@ -587,11 +407,8 @@ class HeartFChatting:
logger.error(f"{self.log_prefix} FOCUS聊天处理失败: {e}")
logger.error(traceback.format_exc())
return {
"loop_observation_info": {},
"loop_processor_info": {},
"loop_plan_info": {
"action_result": {"action_type": "error", "action_data": {}, "reasoning": f"处理失败: {e}"},
"observed_messages": "",
},
"loop_action_info": {"action_taken": False, "reply_text": "", "command": "", "taken_time": time.time()},
}
@@ -636,7 +453,7 @@ class HeartFChatting:
return False, "", ""
if not action_handler:
logger.warning(f"{self.log_prefix} 未能创建动作处理器: {action}, 原因: {reasoning}")
logger.warning(f"{self.log_prefix} 未能创建动作处理器: {action}")
return False, "", ""
# 处理动作并获取结果