Merge branch 'dev' of https://github.com/MoFox-Studio/MoFox_Bot into dev
This commit is contained in:
@@ -32,7 +32,10 @@ import time
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from enum import Enum
|
||||
from typing import Any
|
||||
from typing import Any, Type, TypeVar
|
||||
|
||||
E = TypeVar("E", bound=Enum)
|
||||
|
||||
|
||||
import orjson
|
||||
|
||||
@@ -49,6 +52,21 @@ from src.llm_models.utils_model import LLMRequest
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
CHINESE_TO_MEMORY_TYPE: dict[str, MemoryType] = {
|
||||
"个人事实": MemoryType.PERSONAL_FACT,
|
||||
"事件": MemoryType.EVENT,
|
||||
"偏好": MemoryType.PREFERENCE,
|
||||
"观点": MemoryType.OPINION,
|
||||
"关系": MemoryType.RELATIONSHIP,
|
||||
"情感": MemoryType.EMOTION,
|
||||
"知识": MemoryType.KNOWLEDGE,
|
||||
"技能": MemoryType.SKILL,
|
||||
"目标": MemoryType.GOAL,
|
||||
"经验": MemoryType.EXPERIENCE,
|
||||
"上下文": MemoryType.CONTEXTUAL,
|
||||
}
|
||||
|
||||
|
||||
class ExtractionStrategy(Enum):
|
||||
"""提取策略"""
|
||||
|
||||
@@ -428,7 +446,7 @@ class MemoryBuilder:
|
||||
subject=normalized_subject,
|
||||
predicate=predicate_value,
|
||||
obj=object_value,
|
||||
memory_type=MemoryType(mem_data.get("type", "contextual")),
|
||||
memory_type=self._resolve_memory_type(mem_data.get("type")),
|
||||
chat_id=context.get("chat_id"),
|
||||
source_context=mem_data.get("reasoning", ""),
|
||||
importance=importance_level,
|
||||
@@ -459,7 +477,33 @@ class MemoryBuilder:
|
||||
|
||||
return memories
|
||||
|
||||
def _parse_enum_value(self, enum_cls: type[Enum], raw_value: Any, default: Enum, field_name: str) -> Enum:
|
||||
def _resolve_memory_type(self, type_str: Any) -> MemoryType:
|
||||
"""健壮地解析记忆类型,兼容中文和英文"""
|
||||
if not isinstance(type_str, str) or not type_str.strip():
|
||||
return MemoryType.CONTEXTUAL
|
||||
|
||||
cleaned_type = type_str.strip()
|
||||
|
||||
# 尝试中文映射
|
||||
if cleaned_type in CHINESE_TO_MEMORY_TYPE:
|
||||
return CHINESE_TO_MEMORY_TYPE[cleaned_type]
|
||||
|
||||
# 尝试直接作为枚举值解析
|
||||
try:
|
||||
return MemoryType(cleaned_type.lower().replace(" ", "_"))
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# 尝试作为枚举名解析
|
||||
try:
|
||||
return MemoryType[cleaned_type.upper()]
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
logger.warning(f"无法解析未知的记忆类型 '{type_str}',回退到上下文类型")
|
||||
return MemoryType.CONTEXTUAL
|
||||
|
||||
def _parse_enum_value(self, enum_cls: Type[E], raw_value: Any, default: E, field_name: str) -> E:
|
||||
"""解析枚举值,兼容数字/字符串表示"""
|
||||
if isinstance(raw_value, enum_cls):
|
||||
return raw_value
|
||||
|
||||
@@ -162,7 +162,6 @@ class MemorySystem:
|
||||
async def initialize(self):
|
||||
"""异步初始化记忆系统"""
|
||||
try:
|
||||
logger.info("正在初始化记忆系统...")
|
||||
|
||||
# 初始化LLM模型
|
||||
fallback_task = getattr(self.llm_model, "model_for_task", None) if self.llm_model else None
|
||||
@@ -268,11 +267,8 @@ class MemorySystem:
|
||||
logger.warning(f"海马体采样器初始化失败: {e}")
|
||||
self.hippocampus_sampler = None
|
||||
|
||||
# 统一存储已经自动加载数据,无需额外加载
|
||||
logger.info("✅ 简化版记忆系统初始化完成")
|
||||
|
||||
self.status = MemorySystemStatus.READY
|
||||
logger.info("✅ 记忆系统初始化完成")
|
||||
|
||||
except Exception as e:
|
||||
self.status = MemorySystemStatus.ERROR
|
||||
@@ -1425,16 +1421,6 @@ class MemorySystem:
|
||||
def _fingerprint_key(user_id: str, fingerprint: str) -> str:
|
||||
return f"{user_id!s}:{fingerprint}"
|
||||
|
||||
def get_system_stats(self) -> dict[str, Any]:
|
||||
"""获取系统统计信息"""
|
||||
return {
|
||||
"status": self.status.value,
|
||||
"total_memories": self.total_memories,
|
||||
"last_build_time": self.last_build_time,
|
||||
"last_retrieval_time": self.last_retrieval_time,
|
||||
"config": asdict(self.config),
|
||||
}
|
||||
|
||||
def _compute_memory_score(self, query_text: str, memory: MemoryChunk, context: dict[str, Any]) -> float:
|
||||
"""根据查询和上下文为记忆计算匹配分数"""
|
||||
tokens_query = self._tokenize_text(query_text)
|
||||
@@ -1542,7 +1528,7 @@ class MemorySystem:
|
||||
|
||||
# 保存统一存储数据
|
||||
if self.unified_storage:
|
||||
await self.unified_storage.cleanup()
|
||||
self.unified_storage.cleanup()
|
||||
|
||||
logger.info("✅ 简化记忆系统已关闭")
|
||||
|
||||
|
||||
@@ -964,6 +964,11 @@ class VectorMemoryStorage:
|
||||
|
||||
logger.info("Vector记忆存储系统已停止")
|
||||
|
||||
def cleanup(self):
|
||||
"""清理资源,兼容旧接口"""
|
||||
logger.info("正在清理VectorMemoryStorage资源...")
|
||||
self.stop()
|
||||
|
||||
|
||||
# 全局实例(可选)
|
||||
_global_vector_storage = None
|
||||
|
||||
Reference in New Issue
Block a user