mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge branch 'main' into feat/demo
This commit is contained in:
commit
8f3a09f85a
15 changed files with 925 additions and 8 deletions
|
|
@ -0,0 +1,26 @@
|
||||||
|
-- 添加memU记忆配置
|
||||||
|
-- memU是一个开源的AI记忆框架,提供长期记忆管理服务
|
||||||
|
|
||||||
|
-- 添加memU Memory Provider
|
||||||
|
delete from `ai_model_provider` where id = 'SYSTEM_Memory_memu';
|
||||||
|
INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) VALUES
|
||||||
|
('SYSTEM_Memory_memu', 'Memory', 'memu', 'memU记忆', '[{"key":"api_key","label":"API密钥","type":"password"},{"key":"base_url","label":"API地址","type":"string"},{"key":"user_name","label":"用户名称","type":"string"},{"key":"agent_name","label":"Agent名称","type":"string"}]', 4, 1, NOW(), 1, NOW());
|
||||||
|
|
||||||
|
-- 添加memU Memory Config
|
||||||
|
delete from `ai_model_config` where id = 'Memory_memu';
|
||||||
|
INSERT INTO `ai_model_config` VALUES (
|
||||||
|
'Memory_memu',
|
||||||
|
'Memory',
|
||||||
|
'memu',
|
||||||
|
'memU记忆',
|
||||||
|
0,
|
||||||
|
1,
|
||||||
|
'{"type": "memu", "api_key": "mu_SJPB0t8dtY0IwL0B0RjpiVKbTEI4w8MD8YkYSVItNzxe-t3DlOtHIJnp53tJ-kr6BL06-uPN0U5WPGs4EpT5iuMZMsrfI1KYvVfg1w", "base_url": "https://api.memu.so", "user_name": "用户", "agent_name": "小智"}',
|
||||||
|
'https://memu.pro/docs#memory',
|
||||||
|
'memU是一个开源的AI记忆框架,提供自主管理、组织和演进AI记忆的高级代理记忆系统。支持自动分类、语义搜索和长期记忆管理。',
|
||||||
|
4,
|
||||||
|
NULL,
|
||||||
|
NULL,
|
||||||
|
NULL,
|
||||||
|
NULL
|
||||||
|
);
|
||||||
|
|
@ -409,6 +409,13 @@ databaseChangeLog:
|
||||||
- sqlFile:
|
- sqlFile:
|
||||||
encoding: utf8
|
encoding: utf8
|
||||||
path: classpath:db/changelog/202511051120.sql
|
path: classpath:db/changelog/202511051120.sql
|
||||||
|
- changeSet:
|
||||||
|
id: 202511061415
|
||||||
|
author: leo
|
||||||
|
changes:
|
||||||
|
- sqlFile:
|
||||||
|
encoding: utf8
|
||||||
|
path: classpath:db/changelog/202511061415.sql
|
||||||
- changeSet:
|
- changeSet:
|
||||||
id: 202511071245
|
id: 202511071245
|
||||||
author: harold
|
author: harold
|
||||||
|
|
|
||||||
11
main/memu.py
Normal file
11
main/memu.py
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from memu import MemuClient
|
||||||
|
|
||||||
|
# Initialize MemU client
|
||||||
|
memu_client = MemuClient(
|
||||||
|
base_url="https://api.memu.so",
|
||||||
|
api_key=os.getenv("MEMU_API_KEY")
|
||||||
|
)
|
||||||
|
|
||||||
|
print("✅ MemU client initialized successfully!")
|
||||||
|
|
@ -219,7 +219,7 @@ selected_module:
|
||||||
# TTS将根据配置名称对应的type调用实际的TTS适配器
|
# TTS将根据配置名称对应的type调用实际的TTS适配器
|
||||||
TTS: EdgeTTS
|
TTS: EdgeTTS
|
||||||
# 记忆模块,默认不开启记忆;如果想使用超长记忆,推荐使用mem0ai;如果注重隐私,请使用本地的mem_local_short
|
# 记忆模块,默认不开启记忆;如果想使用超长记忆,推荐使用mem0ai;如果注重隐私,请使用本地的mem_local_short
|
||||||
Memory: nomem
|
Memory: memu
|
||||||
# 意图识别模块开启后,可以播放音乐、控制音量、识别退出指令。
|
# 意图识别模块开启后,可以播放音乐、控制音量、识别退出指令。
|
||||||
# 不想开通意图识别,就设置成:nointent
|
# 不想开通意图识别,就设置成:nointent
|
||||||
# 意图识别可使用intent_llm。优点:通用性强,缺点:增加串行前置意图识别模块,会增加处理时间,支持控制音量大小等iot操作
|
# 意图识别可使用intent_llm。优点:通用性强,缺点:增加串行前置意图识别模块,会增加处理时间,支持控制音量大小等iot操作
|
||||||
|
|
@ -271,6 +271,14 @@ Memory:
|
||||||
# https://app.mem0.ai/dashboard/api-keys
|
# https://app.mem0.ai/dashboard/api-keys
|
||||||
# 每月有1000次免费调用
|
# 每月有1000次免费调用
|
||||||
api_key: 你的mem0ai api key
|
api_key: 你的mem0ai api key
|
||||||
|
memu:
|
||||||
|
type: memu
|
||||||
|
# https://app.memu.so/api-key/
|
||||||
|
# MemU AI记忆框架 - 提供长期记忆管理服务
|
||||||
|
api_key: mu_SJPB0t8dtY0IwL0B0RjpiVKbTEI4w8MD8YkYSVItNzxe-t3DlOtHIJnp53tJ-kr6BL06-uPN0U5WPGs4EpT5iuMZMsrfI1KYvVfg1w
|
||||||
|
base_url: https://api.memu.so
|
||||||
|
user_name: 用户
|
||||||
|
agent_name: 小智
|
||||||
nomem:
|
nomem:
|
||||||
# 不想使用记忆功能,可以使用nomem
|
# 不想使用记忆功能,可以使用nomem
|
||||||
type: nomem
|
type: nomem
|
||||||
|
|
|
||||||
189
main/xiaozhi-server/core/api/chat_history_handler.py
Normal file
189
main/xiaozhi-server/core/api/chat_history_handler.py
Normal file
|
|
@ -0,0 +1,189 @@
|
||||||
|
from aiohttp import web
|
||||||
|
from core.api.base_handler import BaseHandler
|
||||||
|
from config.logger import setup_logging
|
||||||
|
import mysql.connector
|
||||||
|
from mysql.connector import Error
|
||||||
|
import yaml
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
|
class ChatHistoryHandler(BaseHandler):
|
||||||
|
"""聊天记录 API 处理器"""
|
||||||
|
|
||||||
|
def __init__(self, config: dict):
|
||||||
|
super().__init__(config)
|
||||||
|
self.logger = setup_logging()
|
||||||
|
self.db_config = self._load_db_config()
|
||||||
|
|
||||||
|
def _load_db_config(self):
|
||||||
|
"""从custom_config.yaml加载数据库配置"""
|
||||||
|
try:
|
||||||
|
project_dir = Path(__file__).parent.parent.parent
|
||||||
|
custom_config_path = project_dir / "custom_config.yaml"
|
||||||
|
|
||||||
|
if not custom_config_path.exists():
|
||||||
|
self.logger.bind(tag=TAG).warning(f"custom_config.yaml 文件不存在: {custom_config_path}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
with open(custom_config_path, "r", encoding="utf-8") as f:
|
||||||
|
custom_config = yaml.safe_load(f)
|
||||||
|
|
||||||
|
# 检查是否启用了read_config_from_api
|
||||||
|
read_config_from_api = custom_config.get("read_config_from_api", False)
|
||||||
|
|
||||||
|
if not read_config_from_api:
|
||||||
|
self.logger.bind(tag=TAG).info("read_config_from_api未启用,聊天记录API将不可用")
|
||||||
|
return None
|
||||||
|
|
||||||
|
# 从Docker配置或本地配置中读取数据库信息
|
||||||
|
mysql_config = custom_config.get("mysql", {})
|
||||||
|
|
||||||
|
if not mysql_config:
|
||||||
|
self.logger.bind(tag=TAG).warning("未找到MySQL配置")
|
||||||
|
return None
|
||||||
|
|
||||||
|
db_config = {
|
||||||
|
"host": mysql_config.get("host", "localhost"),
|
||||||
|
"port": mysql_config.get("port", 3306),
|
||||||
|
"user": mysql_config.get("user", "root"),
|
||||||
|
"password": mysql_config.get("password", ""),
|
||||||
|
"database": mysql_config.get("database", "xiaozhi")
|
||||||
|
}
|
||||||
|
|
||||||
|
self.logger.bind(tag=TAG).info(f"数据库配置加载成功: {db_config['host']}:{db_config['port']}")
|
||||||
|
return db_config
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"加载数据库配置失败: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _get_db_connection(self):
|
||||||
|
"""获取数据库连接"""
|
||||||
|
if not self.db_config:
|
||||||
|
raise Exception("数据库未配置")
|
||||||
|
|
||||||
|
try:
|
||||||
|
connection = mysql.connector.connect(**self.db_config)
|
||||||
|
return connection
|
||||||
|
except Error as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"数据库连接失败: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
async def handle_options(self, request):
|
||||||
|
"""处理 OPTIONS 请求(CORS 预检)"""
|
||||||
|
response = web.Response()
|
||||||
|
self._add_cors_headers(response)
|
||||||
|
response.headers["Access-Control-Allow-Methods"] = "GET, OPTIONS"
|
||||||
|
return response
|
||||||
|
|
||||||
|
async def handle_get_by_session(self, request):
|
||||||
|
"""根据session_id获取聊天记录"""
|
||||||
|
response = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 获取路径参数
|
||||||
|
session_id = request.match_info.get('session_id')
|
||||||
|
|
||||||
|
if not session_id:
|
||||||
|
response = web.json_response({
|
||||||
|
"success": False,
|
||||||
|
"error": "缺少 session_id 参数"
|
||||||
|
})
|
||||||
|
self._add_cors_headers(response)
|
||||||
|
return response
|
||||||
|
|
||||||
|
# 查询数据库
|
||||||
|
connection = self._get_db_connection()
|
||||||
|
cursor = connection.cursor(dictionary=True)
|
||||||
|
|
||||||
|
query = """
|
||||||
|
SELECT
|
||||||
|
id,
|
||||||
|
mac_address,
|
||||||
|
agent_id,
|
||||||
|
session_id,
|
||||||
|
chat_type,
|
||||||
|
content,
|
||||||
|
created_at
|
||||||
|
FROM ai_agent_chat_history
|
||||||
|
WHERE session_id = %s
|
||||||
|
ORDER BY created_at ASC
|
||||||
|
"""
|
||||||
|
|
||||||
|
cursor.execute(query, (session_id,))
|
||||||
|
records = cursor.fetchall()
|
||||||
|
|
||||||
|
cursor.close()
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
# 转换为JSON可序列化的格式
|
||||||
|
chat_history = []
|
||||||
|
for record in records:
|
||||||
|
chat_history.append({
|
||||||
|
"id": record["id"],
|
||||||
|
"mac_address": record["mac_address"],
|
||||||
|
"agent_id": record["agent_id"],
|
||||||
|
"session_id": record["session_id"],
|
||||||
|
"chat_type": record["chat_type"], # 1-用户, 2-智能体
|
||||||
|
"content": record["content"],
|
||||||
|
"created_at": record["created_at"].isoformat() if record["created_at"] else None
|
||||||
|
})
|
||||||
|
|
||||||
|
response = web.json_response({
|
||||||
|
"success": True,
|
||||||
|
"data": chat_history,
|
||||||
|
"message": f"找到 {len(chat_history)} 条聊天记录"
|
||||||
|
})
|
||||||
|
self._add_cors_headers(response)
|
||||||
|
return response
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"查询聊天记录失败: {e}")
|
||||||
|
response = web.json_response({
|
||||||
|
"success": False,
|
||||||
|
"error": str(e)
|
||||||
|
})
|
||||||
|
self._add_cors_headers(response)
|
||||||
|
return response
|
||||||
|
|
||||||
|
async def handle_check_memory(self, request):
|
||||||
|
"""检查某会话是否已生成记忆"""
|
||||||
|
response = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 获取路径参数
|
||||||
|
session_id = request.match_info.get('session_id')
|
||||||
|
|
||||||
|
if not session_id:
|
||||||
|
response = web.json_response({
|
||||||
|
"success": False,
|
||||||
|
"error": "缺少 session_id 参数"
|
||||||
|
})
|
||||||
|
self._add_cors_headers(response)
|
||||||
|
return response
|
||||||
|
|
||||||
|
# 这里需要调用MEMu API检查是否有该session_id的记忆
|
||||||
|
# 暂时返回简单响应,实际逻辑需要与MEMu集成
|
||||||
|
response = web.json_response({
|
||||||
|
"success": True,
|
||||||
|
"data": {
|
||||||
|
"session_id": session_id,
|
||||||
|
"has_memory": False, # 需要实际检查
|
||||||
|
"memory_count": 0
|
||||||
|
},
|
||||||
|
"message": "检查完成"
|
||||||
|
})
|
||||||
|
self._add_cors_headers(response)
|
||||||
|
return response
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"检查记忆失败: {e}")
|
||||||
|
response = web.json_response({
|
||||||
|
"success": False,
|
||||||
|
"error": str(e)
|
||||||
|
})
|
||||||
|
self._add_cors_headers(response)
|
||||||
|
return response
|
||||||
|
|
||||||
437
main/xiaozhi-server/core/api/memu_handler.py
Normal file
437
main/xiaozhi-server/core/api/memu_handler.py
Normal file
|
|
@ -0,0 +1,437 @@
|
||||||
|
from aiohttp import web
|
||||||
|
from core.api.base_handler import BaseHandler
|
||||||
|
from config.logger import setup_logging
|
||||||
|
|
||||||
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
|
class MemuHandler(BaseHandler):
|
||||||
|
"""MEMu 记忆管理 API 处理器"""
|
||||||
|
|
||||||
|
def __init__(self, config: dict):
|
||||||
|
super().__init__(config)
|
||||||
|
self.logger = setup_logging()
|
||||||
|
self.memu_client = None
|
||||||
|
self.user_id_aliases = {}
|
||||||
|
self.default_user_id = None
|
||||||
|
self.default_agent_id = "xiaozhi_agent"
|
||||||
|
|
||||||
|
# 初始化 MEMu 客户端
|
||||||
|
self._init_memu_client()
|
||||||
|
|
||||||
|
def _init_memu_client(self):
|
||||||
|
"""初始化 MEMu 客户端
|
||||||
|
|
||||||
|
注意:记忆管理页面独立于系统的记忆模块配置
|
||||||
|
只要配置了 MEMu API Key,就可以使用记忆管理功能
|
||||||
|
从 custom_config.yaml 直接读取 MEMu 配置
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# 从 custom_config.yaml 文件直接读取 MEMu 配置
|
||||||
|
import os
|
||||||
|
import yaml
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
# 获取项目根目录
|
||||||
|
project_dir = Path(__file__).parent.parent.parent
|
||||||
|
custom_config_path = project_dir / "custom_config.yaml"
|
||||||
|
|
||||||
|
if not custom_config_path.exists():
|
||||||
|
self.logger.bind(tag=TAG).warning(f"custom_config.yaml 文件不存在: {custom_config_path}")
|
||||||
|
return
|
||||||
|
|
||||||
|
with open(custom_config_path, "r", encoding="utf-8") as f:
|
||||||
|
custom_config = yaml.safe_load(f)
|
||||||
|
|
||||||
|
memory_module_config = custom_config.get("Memory", {}).get("memu", {})
|
||||||
|
if memory_module_config:
|
||||||
|
from memu import MemuClient
|
||||||
|
|
||||||
|
self.default_agent_id = memory_module_config.get("default_agent_id", self.default_agent_id)
|
||||||
|
self.default_user_id = self._standardize_id(memory_module_config.get("default_user_id"))
|
||||||
|
alias_config = memory_module_config.get("user_id_aliases", {}) or {}
|
||||||
|
self.user_id_aliases = {
|
||||||
|
self._standardize_id(alias): self._standardize_id(real_id)
|
||||||
|
for alias, real_id in alias_config.items()
|
||||||
|
if alias and real_id
|
||||||
|
}
|
||||||
|
|
||||||
|
api_key = memory_module_config.get("api_key", "")
|
||||||
|
base_url = memory_module_config.get("base_url", "https://api.memu.so")
|
||||||
|
|
||||||
|
if api_key and "你" not in api_key:
|
||||||
|
self.memu_client = MemuClient(
|
||||||
|
base_url=base_url,
|
||||||
|
api_key=api_key
|
||||||
|
)
|
||||||
|
self.logger.bind(tag=TAG).info("MEMu 客户端初始化成功(记忆管理 API)")
|
||||||
|
else:
|
||||||
|
self.logger.bind(tag=TAG).warning("MEMu API Key 未配置或无效")
|
||||||
|
else:
|
||||||
|
self.logger.bind(tag=TAG).warning("custom_config.yaml 中未找到 Memory.memu 配置")
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"初始化 MEMu 客户端失败: {e}")
|
||||||
|
|
||||||
|
async def handle_options(self, request):
|
||||||
|
"""处理 OPTIONS 请求(CORS 预检)"""
|
||||||
|
response = web.Response()
|
||||||
|
self._add_cors_headers(response)
|
||||||
|
response.headers["Access-Control-Allow-Methods"] = "POST, OPTIONS"
|
||||||
|
return response
|
||||||
|
|
||||||
|
async def handle_post(self, request):
|
||||||
|
"""处理 POST 请求"""
|
||||||
|
response = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 检查 MEMu 客户端是否可用
|
||||||
|
if not self.memu_client:
|
||||||
|
response = web.json_response({
|
||||||
|
"success": False,
|
||||||
|
"error": "MEMu 服务未配置或未启用"
|
||||||
|
})
|
||||||
|
self._add_cors_headers(response)
|
||||||
|
return response
|
||||||
|
|
||||||
|
# 解析请求数据
|
||||||
|
try:
|
||||||
|
data = await request.json()
|
||||||
|
except Exception as e:
|
||||||
|
response = web.json_response({
|
||||||
|
"success": False,
|
||||||
|
"error": f"请求数据格式错误: {str(e)}"
|
||||||
|
})
|
||||||
|
self._add_cors_headers(response)
|
||||||
|
return response
|
||||||
|
|
||||||
|
action = data.get("action")
|
||||||
|
user_id = self._normalize_user_id(data.get("user_id"))
|
||||||
|
agent_id = data.get("agent_id") or self.default_agent_id
|
||||||
|
|
||||||
|
if not user_id:
|
||||||
|
response = web.json_response({
|
||||||
|
"success": False,
|
||||||
|
"error": "缺少 user_id 参数"
|
||||||
|
})
|
||||||
|
self._add_cors_headers(response)
|
||||||
|
return response
|
||||||
|
|
||||||
|
# 根据不同的 action 执行相应操作
|
||||||
|
if action == "get_all":
|
||||||
|
result = await self._get_all_memories(user_id, agent_id)
|
||||||
|
elif action == "search":
|
||||||
|
query = data.get("query")
|
||||||
|
top_k = data.get("top_k", 10)
|
||||||
|
result = await self._search_memories(user_id, agent_id, query, top_k)
|
||||||
|
elif action == "get_categories":
|
||||||
|
topic = data.get("topic")
|
||||||
|
top_k = data.get("top_k", 5)
|
||||||
|
result = await self._get_categories(user_id, agent_id, topic, top_k)
|
||||||
|
elif action == "get_by_session":
|
||||||
|
session_id = data.get("session_id")
|
||||||
|
result = await self._get_memories_by_session(user_id, agent_id, session_id)
|
||||||
|
elif action == "delete":
|
||||||
|
result = await self._delete_memories(user_id, agent_id)
|
||||||
|
else:
|
||||||
|
result = {
|
||||||
|
"success": False,
|
||||||
|
"error": f"未知操作: {action}"
|
||||||
|
}
|
||||||
|
|
||||||
|
response = web.json_response(result)
|
||||||
|
self._add_cors_headers(response)
|
||||||
|
return response
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"处理请求时发生错误: {e}")
|
||||||
|
response = web.json_response({
|
||||||
|
"success": False,
|
||||||
|
"error": str(e)
|
||||||
|
})
|
||||||
|
self._add_cors_headers(response)
|
||||||
|
return response
|
||||||
|
|
||||||
|
async def _get_all_memories(self, user_id: str, agent_id: str = None):
|
||||||
|
"""获取所有记忆"""
|
||||||
|
try:
|
||||||
|
# 尝试使用新版API参数,如果失败则使用旧版API
|
||||||
|
try:
|
||||||
|
result = self.memu_client.retrieve_default_categories(
|
||||||
|
user_id=user_id,
|
||||||
|
agent_id=agent_id,
|
||||||
|
want_memory_items=True
|
||||||
|
)
|
||||||
|
except TypeError:
|
||||||
|
# 旧版本不支持want_memory_items参数
|
||||||
|
self.logger.bind(tag=TAG).warning("MEMu API不支持want_memory_items参数,使用默认方式获取")
|
||||||
|
result = self.memu_client.retrieve_default_categories(
|
||||||
|
user_id=user_id,
|
||||||
|
agent_id=agent_id
|
||||||
|
)
|
||||||
|
|
||||||
|
# 将MEMu对象转换为可序列化的字典
|
||||||
|
data = self._convert_to_dict(result)
|
||||||
|
|
||||||
|
# 处理返回的数据结构
|
||||||
|
# MEMu API 返回格式: {"categories": [...], "total_categories": N}
|
||||||
|
categories_list = []
|
||||||
|
if isinstance(data, dict) and "categories" in data:
|
||||||
|
categories_list = data["categories"]
|
||||||
|
elif isinstance(data, list):
|
||||||
|
categories_list = data
|
||||||
|
|
||||||
|
# 解析并规范化分类数据
|
||||||
|
normalized_categories = []
|
||||||
|
for category in categories_list:
|
||||||
|
# 处理 memory_items 字段(可能为 None 或数组)
|
||||||
|
memory_items = category.get("memory_items") or category.get("memories") or []
|
||||||
|
|
||||||
|
# 规范化记忆项
|
||||||
|
normalized_memories = []
|
||||||
|
if memory_items and isinstance(memory_items, list):
|
||||||
|
for memory in memory_items:
|
||||||
|
# 确保每个记忆项都有 metadata 字段
|
||||||
|
if isinstance(memory, dict) and "metadata" not in memory:
|
||||||
|
memory["metadata"] = {}
|
||||||
|
normalized_memories.append(memory)
|
||||||
|
|
||||||
|
# 创建规范化的分类对象
|
||||||
|
normalized_category = {
|
||||||
|
"name": category.get("name", "未分类"),
|
||||||
|
"type": category.get("type", "auto"),
|
||||||
|
"description": category.get("description", ""),
|
||||||
|
"summary": category.get("summary", ""),
|
||||||
|
"count": len(normalized_memories),
|
||||||
|
"memories": normalized_memories, # 统一使用 memories 字段名
|
||||||
|
}
|
||||||
|
normalized_categories.append(normalized_category)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"data": normalized_categories,
|
||||||
|
"message": "获取记忆成功"
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"获取所有记忆失败: {e}")
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"error": str(e)
|
||||||
|
}
|
||||||
|
|
||||||
|
def _standardize_id(self, value):
|
||||||
|
if not value:
|
||||||
|
return None
|
||||||
|
normalized = str(value).strip()
|
||||||
|
if ":" in normalized:
|
||||||
|
normalized = normalized.upper()
|
||||||
|
return normalized or None
|
||||||
|
|
||||||
|
def _normalize_user_id(self, user_id):
|
||||||
|
normalized = self._standardize_id(user_id)
|
||||||
|
if not normalized:
|
||||||
|
return self.default_user_id
|
||||||
|
if normalized in self.user_id_aliases:
|
||||||
|
alias_target = self.user_id_aliases[normalized]
|
||||||
|
self.logger.bind(tag=TAG).info(f"使用 user_id 别名映射: {normalized} -> {alias_target}")
|
||||||
|
return alias_target
|
||||||
|
# 当仍使用默认占位值时,尝试 fallback
|
||||||
|
if normalized in {"XIAOZHI-WEB-TEST", "TEST-DEVICE-WEB"} and self.default_user_id:
|
||||||
|
self.logger.bind(tag=TAG).info(f"使用默认 user_id: {self.default_user_id}")
|
||||||
|
return self.default_user_id
|
||||||
|
return normalized
|
||||||
|
|
||||||
|
async def _search_memories(self, user_id: str, agent_id: str, query: str, top_k: int):
|
||||||
|
"""搜索记忆"""
|
||||||
|
try:
|
||||||
|
if not query:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"error": "缺少 query 参数"
|
||||||
|
}
|
||||||
|
|
||||||
|
result = self.memu_client.retrieve_related_memory_items(
|
||||||
|
user_id=user_id,
|
||||||
|
agent_id=agent_id,
|
||||||
|
query=query,
|
||||||
|
top_k=top_k,
|
||||||
|
min_similarity=0.3
|
||||||
|
)
|
||||||
|
|
||||||
|
# 将MEMu对象转换为可序列化的字典
|
||||||
|
data = self._convert_to_dict(result)
|
||||||
|
|
||||||
|
# 确保metadata被正确返回
|
||||||
|
if data and isinstance(data, list):
|
||||||
|
for memory in data:
|
||||||
|
if "metadata" not in memory:
|
||||||
|
memory["metadata"] = {}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"data": data,
|
||||||
|
"message": f"搜索成功,找到 {len(data) if data else 0} 条记忆"
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"搜索记忆失败: {e}")
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"error": str(e)
|
||||||
|
}
|
||||||
|
|
||||||
|
async def _get_categories(self, user_id: str, agent_id: str, topic: str, top_k: int):
|
||||||
|
"""获取记忆分类"""
|
||||||
|
try:
|
||||||
|
if not topic:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"error": "缺少 topic 参数"
|
||||||
|
}
|
||||||
|
|
||||||
|
result = self.memu_client.retrieve_related_clustered_categories(
|
||||||
|
user_id=user_id,
|
||||||
|
agent_id=agent_id,
|
||||||
|
category_query=topic,
|
||||||
|
top_k=top_k,
|
||||||
|
want_summary=True
|
||||||
|
)
|
||||||
|
|
||||||
|
# 将MEMu对象转换为可序列化的字典
|
||||||
|
data = self._convert_to_dict(result)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"data": data,
|
||||||
|
"message": f"获取分类成功,找到 {len(data) if data else 0} 个分类"
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"获取分类失败: {e}")
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"error": str(e)
|
||||||
|
}
|
||||||
|
|
||||||
|
async def _delete_memories(self, user_id: str, agent_id: str = None):
|
||||||
|
"""删除记忆"""
|
||||||
|
try:
|
||||||
|
result = self.memu_client.delete_memories(
|
||||||
|
user_id=user_id,
|
||||||
|
agent_id=agent_id
|
||||||
|
)
|
||||||
|
|
||||||
|
# 将MEMu对象转换为可序列化的字典
|
||||||
|
data = self._convert_to_dict(result)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"data": data,
|
||||||
|
"message": "记忆删除成功"
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"删除记忆失败: {e}")
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"error": str(e)
|
||||||
|
}
|
||||||
|
|
||||||
|
def _convert_to_dict(self, obj):
|
||||||
|
"""将MEMu对象转换为可JSON序列化的字典"""
|
||||||
|
import json
|
||||||
|
|
||||||
|
if obj is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# 如果已经是基本类型,直接返回
|
||||||
|
if isinstance(obj, (str, int, float, bool)):
|
||||||
|
return obj
|
||||||
|
|
||||||
|
# 如果是列表,递归转换每个元素
|
||||||
|
if isinstance(obj, list):
|
||||||
|
return [self._convert_to_dict(item) for item in obj]
|
||||||
|
|
||||||
|
# 如果是字典,递归转换每个值
|
||||||
|
if isinstance(obj, dict):
|
||||||
|
return {key: self._convert_to_dict(value) for key, value in obj.items()}
|
||||||
|
|
||||||
|
# 如果是对象,尝试多种方式转换
|
||||||
|
try:
|
||||||
|
# 方法1: 尝试使用对象的dict()方法
|
||||||
|
if hasattr(obj, 'dict'):
|
||||||
|
return self._convert_to_dict(obj.dict())
|
||||||
|
|
||||||
|
# 方法2: 尝试使用对象的model_dump()方法(pydantic v2)
|
||||||
|
if hasattr(obj, 'model_dump'):
|
||||||
|
return self._convert_to_dict(obj.model_dump())
|
||||||
|
|
||||||
|
# 方法3: 尝试使用__dict__属性
|
||||||
|
if hasattr(obj, '__dict__'):
|
||||||
|
return self._convert_to_dict(obj.__dict__)
|
||||||
|
|
||||||
|
# 方法4: 尝试转换为字符串
|
||||||
|
return str(obj)
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).warning(f"对象转换失败,使用字符串表示: {e}")
|
||||||
|
return str(obj)
|
||||||
|
|
||||||
|
async def _get_memories_by_session(self, user_id: str, agent_id: str, session_id: str):
|
||||||
|
"""根据session_id获取记忆"""
|
||||||
|
try:
|
||||||
|
if not session_id:
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"error": "缺少 session_id 参数"
|
||||||
|
}
|
||||||
|
|
||||||
|
# 获取所有记忆 - 兼容新旧版本API
|
||||||
|
try:
|
||||||
|
all_categories = self.memu_client.retrieve_default_categories(
|
||||||
|
user_id=user_id,
|
||||||
|
agent_id=agent_id,
|
||||||
|
want_memory_items=True
|
||||||
|
)
|
||||||
|
except TypeError:
|
||||||
|
# 旧版本不支持want_memory_items参数
|
||||||
|
self.logger.bind(tag=TAG).warning("MEMu API不支持want_memory_items参数,使用默认方式获取")
|
||||||
|
all_categories = self.memu_client.retrieve_default_categories(
|
||||||
|
user_id=user_id,
|
||||||
|
agent_id=agent_id
|
||||||
|
)
|
||||||
|
|
||||||
|
# 将MEMu对象转换为可序列化的字典
|
||||||
|
categories_data = self._convert_to_dict(all_categories)
|
||||||
|
|
||||||
|
# 处理返回的数据结构
|
||||||
|
categories_list = []
|
||||||
|
if isinstance(categories_data, dict) and "categories" in categories_data:
|
||||||
|
categories_list = categories_data["categories"]
|
||||||
|
elif isinstance(categories_data, list):
|
||||||
|
categories_list = categories_data
|
||||||
|
|
||||||
|
# 筛选包含指定session_id的记忆
|
||||||
|
filtered_memories = []
|
||||||
|
for category in categories_list:
|
||||||
|
# 处理 memory_items 字段(可能为 None 或数组)
|
||||||
|
memory_items = category.get("memory_items") or category.get("memories") or []
|
||||||
|
|
||||||
|
if memory_items and isinstance(memory_items, list):
|
||||||
|
for memory in memory_items:
|
||||||
|
metadata = memory.get("metadata", {})
|
||||||
|
if metadata.get("session_id") == session_id:
|
||||||
|
# 添加分类信息
|
||||||
|
memory["category_name"] = category.get("name", "未分类")
|
||||||
|
# 确保 metadata 存在
|
||||||
|
if "metadata" not in memory:
|
||||||
|
memory["metadata"] = metadata
|
||||||
|
filtered_memories.append(memory)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"data": filtered_memories,
|
||||||
|
"message": f"找到 {len(filtered_memories)} 条与会话 {session_id} 相关的记忆"
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"按会话查询记忆失败: {e}")
|
||||||
|
return {
|
||||||
|
"success": False,
|
||||||
|
"error": str(e)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -230,6 +230,14 @@ class ConnectionHandler:
|
||||||
"""保存记忆并关闭连接"""
|
"""保存记忆并关闭连接"""
|
||||||
try:
|
try:
|
||||||
if self.memory:
|
if self.memory:
|
||||||
|
# 准备上下文信息
|
||||||
|
context = {
|
||||||
|
"session_id": self.session_id,
|
||||||
|
"device_id": self.device_id,
|
||||||
|
"mac_address": getattr(self, 'mac_address', None),
|
||||||
|
"agent_id": getattr(self, 'agent_id', None),
|
||||||
|
}
|
||||||
|
|
||||||
# 使用线程池异步保存记忆
|
# 使用线程池异步保存记忆
|
||||||
def save_memory_task():
|
def save_memory_task():
|
||||||
try:
|
try:
|
||||||
|
|
@ -237,7 +245,7 @@ class ConnectionHandler:
|
||||||
loop = asyncio.new_event_loop()
|
loop = asyncio.new_event_loop()
|
||||||
asyncio.set_event_loop(loop)
|
asyncio.set_event_loop(loop)
|
||||||
loop.run_until_complete(
|
loop.run_until_complete(
|
||||||
self.memory.save_memory(self.dialogue.dialogue)
|
self.memory.save_memory(self.dialogue.dialogue, context)
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(f"保存记忆失败: {e}")
|
self.logger.bind(tag=TAG).error(f"保存记忆失败: {e}")
|
||||||
|
|
|
||||||
|
|
@ -3,9 +3,18 @@ from aiohttp import web
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from core.api.ota_handler import OTAHandler
|
from core.api.ota_handler import OTAHandler
|
||||||
from core.api.vision_handler import VisionHandler
|
from core.api.vision_handler import VisionHandler
|
||||||
|
from core.api.memu_handler import MemuHandler
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
# 尝试导入 ChatHistoryHandler(可选)
|
||||||
|
try:
|
||||||
|
from core.api.chat_history_handler import ChatHistoryHandler
|
||||||
|
CHAT_HISTORY_AVAILABLE = True
|
||||||
|
except ImportError as e:
|
||||||
|
CHAT_HISTORY_AVAILABLE = False
|
||||||
|
print(f"警告: ChatHistoryHandler 不可用 (缺少依赖: {e}),聊天记录API将被禁用")
|
||||||
|
|
||||||
|
|
||||||
class SimpleHttpServer:
|
class SimpleHttpServer:
|
||||||
def __init__(self, config: dict):
|
def __init__(self, config: dict):
|
||||||
|
|
@ -13,6 +22,19 @@ class SimpleHttpServer:
|
||||||
self.logger = setup_logging()
|
self.logger = setup_logging()
|
||||||
self.ota_handler = OTAHandler(config)
|
self.ota_handler = OTAHandler(config)
|
||||||
self.vision_handler = VisionHandler(config)
|
self.vision_handler = VisionHandler(config)
|
||||||
|
self.memu_handler = MemuHandler(config)
|
||||||
|
|
||||||
|
# 仅在可用时初始化 ChatHistoryHandler
|
||||||
|
if CHAT_HISTORY_AVAILABLE:
|
||||||
|
try:
|
||||||
|
self.chat_history_handler = ChatHistoryHandler(config)
|
||||||
|
self.logger.bind(tag=TAG).info("ChatHistoryHandler 初始化成功")
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).warning(f"ChatHistoryHandler 初始化失败: {e}")
|
||||||
|
self.chat_history_handler = None
|
||||||
|
else:
|
||||||
|
self.chat_history_handler = None
|
||||||
|
self.logger.bind(tag=TAG).info("ChatHistoryHandler 未启用")
|
||||||
|
|
||||||
def _get_websocket_url(self, local_ip: str, port: int) -> str:
|
def _get_websocket_url(self, local_ip: str, port: int) -> str:
|
||||||
"""获取websocket地址
|
"""获取websocket地址
|
||||||
|
|
@ -58,6 +80,28 @@ class SimpleHttpServer:
|
||||||
web.options("/mcp/vision/explain", self.vision_handler.handle_post),
|
web.options("/mcp/vision/explain", self.vision_handler.handle_post),
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# 添加 MEMu 记忆管理路由
|
||||||
|
app.add_routes(
|
||||||
|
[
|
||||||
|
web.post("/api/memu/memories", self.memu_handler.handle_post),
|
||||||
|
web.options("/api/memu/memories", self.memu_handler.handle_options),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
# 添加聊天记录查询路由(仅在可用时)
|
||||||
|
if self.chat_history_handler:
|
||||||
|
app.add_routes(
|
||||||
|
[
|
||||||
|
web.get("/api/chat-history/session/{session_id}", self.chat_history_handler.handle_get_by_session),
|
||||||
|
web.options("/api/chat-history/session/{session_id}", self.chat_history_handler.handle_options),
|
||||||
|
web.get("/api/chat-history/has-memory/{session_id}", self.chat_history_handler.handle_check_memory),
|
||||||
|
web.options("/api/chat-history/has-memory/{session_id}", self.chat_history_handler.handle_options),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
self.logger.bind(tag=TAG).info("聊天记录API路由已启用")
|
||||||
|
else:
|
||||||
|
self.logger.bind(tag=TAG).info("聊天记录API路由已禁用(ChatHistoryHandler不可用)")
|
||||||
|
|
||||||
# 运行服务
|
# 运行服务
|
||||||
runner = web.AppRunner(app)
|
runner = web.AppRunner(app)
|
||||||
|
|
|
||||||
|
|
@ -14,8 +14,13 @@ class MemoryProviderBase(ABC):
|
||||||
self.llm = llm
|
self.llm = llm
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
async def save_memory(self, msgs):
|
async def save_memory(self, msgs, context=None):
|
||||||
"""Save a new memory for specific role and return memory ID"""
|
"""Save a new memory for specific role and return memory ID
|
||||||
|
|
||||||
|
Args:
|
||||||
|
msgs: 对话消息列表
|
||||||
|
context: 额外的上下文信息,包含session_id、mac_address等
|
||||||
|
"""
|
||||||
print("this is base func", msgs)
|
print("this is base func", msgs)
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
|
|
|
||||||
|
|
@ -29,7 +29,7 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}")
|
logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}")
|
||||||
self.use_mem0 = False
|
self.use_mem0 = False
|
||||||
|
|
||||||
async def save_memory(self, msgs):
|
async def save_memory(self, msgs, context=None):
|
||||||
if not self.use_mem0:
|
if not self.use_mem0:
|
||||||
return None
|
return None
|
||||||
if len(msgs) < 2:
|
if len(msgs) < 2:
|
||||||
|
|
|
||||||
|
|
@ -144,7 +144,7 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
with open(self.memory_path, "w", encoding="utf-8") as f:
|
with open(self.memory_path, "w", encoding="utf-8") as f:
|
||||||
yaml.dump(all_memory, f, allow_unicode=True)
|
yaml.dump(all_memory, f, allow_unicode=True)
|
||||||
|
|
||||||
async def save_memory(self, msgs):
|
async def save_memory(self, msgs, context=None):
|
||||||
# 打印使用的模型信息
|
# 打印使用的模型信息
|
||||||
model_info = getattr(self.llm, "model_name", str(self.llm.__class__.__name__))
|
model_info = getattr(self.llm, "model_name", str(self.llm.__class__.__name__))
|
||||||
logger.bind(tag=TAG).debug(f"使用记忆保存模型: {model_info}")
|
logger.bind(tag=TAG).debug(f"使用记忆保存模型: {model_info}")
|
||||||
|
|
|
||||||
159
main/xiaozhi-server/core/providers/memory/memu/memu.py
Normal file
159
main/xiaozhi-server/core/providers/memory/memu/memu.py
Normal file
|
|
@ -0,0 +1,159 @@
|
||||||
|
import traceback
|
||||||
|
|
||||||
|
from ..base import MemoryProviderBase, logger
|
||||||
|
from memu import MemuClient
|
||||||
|
from core.utils.util import check_model_key
|
||||||
|
|
||||||
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
|
class MemoryProvider(MemoryProviderBase):
|
||||||
|
def __init__(self, config, summary_memory=None):
|
||||||
|
super().__init__(config)
|
||||||
|
self.api_key = config.get("api_key", "")
|
||||||
|
self.base_url = config.get("base_url", "https://api.memu.so")
|
||||||
|
self.user_name = config.get("user_name", "用户")
|
||||||
|
self.agent_name = config.get("agent_name", "小智")
|
||||||
|
|
||||||
|
model_key_msg = check_model_key("MemU", self.api_key)
|
||||||
|
if model_key_msg:
|
||||||
|
logger.bind(tag=TAG).error(model_key_msg)
|
||||||
|
self.use_memu = False
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
self.use_memu = True
|
||||||
|
|
||||||
|
try:
|
||||||
|
self.client = MemuClient(
|
||||||
|
base_url=self.base_url,
|
||||||
|
api_key=self.api_key
|
||||||
|
)
|
||||||
|
logger.bind(tag=TAG).info("成功连接到 MemU 服务")
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"连接到 MemU 服务时发生错误: {str(e)}")
|
||||||
|
logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}")
|
||||||
|
self.use_memu = False
|
||||||
|
|
||||||
|
async def save_memory(self, msgs, context=None):
|
||||||
|
if not self.use_memu:
|
||||||
|
return None
|
||||||
|
if len(msgs) < 2:
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Format the conversation as a single text string for memU
|
||||||
|
conversation_text = ""
|
||||||
|
for message in msgs:
|
||||||
|
if message.role == "system":
|
||||||
|
continue
|
||||||
|
role_name = self.user_name if message.role == "user" else self.agent_name
|
||||||
|
conversation_text += f"{role_name}: {message.content}\n"
|
||||||
|
|
||||||
|
if not conversation_text.strip():
|
||||||
|
return None
|
||||||
|
|
||||||
|
# 准备session_date参数(MEMu SDK支持的参数)
|
||||||
|
import time
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
session_date = None
|
||||||
|
context_info = {}
|
||||||
|
if context:
|
||||||
|
# 记录上下文信息到日志
|
||||||
|
if "session_id" in context:
|
||||||
|
context_info["session_id"] = context["session_id"]
|
||||||
|
if "mac_address" in context:
|
||||||
|
context_info["mac_address"] = context["mac_address"]
|
||||||
|
if "device_id" in context:
|
||||||
|
context_info["device_id"] = context["device_id"]
|
||||||
|
|
||||||
|
# 使用当前时间作为session_date
|
||||||
|
session_date = datetime.now().strftime("%Y-%m-%d")
|
||||||
|
|
||||||
|
# Use memorize_conversation to store the memory
|
||||||
|
result = self.client.memorize_conversation(
|
||||||
|
conversation=conversation_text.strip(),
|
||||||
|
user_id=self.role_id,
|
||||||
|
user_name=self.user_name,
|
||||||
|
agent_id="xiaozhi_agent",
|
||||||
|
agent_name=self.agent_name,
|
||||||
|
session_date=session_date
|
||||||
|
)
|
||||||
|
logger.bind(tag=TAG).info(f"保存记忆成功,context: {context_info}, session_date: {session_date}")
|
||||||
|
logger.bind(tag=TAG).debug(f"Save memory result: {result}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"保存记忆失败: {str(e)}")
|
||||||
|
logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def query_memory(self, query: str) -> str:
|
||||||
|
if not self.use_memu:
|
||||||
|
return ""
|
||||||
|
try:
|
||||||
|
# Use retrieve_related_memory_items to retrieve memories
|
||||||
|
results = self.client.retrieve_related_memory_items(
|
||||||
|
user_id=self.role_id,
|
||||||
|
agent_id="xiaozhi_agent",
|
||||||
|
query=query,
|
||||||
|
top_k=10,
|
||||||
|
min_similarity=0.3
|
||||||
|
)
|
||||||
|
|
||||||
|
# 转换结果
|
||||||
|
if hasattr(results, 'model_dump'):
|
||||||
|
data = results.model_dump()
|
||||||
|
elif hasattr(results, 'dict'):
|
||||||
|
data = results.dict() if callable(results.dict) else results
|
||||||
|
else:
|
||||||
|
data = results
|
||||||
|
|
||||||
|
# 检查是否有记忆项
|
||||||
|
memory_items = []
|
||||||
|
if isinstance(data, dict) and 'memory_items' in data:
|
||||||
|
memory_items = data['memory_items']
|
||||||
|
elif isinstance(data, list):
|
||||||
|
memory_items = data
|
||||||
|
|
||||||
|
if not memory_items:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
# Format each memory entry with its timestamp
|
||||||
|
memories = []
|
||||||
|
for entry in memory_items:
|
||||||
|
if hasattr(entry, 'model_dump'):
|
||||||
|
entry_dict = entry.model_dump()
|
||||||
|
elif hasattr(entry, 'dict'):
|
||||||
|
entry_dict = entry.dict() if callable(entry.dict) else entry
|
||||||
|
else:
|
||||||
|
entry_dict = entry
|
||||||
|
|
||||||
|
timestamp = entry_dict.get("created_at", "")
|
||||||
|
if timestamp:
|
||||||
|
try:
|
||||||
|
# Parse and reformat the timestamp
|
||||||
|
dt = timestamp.split(".")[0] # Remove milliseconds
|
||||||
|
formatted_time = dt.replace("T", " ")
|
||||||
|
except:
|
||||||
|
formatted_time = timestamp
|
||||||
|
else:
|
||||||
|
formatted_time = "未知时间"
|
||||||
|
|
||||||
|
memory = entry_dict.get("content", "") or entry_dict.get("memory", "")
|
||||||
|
if memory:
|
||||||
|
# Store tuple of (timestamp, formatted_string) for sorting
|
||||||
|
memories.append((timestamp, f"[{formatted_time}] {memory}"))
|
||||||
|
|
||||||
|
if not memories:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
# Sort by timestamp in descending order (newest first)
|
||||||
|
memories.sort(key=lambda x: x[0], reverse=True)
|
||||||
|
|
||||||
|
# Extract only the formatted strings
|
||||||
|
memories_str = "\n".join(f"- {memory[1]}" for memory in memories)
|
||||||
|
logger.bind(tag=TAG).debug(f"Query results: {memories_str}")
|
||||||
|
return memories_str
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"查询记忆失败: {str(e)}")
|
||||||
|
logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}")
|
||||||
|
return ""
|
||||||
|
|
@ -11,7 +11,7 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
def __init__(self, config, summary_memory=None):
|
def __init__(self, config, summary_memory=None):
|
||||||
super().__init__(config)
|
super().__init__(config)
|
||||||
|
|
||||||
async def save_memory(self, msgs):
|
async def save_memory(self, msgs, context=None):
|
||||||
logger.bind(tag=TAG).debug("nomem mode: No memory saving is performed.")
|
logger.bind(tag=TAG).debug("nomem mode: No memory saving is performed.")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -38,7 +38,15 @@ server:
|
||||||
manager-api:
|
manager-api:
|
||||||
url: http://xiaozhi-esp32-server-web:8002/xiaozhi
|
url: http://xiaozhi-esp32-server-web:8002/xiaozhi
|
||||||
# This secret is used for local development, it will be replaced by the actual secret when the server is deployed
|
# This secret is used for local development, it will be replaced by the actual secret when the server is deployed
|
||||||
secret: 613be043-dc7e-4f5e-b775-e318e5bc87a3
|
secret: 613be043-dc7e-4f5e-b775-e318e5bc87a3
|
||||||
|
|
||||||
|
# MySQL配置(用于聊天记录和记忆关联)
|
||||||
|
mysql:
|
||||||
|
host: localhost
|
||||||
|
port: 3306
|
||||||
|
user: root
|
||||||
|
password: ""
|
||||||
|
database: xiaozhi
|
||||||
|
|
||||||
log:
|
log:
|
||||||
# 设置控制台输出的日志格式,时间、日志级别、标签、消息
|
# 设置控制台输出的日志格式,时间、日志级别、标签、消息
|
||||||
|
|
@ -249,6 +257,20 @@ Memory:
|
||||||
# https://app.mem0.ai/dashboard/api-keys
|
# https://app.mem0.ai/dashboard/api-keys
|
||||||
# 每月有1000次免费调用
|
# 每月有1000次免费调用
|
||||||
api_key: 你的mem0ai api key
|
api_key: 你的mem0ai api key
|
||||||
|
memu:
|
||||||
|
type: memu
|
||||||
|
# https://app.memu.so/api-key/
|
||||||
|
# MemU AI记忆框架 - 提供长期记忆管理服务
|
||||||
|
api_key: mu_SJPB0t8dtY0IwL0B0RjpiVKbTEI4w8MD8YkYSVItNzxe-t3DlOtHIJnp53tJ-kr6BL06-uPN0U5WPGs4EpT5iuMZMsrfI1KYvVfg1w
|
||||||
|
base_url: https://api.memu.so
|
||||||
|
user_name: 用户
|
||||||
|
agent_name: 小智
|
||||||
|
# 默认用于管理后台查询的 user_id / agent_id,可选
|
||||||
|
default_user_id: "51:3F:8D:59:D3:DB"
|
||||||
|
default_agent_id: xiaozhi_agent
|
||||||
|
# 如果管理后台仍使用占位ID,可通过别名映射到真实 device_id
|
||||||
|
user_id_aliases:
|
||||||
|
xiaozhi-web-test: "51:3F:8D:59:D3:DB"
|
||||||
nomem:
|
nomem:
|
||||||
# 不想使用记忆功能,可以使用nomem
|
# 不想使用记忆功能,可以使用nomem
|
||||||
type: nomem
|
type: nomem
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,7 @@ loguru==0.7.3
|
||||||
requests==2.32.5
|
requests==2.32.5
|
||||||
cozepy==0.19.0
|
cozepy==0.19.0
|
||||||
mem0ai==1.0.0
|
mem0ai==1.0.0
|
||||||
|
memu-py
|
||||||
bs4==0.0.2
|
bs4==0.0.2
|
||||||
modelscope==1.23.2
|
modelscope==1.23.2
|
||||||
sherpa_onnx==1.12.11
|
sherpa_onnx==1.12.11
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue