基本完成,舒适性修补
This commit is contained in:
@@ -561,6 +561,98 @@ class ChatService:
|
||||
except Exception as e:
|
||||
logger.error(f"总结聊天消息失败 {role_name}/{chat_name}: {str(e)}")
|
||||
raise
|
||||
|
||||
def create_branch(
|
||||
self,
|
||||
role_name: str,
|
||||
chat_name: str,
|
||||
target_floor: int,
|
||||
new_chat_name: Optional[str] = None
|
||||
) -> Dict:
|
||||
"""
|
||||
创建聊天分支
|
||||
|
||||
复制目标楼层及之前的所有内容到一个新的聊天记录
|
||||
|
||||
Args:
|
||||
role_name: 角色名称
|
||||
chat_name: 原聊天名称
|
||||
target_floor: 目标楼层(包含该楼层及之前的内容)
|
||||
new_chat_name: 新聊天名称(可选,默认自动生成)
|
||||
|
||||
Returns:
|
||||
Dict: {
|
||||
"success": bool,
|
||||
"new_chat_name": str,
|
||||
"message_count": int
|
||||
}
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 聊天不存在
|
||||
ValueError: 楼层不存在
|
||||
"""
|
||||
chat_file = self.chat_dir / role_name / f"{chat_name}.jsonl"
|
||||
|
||||
if not chat_file.exists():
|
||||
raise FileNotFoundError(f"Chat not found: {role_name}/{chat_name}")
|
||||
|
||||
try:
|
||||
# 读取所有行
|
||||
with open(chat_file, 'r', encoding='utf-8') as f:
|
||||
lines = f.readlines()
|
||||
|
||||
if not lines:
|
||||
raise ValueError(f"Empty chat file: {role_name}/{chat_name}")
|
||||
|
||||
# 验证目标楼层
|
||||
# floor + 1 是因为第0行是header
|
||||
message_line_index = target_floor + 1
|
||||
if message_line_index >= len(lines):
|
||||
raise ValueError(f"Floor {target_floor} not found in chat (total messages: {len(lines) - 1})")
|
||||
|
||||
# 生成新聊天名称
|
||||
if not new_chat_name:
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
new_chat_name = f"branch_{chat_name}_{timestamp}"
|
||||
|
||||
# 创建新聊天文件
|
||||
new_chat_file = self.chat_dir / role_name / f"{new_chat_name}.jsonl"
|
||||
|
||||
if new_chat_file.exists():
|
||||
raise FileExistsError(f"Branch chat already exists: {new_chat_name}")
|
||||
|
||||
# 复制 header 和目标楼层及之前的消息
|
||||
branch_lines = [lines[0]] # header
|
||||
for i in range(1, message_line_index + 1):
|
||||
msg_data = json.loads(lines[i])
|
||||
# 重新分配 floor(从0开始)
|
||||
msg_data["floor"] = i - 1
|
||||
branch_lines.append(json.dumps(msg_data, ensure_ascii=False) + '\n')
|
||||
|
||||
# 写入新文件
|
||||
with open(new_chat_file, 'w', encoding='utf-8') as f:
|
||||
f.writelines(branch_lines)
|
||||
|
||||
message_count = len(branch_lines) - 1 # 减去header
|
||||
|
||||
logger.info(
|
||||
f"[ChatService] 创建分支成功: {role_name}/{chat_name} -> {new_chat_name}, "
|
||||
f"楼层: 0-{target_floor}, 消息数: {message_count}"
|
||||
)
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"new_chat_name": new_chat_name,
|
||||
"message_count": message_count,
|
||||
"branched_from": chat_name,
|
||||
"target_floor": target_floor
|
||||
}
|
||||
|
||||
except (FileExistsError, ValueError):
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"创建分支失败 {role_name}/{chat_name}: {str(e)}")
|
||||
raise
|
||||
|
||||
|
||||
# 全局实例
|
||||
|
||||
Reference in New Issue
Block a user