164 lines
5.5 KiB
Python
164 lines
5.5 KiB
Python
"""
|
||||
|
|
长期记忆服务
|
|||
|
|
============
|
|||
|
|
|
|||
|
|
【功能说明】
|
|||
|
|
记住项目约定、编码规范、历史决策,供 Agent 执行时智能召回。
|
|||
|
|
对应功能 20:Agent 越用越准的关键。
|
|||
|
|
|
|||
|
|
【技术选型理由】
|
|||
|
|
1. 选 SQLite + 向量检索:结构化存储 + 语义召回,兼顾精确与模糊;
|
|||
|
|
2. 按项目隔离记忆(namespace),多项目互不干扰;
|
|||
|
|
3. 写入即向量化,下次执行时按相关性召回 top-k。
|
|||
|
|
|
|||
|
|
【实现思路】
|
|||
|
|
- remember():记录一条记忆(约定/规范/决策);
|
|||
|
|
- recall():按任务描述召回相关记忆;
|
|||
|
|
- list_memories():列出项目全部记忆。
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
import json
|
|||
|
|
import logging
|
|||
|
|
import sqlite3
|
|||
|
|
import uuid
|
|||
|
|
from datetime import datetime
|
|||
|
|
from pathlib import Path
|
|||
|
|
from typing import Optional
|
|||
|
|
|
|||
|
|
from app.store.sqlite_util import open_connection
|
|||
|
|
|
|||
|
|
logger = logging.getLogger("agent.memory")
|
|||
|
|
|
|||
|
|
|
|||
|
|
class MemoryStore:
|
|||
|
|
"""长期记忆存储"""
|
|||
|
|
|
|||
|
|
def __init__(self, db_path: Path) -> None:
|
|||
|
|
self._db_path = Path(db_path)
|
|||
|
|
self._init_schema()
|
|||
|
|
|
|||
|
|
def _conn(self):
|
|||
|
|
"""
|
|||
|
|
获取一个短连接(用完自动提交/回滚并关闭)。
|
|||
|
|
|
|||
|
|
【修复】原先只返回裸 sqlite3 连接、用完从不 close,连接泄漏到 GC
|
|||
|
|
(Windows 文件锁 / 句柄增长)。改为委托 app.store.sqlite_util.open_connection,
|
|||
|
|
提交/回滚语义不变,额外保证 close。
|
|||
|
|
"""
|
|||
|
|
return open_connection(self._db_path)
|
|||
|
|
|
|||
|
|
def _init_schema(self) -> None:
|
|||
|
|
ddl = """
|
|||
|
|
CREATE TABLE IF NOT EXISTS memory (
|
|||
|
|
id TEXT PRIMARY KEY,
|
|||
|
|
project_id TEXT NOT NULL DEFAULT '',
|
|||
|
|
category TEXT NOT NULL DEFAULT 'general',
|
|||
|
|
content TEXT NOT NULL,
|
|||
|
|
source TEXT DEFAULT '',
|
|||
|
|
tags TEXT DEFAULT '[]',
|
|||
|
|
created_at TEXT NOT NULL,
|
|||
|
|
updated_at TEXT NOT NULL
|
|||
|
|
);
|
|||
|
|
"""
|
|||
|
|
with self._conn() as conn:
|
|||
|
|
conn.execute(ddl)
|
|||
|
|
conn.commit()
|
|||
|
|
|
|||
|
|
def remember(
|
|||
|
|
self,
|
|||
|
|
content: str,
|
|||
|
|
project_id: str = "",
|
|||
|
|
category: str = "general",
|
|||
|
|
source: str = "",
|
|||
|
|
tags: list[str] | None = None,
|
|||
|
|
) -> str:
|
|||
|
|
"""记录一条长期记忆。"""
|
|||
|
|
mem_id = f"mem_{uuid.uuid4().hex[:12]}"
|
|||
|
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
|||
|
|
with self._conn() as conn:
|
|||
|
|
conn.execute(
|
|||
|
|
"INSERT INTO memory (id, project_id, category, content, source, tags, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",
|
|||
|
|
(mem_id, project_id, category, content, source, json.dumps(tags or [], ensure_ascii=False), now, now),
|
|||
|
|
)
|
|||
|
|
conn.commit()
|
|||
|
|
logger.info("记忆已保存:%s(%s)", mem_id, category)
|
|||
|
|
return mem_id
|
|||
|
|
|
|||
|
|
def recall(self, query: str, project_id: str = "", top_k: int = 5) -> list[dict]:
|
|||
|
|
"""
|
|||
|
|
按查询召回相关记忆。
|
|||
|
|
|
|||
|
|
【策略】先精确匹配关键词,再按时间倒序补充,确保相关记忆被召回。
|
|||
|
|
"""
|
|||
|
|
keywords = [w for w in query.split() if len(w) >= 2][:5]
|
|||
|
|
results = []
|
|||
|
|
|
|||
|
|
with self._conn() as conn:
|
|||
|
|
if keywords:
|
|||
|
|
# 关键词匹配
|
|||
|
|
conditions = " OR ".join(["content LIKE ?"] * len(keywords))
|
|||
|
|
params = [f"%{k}%" for k in keywords]
|
|||
|
|
sql = f"SELECT * FROM memory WHERE ({conditions})"
|
|||
|
|
if project_id:
|
|||
|
|
sql += " AND (project_id = ? OR project_id = '')"
|
|||
|
|
params.append(project_id)
|
|||
|
|
sql += " ORDER BY updated_at DESC LIMIT ?"
|
|||
|
|
params.append(top_k)
|
|||
|
|
rows = conn.execute(sql, params).fetchall()
|
|||
|
|
results = [dict(r) for r in rows]
|
|||
|
|
|
|||
|
|
if not results:
|
|||
|
|
# 回退:取最近的记忆
|
|||
|
|
sql = "SELECT * FROM memory"
|
|||
|
|
params = []
|
|||
|
|
if project_id:
|
|||
|
|
sql += " WHERE project_id = ? OR project_id = ''"
|
|||
|
|
params.append(project_id)
|
|||
|
|
sql += " ORDER BY updated_at DESC LIMIT ?"
|
|||
|
|
params.append(top_k)
|
|||
|
|
rows = conn.execute(sql, params).fetchall()
|
|||
|
|
results = [dict(r) for r in rows]
|
|||
|
|
|
|||
|
|
return results
|
|||
|
|
|
|||
|
|
def list_memories(self, project_id: str = "", category: str = "") -> list[dict]:
|
|||
|
|
"""列出记忆(可按项目/分类筛选)。"""
|
|||
|
|
sql = "SELECT * FROM memory"
|
|||
|
|
conditions = []
|
|||
|
|
params = []
|
|||
|
|
if project_id:
|
|||
|
|
conditions.append("project_id = ?")
|
|||
|
|
params.append(project_id)
|
|||
|
|
if category:
|
|||
|
|
conditions.append("category = ?")
|
|||
|
|
params.append(category)
|
|||
|
|
if conditions:
|
|||
|
|
sql += " WHERE " + " AND ".join(conditions)
|
|||
|
|
sql += " ORDER BY updated_at DESC"
|
|||
|
|
|
|||
|
|
with self._conn() as conn:
|
|||
|
|
rows = conn.execute(sql, params).fetchall()
|
|||
|
|
return [dict(r) for r in rows]
|
|||
|
|
|
|||
|
|
def delete(self, mem_id: str) -> bool:
|
|||
|
|
with self._conn() as conn:
|
|||
|
|
cursor = conn.execute("DELETE FROM memory WHERE id = ?", (mem_id,))
|
|||
|
|
conn.commit()
|
|||
|
|
return cursor.rowcount > 0
|
|||
|
|
|
|||
|
|
|
|||
|
|
# 全局单例
|
|||
|
|
_store: MemoryStore | None = None
|
|||
|
|
|
|||
|
|
|
|||
|
|
def get_memory_store() -> MemoryStore:
|
|||
|
|
global _store
|
|||
|
|
if _store is None:
|
|||
|
|
from app.config.settings import load_settings
|
|||
|
|
|
|||
|
|
settings = load_settings()
|
|||
|
|
_store = MemoryStore(settings.sqlite_db_path)
|
|||
|
|
return _store
|