Spaces:
Sleeping
Sleeping
File size: 5,325 Bytes
4cfe4fa | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 | """
Memory Manager - Lưu trữ và quản lý lịch sử hội thoại
"""
import json
import os
from datetime import datetime
from typing import List, Dict, Optional
from pathlib import Path
class MemoryManager:
def __init__(self, storage_dir: str = "conversation_history"):
"""
Initialize Memory Manager
Args:
storage_dir: Thư mục lưu trữ lịch sử hội thoại
"""
self.storage_dir = Path(storage_dir)
self.storage_dir.mkdir(exist_ok=True)
self.current_session_file = None
def create_new_session(self) -> str:
"""
Tạo session mới
Returns:
Session ID
"""
session_id = datetime.now().strftime("%Y%m%d_%H%M%S")
self.current_session_file = self.storage_dir / f"session_{session_id}.json"
# Tạo file session mới
session_data = {
"session_id": session_id,
"created_at": datetime.now().isoformat(),
"messages": []
}
self._save_session(session_data)
return session_id
def save_message(self, role: str, content: str, metadata: Dict = None):
"""
Lưu tin nhắn vào session hiện tại
Args:
role: 'user' hoặc 'assistant'
content: Nội dung tin nhắn
metadata: Thông tin bổ sung (action, q_values, etc.)
"""
if not self.current_session_file:
self.create_new_session()
session_data = self._load_session()
message = {
"role": role,
"content": content,
"timestamp": datetime.now().isoformat()
}
if metadata:
message.update(metadata)
session_data["messages"].append(message)
self._save_session(session_data)
def load_session(self, session_id: str) -> Optional[Dict]:
"""
Load session theo ID
Args:
session_id: ID của session cần load
Returns:
Session data hoặc None nếu không tìm thấy
"""
session_file = self.storage_dir / f"session_{session_id}.json"
if not session_file.exists():
return None
with open(session_file, 'r', encoding='utf-8') as f:
return json.load(f)
def get_all_sessions(self) -> List[Dict]:
"""
Lấy danh sách tất cả sessions
Returns:
List các session info
"""
sessions = []
for file in self.storage_dir.glob("session_*.json"):
try:
with open(file, 'r', encoding='utf-8') as f:
data = json.load(f)
sessions.append({
"session_id": data["session_id"],
"created_at": data["created_at"],
"message_count": len(data["messages"]),
"file": str(file)
})
except Exception as e:
print(f"Error loading session {file}: {e}")
# Sắp xếp theo thời gian tạo (mới nhất trước)
sessions.sort(key=lambda x: x["created_at"], reverse=True)
return sessions
def delete_session(self, session_id: str) -> bool:
"""
Xóa session
Args:
session_id: ID của session cần xóa
Returns:
True nếu xóa thành công
"""
session_file = self.storage_dir / f"session_{session_id}.json"
if session_file.exists():
session_file.unlink()
return True
return False
def _load_session(self) -> Dict:
"""Load session hiện tại"""
if not self.current_session_file or not self.current_session_file.exists():
return {
"session_id": "default",
"created_at": datetime.now().isoformat(),
"messages": []
}
with open(self.current_session_file, 'r', encoding='utf-8') as f:
return json.load(f)
def _save_session(self, session_data: Dict):
"""Lưu session data"""
if not self.current_session_file:
return
with open(self.current_session_file, 'w', encoding='utf-8') as f:
json.dump(session_data, f, ensure_ascii=False, indent=2)
def get_current_messages(self) -> List[Dict]:
"""Lấy tất cả messages của session hiện tại"""
session_data = self._load_session()
return session_data.get("messages", [])
def export_session(self, session_id: str, output_file: str):
"""
Export session ra file
Args:
session_id: ID của session
output_file: Đường dẫn file output
"""
session_data = self.load_session(session_id)
if not session_data:
return False
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(session_data, f, ensure_ascii=False, indent=2)
return True
|