初步开始重写聊天系统

This commit is contained in:
Windpicker-owo
2025-09-15 13:11:37 +08:00
committed by Windpicker-owo
parent 724b2280eb
commit bd1ebbcc53
7 changed files with 1276 additions and 63 deletions

View File

@@ -1,8 +1,13 @@
"""
PlanExecutor: 接收 Plan 对象并执行其中的所有动作。
集成用户关系追踪机制,自动记录交互并更新关系。
"""
import asyncio
import time
from typing import Dict, List
from src.chat.planner_actions.action_manager import ActionManager
from src.common.data_models.info_data_model import Plan
from src.common.data_models.info_data_model import Plan, ActionPlannerInfo
from src.common.logger import get_logger
logger = get_logger("plan_executor")
@@ -10,49 +15,286 @@ logger = get_logger("plan_executor")
class PlanExecutor:
"""
负责接收一个 Plan 对象,并执行其中最终确定的所有动作
增强版PlanExecutor集成用户关系追踪机制
这个类是规划流程的最后一步,将规划结果转化为实际的动作执行。
Attributes:
action_manager (ActionManager): 用于实际执行各种动作的管理器实例。
功能:
1. 执行Plan中的所有动作
2. 自动记录用户交互并添加到关系追踪
3. 分类执行回复动作和其他动作
4. 提供完整的执行统计和监控
"""
def __init__(self, action_manager: ActionManager):
"""
初始化 PlanExecutor。
初始化增强版PlanExecutor。
Args:
action_manager (ActionManager): 一个 ActionManager 实例,用于执行动作
action_manager (ActionManager): 用于实际执行各种动作的管理器实例
"""
self.action_manager = action_manager
@staticmethod
async def execute(plan: Plan):
"""
遍历并执行 Plan 对象中 `decided_actions` 列表里的所有动作。
# 执行统计
self.execution_stats = {
"total_executed": 0,
"successful_executions": 0,
"failed_executions": 0,
"reply_executions": 0,
"other_action_executions": 0,
"execution_times": [],
}
如果动作类型为 "no_action",则会记录原因并跳过。
否则,它将调用 ActionManager 来执行相应的动作。
# 用户关系追踪引用
self.relationship_tracker = None
def set_relationship_tracker(self, relationship_tracker):
"""设置关系追踪器"""
self.relationship_tracker = relationship_tracker
async def execute(self, plan: Plan) -> Dict[str, any]:
"""
遍历并执行Plan对象中`decided_actions`列表里的所有动作。
Args:
plan (Plan): 包含待执行动作列表的 Plan 对象。
plan (Plan): 包含待执行动作列表的Plan对象。
Returns:
Dict[str, any]: 执行结果统计信息
"""
if not plan.decided_actions:
logger.info("没有需要执行的动作。")
return
return {"executed_count": 0, "results": []}
execution_results = []
reply_actions = []
other_actions = []
# 分类动作:回复动作和其他动作
for action_info in plan.decided_actions:
if action_info.action_type == "no_action":
logger.info(f"规划器决策不执行动作,原因: {action_info.reasoning}")
continue
if action_info.action_type in ["reply", "proactive_reply"]:
reply_actions.append(action_info)
else:
other_actions.append(action_info)
# TODO: 对接 ActionManager 的执行方法
# 这是一个示例调用,需要根据 ActionManager 的最终实现进行调整
logger.info(f"执行动作: {action_info.action_type}, 原因: {action_info.reasoning}")
# await self.action_manager.execute_action(
# action_name=action_info.action_type,
# action_data=action_info.action_data,
# reasoning=action_info.reasoning,
# action_message=action_info.action_message,
# )
# 执行回复动作(优先执行)
if reply_actions:
reply_result = await self._execute_reply_actions(reply_actions, plan)
execution_results.extend(reply_result["results"])
self.execution_stats["reply_executions"] += len(reply_actions)
# 并行执行其他动作
if other_actions:
other_result = await self._execute_other_actions(other_actions, plan)
execution_results.extend(other_result["results"])
self.execution_stats["other_action_executions"] += len(other_actions)
# 更新总体统计
self.execution_stats["total_executed"] += len(plan.decided_actions)
successful_count = sum(1 for r in execution_results if r["success"])
self.execution_stats["successful_executions"] += successful_count
self.execution_stats["failed_executions"] += len(execution_results) - successful_count
logger.info(f"动作执行完成: 总数={len(plan.decided_actions)}, 成功={successful_count}, 失败={len(execution_results) - successful_count}")
return {
"executed_count": len(plan.decided_actions),
"successful_count": successful_count,
"failed_count": len(execution_results) - successful_count,
"results": execution_results,
}
async def _execute_reply_actions(self, reply_actions: List[ActionPlannerInfo], plan: Plan) -> Dict[str, any]:
"""执行回复动作"""
results = []
for action_info in reply_actions:
result = await self._execute_single_reply_action(action_info, plan)
results.append(result)
return {"results": results}
async def _execute_single_reply_action(self, action_info: ActionPlannerInfo, plan: Plan) -> Dict[str, any]:
"""执行单个回复动作"""
start_time = time.time()
success = False
error_message = ""
reply_content = ""
try:
logger.info(f"执行回复动作: {action_info.action_type}, 原因: {action_info.reasoning}")
# 构建回复动作参数
action_params = {
"chat_id": plan.chat_id,
"target_message": action_info.action_message,
"reasoning": action_info.reasoning,
"action_data": action_info.action_data or {},
}
# 通过动作管理器执行回复
reply_content = await self.action_manager.execute_action(
action_name=action_info.action_type,
**action_params
)
success = True
logger.info(f"回复动作执行成功: {action_info.action_type}")
except Exception as e:
error_message = str(e)
logger.error(f"执行回复动作失败: {action_info.action_type}, 错误: {error_message}")
# 记录用户关系追踪
if success and action_info.action_message:
await self._track_user_interaction(action_info, plan, reply_content)
execution_time = time.time() - start_time
self.execution_stats["execution_times"].append(execution_time)
return {
"action_type": action_info.action_type,
"success": success,
"error_message": error_message,
"execution_time": execution_time,
"reasoning": action_info.reasoning,
"reply_content": reply_content[:200] + "..." if len(reply_content) > 200 else reply_content,
}
async def _execute_other_actions(self, other_actions: List[ActionPlannerInfo], plan: Plan) -> Dict[str, any]:
"""执行其他动作"""
results = []
# 并行执行其他动作
tasks = []
for action_info in other_actions:
task = self._execute_single_other_action(action_info, plan)
tasks.append(task)
if tasks:
executed_results = await asyncio.gather(*tasks, return_exceptions=True)
for i, result in enumerate(executed_results):
if isinstance(result, Exception):
logger.error(f"执行动作 {other_actions[i].action_type} 时发生异常: {result}")
results.append({
"action_type": other_actions[i].action_type,
"success": False,
"error_message": str(result),
"execution_time": 0,
"reasoning": other_actions[i].reasoning,
})
else:
results.append(result)
return {"results": results}
async def _execute_single_other_action(self, action_info: ActionPlannerInfo, plan: Plan) -> Dict[str, any]:
"""执行单个其他动作"""
start_time = time.time()
success = False
error_message = ""
try:
logger.info(f"执行其他动作: {action_info.action_type}, 原因: {action_info.reasoning}")
# 构建动作参数
action_params = {
"chat_id": plan.chat_id,
"target_message": action_info.action_message,
"reasoning": action_info.reasoning,
"action_data": action_info.action_data or {},
}
# 通过动作管理器执行动作
await self.action_manager.execute_action(
action_name=action_info.action_type,
**action_params
)
success = True
logger.info(f"其他动作执行成功: {action_info.action_type}")
except Exception as e:
error_message = str(e)
logger.error(f"执行其他动作失败: {action_info.action_type}, 错误: {error_message}")
execution_time = time.time() - start_time
self.execution_stats["execution_times"].append(execution_time)
return {
"action_type": action_info.action_type,
"success": success,
"error_message": error_message,
"execution_time": execution_time,
"reasoning": action_info.reasoning,
}
async def _track_user_interaction(self, action_info: ActionPlannerInfo, plan: Plan, reply_content: str):
"""追踪用户交互"""
try:
if not action_info.action_message:
return
# 获取用户信息
user_id = action_info.action_message.user_id
user_name = action_info.action_message.user_nickname or user_id
user_message = action_info.action_message.content
# 如果有设置关系追踪器,添加交互记录
if self.relationship_tracker:
self.relationship_tracker.add_interaction(
user_id=user_id,
user_name=user_name,
user_message=user_message,
bot_reply=reply_content,
reply_timestamp=time.time()
)
logger.debug(f"已添加用户交互追踪: {user_id}")
except Exception as e:
logger.error(f"追踪用户交互时出错: {e}")
def get_execution_stats(self) -> Dict[str, any]:
"""获取执行统计信息"""
stats = self.execution_stats.copy()
# 计算平均执行时间
if stats["execution_times"]:
avg_time = sum(stats["execution_times"]) / len(stats["execution_times"])
stats["average_execution_time"] = avg_time
stats["max_execution_time"] = max(stats["execution_times"])
stats["min_execution_time"] = min(stats["execution_times"])
else:
stats["average_execution_time"] = 0
stats["max_execution_time"] = 0
stats["min_execution_time"] = 0
# 移除执行时间列表以避免返回过大数据
stats.pop("execution_times", None)
return stats
def reset_stats(self):
"""重置统计信息"""
self.execution_stats = {
"total_executed": 0,
"successful_executions": 0,
"failed_executions": 0,
"reply_executions": 0,
"other_action_executions": 0,
"execution_times": [],
}
def get_recent_performance(self, limit: int = 10) -> List[Dict[str, any]]:
"""获取最近的执行性能"""
recent_times = self.execution_stats["execution_times"][-limit:]
if not recent_times:
return []
return [
{
"execution_index": i + 1,
"execution_time": time_val,
"timestamp": time.time() - (len(recent_times) - i) * 60, # 估算时间戳
}
for i, time_val in enumerate(recent_times)
]

View File

@@ -1,6 +1,8 @@
"""
主规划器入口,负责协调 PlanGenerator, PlanFilter, 和 PlanExecutor。
集成兴趣度评分系统和用户关系追踪机制,实现智能化的聊天决策。
"""
import time
from dataclasses import asdict
from typing import Dict, List, Optional, Tuple
@@ -8,7 +10,11 @@ from src.chat.planner_actions.action_manager import ActionManager
from src.chat.planner_actions.plan_executor import PlanExecutor
from src.chat.planner_actions.plan_filter import PlanFilter
from src.chat.planner_actions.plan_generator import PlanGenerator
from src.chat.affinity_flow.interest_scoring import InterestScoringSystem
from src.chat.affinity_flow.relationship_tracker import UserRelationshipTracker
from src.common.data_models.info_data_model import Plan
from src.common.logger import get_logger
from src.config.config import global_config
from src.plugin_system.base.component_types import ChatMode
import src.chat.planner_actions.planner_prompts #noga # noqa: F401
# 导入提示词模块以确保其被初始化
@@ -16,26 +22,22 @@ import src.chat.planner_actions.planner_prompts #noga # noqa: F401
logger = get_logger("planner")
class ActionPlanner:
"""
ActionPlanner 是规划系统的核心协调器
增强版ActionPlanner,集成兴趣度评分和用户关系追踪机制
它负责整合规划流程的三个主要阶段
1. **生成 (Generate)**: 使用 PlanGenerator 创建一个初始的行动计划。
2. **筛选 (Filter)**: 使用 PlanFilter 对生成的计划进行审查和优化。
3. **执行 (Execute)**: 使用 PlanExecutor 执行最终确定的行动。
Attributes:
chat_id (str): 当前聊天的唯一标识符。
action_manager (ActionManager): 用于执行具体动作的管理器。
generator (PlanGenerator): 负责生成初始计划。
filter (PlanFilter): 负责筛选和优化计划。
executor (PlanExecutor): 负责执行最终计划。
核心功能
1. 兴趣度评分系统:根据兴趣匹配度、关系分、提及度、时间因子对消息评分
2. 用户关系追踪:自动追踪用户交互并更新关系分
3. 智能回复决策:基于兴趣度阈值和连续不回复概率的智能决策
4. 完整的规划流程:生成→筛选→执行的完整三阶段流程
"""
def __init__(self, chat_id: str, action_manager: ActionManager):
"""
初始化 ActionPlanner。
初始化增强版ActionPlanner。
Args:
chat_id (str): 当前聊天的 ID。
@@ -47,48 +49,197 @@ class ActionPlanner:
self.filter = PlanFilter()
self.executor = PlanExecutor(action_manager)
async def plan(
self, mode: ChatMode = ChatMode.FOCUS
) -> Tuple[List[Dict], Optional[Dict]]:
"""
执行从生成到执行的完整规划流程。
# 初始化兴趣度评分系统
self.interest_scoring = InterestScoringSystem()
这个方法按顺序协调生成、筛选和执行三个阶段。
# 初始化用户关系追踪器
self.relationship_tracker = UserRelationshipTracker(self.interest_scoring)
# 设置执行器的关系追踪器
self.executor.set_relationship_tracker(self.relationship_tracker)
# 规划器统计
self.planner_stats = {
"total_plans": 0,
"successful_plans": 0,
"failed_plans": 0,
"replies_generated": 0,
"other_actions_executed": 0,
}
async def plan(self, mode: ChatMode = ChatMode.FOCUS, use_enhanced: bool = True) -> Tuple[List[Dict], Optional[Dict]]:
"""
执行完整的增强版规划流程。
Args:
mode (ChatMode): 当前的聊天模式,默认为 FOCUS。
use_enhanced (bool): 是否使用增强功能,默认为 True。
Returns:
Tuple[List[Dict], Optional[Dict]]: 一个元组,包含:
- final_actions_dict (List[Dict]): 最终确定的动作列表(字典格式)。
- final_target_message_dict (Optional[Dict]): 最终的目标消息(字典格式),如果没有则为 None
这与旧版 planner 的返回值保持兼容。
- final_target_message_dict (Optional[Dict]): 最终的目标消息(字典格式)。
"""
# 1. 生成初始 Plan
initial_plan = await self.generator.generate(mode)
try:
self.planner_stats["total_plans"] += 1
# 2. 筛选 Plan
filtered_plan = await self.filter.filter(initial_plan)
if use_enhanced:
return await self._enhanced_plan_flow(mode)
else:
return await self._standard_plan_flow(mode)
# 3. 执行 Plan(临时引爆因为它暂时还跑不了)
#await self.executor.execute(filtered_plan)
except Exception as e:
logger.error(f"规划流程出错: {e}")
self.planner_stats["failed_plans"] += 1
return [], None
# 4. 返回结果 (与旧版 planner 的返回值保持兼容)
final_actions = filtered_plan.decided_actions or []
async def _enhanced_plan_flow(self, mode: ChatMode) -> Tuple[List[Dict], Optional[Dict]]:
"""执行增强版规划流程"""
try:
# 1. 生成初始 Plan
initial_plan = await self.generator.generate(mode)
# 2. 兴趣度评分
if initial_plan.chat_history:
bot_nickname = global_config.bot.nickname
interest_scores = self.interest_scoring.calculate_interest_scores(
initial_plan.chat_history, bot_nickname
)
# 3. 根据兴趣度调整可用动作
if interest_scores:
latest_score = max(interest_scores, key=lambda s: s.total_score)
should_reply = self.interest_scoring.should_reply(latest_score)
if not should_reply and "reply" in initial_plan.available_actions:
logger.info(f"消息兴趣度不足({latest_score.total_score:.2f})移除reply动作")
del initial_plan.available_actions["reply"]
self.interest_scoring.record_reply_action(False)
else:
self.interest_scoring.record_reply_action(True)
# 4. 筛选 Plan
filtered_plan = await self.filter.filter(initial_plan)
# 5. 执行 Plan
await self._execute_plan_with_tracking(filtered_plan)
# 6. 检查关系更新
await self.relationship_tracker.check_and_update_relationships()
# 7. 返回结果
return self._build_return_result(filtered_plan)
except Exception as e:
logger.error(f"增强版规划流程出错: {e}")
self.planner_stats["failed_plans"] += 1
return [], None
async def _standard_plan_flow(self, mode: ChatMode) -> Tuple[List[Dict], Optional[Dict]]:
"""执行标准规划流程"""
try:
# 1. 生成初始 Plan
initial_plan = await self.generator.generate(mode)
# 2. 筛选 Plan
filtered_plan = await self.filter.filter(initial_plan)
# 3. 执行 Plan
await self._execute_plan_with_tracking(filtered_plan)
# 4. 返回结果
return self._build_return_result(filtered_plan)
except Exception as e:
logger.error(f"标准规划流程出错: {e}")
self.planner_stats["failed_plans"] += 1
return [], None
async def _execute_plan_with_tracking(self, plan: Plan):
"""执行Plan并追踪用户关系"""
if not plan.decided_actions:
return
for action_info in plan.decided_actions:
if action_info.action_type in ["reply", "proactive_reply"] and action_info.action_message:
# 记录用户交互
self.relationship_tracker.add_interaction(
user_id=action_info.action_message.user_id,
user_name=action_info.action_message.user_nickname or action_info.action_message.user_id,
user_message=action_info.action_message.content,
bot_reply="Bot回复内容", # 这里需要实际的回复内容
reply_timestamp=time.time()
)
# 执行动作
try:
await self.action_manager.execute_action(
action_name=action_info.action_type,
chat_id=self.chat_id,
target_message=action_info.action_message,
reasoning=action_info.reasoning,
action_data=action_info.action_data or {},
)
self.planner_stats["successful_plans"] += 1
if action_info.action_type in ["reply", "proactive_reply"]:
self.planner_stats["replies_generated"] += 1
else:
self.planner_stats["other_actions_executed"] += 1
except Exception as e:
logger.error(f"执行动作失败: {action_info.action_type}, 错误: {e}")
def _build_return_result(self, plan: Plan) -> Tuple[List[Dict], Optional[Dict]]:
"""构建返回结果"""
final_actions = plan.decided_actions or []
final_target_message = next(
(act.action_message for act in final_actions if act.action_message), None
)
final_actions_dict = [asdict(act) for act in final_actions]
# action_message现在可能是字典而不是dataclass实例需要特殊处理
if final_target_message:
if hasattr(final_target_message, '__dataclass_fields__'):
# 如果是dataclass实例使用asdict转换
final_target_message_dict = asdict(final_target_message)
else:
# 如果已经是字典,直接使用
final_target_message_dict = final_target_message
else:
final_target_message_dict = None
return final_actions_dict, final_target_message_dict
def get_user_relationship(self, user_id: str) -> float:
"""获取用户关系分"""
return self.interest_scoring.get_user_relationship(user_id)
def update_interest_keywords(self, new_keywords: Dict[str, List[str]]):
"""更新兴趣关键词"""
self.interest_scoring.interest_keywords.update(new_keywords)
logger.info(f"已更新兴趣关键词: {list(new_keywords.keys())}")
def get_planner_stats(self) -> Dict[str, any]:
"""获取规划器统计"""
return self.planner_stats.copy()
def get_interest_scoring_stats(self) -> Dict[str, any]:
"""获取兴趣度评分统计"""
return {
"no_reply_count": self.interest_scoring.no_reply_count,
"max_no_reply_count": self.interest_scoring.max_no_reply_count,
"reply_threshold": self.interest_scoring.reply_threshold,
"mention_threshold": self.interest_scoring.mention_threshold,
"user_relationships": len(self.interest_scoring.user_relationships),
}
def get_relationship_stats(self) -> Dict[str, any]:
"""获取用户关系统计"""
return {
"tracking_users": len(self.relationship_tracker.tracking_users),
"relationship_history": len(self.relationship_tracker.relationship_history),
"max_tracking_users": self.relationship_tracker.max_tracking_users,
}
# 全局兴趣度评分系统实例
interest_scoring_system = InterestScoringSystem()