🤖 自动格式化代码 [skip ci]
This commit is contained in:
@@ -23,8 +23,9 @@ MAX_STREAMS_TO_DISPLAY = 15 # 最多显示多少个聊天流的折线图 (可以
|
||||
# *** 添加 Matplotlib 中文字体配置 ***
|
||||
# 尝试使用 'SimHei' 或 'Microsoft YaHei',如果找不到,matplotlib 会回退到默认字体
|
||||
# 确保你的系统上安装了这些字体
|
||||
matplotlib.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei']
|
||||
matplotlib.rcParams['axes.unicode_minus'] = False # 解决负号'-'显示为方块的问题
|
||||
matplotlib.rcParams["font.sans-serif"] = ["SimHei", "Microsoft YaHei"]
|
||||
matplotlib.rcParams["axes.unicode_minus"] = False # 解决负号'-'显示为方块的问题
|
||||
|
||||
|
||||
class InterestMonitorApp:
|
||||
def __init__(self, root):
|
||||
@@ -49,7 +50,7 @@ class InterestMonitorApp:
|
||||
|
||||
# --- 第一个选项卡:所有流 ---
|
||||
self.frame_all = ttk.Frame(self.notebook, padding="5 5 5 5")
|
||||
self.notebook.add(self.frame_all, text='所有聊天流')
|
||||
self.notebook.add(self.frame_all, text="所有聊天流")
|
||||
|
||||
# 状态标签
|
||||
self.status_label = tk.Label(root, text="Initializing...", anchor="w", fg="grey")
|
||||
@@ -67,14 +68,16 @@ class InterestMonitorApp:
|
||||
|
||||
# --- 第二个选项卡:单个流 ---
|
||||
self.frame_single = ttk.Frame(self.notebook, padding="5 5 5 5")
|
||||
self.notebook.add(self.frame_single, text='单个聊天流详情')
|
||||
self.notebook.add(self.frame_single, text="单个聊天流详情")
|
||||
|
||||
# 单个流选项卡的上部控制区域
|
||||
self.control_frame_single = ttk.Frame(self.frame_single)
|
||||
self.control_frame_single.pack(side=tk.TOP, fill=tk.X, pady=5)
|
||||
|
||||
ttk.Label(self.control_frame_single, text="选择聊天流:").pack(side=tk.LEFT, padx=(0, 5))
|
||||
self.stream_selector = ttk.Combobox(self.control_frame_single, textvariable=self.selected_stream_id, state="readonly", width=50)
|
||||
self.stream_selector = ttk.Combobox(
|
||||
self.control_frame_single, textvariable=self.selected_stream_id, state="readonly", width=50
|
||||
)
|
||||
self.stream_selector.pack(side=tk.LEFT, fill=tk.X, expand=True)
|
||||
self.stream_selector.bind("<<ComboboxSelected>>", self.on_stream_selected)
|
||||
|
||||
@@ -82,7 +85,9 @@ class InterestMonitorApp:
|
||||
self.fig_single = Figure(figsize=(5, 4), dpi=100)
|
||||
# 修改:创建两个子图,一个显示兴趣度,一个显示概率
|
||||
self.ax_single_interest = self.fig_single.add_subplot(211) # 2行1列的第1个
|
||||
self.ax_single_probability = self.fig_single.add_subplot(212, sharex=self.ax_single_interest) # 2行1列的第2个,共享X轴
|
||||
self.ax_single_probability = self.fig_single.add_subplot(
|
||||
212, sharex=self.ax_single_interest
|
||||
) # 2行1列的第2个,共享X轴
|
||||
|
||||
# 创建 Tkinter 画布嵌入 Matplotlib 图表 (用于第二个选项卡)
|
||||
self.canvas_single = FigureCanvasTkAgg(self.fig_single, master=self.frame_single) # <--- 放入 frame_single
|
||||
@@ -118,7 +123,7 @@ class InterestMonitorApp:
|
||||
time_threshold = current_time - (15 * 60) # 30 minutes in seconds
|
||||
|
||||
try:
|
||||
with open(LOG_FILE_PATH, 'r', encoding='utf-8') as f:
|
||||
with open(LOG_FILE_PATH, "r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
read_count += 1
|
||||
try:
|
||||
@@ -131,7 +136,9 @@ class InterestMonitorApp:
|
||||
|
||||
stream_id = log_entry.get("stream_id")
|
||||
interest_level = log_entry.get("interest_level")
|
||||
group_name = log_entry.get("group_name", stream_id) # *** Get group_name, fallback to stream_id ***
|
||||
group_name = log_entry.get(
|
||||
"group_name", stream_id
|
||||
) # *** Get group_name, fallback to stream_id ***
|
||||
reply_probability = log_entry.get("reply_probability") # <--- 获取概率值
|
||||
|
||||
# *** Check other required fields AFTER time filtering ***
|
||||
@@ -192,12 +199,16 @@ class InterestMonitorApp:
|
||||
"""更新单个流选项卡中的 Combobox 列表"""
|
||||
# 创建 (display_name, stream_id) 对的列表,按 display_name 排序
|
||||
available_streams = sorted(
|
||||
[(name, sid) for sid, name in self.stream_display_names.items() if sid in self.stream_history and self.stream_history[sid]],
|
||||
key=lambda item: item[0] # 按显示名称排序
|
||||
[
|
||||
(name, sid)
|
||||
for sid, name in self.stream_display_names.items()
|
||||
if sid in self.stream_history and self.stream_history[sid]
|
||||
],
|
||||
key=lambda item: item[0], # 按显示名称排序
|
||||
)
|
||||
|
||||
# 更新 Combobox 的值 (仅显示 display_name)
|
||||
self.stream_selector['values'] = [name for name, sid in available_streams]
|
||||
self.stream_selector["values"] = [name for name, sid in available_streams]
|
||||
|
||||
# 检查当前选中的 stream_id 是否仍然有效
|
||||
current_selection_name = self.selected_stream_id.get()
|
||||
@@ -220,7 +231,7 @@ class InterestMonitorApp:
|
||||
self.ax.set_title("兴趣度随时间变化图 (所有活跃流)")
|
||||
self.ax.set_xlabel("时间")
|
||||
self.ax.set_ylabel("兴趣度")
|
||||
self.ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))
|
||||
self.ax.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S"))
|
||||
self.ax.grid(True)
|
||||
self.ax.set_ylim(0, 10) # 固定 Y 轴范围 0-10
|
||||
|
||||
@@ -229,7 +240,7 @@ class InterestMonitorApp:
|
||||
active_streams = sorted(
|
||||
self.stream_history.items(),
|
||||
key=lambda item: item[1][-1][1] if item[1] else 0, # 按最后兴趣度排序
|
||||
reverse=True
|
||||
reverse=True,
|
||||
)[:MAX_STREAMS_TO_DISPLAY]
|
||||
|
||||
all_times = [] # 用于确定 X 轴范围
|
||||
@@ -251,11 +262,11 @@ class InterestMonitorApp:
|
||||
mpl_dates,
|
||||
interests,
|
||||
label=display_label, # *** Use display_label ***
|
||||
color=self.stream_colors.get(stream_id, 'grey'),
|
||||
marker='.',
|
||||
color=self.stream_colors.get(stream_id, "grey"),
|
||||
marker=".",
|
||||
markersize=3,
|
||||
linestyle='-',
|
||||
linewidth=1
|
||||
linestyle="-",
|
||||
linewidth=1,
|
||||
)
|
||||
except ValueError as e:
|
||||
print(f"Skipping plot for {stream_id} due to invalid timestamp: {e}")
|
||||
@@ -277,16 +288,14 @@ class InterestMonitorApp:
|
||||
one_hour_ago = now - timedelta(hours=1)
|
||||
self.ax.set_xlim(one_hour_ago, now)
|
||||
|
||||
|
||||
# 添加图例
|
||||
if active_streams:
|
||||
# 调整图例位置和大小
|
||||
# 字体已通过全局 matplotlib.rcParams 设置
|
||||
self.ax.legend(loc='upper left', bbox_to_anchor=(1.02, 1), borderaxespad=0., fontsize='x-small')
|
||||
self.ax.legend(loc="upper left", bbox_to_anchor=(1.02, 1), borderaxespad=0.0, fontsize="x-small")
|
||||
# 调整布局,确保图例不被裁剪
|
||||
self.fig.tight_layout(rect=[0, 0, 0.85, 1]) # 右侧留出空间给图例
|
||||
|
||||
|
||||
self.canvas.draw() # 重绘画布
|
||||
|
||||
def update_single_stream_plot(self):
|
||||
@@ -305,7 +314,7 @@ class InterestMonitorApp:
|
||||
self.ax_single_probability.set_ylabel("概率")
|
||||
self.ax_single_probability.grid(True)
|
||||
self.ax_single_probability.set_ylim(0, 1.05) # 固定 Y 轴范围 0-1
|
||||
self.ax_single_probability.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))
|
||||
self.ax_single_probability.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S"))
|
||||
|
||||
selected_name = self.selected_stream_id.get()
|
||||
selected_sid = None
|
||||
@@ -329,11 +338,11 @@ class InterestMonitorApp:
|
||||
self.ax_single_interest.plot(
|
||||
mpl_dates,
|
||||
interests,
|
||||
color=self.stream_colors.get(selected_sid, 'blue'),
|
||||
marker='.',
|
||||
color=self.stream_colors.get(selected_sid, "blue"),
|
||||
marker=".",
|
||||
markersize=3,
|
||||
linestyle='-',
|
||||
linewidth=1
|
||||
linestyle="-",
|
||||
linewidth=1,
|
||||
)
|
||||
except ValueError as e:
|
||||
print(f"Skipping interest plot for {selected_sid} due to invalid timestamp: {e}")
|
||||
@@ -349,11 +358,11 @@ class InterestMonitorApp:
|
||||
self.ax_single_probability.plot(
|
||||
prob_mpl_dates,
|
||||
probabilities,
|
||||
color=self.stream_colors.get(selected_sid, 'green'), # 可以用不同颜色
|
||||
marker='.',
|
||||
color=self.stream_colors.get(selected_sid, "green"), # 可以用不同颜色
|
||||
marker=".",
|
||||
markersize=3,
|
||||
linestyle='-',
|
||||
linewidth=1
|
||||
linestyle="-",
|
||||
linewidth=1,
|
||||
)
|
||||
except ValueError as e:
|
||||
print(f"Skipping probability plot for {selected_sid} due to invalid timestamp: {e}")
|
||||
@@ -387,6 +396,7 @@ class InterestMonitorApp:
|
||||
except Exception as e:
|
||||
# 提供更详细的错误信息
|
||||
import traceback
|
||||
|
||||
error_msg = f"Error during update: {e}\n{traceback.format_exc()}"
|
||||
self.set_status(error_msg, "red")
|
||||
print(error_msg) # 打印详细错误到控制台
|
||||
@@ -398,13 +408,14 @@ class InterestMonitorApp:
|
||||
"""更新状态栏标签"""
|
||||
# 限制状态栏消息长度
|
||||
max_len = 150
|
||||
display_message = (message[:max_len] + '...') if len(message) > max_len else message
|
||||
display_message = (message[:max_len] + "...") if len(message) > max_len else message
|
||||
self.status_label.config(text=display_message, fg=color)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 导入 timedelta 用于默认时间范围
|
||||
from datetime import timedelta
|
||||
|
||||
root = tk.Tk()
|
||||
app = InterestMonitorApp(root)
|
||||
root.mainloop()
|
||||
@@ -22,9 +22,7 @@ class ToolUser:
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
async def _build_tool_prompt(
|
||||
message_txt: str, chat_stream: ChatStream, subheartflow: SubHeartflow = None
|
||||
):
|
||||
async def _build_tool_prompt(message_txt: str, chat_stream: ChatStream, subheartflow: SubHeartflow = None):
|
||||
"""构建工具使用的提示词
|
||||
|
||||
Args:
|
||||
@@ -114,9 +112,7 @@ class ToolUser:
|
||||
logger.error(f"执行工具调用时发生错误: {str(e)}")
|
||||
return None
|
||||
|
||||
async def use_tool(
|
||||
self, message_txt: str, chat_stream: ChatStream, sub_heartflow: SubHeartflow = None
|
||||
):
|
||||
async def use_tool(self, message_txt: str, chat_stream: ChatStream, sub_heartflow: SubHeartflow = None):
|
||||
"""使用工具辅助思考,判断是否需要额外信息
|
||||
|
||||
Args:
|
||||
|
||||
@@ -87,13 +87,19 @@ class ChattingObservation(Observation):
|
||||
# 如果没有获取到限制数量内的较新消息,可能仍然有更早的消息,但我们只关注最近的
|
||||
# 检查是否有任何新消息(即使超出限制),以决定是否更新 last_observe_time
|
||||
# 注意:这里的查询也可能与其他并发 observe 冲突,但锁保护了状态更新
|
||||
any_new_message = db.messages.find_one({"chat_id": self.chat_id, "time": {"$gt": self.last_observe_time}})
|
||||
any_new_message = db.messages.find_one(
|
||||
{"chat_id": self.chat_id, "time": {"$gt": self.last_observe_time}}
|
||||
)
|
||||
if not any_new_message:
|
||||
return # 确实没有新消息
|
||||
|
||||
# 如果有超过限制的更早的新消息,仍然需要更新时间戳,防止重复获取旧消息
|
||||
# 但不将它们加入 talking_message
|
||||
latest_message_time_cursor = db.messages.find({"chat_id": self.chat_id, "time": {"$gt": self.last_observe_time}}).sort("time", -1).limit(1)
|
||||
latest_message_time_cursor = (
|
||||
db.messages.find({"chat_id": self.chat_id, "time": {"$gt": self.last_observe_time}})
|
||||
.sort("time", -1)
|
||||
.limit(1)
|
||||
)
|
||||
latest_time_doc = next(latest_message_time_cursor, None)
|
||||
if latest_time_doc:
|
||||
# 确保只在严格大于时更新,避免因并发查询导致时间戳回退
|
||||
@@ -106,7 +112,9 @@ class ChattingObservation(Observation):
|
||||
truly_new_messages = [msg for msg in new_messages if msg["time"] > self.last_observe_time]
|
||||
|
||||
if not truly_new_messages:
|
||||
logger.debug(f"Chat {self.chat_id}: Fetched messages, but already processed by another concurrent observe call.")
|
||||
logger.debug(
|
||||
f"Chat {self.chat_id}: Fetched messages, but already processed by another concurrent observe call."
|
||||
)
|
||||
return # 所有获取的消息都已被处理
|
||||
|
||||
# 如果获取到了 truly_new_messages (在限制内且时间戳大于上次记录)
|
||||
@@ -129,7 +137,9 @@ class ChattingObservation(Observation):
|
||||
messages_to_remove_count = len(self.talking_message) - self.max_now_obs_len
|
||||
oldest_messages = self.talking_message[:messages_to_remove_count]
|
||||
self.talking_message = self.talking_message[messages_to_remove_count:] # 保留后半部分,即最新的
|
||||
oldest_messages_str = "\n".join([msg["detailed_plain_text"] for msg in oldest_messages if "detailed_plain_text" in msg]) # 增加检查
|
||||
oldest_messages_str = "\n".join(
|
||||
[msg["detailed_plain_text"] for msg in oldest_messages if "detailed_plain_text" in msg]
|
||||
) # 增加检查
|
||||
oldest_timestamps = [msg["time"] for msg in oldest_messages]
|
||||
|
||||
# 调用 LLM 总结主题
|
||||
@@ -173,7 +183,9 @@ class ChattingObservation(Observation):
|
||||
now_message_str += self.translate_message_list_to_str(talking_message=self.talking_message)
|
||||
self.now_message_info = now_message_str
|
||||
|
||||
logger.debug(f"Chat {self.chat_id} - 压缩早期记忆:{self.mid_memory_info}\n现在聊天内容:{self.now_message_info}")
|
||||
logger.debug(
|
||||
f"Chat {self.chat_id} - 压缩早期记忆:{self.mid_memory_info}\n现在聊天内容:{self.now_message_info}"
|
||||
)
|
||||
# 锁在退出 async with 块时自动释放
|
||||
|
||||
async def update_talking_summary(self, new_messages_str):
|
||||
|
||||
@@ -165,8 +165,10 @@ class SubHeartflow:
|
||||
|
||||
# 检查是否超过指定时间没有激活 (例如,没有被调用进行思考)
|
||||
if current_time - self.last_active_time > global_config.sub_heart_flow_stop_time: # 例如 5 分钟
|
||||
logger.info(f"子心流 {self.subheartflow_id} 超过 {global_config.sub_heart_flow_stop_time} 秒没有激活,正在销毁..."
|
||||
f" (Last active: {datetime.fromtimestamp(self.last_active_time).strftime('%Y-%m-%d %H:%M:%S')})")
|
||||
logger.info(
|
||||
f"子心流 {self.subheartflow_id} 超过 {global_config.sub_heart_flow_stop_time} 秒没有激活,正在销毁..."
|
||||
f" (Last active: {datetime.fromtimestamp(self.last_active_time).strftime('%Y-%m-%d %H:%M:%S')})"
|
||||
)
|
||||
# 在这里添加实际的销毁逻辑,例如从主 Heartflow 管理器中移除自身
|
||||
# heartflow.remove_subheartflow(self.subheartflow_id) # 假设有这样的方法
|
||||
break # 退出循环以停止任务
|
||||
@@ -198,7 +200,10 @@ class SubHeartflow:
|
||||
logger.error(f"[{self.subheartflow_id}] do_observe called but no valid observation found.")
|
||||
|
||||
async def do_thinking_before_reply(
|
||||
self, chat_stream: ChatStream, extra_info: str, obs_id: list[str] = None # 修改 obs_id 类型为 list[str]
|
||||
self,
|
||||
chat_stream: ChatStream,
|
||||
extra_info: str,
|
||||
obs_id: list[str] = None, # 修改 obs_id 类型为 list[str]
|
||||
):
|
||||
async with self._thinking_lock: # 获取思考锁
|
||||
# --- 在思考前确保观察已执行 --- #
|
||||
@@ -220,13 +225,14 @@ class SubHeartflow:
|
||||
chat_observe_info = observation.get_observe_info(obs_id)
|
||||
logger.debug(f"[{self.subheartflow_id}] Using specific observation IDs: {obs_id}")
|
||||
except Exception as e:
|
||||
logger.error(f"[{self.subheartflow_id}] Error getting observe info with IDs {obs_id}: {e}. Falling back.")
|
||||
logger.error(
|
||||
f"[{self.subheartflow_id}] Error getting observe info with IDs {obs_id}: {e}. Falling back."
|
||||
)
|
||||
chat_observe_info = observation.get_observe_info() # 出错时回退到默认观察
|
||||
else:
|
||||
chat_observe_info = observation.get_observe_info()
|
||||
logger.debug(f"[{self.subheartflow_id}] Using default observation info.")
|
||||
|
||||
|
||||
# --- 构建 Prompt (基本逻辑不变) --- #
|
||||
extra_info_prompt = ""
|
||||
if extra_info:
|
||||
|
||||
@@ -125,8 +125,6 @@ class ChatBot:
|
||||
|
||||
await self.heartFC_processor.process_message(message_data)
|
||||
|
||||
|
||||
|
||||
elif global_config.response_mode == "reasoning":
|
||||
# logger.debug(f"开始推理模式{str(message_data)[:50]}...")
|
||||
await self.reasoning_chat.process_message(message_data)
|
||||
|
||||
@@ -37,7 +37,11 @@ class ResponseGenerator:
|
||||
self.current_model_type = "r1" # 默认使用 R1
|
||||
self.current_model_name = "unknown model"
|
||||
|
||||
async def generate_response(self, message: MessageRecv, thinking_id: str,) -> Optional[List[str]]:
|
||||
async def generate_response(
|
||||
self,
|
||||
message: MessageRecv,
|
||||
thinking_id: str,
|
||||
) -> Optional[List[str]]:
|
||||
"""根据当前模型类型选择对应的生成函数"""
|
||||
|
||||
logger.info(
|
||||
@@ -47,16 +51,12 @@ class ResponseGenerator:
|
||||
arousal_multiplier = MoodManager.get_instance().get_arousal_multiplier()
|
||||
|
||||
with Timer() as t_generate_response:
|
||||
|
||||
current_model = self.model_normal
|
||||
current_model.temperature = (
|
||||
global_config.llm_normal["temp"] * arousal_multiplier
|
||||
) # 激活度越高,温度越高
|
||||
current_model.temperature = global_config.llm_normal["temp"] * arousal_multiplier # 激活度越高,温度越高
|
||||
model_response = await self._generate_response_with_model(
|
||||
message, current_model, thinking_id, mode="normal"
|
||||
)
|
||||
|
||||
|
||||
if model_response:
|
||||
logger.info(
|
||||
f"{global_config.BOT_NICKNAME}的回复是:{model_response},生成回复时间: {t_generate_response.human_readable}"
|
||||
|
||||
@@ -33,6 +33,7 @@ logger = get_module_logger("heartFC_chat", config=chat_config)
|
||||
# 新增常量
|
||||
INTEREST_MONITOR_INTERVAL_SECONDS = 1
|
||||
|
||||
|
||||
class HeartFC_Chat:
|
||||
_instance = None # For potential singleton access if needed by MessageManager
|
||||
|
||||
@@ -59,6 +60,7 @@ class HeartFC_Chat:
|
||||
@classmethod
|
||||
def get_instance(cls):
|
||||
return cls._instance
|
||||
|
||||
# --- End Added Class Method ---
|
||||
|
||||
async def start(self):
|
||||
@@ -95,6 +97,7 @@ class HeartFC_Chat:
|
||||
return None
|
||||
self.pf_chatting_instances[stream_id] = instance
|
||||
return self.pf_chatting_instances[stream_id]
|
||||
|
||||
# --- End Added PFChatting Instance Manager ---
|
||||
|
||||
async def _interest_monitor_loop(self):
|
||||
@@ -121,7 +124,9 @@ class HeartFC_Chat:
|
||||
# if should_trigger:
|
||||
# logger.info(f"[{stream_name}] 基于兴趣概率决定启动交流模式 (概率: {interest_chatting.current_reply_probability:.4f})。")
|
||||
else:
|
||||
logger.trace(f"[{stream_name}] 没有找到对应的 InterestChatting 实例,跳过基于兴趣的触发检查。")
|
||||
logger.trace(
|
||||
f"[{stream_name}] 没有找到对应的 InterestChatting 实例,跳过基于兴趣的触发检查。"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"检查兴趣触发器时出错 流 {stream_name}: {e}")
|
||||
logger.error(traceback.format_exc())
|
||||
@@ -169,7 +174,9 @@ class HeartFC_Chat:
|
||||
MessageManager().add_message(thinking_message)
|
||||
return thinking_id
|
||||
|
||||
async def _send_response_messages(self, anchor_message: Optional[MessageRecv], response_set: List[str], thinking_id) -> Optional[MessageSending]:
|
||||
async def _send_response_messages(
|
||||
self, anchor_message: Optional[MessageRecv], response_set: List[str], thinking_id
|
||||
) -> Optional[MessageSending]:
|
||||
"""发送回复消息 (尝试锚定到 anchor_message)"""
|
||||
if not anchor_message or not anchor_message.chat_stream:
|
||||
logger.error("无法发送回复,缺少有效的锚点消息或聊天流。")
|
||||
@@ -271,7 +278,7 @@ class HeartFC_Chat:
|
||||
await relationship_manager.calculate_update_relationship_value(
|
||||
chat_stream=anchor_message.chat_stream, # 使用锚点消息的流
|
||||
label=emotion,
|
||||
stance=stance
|
||||
stance=stance,
|
||||
)
|
||||
self.mood_manager.update_mood_from_emotion(emotion, global_config.mood_intensity_factor)
|
||||
|
||||
@@ -314,18 +321,31 @@ class HeartFC_Chat:
|
||||
if observed_messages:
|
||||
try:
|
||||
last_msg_dict = observed_messages[-1]
|
||||
logger.debug(f"[{stream_name}] Attempting to reconstruct MessageRecv from last observed message.")
|
||||
logger.debug(
|
||||
f"[{stream_name}] Attempting to reconstruct MessageRecv from last observed message."
|
||||
)
|
||||
anchor_message = MessageRecv(last_msg_dict, chat_stream=chat)
|
||||
if not (anchor_message and anchor_message.message_info and anchor_message.message_info.message_id and anchor_message.message_info.user_info):
|
||||
if not (
|
||||
anchor_message
|
||||
and anchor_message.message_info
|
||||
and anchor_message.message_info.message_id
|
||||
and anchor_message.message_info.user_info
|
||||
):
|
||||
raise ValueError("Reconstructed MessageRecv missing essential info.")
|
||||
userinfo = anchor_message.message_info.user_info
|
||||
messageinfo = anchor_message.message_info
|
||||
logger.debug(f"[{stream_name}] Successfully reconstructed anchor message: ID={messageinfo.message_id}, Sender={userinfo.user_nickname}")
|
||||
logger.debug(
|
||||
f"[{stream_name}] Successfully reconstructed anchor message: ID={messageinfo.message_id}, Sender={userinfo.user_nickname}"
|
||||
)
|
||||
except Exception as e_reconstruct:
|
||||
logger.warning(f"[{stream_name}] Reconstructing MessageRecv from observed message failed: {e_reconstruct}. Will create placeholder.")
|
||||
logger.warning(
|
||||
f"[{stream_name}] Reconstructing MessageRecv from observed message failed: {e_reconstruct}. Will create placeholder."
|
||||
)
|
||||
reconstruction_failed = True
|
||||
else:
|
||||
logger.warning(f"[{stream_name}] observed_messages is empty. Will create placeholder anchor message.")
|
||||
logger.warning(
|
||||
f"[{stream_name}] observed_messages is empty. Will create placeholder anchor message."
|
||||
)
|
||||
reconstruction_failed = True # Treat empty observed_messages as a failure to reconstruct
|
||||
|
||||
# 如果重建失败或 observed_messages 为空,创建占位符
|
||||
@@ -337,7 +357,7 @@ class HeartFC_Chat:
|
||||
platform=chat.platform,
|
||||
group_info=chat.group_info,
|
||||
user_info=placeholder_user,
|
||||
time=time.time()
|
||||
time=time.time(),
|
||||
# 其他 BaseMessageInfo 可能需要的字段设为默认值或 None
|
||||
)
|
||||
# 创建 MessageRecv 实例,注意它需要消息字典结构,我们创建一个最小化的
|
||||
@@ -353,7 +373,9 @@ class HeartFC_Chat:
|
||||
anchor_message.update_chat_stream(chat)
|
||||
userinfo = anchor_message.message_info.user_info
|
||||
messageinfo = anchor_message.message_info
|
||||
logger.info(f"[{stream_name}] Created placeholder anchor message: ID={messageinfo.message_id}, Sender={userinfo.user_nickname}")
|
||||
logger.info(
|
||||
f"[{stream_name}] Created placeholder anchor message: ID={messageinfo.message_id}, Sender={userinfo.user_nickname}"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[{stream_name}] 获取或创建锚点消息时出错: {e}")
|
||||
@@ -364,7 +386,7 @@ class HeartFC_Chat:
|
||||
try:
|
||||
container = MessageManager().get_container(chat.stream_id)
|
||||
thinking_count = container.count_thinking_messages()
|
||||
max_thinking_messages = getattr(global_config, 'max_concurrent_thinking_messages', 3)
|
||||
max_thinking_messages = getattr(global_config, "max_concurrent_thinking_messages", 3)
|
||||
if thinking_count >= max_thinking_messages:
|
||||
logger.warning(f"聊天流 {stream_name} 已有 {thinking_count} 条思考消息,取消回复。")
|
||||
return
|
||||
@@ -403,11 +425,13 @@ class HeartFC_Chat:
|
||||
for msg_dict in observed_messages:
|
||||
# 假设 detailed_plain_text 字段包含所需文本
|
||||
# 你可能需要更复杂的逻辑来格式化,例如添加发送者和时间
|
||||
text = msg_dict.get('detailed_plain_text', '')
|
||||
text = msg_dict.get("detailed_plain_text", "")
|
||||
if text:
|
||||
context_texts.append(text)
|
||||
observation_context_text = "\n".join(context_texts)
|
||||
logger.debug(f"[{stream_name}] Context for tools:\n{observation_context_text[-200:]}...") # 打印部分上下文
|
||||
logger.debug(
|
||||
f"[{stream_name}] Context for tools:\n{observation_context_text[-200:]}..."
|
||||
) # 打印部分上下文
|
||||
else:
|
||||
logger.warning(f"[{stream_name}] observed_messages 列表为空,无法为工具提供上下文。")
|
||||
|
||||
@@ -416,7 +440,7 @@ class HeartFC_Chat:
|
||||
tool_result = await self.tool_user.use_tool(
|
||||
message_txt=observation_context_text, # <--- 使用观察上下文
|
||||
chat_stream=chat,
|
||||
sub_heartflow=sub_hf
|
||||
sub_heartflow=sub_hf,
|
||||
)
|
||||
if tool_result.get("used_tools", False):
|
||||
if "structured_info" in tool_result:
|
||||
@@ -496,7 +520,9 @@ class HeartFC_Chat:
|
||||
# --- 12. 记录性能日志 --- #
|
||||
timing_str = " | ".join([f"{step}: {duration:.2f}秒" for step, duration in timing_results.items()])
|
||||
response_msg = " ".join(response_set) if response_set else "无回复"
|
||||
logger.info(f"[{stream_name}] 回复任务完成 (Observation Triggered): | 思维消息: {response_msg[:30]}... | 性能计时: {timing_str}")
|
||||
logger.info(
|
||||
f"[{stream_name}] 回复任务完成 (Observation Triggered): | 思维消息: {response_msg[:30]}... | 性能计时: {timing_str}"
|
||||
)
|
||||
|
||||
# --- 13. 更新关系情绪 (使用 anchor_message) ---
|
||||
if first_bot_msg: # 仅在成功发送消息后
|
||||
@@ -514,6 +540,7 @@ class HeartFC_Chat:
|
||||
finally:
|
||||
# 可以在这里添加清理逻辑,如果有的话
|
||||
pass
|
||||
|
||||
# --- 结束重构 ---
|
||||
|
||||
# _create_thinking_message, _send_response_messages, _handle_emoji, _update_relationship
|
||||
|
||||
@@ -24,10 +24,13 @@ logger = get_module_logger("heartFC_processor", config=processor_config)
|
||||
# # 定义兴趣度增加触发回复的阈值 (移至 InterestManager)
|
||||
# INTEREST_INCREASE_THRESHOLD = 0.5
|
||||
|
||||
|
||||
class HeartFC_Processor:
|
||||
def __init__(self, chat_instance: HeartFC_Chat):
|
||||
self.storage = MessageStorage()
|
||||
self.interest_manager = InterestManager() # TODO: 可能需要传递 chat_instance 给 InterestManager 或修改其方法签名
|
||||
self.interest_manager = (
|
||||
InterestManager()
|
||||
) # TODO: 可能需要传递 chat_instance 给 InterestManager 或修改其方法签名
|
||||
self.chat_instance = chat_instance # 持有 HeartFC_Chat 实例
|
||||
|
||||
async def process_message(self, message_data: str) -> None:
|
||||
@@ -50,7 +53,9 @@ class HeartFC_Processor:
|
||||
group_info=groupinfo,
|
||||
)
|
||||
if not chat:
|
||||
logger.error(f"无法为消息创建或获取聊天流: user {userinfo.user_id}, group {groupinfo.group_id if groupinfo else 'None'}")
|
||||
logger.error(
|
||||
f"无法为消息创建或获取聊天流: user {userinfo.user_id}, group {groupinfo.group_id if groupinfo else 'None'}"
|
||||
)
|
||||
return
|
||||
|
||||
message.update_chat_stream(chat)
|
||||
@@ -77,9 +82,11 @@ class HeartFC_Processor:
|
||||
if message.message_segment.type != "seglist":
|
||||
F_type = message.message_segment.type
|
||||
else:
|
||||
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
|
||||
):
|
||||
F_type = message.message_segment.data[0].type
|
||||
if F_type == "text":
|
||||
logger.debug(f"触发缓冲,消息:{message.processed_plain_text}")
|
||||
@@ -107,7 +114,8 @@ class HeartFC_Processor:
|
||||
try:
|
||||
with Timer("记忆激活", timing_results):
|
||||
interested_rate = await HippocampusManager.get_instance().get_activate_from_text(
|
||||
message.processed_plain_text, fast_retrieval=True # 使用更新后的文本
|
||||
message.processed_plain_text,
|
||||
fast_retrieval=True, # 使用更新后的文本
|
||||
)
|
||||
logger.trace(f"记忆激活率 (通过缓冲后): {interested_rate:.2f}")
|
||||
except Exception as e:
|
||||
@@ -121,7 +129,9 @@ class HeartFC_Processor:
|
||||
try:
|
||||
self.interest_manager.increase_interest(chat.stream_id, value=interested_rate)
|
||||
current_interest = self.interest_manager.get_interest(chat.stream_id) # 获取更新后的值用于日志
|
||||
logger.trace(f"使用激活率 {interested_rate:.2f} 更新后 (通过缓冲后),当前兴趣度: {current_interest:.2f}")
|
||||
logger.trace(
|
||||
f"使用激活率 {interested_rate:.2f} 更新后 (通过缓冲后),当前兴趣度: {current_interest:.2f}"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"更新兴趣度失败: {e}") # 调整日志消息
|
||||
|
||||
@@ -12,7 +12,7 @@ from src.plugins.chat.chat_stream import chat_manager # *** Import ChatManager *
|
||||
# 定义日志配置 (使用 loguru 格式)
|
||||
interest_log_config = LogConfig(
|
||||
console_format=DEFAULT_CONFIG["console_format"], # 使用默认控制台格式
|
||||
file_format=DEFAULT_CONFIG["file_format"] # 使用默认文件格式
|
||||
file_format=DEFAULT_CONFIG["file_format"], # 使用默认文件格式
|
||||
)
|
||||
logger = get_module_logger("InterestManager", config=interest_log_config)
|
||||
|
||||
@@ -38,15 +38,18 @@ PROBABILITY_DECAY_FACTOR_PER_SECOND = 0.3 # 低于阈值时,每秒概率衰
|
||||
MAX_REPLY_PROBABILITY = 1 # 回复概率上限 (示例值)
|
||||
# --- 结束:概率回复相关常量 ---
|
||||
|
||||
|
||||
class InterestChatting:
|
||||
def __init__(self,
|
||||
def __init__(
|
||||
self,
|
||||
decay_rate=DEFAULT_DECAY_RATE_PER_SECOND,
|
||||
max_interest=MAX_INTEREST,
|
||||
trigger_threshold=REPLY_TRIGGER_THRESHOLD,
|
||||
base_reply_probability=BASE_REPLY_PROBABILITY,
|
||||
increase_rate=PROBABILITY_INCREASE_RATE_PER_SECOND,
|
||||
decay_factor=PROBABILITY_DECAY_FACTOR_PER_SECOND,
|
||||
max_probability=MAX_REPLY_PROBABILITY):
|
||||
max_probability=MAX_REPLY_PROBABILITY,
|
||||
):
|
||||
self.interest_level: float = 0.0
|
||||
self.last_update_time: float = time.time() # 同时作为兴趣和概率的更新时间基准
|
||||
self.decay_rate_per_second: float = decay_rate
|
||||
@@ -76,11 +79,15 @@ class InterestChatting:
|
||||
else:
|
||||
# 检查 decay_rate_per_second 是否为非正数,避免 math domain error
|
||||
if self.decay_rate_per_second <= 0:
|
||||
logger.warning(f"InterestChatting encountered non-positive decay rate: {self.decay_rate_per_second}. Setting interest to 0.")
|
||||
logger.warning(
|
||||
f"InterestChatting encountered non-positive decay rate: {self.decay_rate_per_second}. Setting interest to 0."
|
||||
)
|
||||
self.interest_level = 0.0
|
||||
# 检查 interest_level 是否为负数,虽然理论上不应发生,但以防万一
|
||||
elif self.interest_level < 0:
|
||||
logger.warning(f"InterestChatting encountered negative interest level: {self.interest_level}. Setting interest to 0.")
|
||||
logger.warning(
|
||||
f"InterestChatting encountered negative interest level: {self.interest_level}. Setting interest to 0."
|
||||
)
|
||||
self.interest_level = 0.0
|
||||
else:
|
||||
try:
|
||||
@@ -88,7 +95,9 @@ class InterestChatting:
|
||||
self.interest_level *= decay_factor
|
||||
except ValueError as e:
|
||||
# 捕获潜在的 math domain error,例如对负数开非整数次方(虽然已加保护)
|
||||
logger.error(f"Math error during decay calculation: {e}. Rate: {self.decay_rate_per_second}, Delta: {time_delta}, Level: {self.interest_level}. Setting interest to 0.")
|
||||
logger.error(
|
||||
f"Math error during decay calculation: {e}. Rate: {self.decay_rate_per_second}, Delta: {time_delta}, Level: {self.interest_level}. Setting interest to 0."
|
||||
)
|
||||
self.interest_level = 0.0
|
||||
|
||||
# 防止低于阈值 (如果需要)
|
||||
@@ -110,7 +119,9 @@ class InterestChatting:
|
||||
if not self.is_above_threshold:
|
||||
# 刚跨过阈值,重置为基础概率
|
||||
self.current_reply_probability = self.base_reply_probability
|
||||
logger.debug(f"兴趣跨过阈值 ({self.trigger_threshold}). 概率重置为基础值: {self.base_reply_probability:.4f}")
|
||||
logger.debug(
|
||||
f"兴趣跨过阈值 ({self.trigger_threshold}). 概率重置为基础值: {self.base_reply_probability:.4f}"
|
||||
)
|
||||
else:
|
||||
# 持续高于阈值,线性增加概率
|
||||
increase_amount = self.probability_increase_rate * time_delta
|
||||
@@ -196,7 +207,7 @@ class InterestChatting:
|
||||
"last_update_time": self.last_update_time,
|
||||
"current_reply_probability": round(self.current_reply_probability, 4), # 添加概率到状态
|
||||
"is_above_threshold": self.is_above_threshold, # 添加阈值状态
|
||||
"last_interaction_time": self.last_interaction_time # 新增:添加最后交互时间到状态
|
||||
"last_interaction_time": self.last_interaction_time, # 新增:添加最后交互时间到状态
|
||||
# 可以选择性地暴露 last_increase_amount 给状态,方便调试
|
||||
# "last_increase_amount": round(self.last_increase_amount, 2)
|
||||
}
|
||||
@@ -286,7 +297,7 @@ class InterestManager:
|
||||
all_states = self.get_all_interest_states() # 获取当前所有状态
|
||||
|
||||
# 以追加模式打开历史日志文件
|
||||
with open(self._history_log_file_path, 'a', encoding='utf-8') as f:
|
||||
with open(self._history_log_file_path, "a", encoding="utf-8") as f:
|
||||
count = 0
|
||||
for stream_id, state in all_states.items():
|
||||
# *** Get group name from ChatManager ***
|
||||
@@ -298,7 +309,11 @@ class InterestManager:
|
||||
group_name = chat_stream.group_info.group_name
|
||||
elif chat_stream and not chat_stream.group_info:
|
||||
# Handle private chats - maybe use user nickname?
|
||||
group_name = f"私聊_{chat_stream.user_info.user_nickname}" if chat_stream.user_info else stream_id
|
||||
group_name = (
|
||||
f"私聊_{chat_stream.user_info.user_nickname}"
|
||||
if chat_stream.user_info
|
||||
else stream_id
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Could not get group name for stream_id {stream_id}: {e}")
|
||||
# Fallback to stream_id is already handled by default value
|
||||
@@ -310,11 +325,11 @@ class InterestManager:
|
||||
"group_name": group_name, # *** Add group_name ***
|
||||
# --- 新增:记录概率相关信息 ---
|
||||
"reply_probability": state.get("current_reply_probability", 0.0),
|
||||
"is_above_threshold": state.get("is_above_threshold", False)
|
||||
"is_above_threshold": state.get("is_above_threshold", False),
|
||||
# --- 结束新增 ---
|
||||
}
|
||||
# 将每个条目作为单独的 JSON 行写入
|
||||
f.write(json.dumps(log_entry, ensure_ascii=False) + '\n')
|
||||
f.write(json.dumps(log_entry, ensure_ascii=False) + "\n")
|
||||
count += 1
|
||||
# logger.debug(f"Successfully appended {count} interest history entries to {self._history_log_file_path}")
|
||||
|
||||
@@ -355,27 +370,24 @@ class InterestManager:
|
||||
if self._cleanup_task is None or self._cleanup_task.done():
|
||||
self._cleanup_task = asyncio.create_task(
|
||||
self._periodic_cleanup_task(
|
||||
interval_seconds=CLEANUP_INTERVAL_SECONDS,
|
||||
max_age_seconds=INACTIVE_THRESHOLD_SECONDS
|
||||
interval_seconds=CLEANUP_INTERVAL_SECONDS, max_age_seconds=INACTIVE_THRESHOLD_SECONDS
|
||||
)
|
||||
)
|
||||
logger.info(f"已创建定期清理任务。间隔时间: {CLEANUP_INTERVAL_SECONDS}秒, 不活跃阈值: {INACTIVE_THRESHOLD_SECONDS}秒")
|
||||
logger.info(
|
||||
f"已创建定期清理任务。间隔时间: {CLEANUP_INTERVAL_SECONDS}秒, 不活跃阈值: {INACTIVE_THRESHOLD_SECONDS}秒"
|
||||
)
|
||||
else:
|
||||
logger.warning("跳过创建清理任务:任务已在运行或存在。")
|
||||
|
||||
if self._logging_task is None or self._logging_task.done():
|
||||
self._logging_task = asyncio.create_task(
|
||||
self._periodic_log_task(interval_seconds=LOG_INTERVAL_SECONDS)
|
||||
)
|
||||
self._logging_task = asyncio.create_task(self._periodic_log_task(interval_seconds=LOG_INTERVAL_SECONDS))
|
||||
logger.info(f"已创建定期日志任务。间隔时间: {LOG_INTERVAL_SECONDS}秒")
|
||||
else:
|
||||
logger.warning("跳过创建日志任务:任务已在运行或存在。")
|
||||
|
||||
# 启动新的衰减任务
|
||||
if self._decay_task is None or self._decay_task.done():
|
||||
self._decay_task = asyncio.create_task(
|
||||
self._periodic_decay_task()
|
||||
)
|
||||
self._decay_task = asyncio.create_task(self._periodic_decay_task())
|
||||
logger.info("已创建定期衰减任务。间隔时间: 1秒")
|
||||
else:
|
||||
logger.warning("跳过创建衰减任务:任务已在运行或存在。")
|
||||
@@ -414,7 +426,7 @@ class InterestManager:
|
||||
base_reply_probability=BASE_REPLY_PROBABILITY,
|
||||
increase_rate=PROBABILITY_INCREASE_RATE_PER_SECOND,
|
||||
decay_factor=PROBABILITY_DECAY_FACTOR_PER_SECOND,
|
||||
max_probability=MAX_REPLY_PROBABILITY
|
||||
max_probability=MAX_REPLY_PROBABILITY,
|
||||
)
|
||||
# --- 结束修改 ---
|
||||
# 首次创建时兴趣为 0,由第一次消息的 activate rate 决定初始值
|
||||
@@ -434,7 +446,9 @@ class InterestManager:
|
||||
# 调用修改后的 increase_interest,不再传入 message
|
||||
interest_chatting.increase_interest(current_time, value)
|
||||
stream_name = chat_manager.get_stream_name(stream_id) or stream_id # 获取流名称
|
||||
logger.debug(f"增加了聊天流 {stream_name} 的兴趣度 {value:.2f},当前值为 {interest_chatting.interest_level:.2f}") # 更新日志
|
||||
logger.debug(
|
||||
f"增加了聊天流 {stream_name} 的兴趣度 {value:.2f},当前值为 {interest_chatting.interest_level:.2f}"
|
||||
) # 更新日志
|
||||
|
||||
def decrease_interest(self, stream_id: str, value: float):
|
||||
"""降低指定聊天流的兴趣度"""
|
||||
@@ -444,7 +458,9 @@ class InterestManager:
|
||||
if interest_chatting:
|
||||
interest_chatting.decrease_interest(current_time, value)
|
||||
stream_name = chat_manager.get_stream_name(stream_id) or stream_id # 获取流名称
|
||||
logger.debug(f"降低了聊天流 {stream_name} 的兴趣度 {value:.2f},当前值为 {interest_chatting.interest_level:.2f}")
|
||||
logger.debug(
|
||||
f"降低了聊天流 {stream_name} 的兴趣度 {value:.2f},当前值为 {interest_chatting.interest_level:.2f}"
|
||||
)
|
||||
else:
|
||||
stream_name = chat_manager.get_stream_name(stream_id) or stream_id # 获取流名称
|
||||
logger.warning(f"尝试降低不存在的聊天流 {stream_name} 的兴趣度")
|
||||
@@ -469,7 +485,9 @@ class InterestManager:
|
||||
should_remove = False
|
||||
reason = ""
|
||||
# 只有设置了 max_age_seconds 才检查时间
|
||||
if max_age_seconds is not None and (current_time - last_interaction) > max_age_seconds: # 使用 last_interaction
|
||||
if (
|
||||
max_age_seconds is not None and (current_time - last_interaction) > max_age_seconds
|
||||
): # 使用 last_interaction
|
||||
should_remove = True
|
||||
reason = f"inactive time ({current_time - last_interaction:.0f}s) > max age ({max_age_seconds}s)" # 更新日志信息
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ logger = get_module_logger("msg_sender", config=sender_config)
|
||||
|
||||
class MessageSender:
|
||||
"""发送器"""
|
||||
|
||||
_instance = None
|
||||
|
||||
def __new__(cls, *args, **kwargs):
|
||||
@@ -32,7 +33,7 @@ class MessageSender:
|
||||
|
||||
def __init__(self):
|
||||
# 确保 __init__ 只被调用一次
|
||||
if not hasattr(self, '_initialized'):
|
||||
if not hasattr(self, "_initialized"):
|
||||
self.message_interval = (0.5, 1) # 消息间隔时间范围(秒)
|
||||
self.last_send_time = 0
|
||||
self._current_bot = None
|
||||
@@ -42,7 +43,6 @@ class MessageSender:
|
||||
"""设置当前bot实例"""
|
||||
pass
|
||||
|
||||
|
||||
async def send_via_ws(self, message: MessageSending) -> None:
|
||||
try:
|
||||
await global_api.send_message(message)
|
||||
@@ -56,7 +56,6 @@ class MessageSender:
|
||||
"""发送消息"""
|
||||
|
||||
if isinstance(message, MessageSending):
|
||||
|
||||
typing_time = calculate_typing_time(
|
||||
input_string=message.processed_plain_text,
|
||||
thinking_start_time=message.thinking_start_time,
|
||||
@@ -143,6 +142,7 @@ class MessageContainer:
|
||||
|
||||
class MessageManager:
|
||||
"""管理所有聊天流的消息容器"""
|
||||
|
||||
_instance = None
|
||||
|
||||
def __new__(cls, *args, **kwargs):
|
||||
@@ -152,7 +152,7 @@ class MessageManager:
|
||||
|
||||
def __init__(self):
|
||||
# 确保 __init__ 只被调用一次
|
||||
if not hasattr(self, '_initialized'):
|
||||
if not hasattr(self, "_initialized"):
|
||||
self.containers: Dict[str, MessageContainer] = {} # chat_id -> MessageContainer
|
||||
self.storage = MessageStorage()
|
||||
self._running = True
|
||||
|
||||
@@ -17,7 +17,7 @@ from src.plugins.models.utils_model import LLMRequest
|
||||
# 定义日志配置 (使用 loguru 格式)
|
||||
interest_log_config = LogConfig(
|
||||
console_format=DEFAULT_CONFIG["console_format"], # 使用默认控制台格式
|
||||
file_format=DEFAULT_CONFIG["file_format"] # 使用默认文件格式
|
||||
file_format=DEFAULT_CONFIG["file_format"], # 使用默认文件格式
|
||||
)
|
||||
logger = get_module_logger("PFChattingLoop", config=interest_log_config) # Logger Name Changed
|
||||
|
||||
@@ -38,30 +38,29 @@ PLANNER_TOOL_DEFINITION = [
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["no_reply", "text_reply", "emoji_reply"],
|
||||
"description": "决定采取的行动:'no_reply'(不回复), 'text_reply'(文本回复) 或 'emoji_reply'(表情回复)。"
|
||||
},
|
||||
"reasoning": {
|
||||
"type": "string",
|
||||
"description": "做出此决定的简要理由。"
|
||||
"description": "决定采取的行动:'no_reply'(不回复), 'text_reply'(文本回复) 或 'emoji_reply'(表情回复)。",
|
||||
},
|
||||
"reasoning": {"type": "string", "description": "做出此决定的简要理由。"},
|
||||
"emoji_query": {
|
||||
"type": "string",
|
||||
"description": '如果行动是\'emoji_reply\',则指定表情的主题或概念(例如,"开心"、"困惑")。仅在需要表情回复时提供。'
|
||||
}
|
||||
"description": '如果行动是\'emoji_reply\',则指定表情的主题或概念(例如,"开心"、"困惑")。仅在需要表情回复时提供。',
|
||||
},
|
||||
},
|
||||
"required": ["action", "reasoning"], # 强制要求提供行动和理由
|
||||
},
|
||||
},
|
||||
"required": ["action", "reasoning"] # 强制要求提供行动和理由
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
class PFChatting:
|
||||
"""
|
||||
Manages a continuous Plan-Filter-Check (now Plan-Replier-Sender) loop
|
||||
for generating replies within a specific chat stream, controlled by a timer.
|
||||
The loop runs as long as the timer > 0.
|
||||
"""
|
||||
def __init__(self, chat_id: str, heartfc_chat_instance: 'HeartFC_Chat'):
|
||||
|
||||
def __init__(self, chat_id: str, heartfc_chat_instance: "HeartFC_Chat"):
|
||||
"""
|
||||
初始化PFChatting实例。
|
||||
|
||||
@@ -82,7 +81,7 @@ class PFChatting:
|
||||
model=global_config.llm_normal,
|
||||
temperature=global_config.llm_normal["temp"],
|
||||
max_tokens=1000,
|
||||
request_type="action_planning"
|
||||
request_type="action_planning",
|
||||
)
|
||||
|
||||
# Internal state for loop control
|
||||
@@ -96,7 +95,6 @@ class PFChatting:
|
||||
# Removed pending_replies as processing is now serial within the loop
|
||||
# self.pending_replies: Dict[str, PendingReply] = {}
|
||||
|
||||
|
||||
def _get_log_prefix(self) -> str:
|
||||
"""获取日志前缀,包含可读的流名称"""
|
||||
stream_name = chat_manager.get_stream_name(self.stream_id) or self.stream_id
|
||||
@@ -156,7 +154,9 @@ class PFChatting:
|
||||
self._trigger_count_this_activation += 1
|
||||
duration_to_add = self._last_added_duration * 0.5
|
||||
self._last_added_duration = duration_to_add # 更新上次增加的值
|
||||
logger.info(f"{log_prefix} Trigger #{self._trigger_count_this_activation}. Adding {duration_to_add:.2f}s (50% of previous). Timer was {self._loop_timer:.1f}s.")
|
||||
logger.info(
|
||||
f"{log_prefix} Trigger #{self._trigger_count_this_activation}. Adding {duration_to_add:.2f}s (50% of previous). Timer was {self._loop_timer:.1f}s."
|
||||
)
|
||||
|
||||
# 添加计算出的时间
|
||||
new_timer_value = self._loop_timer + duration_to_add
|
||||
@@ -176,7 +176,6 @@ class PFChatting:
|
||||
elif self._loop_active:
|
||||
logger.debug(f"{log_prefix} Loop already active. Timer extended.")
|
||||
|
||||
|
||||
def _handle_loop_completion(self, task: asyncio.Task):
|
||||
"""当 _run_pf_loop 任务完成时执行的回调。"""
|
||||
log_prefix = self._get_log_prefix()
|
||||
@@ -201,7 +200,6 @@ class PFChatting:
|
||||
logger.warning(f"{log_prefix} PFChatting: 锁没有正常释放")
|
||||
self._processing_lock.release()
|
||||
|
||||
|
||||
async def _run_pf_loop(self):
|
||||
"""
|
||||
主循环,当计时器>0时持续进行计划并可能回复消息
|
||||
@@ -214,7 +212,9 @@ class PFChatting:
|
||||
async with self._timer_lock:
|
||||
current_timer = self._loop_timer
|
||||
if current_timer <= 0:
|
||||
logger.info(f"{self._get_log_prefix()} PFChatting: 聊太久了,麦麦打算休息一下(已经聊了{current_timer:.1f}秒),退出PFChatting")
|
||||
logger.info(
|
||||
f"{self._get_log_prefix()} PFChatting: 聊太久了,麦麦打算休息一下(已经聊了{current_timer:.1f}秒),退出PFChatting"
|
||||
)
|
||||
break # 退出条件:计时器到期
|
||||
|
||||
# 记录循环开始时间
|
||||
@@ -259,7 +259,7 @@ class PFChatting:
|
||||
anchor_message=anchor_message,
|
||||
thinking_id=thinking_id,
|
||||
current_mind=current_mind,
|
||||
send_emoji=send_emoji_from_tools
|
||||
send_emoji=send_emoji_from_tools,
|
||||
)
|
||||
except Exception as e_replier:
|
||||
logger.error(f"{self._get_log_prefix()} 循环: 回复器工作失败: {e_replier}")
|
||||
@@ -324,7 +324,9 @@ class PFChatting:
|
||||
cycle_duration = time.monotonic() - loop_cycle_start_time
|
||||
async with self._timer_lock:
|
||||
self._loop_timer -= cycle_duration
|
||||
logger.debug(f"{self._get_log_prefix()} PFChatting: 麦麦聊了{cycle_duration:.2f}秒. 还能聊: {self._loop_timer:.1f}s.")
|
||||
logger.debug(
|
||||
f"{self._get_log_prefix()} PFChatting: 麦麦聊了{cycle_duration:.2f}秒. 还能聊: {self._loop_timer:.1f}s."
|
||||
)
|
||||
|
||||
# --- Delay ---
|
||||
# Add a small delay, especially if no action was taken, to prevent busy-waiting
|
||||
@@ -385,22 +387,24 @@ class PFChatting:
|
||||
try:
|
||||
observation_context_text = ""
|
||||
if observed_messages:
|
||||
context_texts = [msg.get('detailed_plain_text', '') for msg in observed_messages if msg.get('detailed_plain_text')]
|
||||
context_texts = [
|
||||
msg.get("detailed_plain_text", "") for msg in observed_messages if msg.get("detailed_plain_text")
|
||||
]
|
||||
observation_context_text = "\n".join(context_texts)
|
||||
logger.debug(f"{log_prefix}[Planner] Context for tools: {observation_context_text[:100]}...")
|
||||
|
||||
if observation_context_text and self.sub_hf:
|
||||
# Ensure SubHeartflow exists for tool use context
|
||||
tool_result = await self.heartfc_chat.tool_user.use_tool(
|
||||
message_txt=observation_context_text,
|
||||
chat_stream=self.chat_stream,
|
||||
sub_heartflow=self.sub_hf
|
||||
message_txt=observation_context_text, chat_stream=self.chat_stream, sub_heartflow=self.sub_hf
|
||||
)
|
||||
if tool_result.get("used_tools", False):
|
||||
tool_result_info = tool_result.get("structured_info", {})
|
||||
logger.debug(f"{log_prefix}[Planner] Tool results: {tool_result_info}")
|
||||
if "mid_chat_mem" in tool_result_info:
|
||||
get_mid_memory_id = [mem["content"] for mem in tool_result_info["mid_chat_mem"] if "content" in mem]
|
||||
get_mid_memory_id = [
|
||||
mem["content"] for mem in tool_result_info["mid_chat_mem"] if "content" in mem
|
||||
]
|
||||
if "send_emoji" in tool_result_info and tool_result_info["send_emoji"]:
|
||||
send_emoji_from_tools = tool_result_info["send_emoji"][0].get("content", "") # Use renamed var
|
||||
elif not self.sub_hf:
|
||||
@@ -430,7 +434,6 @@ class PFChatting:
|
||||
logger.error(traceback.format_exc())
|
||||
current_mind = "[心流思考出错]"
|
||||
|
||||
|
||||
# --- 使用 LLM 进行决策 ---
|
||||
action = "no_reply" # Default action
|
||||
emoji_query = ""
|
||||
@@ -462,17 +465,26 @@ class PFChatting:
|
||||
if tool_calls and isinstance(tool_calls, list) and len(tool_calls) > 0:
|
||||
# 通常强制调用后只会有一个 tool_call
|
||||
tool_call = tool_calls[0]
|
||||
if tool_call.get("type") == "function" and tool_call.get("function", {}).get("name") == "decide_reply_action":
|
||||
if (
|
||||
tool_call.get("type") == "function"
|
||||
and tool_call.get("function", {}).get("name") == "decide_reply_action"
|
||||
):
|
||||
try:
|
||||
arguments = json.loads(tool_call["function"]["arguments"])
|
||||
action = arguments.get("action", "no_reply")
|
||||
reasoning = arguments.get("reasoning", "未提供理由")
|
||||
if action == "emoji_reply":
|
||||
# Planner's decision overrides tool's emoji if action is emoji_reply
|
||||
emoji_query = arguments.get("emoji_query", send_emoji_from_tools) # Use tool emoji as default if planner asks for emoji
|
||||
logger.info(f"{log_prefix}[Planner] LLM 决策: {action}, 理由: {reasoning}, EmojiQuery: '{emoji_query}'")
|
||||
emoji_query = arguments.get(
|
||||
"emoji_query", send_emoji_from_tools
|
||||
) # Use tool emoji as default if planner asks for emoji
|
||||
logger.info(
|
||||
f"{log_prefix}[Planner] LLM 决策: {action}, 理由: {reasoning}, EmojiQuery: '{emoji_query}'"
|
||||
)
|
||||
except json.JSONDecodeError as json_e:
|
||||
logger.error(f"{log_prefix}[Planner] 解析工具参数失败: {json_e}. Arguments: {tool_call['function'].get('arguments')}")
|
||||
logger.error(
|
||||
f"{log_prefix}[Planner] 解析工具参数失败: {json_e}. Arguments: {tool_call['function'].get('arguments')}"
|
||||
)
|
||||
action = "error"
|
||||
reasoning = "工具参数解析失败"
|
||||
llm_error = True
|
||||
@@ -482,7 +494,9 @@ class PFChatting:
|
||||
reasoning = "处理工具参数时出错"
|
||||
llm_error = True
|
||||
else:
|
||||
logger.warning(f"{log_prefix}[Planner] LLM 未按预期调用 'decide_reply_action' 工具。Tool calls: {tool_calls}")
|
||||
logger.warning(
|
||||
f"{log_prefix}[Planner] LLM 未按预期调用 'decide_reply_action' 工具。Tool calls: {tool_calls}"
|
||||
)
|
||||
action = "error"
|
||||
reasoning = "LLM未调用预期工具"
|
||||
llm_error = True
|
||||
@@ -513,7 +527,7 @@ class PFChatting:
|
||||
"current_mind": current_mind,
|
||||
"send_emoji_from_tools": send_emoji_from_tools, # Emoji suggested by pre-thinking tools
|
||||
"observed_messages": observed_messages,
|
||||
"llm_error": llm_error # Indicate if LLM decision process failed
|
||||
"llm_error": llm_error, # Indicate if LLM decision process failed
|
||||
}
|
||||
|
||||
async def _get_anchor_message(self, observed_messages: List[dict]) -> Optional[MessageRecv]:
|
||||
@@ -535,24 +549,35 @@ class PFChatting:
|
||||
# Attempt reconstruction from the last observed message dictionary
|
||||
anchor_message = MessageRecv(last_msg_dict, chat_stream=self.chat_stream)
|
||||
# Basic validation
|
||||
if not (anchor_message and anchor_message.message_info and anchor_message.message_info.message_id and anchor_message.message_info.user_info):
|
||||
if not (
|
||||
anchor_message
|
||||
and anchor_message.message_info
|
||||
and anchor_message.message_info.message_id
|
||||
and anchor_message.message_info.user_info
|
||||
):
|
||||
raise ValueError("重构的 MessageRecv 缺少必要信息.")
|
||||
logger.debug(f"{self._get_log_prefix()} 重构的锚点消息: ID={anchor_message.message_info.message_id}")
|
||||
logger.debug(
|
||||
f"{self._get_log_prefix()} 重构的锚点消息: ID={anchor_message.message_info.message_id}"
|
||||
)
|
||||
return anchor_message
|
||||
except Exception as e_reconstruct:
|
||||
logger.warning(f"{self._get_log_prefix()} 从观察到的消息重构 MessageRecv 失败: {e_reconstruct}. 创建占位符.")
|
||||
logger.warning(
|
||||
f"{self._get_log_prefix()} 从观察到的消息重构 MessageRecv 失败: {e_reconstruct}. 创建占位符."
|
||||
)
|
||||
else:
|
||||
logger.warning(f"{self._get_log_prefix()} observed_messages 为空. 创建占位符锚点消息.")
|
||||
|
||||
# --- Create Placeholder ---
|
||||
placeholder_id = f"mid_pf_{int(time.time() * 1000)}"
|
||||
placeholder_user = UserInfo(user_id="system_trigger", user_nickname="System Trigger", platform=self.chat_stream.platform)
|
||||
placeholder_user = UserInfo(
|
||||
user_id="system_trigger", user_nickname="System Trigger", platform=self.chat_stream.platform
|
||||
)
|
||||
placeholder_msg_info = BaseMessageInfo(
|
||||
message_id=placeholder_id,
|
||||
platform=self.chat_stream.platform,
|
||||
group_info=self.chat_stream.group_info,
|
||||
user_info=placeholder_user,
|
||||
time=time.time()
|
||||
time=time.time(),
|
||||
)
|
||||
placeholder_msg_dict = {
|
||||
"message_info": placeholder_msg_info.to_dict(),
|
||||
@@ -562,7 +587,9 @@ class PFChatting:
|
||||
}
|
||||
anchor_message = MessageRecv(placeholder_msg_dict)
|
||||
anchor_message.update_chat_stream(self.chat_stream) # Associate with the stream
|
||||
logger.info(f"{self._get_log_prefix()} Created placeholder anchor message: ID={anchor_message.message_info.message_id}")
|
||||
logger.info(
|
||||
f"{self._get_log_prefix()} Created placeholder anchor message: ID={anchor_message.message_info.message_id}"
|
||||
)
|
||||
return anchor_message
|
||||
|
||||
except Exception as e:
|
||||
@@ -579,7 +606,6 @@ class PFChatting:
|
||||
except Exception as e:
|
||||
logger.error(f"{self._get_log_prefix()} Error cleaning up thinking message {thinking_id}: {e}")
|
||||
|
||||
|
||||
async def _sender(self, thinking_id: str, anchor_message: MessageRecv, replier_result: Dict[str, Any]):
|
||||
"""
|
||||
发送器 (Sender): 使用HeartFC_Chat的方法发送生成的回复。
|
||||
@@ -611,13 +637,17 @@ class PFChatting:
|
||||
|
||||
# --- Handle associated emoji (if determined by tools) ---
|
||||
if send_emoji:
|
||||
logger.info(f"{self._get_log_prefix()}[Sender-{thinking_id}] Sending associated emoji: {send_emoji}")
|
||||
logger.info(
|
||||
f"{self._get_log_prefix()}[Sender-{thinking_id}] Sending associated emoji: {send_emoji}"
|
||||
)
|
||||
try:
|
||||
# Use first_bot_msg as anchor if available, otherwise fallback to original anchor
|
||||
emoji_anchor = first_bot_msg if first_bot_msg else anchor_message
|
||||
await self.heartfc_chat._handle_emoji(emoji_anchor, response_set, send_emoji)
|
||||
except Exception as e_emoji:
|
||||
logger.error(f"{self._get_log_prefix()}[Sender-{thinking_id}] Failed to send associated emoji: {e_emoji}")
|
||||
logger.error(
|
||||
f"{self._get_log_prefix()}[Sender-{thinking_id}] Failed to send associated emoji: {e_emoji}"
|
||||
)
|
||||
# Log error but don't fail the whole send process for emoji failure
|
||||
|
||||
# --- Update relationship ---
|
||||
@@ -625,17 +655,20 @@ class PFChatting:
|
||||
await self.heartfc_chat._update_relationship(anchor_message, response_set)
|
||||
logger.debug(f"{self._get_log_prefix()}[Sender-{thinking_id}] Updated relationship.")
|
||||
except Exception as e_rel:
|
||||
logger.error(f"{self._get_log_prefix()}[Sender-{thinking_id}] Failed to update relationship: {e_rel}")
|
||||
logger.error(
|
||||
f"{self._get_log_prefix()}[Sender-{thinking_id}] Failed to update relationship: {e_rel}"
|
||||
)
|
||||
# Log error but don't fail the whole send process for relationship update failure
|
||||
|
||||
else:
|
||||
# Sending failed (e.g., _send_response_messages found thinking message already gone)
|
||||
send_success = False
|
||||
logger.warning(f"{self._get_log_prefix()}[Sender-{thinking_id}] Failed to send reply (maybe thinking message expired or was removed?).")
|
||||
logger.warning(
|
||||
f"{self._get_log_prefix()}[Sender-{thinking_id}] Failed to send reply (maybe thinking message expired or was removed?)."
|
||||
)
|
||||
# No need to clean up thinking message here, _send_response_messages implies it's gone or handled
|
||||
raise RuntimeError("Sending reply failed, _send_response_messages returned None.") # Signal failure
|
||||
|
||||
|
||||
except Exception as e:
|
||||
# Catch potential errors during sending or post-send actions
|
||||
logger.error(f"{self._get_log_prefix()}[Sender-{thinking_id}] Error during sending process: {e}")
|
||||
@@ -647,7 +680,6 @@ class PFChatting:
|
||||
|
||||
# No finally block needed for lock management
|
||||
|
||||
|
||||
async def shutdown(self):
|
||||
"""
|
||||
Gracefully shuts down the PFChatting instance by cancelling the active loop task.
|
||||
@@ -690,25 +722,38 @@ class PFChatting:
|
||||
prompt += "\n你当前没有特别的内部想法。\n"
|
||||
|
||||
if observed_messages:
|
||||
context_text = "\n".join([msg.get('detailed_plain_text', '') for msg in observed_messages if msg.get('detailed_plain_text')])
|
||||
context_text = "\n".join(
|
||||
[msg.get("detailed_plain_text", "") for msg in observed_messages if msg.get("detailed_plain_text")]
|
||||
)
|
||||
prompt += "观察到的最新聊天内容如下:\n---\n"
|
||||
prompt += context_text[:1500] # Limit context length
|
||||
prompt += "\n---\n"
|
||||
else:
|
||||
prompt += "当前没有观察到新的聊天内容。\n"
|
||||
|
||||
prompt += "\n请结合你的内部想法和观察到的聊天内容,分析情况并使用 'decide_reply_action' 工具来决定你的最终行动。\n"
|
||||
prompt += (
|
||||
"\n请结合你的内部想法和观察到的聊天内容,分析情况并使用 'decide_reply_action' 工具来决定你的最终行动。\n"
|
||||
)
|
||||
prompt += "决策依据:\n"
|
||||
prompt += "1. 如果聊天内容无聊、与你无关、或者你的内部想法认为不适合回复,选择 'no_reply'。\n"
|
||||
prompt += "2. 如果聊天内容值得回应,且适合用文字表达(参考你的内部想法),选择 'text_reply'。\n"
|
||||
prompt += "3. 如果聊天内容或你的内部想法适合用一个表情来回应,选择 'emoji_reply' 并提供表情主题 'emoji_query'。\n"
|
||||
prompt += (
|
||||
"3. 如果聊天内容或你的内部想法适合用一个表情来回应,选择 'emoji_reply' 并提供表情主题 'emoji_query'。\n"
|
||||
)
|
||||
prompt += "4. 如果你已经回复过消息,也没有人又回复你,选择'no_reply'。"
|
||||
prompt += "必须调用 'decide_reply_action' 工具并提供 'action' 和 'reasoning'。"
|
||||
|
||||
return prompt
|
||||
|
||||
# --- 回复器 (Replier) 的定义 --- #
|
||||
async def _replier_work(self, observed_messages: List[dict], anchor_message: MessageRecv, thinking_id: str, current_mind: Optional[str], send_emoji: str) -> Optional[Dict[str, Any]]:
|
||||
async def _replier_work(
|
||||
self,
|
||||
observed_messages: List[dict],
|
||||
anchor_message: MessageRecv,
|
||||
thinking_id: str,
|
||||
current_mind: Optional[str],
|
||||
send_emoji: str,
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
回复器 (Replier): 核心逻辑用于生成回复。
|
||||
被 _run_pf_loop 直接调用和 await。
|
||||
@@ -724,7 +769,7 @@ class PFChatting:
|
||||
# 注意:实际的生成调用是在 self.heartfc_chat.gpt.generate_response 中
|
||||
response_set = await self.heartfc_chat.gpt.generate_response(
|
||||
anchor_message,
|
||||
thinking_id
|
||||
thinking_id,
|
||||
# current_mind 不再直接传递给 gpt.generate_response,
|
||||
# 因为 generate_response 内部会通过 thinking_id 或其他方式获取所需上下文
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user