fix:修复引用回复逻辑
This commit is contained in:
@@ -18,7 +18,7 @@ INTEREST_EVAL_INTERVAL_SECONDS = 5
|
||||
# 新增聊天超时检查间隔
|
||||
NORMAL_CHAT_TIMEOUT_CHECK_INTERVAL_SECONDS = 60
|
||||
# 新增状态评估间隔
|
||||
HF_JUDGE_STATE_UPDATE_INTERVAL_SECONDS = 60
|
||||
HF_JUDGE_STATE_UPDATE_INTERVAL_SECONDS = 20
|
||||
# 新增私聊激活检查间隔
|
||||
PRIVATE_CHAT_ACTIVATION_CHECK_INTERVAL_SECONDS = 5 # 与兴趣评估类似,设为5秒
|
||||
|
||||
|
||||
@@ -14,6 +14,8 @@ from src.plugins.utils.chat_message_builder import (
|
||||
)
|
||||
from src.plugins.utils.prompt_builder import Prompt, global_prompt_manager
|
||||
from typing import Optional
|
||||
import difflib
|
||||
from src.plugins.chat.message import MessageRecv # 添加 MessageRecv 导入
|
||||
|
||||
# Import the new utility function
|
||||
from .utils_chat import get_chat_type_and_target_info
|
||||
@@ -227,6 +229,70 @@ class ChattingObservation(Observation):
|
||||
f"Chat {self.chat_id} - 压缩早期记忆:{self.mid_memory_info}\n现在聊天内容:{self.talking_message_str}"
|
||||
)
|
||||
|
||||
async def find_best_matching_message(self, search_str: str, min_similarity: float = 0.6) -> Optional[MessageRecv]:
|
||||
"""
|
||||
在 talking_message 中查找与 search_str 最匹配的消息。
|
||||
|
||||
Args:
|
||||
search_str: 要搜索的字符串。
|
||||
min_similarity: 要求的最低相似度(0到1之间)。
|
||||
|
||||
Returns:
|
||||
匹配的 MessageRecv 实例,如果找不到则返回 None。
|
||||
"""
|
||||
best_match_score = -1.0
|
||||
best_match_dict = None
|
||||
|
||||
if not self.talking_message:
|
||||
logger.debug(f"Chat {self.chat_id}: talking_message is empty, cannot find match for '{search_str}'")
|
||||
return None
|
||||
|
||||
for message_dict in self.talking_message:
|
||||
try:
|
||||
# 临时创建 MessageRecv 以处理文本
|
||||
temp_msg = MessageRecv(message_dict)
|
||||
await temp_msg.process() # 处理消息以获取 processed_plain_text
|
||||
current_text = temp_msg.processed_plain_text
|
||||
|
||||
if not current_text: # 跳过没有文本内容的消息
|
||||
continue
|
||||
|
||||
# 计算相似度
|
||||
matcher = difflib.SequenceMatcher(None, search_str, current_text)
|
||||
score = matcher.ratio()
|
||||
|
||||
# logger.debug(f"Comparing '{search_str}' with '{current_text}', score: {score}") # 可选:用于调试
|
||||
|
||||
if score > best_match_score:
|
||||
best_match_score = score
|
||||
best_match_dict = message_dict
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing message for matching in chat {self.chat_id}: {e}", exc_info=True)
|
||||
continue # 继续处理下一条消息
|
||||
|
||||
if best_match_dict is not None and best_match_score >= min_similarity:
|
||||
logger.debug(f"Found best match for '{search_str}' with score {best_match_score:.2f}")
|
||||
try:
|
||||
final_msg = MessageRecv(best_match_dict)
|
||||
await final_msg.process()
|
||||
# 确保 MessageRecv 实例有关联的 chat_stream
|
||||
if hasattr(self, "chat_stream"):
|
||||
final_msg.update_chat_stream(self.chat_stream)
|
||||
else:
|
||||
logger.warning(
|
||||
f"ChattingObservation instance for chat {self.chat_id} does not have a chat_stream attribute set."
|
||||
)
|
||||
return final_msg
|
||||
except Exception as e:
|
||||
logger.error(f"Error creating final MessageRecv for chat {self.chat_id}: {e}", exc_info=True)
|
||||
return None
|
||||
else:
|
||||
logger.debug(
|
||||
f"No suitable match found for '{search_str}' in chat {self.chat_id} (best score: {best_match_score:.2f}, threshold: {min_similarity})"
|
||||
)
|
||||
return None
|
||||
|
||||
async def has_new_messages_since(self, timestamp: float) -> bool:
|
||||
"""检查指定时间戳之后是否有新消息"""
|
||||
count = num_new_messages_since(chat_id=self.chat_id, timestamp_start=timestamp)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from .observation import Observation, ChattingObservation
|
||||
from .observation import ChattingObservation
|
||||
from src.plugins.models.utils_model import LLMRequest
|
||||
from src.config.config import global_config
|
||||
import time
|
||||
@@ -146,10 +146,9 @@ class SubMind:
|
||||
lines = ["【信息】"]
|
||||
for item in self.structured_info:
|
||||
# 简化展示,突出内容和类型,包含TTL供调试
|
||||
type_str = item.get('type', '未知类型')
|
||||
content_str = item.get('content', '')
|
||||
ttl = item.get('ttl', '?')
|
||||
|
||||
type_str = item.get("type", "未知类型")
|
||||
content_str = item.get("content", "")
|
||||
|
||||
if type_str == "info":
|
||||
lines.append(f"刚刚: {content_str}")
|
||||
elif type_str == "memory":
|
||||
@@ -178,18 +177,24 @@ class SubMind:
|
||||
|
||||
# ---------- 0. 更新和清理 structured_info ----------
|
||||
if self.structured_info:
|
||||
logger.debug(f"{self.log_prefix} 更新前的 structured_info: {safe_json_dumps(self.structured_info, ensure_ascii=False)}")
|
||||
logger.debug(
|
||||
f"{self.log_prefix} 更新前的 structured_info: {safe_json_dumps(self.structured_info, ensure_ascii=False)}"
|
||||
)
|
||||
updated_info = []
|
||||
for item in self.structured_info:
|
||||
item['ttl'] -= 1
|
||||
if item['ttl'] > 0:
|
||||
item["ttl"] -= 1
|
||||
if item["ttl"] > 0:
|
||||
updated_info.append(item)
|
||||
else:
|
||||
logger.debug(f"{self.log_prefix} 移除过期的 structured_info 项: {item['id']}")
|
||||
self.structured_info = updated_info
|
||||
logger.debug(f"{self.log_prefix} 更新后的 structured_info: {safe_json_dumps(self.structured_info, ensure_ascii=False)}")
|
||||
logger.debug(
|
||||
f"{self.log_prefix} 更新后的 structured_info: {safe_json_dumps(self.structured_info, ensure_ascii=False)}"
|
||||
)
|
||||
self._update_structured_info_str()
|
||||
logger.debug(f"{self.log_prefix} 当前完整的 structured_info: {safe_json_dumps(self.structured_info, ensure_ascii=False)}")
|
||||
logger.debug(
|
||||
f"{self.log_prefix} 当前完整的 structured_info: {safe_json_dumps(self.structured_info, ensure_ascii=False)}"
|
||||
)
|
||||
|
||||
# ---------- 1. 准备基础数据 ----------
|
||||
# 获取现有想法和情绪状态
|
||||
@@ -202,10 +207,10 @@ class SubMind:
|
||||
logger.error(f"{self.log_prefix} 无法获取有效的观察对象或缺少聊天类型信息")
|
||||
self.update_current_mind("(观察出错了...)")
|
||||
return self.current_mind, self.past_mind
|
||||
|
||||
|
||||
is_group_chat = observation.is_group_chat
|
||||
# logger.debug(f"is_group_chat: {is_group_chat}")
|
||||
|
||||
|
||||
chat_target_info = observation.chat_target_info
|
||||
chat_target_name = "对方" # Default for private
|
||||
if not is_group_chat and chat_target_info:
|
||||
@@ -496,7 +501,7 @@ class SubMind:
|
||||
tool_instance: 工具使用器实例
|
||||
"""
|
||||
tool_results = []
|
||||
new_structured_items = [] # 收集新产生的结构化信息
|
||||
new_structured_items = [] # 收集新产生的结构化信息
|
||||
|
||||
# 执行所有工具调用
|
||||
for tool_call in tool_calls:
|
||||
@@ -506,26 +511,26 @@ class SubMind:
|
||||
tool_results.append(result)
|
||||
# 创建新的结构化信息项
|
||||
new_item = {
|
||||
"type": result.get("type", "unknown_type"), # 使用 'type' 键
|
||||
"id": result.get("id", f"fallback_id_{time.time()}"), # 使用 'id' 键
|
||||
"content": result.get("content", ""), # 'content' 键保持不变
|
||||
"ttl": 3
|
||||
"type": result.get("type", "unknown_type"), # 使用 'type' 键
|
||||
"id": result.get("id", f"fallback_id_{time.time()}"), # 使用 'id' 键
|
||||
"content": result.get("content", ""), # 'content' 键保持不变
|
||||
"ttl": 3,
|
||||
}
|
||||
new_structured_items.append(new_item)
|
||||
|
||||
except Exception as tool_e:
|
||||
logger.error(f"[{self.subheartflow_id}] 工具执行失败: {tool_e}")
|
||||
logger.error(traceback.format_exc()) # 添加 traceback 记录
|
||||
logger.error(traceback.format_exc()) # 添加 traceback 记录
|
||||
|
||||
# 如果有新的工具结果,记录并更新结构化信息
|
||||
if new_structured_items:
|
||||
self.structured_info.extend(new_structured_items) # 添加到现有列表
|
||||
self.structured_info.extend(new_structured_items) # 添加到现有列表
|
||||
logger.debug(f"工具调用收集到新的结构化信息: {safe_json_dumps(new_structured_items, ensure_ascii=False)}")
|
||||
# logger.debug(f"当前完整的 structured_info: {safe_json_dumps(self.structured_info, ensure_ascii=False)}") # 可以取消注释以查看完整列表
|
||||
self._update_structured_info_str() # 添加新信息后,更新字符串表示
|
||||
self._update_structured_info_str() # 添加新信息后,更新字符串表示
|
||||
|
||||
def update_current_mind(self, response):
|
||||
if self.current_mind: # 只有当 current_mind 非空时才添加到 past_mind
|
||||
if self.current_mind: # 只有当 current_mind 非空时才添加到 past_mind
|
||||
self.past_mind.append(self.current_mind)
|
||||
# 可以考虑限制 past_mind 的大小,例如:
|
||||
# max_past_mind_size = 10
|
||||
|
||||
@@ -128,7 +128,7 @@ class SubHeartflowManager:
|
||||
# 添加聊天观察者
|
||||
observation = ChattingObservation(chat_id=subheartflow_id)
|
||||
await observation.initialize()
|
||||
|
||||
|
||||
new_subflow.add_observation(observation)
|
||||
|
||||
# 注册子心流
|
||||
|
||||
Reference in New Issue
Block a user