feat: 自构建部署可移植化 + aipet/缓存注册 + 记忆系统定制

可移植性(换机 git clone + docker compose -f docker-compose-selfbuild.yml up --build 即用):
- Dockerfile-server: server-base 改 ARG 引用(默认 NJU 镜像,国内自包含;海外可 --build-arg 覆盖)
- docker-compose-selfbuild.yml: 新增自构建 compose(server/web build:,mysql/redis image:)
- .dockerignore: 排除运行时数据目录(**/mysql/、*.db、**/data/),修复 build context 权限错误
- Dockerfile-web: start.sh CRLF→LF(修 exec "no such file or directory")

智控台 provider 注册(纯数据库驱动,前端无白名单):
- 202606191200.sql: 注册 SYSTEM_Memory_aipet 记忆 provider
- 202606120930.sql: 修列名 bug(is_custom→creator/updater)+ cache 改 boolean 开关
- db.changelog-master.yaml: 注册 202606191200
- AddModelDialog.vue: boolean 字段渲染为 el-switch 开关

server 端核心定制入库(此前未提交,换机会缺失):
- core/connection.py: 当天日程注入半稳定系统提示词
- core/providers/memory/aipet/aipet.py: FTS5 检索增强
- xiaozhi-memory/*: memory_manager / fts / sqlite_store / tokenizer / time_parser 检索修复

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
SerenNoble 2026-06-20 23:25:43 +08:00
parent f8222c8461
commit c9c8324cc8
19 changed files with 638 additions and 139 deletions

View file

@ -1,7 +1,16 @@
.git
__pycache__
**/__pycache__
*.pyc
.env
Dockerfile
tmp/
data/
# 运行时数据目录(由 volume 提供,不打包进构建上下文,避免权限/体积问题)
data/
**/data/
**/mysql/
**/uploadfile/
models/
# sqlite 运行库(aipet / xiaozhi-memory 等运行时生成)
*.db
**/*.db

6
.gitignore vendored
View file

@ -186,4 +186,8 @@ uploadfile
!main/manager-mobile/**/env/
!main/manager-mobile/**/.env*
!main/manager-mobile/**/*.json
!main/xiaozhi-server/**/*.json
!main/xiaozhi-server/**/*.json
# 工具索引与运行时产物(不入库)
.codegraph/
main/xiaozhi-server/xiaozhi-memory/data/

View file

@ -1,5 +1,8 @@
# 生产镜像,仅包含应用代码
FROM ghcr.io/xinnan-tech/xiaozhi-esp32-server:server-base
# server-base 在国内需走镜像;海外构建可覆盖:
# docker build --build-arg SERVER_BASE_IMAGE=ghcr.io/xinnan-tech/xiaozhi-esp32-server:server-base ...
ARG SERVER_BASE_IMAGE=ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:server-base
FROM ${SERVER_BASE_IMAGE}
COPY main/xiaozhi-server .

View file

@ -44,7 +44,7 @@ COPY --from=api-builder /app/target/xiaozhi-esp32-api.jar /app/xiaozhi-esp32-api
# 暴露端口
EXPOSE 8002
# 启动脚本
# 启动脚本(仓库脚本为 CRLF 行尾,转成 LF 避免 exec "no such file or directory")
COPY docs/docker/start.sh /start.sh
RUN chmod +x /start.sh
RUN sed -i 's/\r$//' /start.sh /etc/nginx/nginx.conf && chmod +x /start.sh
CMD ["/start.sh"]

View file

@ -0,0 +1,121 @@
# =============================================================================
# 自构建部署(含自定义改动:aipet 记忆 + qwen/doubao 缓存开关 + doubao_cache)
#
# 与官方 docker-compose_all.yml 的区别:
# - server / web 用 build: 从仓库根 Dockerfile 构建,自定义代码烤进镜像(不依赖主机路径)
# - 不再 volume 挂载源码(aipet / xiaozhi-memory / doubao_cache 等已 COPY 进镜像)
# - mysql / redis 仍用 image: 拉(走 docker.1ms.run 国内镜像)
#
# 使用(在仓库根目录):
# 1. 准备 data/config.yaml(智控台/模型配置)—— 新机首次部署需要
# 2. 准备 models/SenseVoiceSmall/model.pt(ASR 模型,按需)
# 3. docker compose -f docker-compose-selfbuild.yml up -d --build
#
# 海外构建 server 镜像:在 .env 或命令行覆盖
# SERVER_BASE_IMAGE=ghcr.io/xinnan-tech/xiaozhi-esp32-server:server-base
#
# 注:web 的 Dockerfile-web 依赖 node/maven/jre(Docker Hub),国内需配置
# /etc/docker/daemon.json 的 registry-mirrors(如 docker.1ms.run)。
# =============================================================================
version: '3'
services:
# Server模块(自定义 Python 烤进镜像)
xiaozhi-esp32-server:
build:
context: .
dockerfile: Dockerfile-server
args:
SERVER_BASE_IMAGE: ${SERVER_BASE_IMAGE:-ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:server-base}
image: xiaozhi-esp32-server:server_aipet
container_name: xiaozhi-esp32-server
depends_on:
- xiaozhi-esp32-server-db
- xiaozhi-esp32-server-redis
restart: always
networks:
- default
ports:
# ws服务端
- "8000:8000"
# http服务的端口,用于视觉分析接口
- "8003:8003"
security_opt:
- seccomp:unconfined
environment:
- TZ=Asia/Shanghai
volumes:
# 配置文件目录(含 config.yaml)
- ./data:/opt/xiaozhi-esp32-server/data
# 模型文件挂接,很重要(ASR 模型,按需提供)
- ./models/SenseVoiceSmall/model.pt:/opt/xiaozhi-esp32-server/models/SenseVoiceSmall/model.pt
# manager-api和manager-web模块(含 aipet 注册 + 缓存开关 changelog)
xiaozhi-esp32-server-web:
build:
context: .
dockerfile: Dockerfile-web
image: xiaozhi-esp32-server:web_aipet
container_name: xiaozhi-esp32-server-web
restart: always
networks:
- default
depends_on:
xiaozhi-esp32-server-db:
condition: service_healthy
xiaozhi-esp32-server-redis:
condition: service_healthy
ports:
# 智控台
- "8002:8002"
environment:
- TZ=Asia/Shanghai
- SPRING_DATASOURCE_DRUID_URL=jdbc:mysql://xiaozhi-esp32-server-db:3306/xiaozhi_esp32_server?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&connectTimeout=30000&socketTimeout=30000&autoReconnect=true&failOverReadOnly=false&maxReconnects=10
- SPRING_DATASOURCE_DRUID_USERNAME=root
- SPRING_DATASOURCE_DRUID_PASSWORD=123456
- SPRING_DATA_REDIS_HOST=xiaozhi-esp32-server-redis
- SPRING_DATA_REDIS_PASSWORD=
- SPRING_DATA_REDIS_PORT=6379
volumes:
# 上传文件目录
- ./uploadfile:/uploadfile
# 数据库模块
xiaozhi-esp32-server-db:
image: docker.1ms.run/mysql:latest
container_name: xiaozhi-esp32-server-db
healthcheck:
test: [ "CMD", "mysqladmin" ,"ping", "-h", "localhost" ]
timeout: 45s
interval: 10s
retries: 10
restart: always
networks:
- default
expose:
- 3306
volumes:
- ./mysql/data:/var/lib/mysql
environment:
- TZ=Asia/Shanghai
- MYSQL_ROOT_PASSWORD=123456
- MYSQL_DATABASE=xiaozhi_esp32_server
- MYSQL_INITDB_ARGS="--character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci"
# redis模块
xiaozhi-esp32-server-redis:
image: docker.1ms.run/redis:8.0
expose:
- 6379
container_name: xiaozhi-esp32-server-redis
restart: always
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 3
networks:
- default
networks:
default:

View file

@ -1,9 +1,9 @@
-- 1. 给 openai LLM provider 添加 cache 字段(千问显式缓存配置)
-- 在现有 fields 末尾追加 cache 字段,类型为 dict(JSON 文本框)
-- 1. 给 openai LLM provider 添加 cache 字段(千问显式缓存开关)
-- 在现有 fields 末尾追加 cache 字段,类型为 boolean(开关)
UPDATE `ai_model_provider` SET `fields` = JSON_ARRAY_APPEND(
`fields`,
'$',
JSON_OBJECT('key', 'cache', 'label', '缓存配置(JSON)', 'type', 'dict')
JSON_OBJECT('key', 'cache', 'label', '是否开启缓存', 'type', 'boolean')
) WHERE `id` = 'SYSTEM_LLM_openai' AND JSON_CONTAINS(
`fields`,
JSON_OBJECT('key', 'cache'),
@ -11,7 +11,7 @@ UPDATE `ai_model_provider` SET `fields` = JSON_ARRAY_APPEND(
) = 0;
-- 2. 新增 doubao_cache LLM provider(豆包 Session 缓存)
INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `is_custom`, `created_at`, `updated_at`)
INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`)
VALUES (
'SYSTEM_LLM_doubao_cache',
'LLM',
@ -23,10 +23,11 @@ VALUES (
{"key": "api_key", "label": "API密钥", "type": "string"},
{"key": "temperature", "label": "温度", "type": "number"},
{"key": "max_tokens", "label": "最大令牌数", "type": "number"},
{"key": "cache", "label": "缓存配置(JSON)", "type": "dict"}
{"key": "cache", "label": "是否开启缓存", "type": "boolean"}
]',
50,
0,
1,
NOW(),
1,
NOW()
);

View file

@ -0,0 +1,15 @@
-- 注册 aipet 记忆 provider(Python 端自定义模块,运行时由 core/providers/memory/aipet/ 动态发现)
-- fields 对齐 config.yaml 的 memory.aipet 段(db_path + retrieval_mode)
INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`)
VALUES (
'SYSTEM_Memory_aipet',
'Memory',
'aipet',
'AIPet本地记忆(FTS5)',
'[{"key":"db_path","label":"数据库路径","type":"string"},{"key":"retrieval_mode","label":"检索模式","type":"string"}]',
10,
1,
NOW(),
1,
NOW()
);

View file

@ -648,3 +648,10 @@ databaseChangeLog:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202606120930.sql
- changeSet:
id: 202606191200
author: aipet
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202606191200.sql

View file

@ -78,7 +78,9 @@
<div v-for="(row, rowIndex) in chunkedCallInfoFields" :key="rowIndex"
style="display: flex; gap: 20px; margin-bottom: 0;">
<el-form-item v-for="field in row" :key="field.prop" :label="field.label" :prop="field.prop" style="flex: 1;">
<el-input v-model="formData.configJson[field.prop]" :placeholder="field.placeholder"
<el-switch v-if="field.type === 'boolean'" v-model="formData.configJson[field.prop]"
:active-value="true" :inactive-value="false" class="custom-switch"></el-switch>
<el-input v-else v-model="formData.configJson[field.prop]" :placeholder="field.placeholder"
:type="field.type || 'text'" class="custom-input-bg" :show-password="field.type === 'password'">
</el-input>
</el-form-item>
@ -164,7 +166,7 @@ export default {
fields: JSON.parse(item.fields || '[]').map(f => ({
label: f.label,
prop: f.key,
type: f.type === 'password' ? 'password' : 'text',
type: f.type === 'password' ? 'password' : f.type === 'boolean' ? 'boolean' : 'text',
placeholder: `请输入${f.key}`
}))
}))
@ -174,7 +176,7 @@ export default {
initConfigJson() {
const defaultConfig = {};
this.providerFields.forEach(field => {
defaultConfig[field.prop] = '';
defaultConfig[field.prop] = field.type === 'boolean' ? false : '';
});
this.formData.configJson = { ...defaultConfig };
},
@ -193,7 +195,12 @@ export default {
initDynamicConfig() {
const newConfig = {};
this.providerFields.forEach(field => {
newConfig[field.prop] = this.formData.configJson[field.prop] || '';
if (field.type === 'boolean') {
const cur = this.formData.configJson[field.prop];
newConfig[field.prop] = cur === undefined || cur === '' ? false : cur;
} else {
newConfig[field.prop] = this.formData.configJson[field.prop] || '';
}
});
this.formData.configJson = newConfig;
},

View file

@ -963,19 +963,26 @@ class ConnectionHandler:
try:
# 使用带记忆的对话
memory_str = None
# 仅当query非空(代表用户询问)时查询记忆
if self.memory is not None and query:
schedule_str = None
if self.memory is not None:
# 仅当query非空(代表用户询问)时查询记忆(注入实时 user 部分)
if query:
future = asyncio.run_coroutine_threadsafe(
self.memory.query_memory(query), self.loop
)
memory_str = future.result()
# 当天日程每轮注入半稳定系统提示词(当天固定,可缓存)
future = asyncio.run_coroutine_threadsafe(
self.memory.query_memory(query), self.loop
self.memory.get_today_schedule(), self.loop
)
memory_str = future.result()
schedule_str = future.result()
if self.intent_type == "function_call" and functions is not None:
# 使用支持functions的streaming接口
llm_responses = self.llm.response_with_functions(
self.session_id,
self.dialogue.get_llm_dialogue_with_memory(
memory_str, self.config.get("voiceprint", {})
memory_str, self.config.get("voiceprint", {}), schedule_str
),
functions=functions,
)
@ -983,7 +990,7 @@ class ConnectionHandler:
llm_responses = self.llm.response(
self.session_id,
self.dialogue.get_llm_dialogue_with_memory(
memory_str, self.config.get("voiceprint", {})
memory_str, self.config.get("voiceprint", {}), schedule_str
),
)
except Exception as e:

View file

@ -302,7 +302,8 @@ class MemoryProvider(MemoryProviderBase):
messages.append({"role": msg.role, "content": content})
result = await self.manager.add_memory(messages, user_id=self.role_id)
# role_id 作为 device_id,user_id 可选
result = await self.manager.add_memory(messages, device_id=self.role_id, user_id=None)
logger.bind(tag=TAG).debug(f"Save memory result: {result}")
except Exception as e:
logger.bind(tag=TAG).error(f"保存记忆失败: {str(e)}")
@ -326,9 +327,11 @@ class MemoryProvider(MemoryProviderBase):
except (json.JSONDecodeError, KeyError):
pass
# role_id 作为 device_id,user_id 为 None(设备级记忆)
memories = await self.manager.search(
query=search_query,
user_id=self.role_id,
device_id=self.role_id,
user_id=None,
top_k=5
)
@ -342,3 +345,40 @@ class MemoryProvider(MemoryProviderBase):
except Exception as e:
logger.bind(tag=TAG).error(f"查询记忆失败: {str(e)}")
return ""
@staticmethod
def _format_when(planned_time, time_description, today):
"""格式化日程时间锚点。优先用绝对日期+相对描述,降低模型对多条日程的时间混淆"""
if planned_time:
date_str = planned_time.strftime("%m-%d")
time_str = planned_time.strftime("%H:%M")
delta = (planned_time.date() - today).days
rel = {0: "今天", 1: "明天", 2: "后天"}.get(delta, f"{delta}天后")
return f"[{date_str} {rel} {time_str}]"
if time_description:
return f"[{time_description}]"
return "[近期]"
async def get_today_schedule(self) -> str:
"""获取当天及近期日程,注入半稳定系统提示词"""
if not self.manager or not getattr(self, "role_id", None):
return ""
try:
intentions = await self.manager.get_upcoming_intentions(
device_id=self.role_id, user_id=None, days=1
)
if not intentions:
return ""
today = datetime.now().date()
lines = [
f"- {self._format_when(it.planned_time, it.time_description, today)} {it.content}"
for it in intentions
]
schedule_str = "\n".join(lines)
logger.bind(tag=TAG).debug(f"今日日程: {schedule_str}")
return schedule_str
except Exception as e:
logger.bind(tag=TAG).error(f"查询日程失败: {str(e)}")
return ""

View file

@ -26,3 +26,7 @@ class MemoryProviderBase(ABC):
def init_memory(self, role_id, llm, **kwargs):
self.role_id = role_id
self.llm = llm
async def get_today_schedule(self) -> str:
"""获取当天日程,注入半稳定系统提示词(默认空,子类按需实现)"""
return ""

View file

@ -92,7 +92,7 @@ class Dialogue:
return result
def get_llm_dialogue_with_memory(
self, memory_str: str = None, voiceprint_config: dict = None
self, memory_str: str = None, voiceprint_config: dict = None, schedule_str: str = None
) -> List[Dict[str, str]]:
# 构建对话
dialogue = []
@ -173,7 +173,11 @@ class Dialogue:
# 清理多余空行
semi_stable_part = re.sub(r"\n{3,}", "\n\n", semi_stable_part).strip()
# 第三段:半稳定 system prompt(日期、农历、位置、天气等)
# 第三段:半稳定 system prompt(日期、农历、位置、天气、日程等)
# 当天日程当天不变,注入半稳定部分可命中缓存;用独立 <schedule> 标签
# 避免 <memory> 块被上面的正则清理逻辑误删
if schedule_str:
semi_stable_part += f"\n<schedule>\n以下是用户近期的安排:\n{schedule_str}\n</schedule>"
if semi_stable_part:
dialogue.append({"role": "system", "content": semi_stable_part})

View file

@ -70,14 +70,16 @@ class MemoryManager:
async def add_memory(
self,
messages: List[Dict[str, str]],
user_id: str
device_id: str,
user_id: Optional[str] = None
) -> Dict[str, int]:
"""
添加记忆
Args:
messages: 消息列表 [{"role": "user", "content": "..."}]
user_id: 用户ID
device_id: 设备ID
user_id: 用户ID(可选)
Returns:
{"added": 0, "updated": 0, "skipped": 0}
@ -89,9 +91,9 @@ class MemoryManager:
# 判断是否使用 LLM 提取
if self.llm_client and self.extraction_config.get("enabled", False):
return await self._add_memory_with_llm(formatted_messages, user_id)
return await self._add_memory_with_llm(formatted_messages, device_id, user_id)
else:
return await self._add_memory_with_rules(formatted_messages, user_id)
return await self._add_memory_with_rules(formatted_messages, device_id, user_id)
def _format_messages(self, messages: List[Dict[str, str]]) -> List[Dict[str, str]]:
"""格式化消息,过滤系统消息和空内容"""
@ -121,13 +123,14 @@ class MemoryManager:
async def _add_memory_with_llm(
self,
messages: List[Dict[str, str]],
user_id: str
device_id: str,
user_id: Optional[str]
) -> Dict[str, int]:
"""使用 LLM 提取记忆"""
results = {"added": 0, "updated": 0, "skipped": 0}
# 1. 获取上下文
context = await self._build_extraction_context(user_id, messages)
context = await self._build_extraction_context(device_id, user_id, messages)
# 2. 构建对话文本
conversation = self._build_conversation_text(messages)
@ -139,18 +142,18 @@ class MemoryManager:
# LLM 失败时回退到规则提取
import logging
logging.error(f"[xiaozhi-memory] LLM extraction failed, falling back to rule-based: {e}")
return await self._add_memory_with_rules(messages, user_id)
return await self._add_memory_with_rules(messages, device_id, user_id)
# 4. 处理提取的事实
for fact in facts:
# 去重检查
existing = await self._find_duplicate(fact.get("content", ""), user_id)
existing = await self._find_duplicate(fact.get("content", ""), device_id, user_id)
if existing:
results["updated"] += 1
else:
# 创建记忆对象
memory = self._fact_to_memory(fact, user_id)
memory = self._fact_to_memory(fact, device_id, user_id)
self.store.add(memory)
# 记录到会话提取列表
@ -163,7 +166,8 @@ class MemoryManager:
async def _add_memory_with_rules(
self,
messages: List[Dict[str, str]],
user_id: str
device_id: str,
user_id: Optional[str]
) -> Dict[str, int]:
"""使用规则匹配提取记忆(原有逻辑)"""
results = {"added": 0, "updated": 0, "skipped": 0}
@ -183,6 +187,7 @@ class MemoryManager:
if is_intention:
memory = IntentionMemory(
id=str(uuid.uuid4()),
device_id=device_id,
user_id=user_id,
content=content,
time_info=time_info if time_info['absolute'] else None,
@ -192,13 +197,14 @@ class MemoryManager:
else:
memory = FactMemory(
id=str(uuid.uuid4()),
device_id=device_id,
user_id=user_id,
content=content,
time_info=time_info if time_info['absolute'] else None
)
# 检查是否已存在相似记忆
existing = await self._find_similar(memory.content, user_id)
existing = await self._find_similar(memory.content, device_id, user_id)
if existing:
await self._update_memory(existing.id, memory)
@ -211,7 +217,8 @@ class MemoryManager:
async def _build_extraction_context(
self,
user_id: str,
device_id: str,
user_id: Optional[str],
messages: List[Dict]
) -> dict:
"""构建 LLM 提取的上下文"""
@ -224,7 +231,7 @@ class MemoryManager:
# 获取相关现有记忆(用于链接)
query_text = " ".join([m.get("content", "") for m in messages[-3:]])
existing_memories = self.store.search_fts(query_text, user_id, top_k=config.get("max_retrieved_memories", 20))
existing_memories = self.store.search_fts(query_text, device_id, user_id, top_k=config.get("max_retrieved_memories", 20))
existing_formatted = [
{"id": m[0].id, "text": m[0].content}
for m in existing_memories
@ -250,11 +257,12 @@ class MemoryManager:
async def _find_duplicate(
self,
content: str,
user_id: str,
device_id: str,
user_id: Optional[str],
threshold: float = 0.85
) -> Optional[BaseMemory]:
"""查找重复记忆"""
results = self.store.search_fts(content, user_id, top_k=5)
results = self.store.search_fts(content, device_id, user_id, top_k=5)
for memory, score in results:
if self._string_similarity(content, memory.content) > threshold:
@ -262,12 +270,13 @@ class MemoryManager:
return None
def _fact_to_memory(self, fact: dict, user_id: str) -> BaseMemory:
def _fact_to_memory(self, fact: dict, device_id: str, user_id: Optional[str]) -> BaseMemory:
"""将 LLM 提取的事实转换为记忆对象"""
fact_type = fact.get("type", "FACT")
common_data = {
"id": str(uuid.uuid4()),
"device_id": device_id,
"user_id": user_id,
"content": fact["content"],
"time_info": fact.get("time_info"),
@ -301,7 +310,8 @@ class MemoryManager:
async def search(
self,
query: str,
user_id: str,
device_id: str,
user_id: Optional[str] = None,
top_k: int = 10
) -> List[BaseMemory]:
"""
@ -309,24 +319,27 @@ class MemoryManager:
Args:
query: 查询文本
user_id: 用户ID
device_id: 设备ID
user_id: 用户ID(可选)
top_k: 返回结果数量
Returns:
记忆列表
"""
return await self.retriever.retrieve(query, user_id, top_k)
return await self.retriever.retrieve(query, device_id, user_id, top_k)
async def get_upcoming_intentions(
self,
user_id: str,
device_id: str,
user_id: Optional[str] = None,
days: int = 7
) -> List[IntentionMemory]:
"""
获取未来N天的意图/计划
Args:
user_id: 用户ID
device_id: 设备ID
user_id: 用户ID(可选)
days: 天数
Returns:
@ -335,7 +348,7 @@ class MemoryManager:
now = datetime.now()
future = now + timedelta(days=days)
return self.store.get_intentions_in_range(user_id, now, future)
return self.store.get_intentions_in_range(device_id, user_id, now, future)
async def update_intention_status(
self,
@ -361,9 +374,9 @@ class MemoryManager:
return self.store.update(memory_id, update_data)
async def get_all_memories(self, user_id: str) -> List[BaseMemory]:
"""获取用户所有记忆"""
return self.store.get_by_user(user_id)
async def get_all_memories(self, device_id: str, user_id: Optional[str] = None) -> List[BaseMemory]:
"""获取设备/用户所有记忆"""
return self.store.get_by_device(device_id, user_id)
async def delete_memory(self, memory_id: str) -> bool:
"""删除记忆"""
@ -372,7 +385,8 @@ class MemoryManager:
async def _find_similar(
self,
content: str,
user_id: str,
device_id: str,
user_id: Optional[str],
threshold: float = 0.8
) -> Optional[BaseMemory]:
"""
@ -380,14 +394,15 @@ class MemoryManager:
Args:
content: 内容
user_id: 用户ID
device_id: 设备ID
user_id: 用户ID(可选)
threshold: 相似度阈值
Returns:
相似记忆或None
"""
# 使用FTS5搜索
results = self.store.search_fts(content, user_id, top_k=5)
results = self.store.search_fts(content, device_id, user_id, top_k=5)
# 检查是否有完全匹配或高度相似的
for memory, score in results:
@ -398,7 +413,7 @@ class MemoryManager:
return None
def _string_similarity(self, s1: str, s2: str) -> float:
"""计算字符串相似度(简单版)"""
"""计算字符串相似度(基于字符重合度)"""
if s1 == s2:
return 1.0
@ -406,12 +421,16 @@ class MemoryManager:
if s1 in s2 or s2 in s1:
return 0.9
# 编辑距离(简化版)
longer = max(s1, s2, key=len)
shorter = min(s1, s2, key=len)
if len(s1) == 0 or len(s2) == 0:
return 0.0
if len(longer) == 0:
return 1.0
# 注意:等长时 max/min(key=len) 会返回同一个字符串,导致 common 恒等于
# len(longer)、相似度恒为 1.0 的 bug(任意等长字符串被判为完全相同)。
# 这里显式区分 longer/shorter。
if len(s1) >= len(s2):
longer, shorter = s1, s2
else:
longer, shorter = s2, s1
# 计算共同字符数
common = sum(1 for c in shorter if c in longer)
@ -443,8 +462,12 @@ class MemoryManager:
async def _update_memory(self, memory_id: str, new_memory: BaseMemory):
"""更新记忆"""
from utils.tokenizer import tokenize_to_string
update_data = {
"content": new_memory.content,
# 同步更新 tokens,否则 FTS5 触发器会用新 content + 旧 tokens 重建索引,
# 导致 content 与 tokens 错位、检索失效。
"tokens": tokenize_to_string(new_memory.content),
"updated_at": datetime.now()
}
@ -466,6 +489,130 @@ class MemoryManager:
if hasattr(self, 'store'):
self.store.close()
async def get_user_profile(self, device_id: str) -> Optional[BaseMemory]:
"""
获取设备用户画像
Args:
device_id: 设备ID
Returns:
用户画像或None
"""
memories = self.store.get_by_device(device_id, user_id=None)
for m in memories:
if m.type.value == "profile":
return m
return None
async def create_or_update_profile(self, device_id: str, profile_data: dict) -> BaseMemory:
"""
创建或更新用户画像
Args:
device_id: 设备ID
profile_data: 画像数据
Returns:
用户画像
"""
from memories.base import UserProfile
existing = await self.get_user_profile(device_id)
if existing:
# 更新现有画像
update_data = {
**profile_data,
"updated_at": datetime.now()
}
self.store.update(existing.id, update_data)
# 返回更新后的画像
memories = self.store.get_by_device(device_id, user_id=None)
for m in memories:
if m.type.value == "profile":
return m
else:
# 创建新画像
profile = UserProfile(
id=str(uuid.uuid4()),
device_id=device_id,
user_id=None,
**profile_data
)
self.store.add(profile)
return profile
async def record_first_meeting(self, device_id: str):
"""
记录或更新第一次见面时间
Args:
device_id: 设备ID
Returns:
互动天数
"""
from memories.base import UserProfile
now = datetime.now()
existing = await self.get_user_profile(device_id)
if existing is None:
# 首次见面,创建用户画像
profile = {
"first_met": now,
"last_interaction": now,
"total_interaction_days": 1
}
await self.create_or_update_profile(device_id, profile)
return 1
else:
# 更新互动天数
days = 1
if existing.first_met:
# 计算从第一次见面到现在的天数
delta = now - existing.first_met
days = delta.days + 1
# 更新画像
await self.create_or_update_profile(device_id, {
"last_interaction": now,
"total_interaction_days": days
})
return days
async def get_interaction_days(self, device_id: str) -> int:
"""
获取互动天数
Args:
device_id: 设备ID
Returns:
互动天数
"""
profile = await self.get_user_profile(device_id)
if profile:
return profile.total_interaction_days or 1
return 1
async def get_days_since_last_interaction(self, device_id: str) -> Optional[int]:
"""
获取距离上次互动的天数
Args:
device_id: 设备ID
Returns:
距上次互动的天数,如果没有记录返回None
"""
profile = await self.get_user_profile(device_id)
if profile and profile.last_interaction:
delta = datetime.now() - profile.last_interaction
return delta.days
return None
# 便捷函数
_default_manager: Optional[MemoryManager] = None

View file

@ -2,7 +2,7 @@
FTS5检索器实现
"""
from datetime import datetime
from typing import List
from typing import List, Optional
from memories.base import BaseMemory
from stores.sqlite_store import SQLiteStore
from utils.tokenizer import tokenize_to_string
@ -17,7 +17,8 @@ class FTS5Retriever:
async def retrieve(
self,
query: str,
user_id: str,
device_id: str,
user_id: Optional[str] = None,
top_k: int = 10
) -> List[BaseMemory]:
"""
@ -25,7 +26,8 @@ class FTS5Retriever:
Args:
query: 查询文本
user_id: 用户ID
device_id: 设备ID
user_id: 用户ID(可选)
top_k: 返回结果数量
Returns:
@ -35,7 +37,7 @@ class FTS5Retriever:
query_tokens = tokenize_to_string(query)
# 使用FTS5 + BM25检索
results = self.store.search_fts(query_tokens, user_id, top_k * 2)
results = self.store.search_fts(query_tokens, device_id, user_id, top_k * 2)
# 多因素加权排序
scored_results = []

View file

@ -34,7 +34,8 @@ class IntentionStatus(str, Enum):
class BaseMemory(BaseModel):
"""基础记忆类"""
id: str
user_id: str
device_id: str # 设备ID(必填)
user_id: Optional[str] = None # 用户ID(可选,支持设备级共享记忆)
type: MemoryType
content: str
original_language: str = "zh" # 原始语言
@ -90,6 +91,7 @@ class PreferenceMemory(BaseMemory):
class UserProfile(BaseMemory):
"""用户画像"""
type: MemoryType = MemoryType.PROFILE
content: str = Field(default="用户画像") # 默认内容
name: Optional[str] = None
nickname: Optional[str] = None
age: Optional[int] = None
@ -98,3 +100,5 @@ class UserProfile(BaseMemory):
relationships: dict = Field(default_factory=dict)
total_memories: int = 0
last_interaction: Optional[datetime] = None
first_met: Optional[datetime] = None # 第一次见面时间
total_interaction_days: int = 0 # 累计互动天数

View file

@ -65,7 +65,8 @@ class SQLiteStore(BaseStore):
self.conn.execute("""
CREATE TABLE IF NOT EXISTS memories (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
device_id TEXT NOT NULL,
user_id TEXT,
type TEXT NOT NULL,
content TEXT NOT NULL,
original_language TEXT,
@ -98,7 +99,9 @@ class SQLiteStore(BaseStore):
preferences TEXT,
relationships TEXT,
total_memories INTEGER DEFAULT 0,
last_interaction TIMESTAMP
last_interaction TIMESTAMP,
first_met TIMESTAMP,
total_interaction_days INTEGER DEFAULT 0
)
""")
@ -106,6 +109,7 @@ class SQLiteStore(BaseStore):
self.conn.execute("""
CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
id,
device_id,
user_id,
content,
tokens,
@ -116,6 +120,8 @@ class SQLiteStore(BaseStore):
""")
# 创建索引
self.conn.execute("CREATE INDEX IF NOT EXISTS idx_device_id ON memories(device_id)")
self.conn.execute("CREATE INDEX IF NOT EXISTS idx_device_user ON memories(device_id, user_id)")
self.conn.execute("CREATE INDEX IF NOT EXISTS idx_user_id ON memories(user_id)")
self.conn.execute("CREATE INDEX IF NOT EXISTS idx_type ON memories(type)")
self.conn.execute("CREATE INDEX IF NOT EXISTS idx_status ON memories(status)")
@ -124,24 +130,24 @@ class SQLiteStore(BaseStore):
# 创建触发器:自动同步FTS5表
self.conn.execute("""
CREATE TRIGGER IF NOT EXISTS memories_ai AFTER INSERT ON memories BEGIN
INSERT INTO memories_fts(rowid, id, user_id, content, tokens)
VALUES (new.rowid, new.id, new.user_id, new.content, new.tokens);
INSERT INTO memories_fts(rowid, id, device_id, user_id, content, tokens)
VALUES (new.rowid, new.id, new.device_id, new.user_id, new.content, new.tokens);
END
""")
self.conn.execute("""
CREATE TRIGGER IF NOT EXISTS memories_ad AFTER DELETE ON memories BEGIN
INSERT INTO memories_fts(memories_fts, rowid, id, user_id, content, tokens)
VALUES ('delete', old.rowid, old.id, old.user_id, old.content, old.tokens);
INSERT INTO memories_fts(memories_fts, rowid, id, device_id, user_id, content, tokens)
VALUES ('delete', old.rowid, old.id, old.device_id, old.user_id, old.content, old.tokens);
END
""")
self.conn.execute("""
CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE ON memories BEGIN
INSERT INTO memories_fts(memories_fts, rowid, id, user_id, content, tokens)
VALUES ('delete', old.rowid, old.id, old.user_id, old.content, old.tokens);
INSERT INTO memories_fts(rowid, id, user_id, content, tokens)
VALUES (new.rowid, new.id, new.user_id, new.content, new.tokens);
INSERT INTO memories_fts(memories_fts, rowid, id, device_id, user_id, content, tokens)
VALUES ('delete', old.rowid, old.id, old.device_id, old.user_id, old.content, old.tokens);
INSERT INTO memories_fts(rowid, id, device_id, user_id, content, tokens)
VALUES (new.rowid, new.id, new.device_id, new.user_id, new.content, new.tokens);
END
""")
@ -156,39 +162,80 @@ class SQLiteStore(BaseStore):
except ImportError:
tokens = memory.content
self.conn.execute("""
INSERT INTO memories (
id, user_id, type, content, original_language,
created_at, updated_at, status, importance,
tokens, related_ids, metadata, time_info,
fact_type, confidence,
intention_status, planned_time, time_description, intention_type,
reminder_sent, reminder_time, completed_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
memory.id,
memory.user_id,
memory.type.value,
memory.content,
memory.original_language,
memory.created_at,
memory.updated_at,
memory.status.value,
memory.importance,
tokens,
json.dumps(memory.related_ids),
json.dumps(memory.metadata),
json.dumps(memory.time_info) if memory.time_info else None,
getattr(memory, 'fact_type', None),
getattr(memory, 'confidence', 1.0),
getattr(memory, 'intention_status', None) if hasattr(memory, 'intention_status') else None,
getattr(memory, 'planned_time', None) if hasattr(memory, 'planned_time') else None,
getattr(memory, 'time_description', None) if hasattr(memory, 'time_description') else None,
getattr(memory, 'intention_type', None) if hasattr(memory, 'intention_type') else None,
getattr(memory, 'reminder_sent', False) if hasattr(memory, 'reminder_sent') else False,
getattr(memory, 'reminder_time', None) if hasattr(memory, 'reminder_time') else None,
getattr(memory, 'completed_at', None) if hasattr(memory, 'completed_at') else None
))
# 根据记忆类型构建不同的 INSERT 语句
if memory.type.value == "profile":
# UserProfile 类型,包含所有 profile 字段
self.conn.execute("""
INSERT INTO memories (
id, device_id, user_id, type, content, original_language,
created_at, updated_at, status, importance,
tokens, related_ids, metadata, time_info,
name, nickname, age, location, preferences, relationships,
total_memories, last_interaction, first_met, total_interaction_days
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
memory.id,
memory.device_id,
memory.user_id,
memory.type.value,
memory.content,
memory.original_language,
memory.created_at,
memory.updated_at,
memory.status.value,
memory.importance,
tokens,
json.dumps(memory.related_ids),
json.dumps(memory.metadata),
json.dumps(memory.time_info) if memory.time_info else None,
getattr(memory, 'name', None),
getattr(memory, 'nickname', None),
getattr(memory, 'age', None),
getattr(memory, 'location', None),
json.dumps(getattr(memory, 'preferences', {})),
json.dumps(getattr(memory, 'relationships', {})),
getattr(memory, 'total_memories', 0),
getattr(memory, 'last_interaction', None),
getattr(memory, 'first_met', None),
getattr(memory, 'total_interaction_days', 0)
))
else:
# 其他记忆类型
self.conn.execute("""
INSERT INTO memories (
id, device_id, user_id, type, content, original_language,
created_at, updated_at, status, importance,
tokens, related_ids, metadata, time_info,
fact_type, confidence,
intention_status, planned_time, time_description, intention_type,
reminder_sent, reminder_time, completed_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
memory.id,
memory.device_id,
memory.user_id,
memory.type.value,
memory.content,
memory.original_language,
memory.created_at,
memory.updated_at,
memory.status.value,
memory.importance,
tokens,
json.dumps(memory.related_ids),
json.dumps(memory.metadata),
json.dumps(memory.time_info) if memory.time_info else None,
getattr(memory, 'fact_type', None),
getattr(memory, 'confidence', 1.0),
getattr(memory, 'intention_status', None) if hasattr(memory, 'intention_status') else None,
getattr(memory, 'planned_time', None) if hasattr(memory, 'planned_time') else None,
getattr(memory, 'time_description', None) if hasattr(memory, 'time_description') else None,
getattr(memory, 'intention_type', None) if hasattr(memory, 'intention_type') else None,
getattr(memory, 'reminder_sent', False) if hasattr(memory, 'reminder_sent') else False,
getattr(memory, 'reminder_time', None) if hasattr(memory, 'reminder_time') else None,
getattr(memory, 'completed_at', None) if hasattr(memory, 'completed_at') else None
))
self.conn.commit()
return memory.id
@ -237,14 +284,25 @@ class SQLiteStore(BaseStore):
return self.conn.total_changes > 0
def get_by_user(self, user_id: str) -> List[BaseMemory]:
"""获取用户所有活跃记忆"""
cursor = self.conn.execute(
"SELECT * FROM memories WHERE user_id = ? AND status = ? ORDER BY created_at DESC",
(user_id, MemoryStatus.ACTIVE.value)
)
"""获取用户所有活跃记忆(兼容旧接口)"""
return self.get_by_device(None, user_id)
def get_by_device(self, device_id: str, user_id: Optional[str] = None) -> List[BaseMemory]:
"""获取设备/用户所有活跃记忆"""
if user_id:
cursor = self.conn.execute(
"SELECT * FROM memories WHERE device_id = ? AND user_id = ? AND status = ? ORDER BY created_at DESC",
(device_id, user_id, MemoryStatus.ACTIVE.value)
)
else:
# 查询设备级记忆(user_id IS NULL)
cursor = self.conn.execute(
"SELECT * FROM memories WHERE device_id = ? AND user_id IS NULL AND status = ? ORDER BY created_at DESC",
(device_id, MemoryStatus.ACTIVE.value)
)
return [self._row_to_memory(row) for row in cursor.fetchall()]
def search_fts(self, query: str, user_id: str, top_k: int = 10) -> List[tuple]:
def search_fts(self, query: str, device_id: str, user_id: Optional[str] = None, top_k: int = 10) -> List[tuple]:
"""
使用FTS5 + BM25全文检索
@ -255,19 +313,38 @@ class SQLiteStore(BaseStore):
safe_query = tokenize_to_string(query)
if not safe_query:
return []
# 用 OR 连接查询词:FTS5 默认空格=AND,含疑问词/虚词的自然语言整句查询
# (如"我叫什么名字")会因词不全而全部落空。改 OR 后任一词命中即返回,
# 由 BM25 排序保证相关性(召回优先于精度,宁多返回交 LLM 判断)。
or_query = " OR ".join(safe_query.split())
cursor = self.conn.execute(f"""
SELECT
m.*,
bm25(memories_fts) as score
FROM memories_fts fts
JOIN memories m ON m.id = fts.id
WHERE m.user_id = ?
AND m.status = 'active'
AND memories_fts MATCH ?
ORDER BY score
LIMIT ?
""", (user_id, safe_query, top_k))
if user_id:
cursor = self.conn.execute(f"""
SELECT
m.*,
bm25(memories_fts) as score
FROM memories_fts fts
JOIN memories m ON m.id = fts.id
WHERE m.device_id = ? AND m.user_id = ?
AND m.status = 'active'
AND memories_fts MATCH ?
ORDER BY score
LIMIT ?
""", (device_id, user_id, or_query, top_k))
else:
# 搜索设备级记忆(user_id IS NULL)
cursor = self.conn.execute(f"""
SELECT
m.*,
bm25(memories_fts) as score
FROM memories_fts fts
JOIN memories m ON m.id = fts.id
WHERE m.device_id = ? AND m.user_id IS NULL
AND m.status = 'active'
AND memories_fts MATCH ?
ORDER BY score
LIMIT ?
""", (device_id, or_query, top_k))
results = []
for row in cursor.fetchall():
@ -278,18 +355,26 @@ class SQLiteStore(BaseStore):
return results
def get_intentions_in_range(
self, user_id: str, start: datetime, end: datetime
self, device_id: str, user_id: Optional[str], start: datetime, end: datetime
) -> List[IntentionMemory]:
"""获取时间范围内的意图"""
cursor = self.conn.execute("""
SELECT * FROM memories
WHERE user_id = ?
AND type = ?
AND status = ?
AND planned_time >= ?
AND planned_time <= ?
ORDER BY planned_time ASC
""", (user_id, MemoryType.INTENTION.value, MemoryStatus.ACTIVE.value, start, end))
if user_id:
cursor = self.conn.execute("""
SELECT * FROM memories
WHERE device_id = ? AND user_id = ?
AND type = ? AND status = ?
AND planned_time >= ? AND planned_time <= ?
ORDER BY planned_time ASC
""", (device_id, user_id, MemoryType.INTENTION.value, MemoryStatus.ACTIVE.value, start, end))
else:
# 查询设备级意图(user_id IS NULL)
cursor = self.conn.execute("""
SELECT * FROM memories
WHERE device_id = ? AND user_id IS NULL
AND type = ? AND status = ?
AND planned_time >= ? AND planned_time <= ?
ORDER BY planned_time ASC
""", (device_id, MemoryType.INTENTION.value, MemoryStatus.ACTIVE.value, start, end))
return [self._row_to_memory(row) for row in cursor.fetchall()]
@ -299,6 +384,7 @@ class SQLiteStore(BaseStore):
common_data = {
'id': row['id'],
'device_id': row['device_id'],
'user_id': row['user_id'],
'type': memory_type,
'content': row['content'],
@ -346,6 +432,8 @@ class SQLiteStore(BaseStore):
common_data['relationships'] = json.loads(row['relationships']) if row['relationships'] else {}
common_data['total_memories'] = row['total_memories'] or 0
common_data['last_interaction'] = datetime.fromisoformat(row['last_interaction']) if row['last_interaction'] else None
common_data['first_met'] = datetime.fromisoformat(row['first_met']) if row['first_met'] else None
common_data['total_interaction_days'] = row['total_interaction_days'] or 0
return UserProfile(**common_data)
return BaseMemory(**common_data)

View file

@ -5,6 +5,12 @@ from datetime import datetime, timedelta
from typing import Optional, Dict, Any
import re
try:
from dateutil.relativedelta import relativedelta
HAS_DATEUTIL = True
except ImportError:
HAS_DATEUTIL = False
class TimeParser:
"""时间解析器"""
@ -127,8 +133,38 @@ class TimeParser:
# N个月后
elif m := re.search(cls.PATTERNS['个月'], text):
months = int(m.group(1))
# 简单处理:假设每月30天
absolute_time = reference_date + timedelta(days=months * 30)
# 使用 relativedelta 进行精确的月份计算
if HAS_DATEUTIL:
absolute_time = reference_date + relativedelta(months=months)
else:
# 回退方案:手动计算月份(考虑不同月份的天数差异)
year = reference_date.year
month = reference_date.month + months
while month > 12:
month -= 12
year += 1
# 保持日期不变,如果目标月份没有该日期,则使用该月最后一天
day = min(reference_date.day, [31, 29 if (year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1])
absolute_time = reference_date.replace(year=year, month=month, day=day)
absolute_time = absolute_time.replace(hour=0, minute=0, second=0, microsecond=0)
result['confidence'] = 0.7
# N个月前
elif m := re.search(cls.PATTERNS['个月前'], text):
months = int(m.group(1))
# 使用 relativedelta 进行精确的月份计算
if HAS_DATEUTIL:
absolute_time = reference_date - relativedelta(months=months)
else:
# 回退方案:手动计算月份
year = reference_date.year
month = reference_date.month - months
while month <= 0:
month += 12
year -= 1
# 保持日期不变,如果目标月份没有该日期,则使用该月最后一天
day = min(reference_date.day, [31, 29 if (year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1])
absolute_time = reference_date.replace(year=year, month=month, day=day)
absolute_time = absolute_time.replace(hour=0, minute=0, second=0, microsecond=0)
result['confidence'] = 0.7

View file

@ -25,11 +25,11 @@ class JiebaTokenizer(Tokenizer):
self.available = False
def tokenize(self, text: str) -> List[str]:
"""使用jieba分词"""
"""使用jieba分词(搜索引擎模式,切出更多子词,提升检索召回)"""
if not self.available:
# 降级到简单分词
return SimpleTokenizer().tokenize(text)
return list(self.jieba.lcut(text))
return list(self.jieba.cut_for_search(text))
class SimpleTokenizer(Tokenizer):