mainspring-memory 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mainspring_memory/__init__.py +40 -0
- mainspring_memory/backend.py +357 -0
- mainspring_memory/pg_backend.py +167 -0
- mainspring_memory/py.typed +0 -0
- mainspring_memory/recall.py +102 -0
- mainspring_memory/semantic.py +120 -0
- mainspring_memory/tools.py +46 -0
- mainspring_memory-0.1.0.dist-info/METADATA +53 -0
- mainspring_memory-0.1.0.dist-info/RECORD +11 -0
- mainspring_memory-0.1.0.dist-info/WHEEL +4 -0
- mainspring_memory-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""mainspring-memory:长期记忆外挂(M5,ADR-002:记忆不进 core,以外挂交付)。
|
|
2
|
+
|
|
3
|
+
实现形态「core 零改动」,全部复用 core 现成装配点:
|
|
4
|
+
|
|
5
|
+
存储层(backend.py) MemoryScope / MemoryRecord / MemoryBackend Protocol /
|
|
6
|
+
InMemoryBackend / SqliteBackend
|
|
7
|
+
语义检索(semantic.py) SemanticBackend:任意 MemoryBackend 的向量召回装饰器
|
|
8
|
+
(⑫,Embedder 由宿主注入,零依赖默认不绑架)
|
|
9
|
+
pg 存储档(pg_backend.py) PostgresBackend:MemoryBackend 的 asyncpg 实现
|
|
10
|
+
(T15-⑭,可选依赖;刻意不进本包 __init__ 的急切导出,
|
|
11
|
+
保持 `import mainspring_memory` 零 asyncpg 依赖)
|
|
12
|
+
召回装配(recall.py) MemoryRecall:core SystemFragmentSource 的记忆领域包装
|
|
13
|
+
(T7-2 正名,原 MemorySkill),resolve 时检索注入 system
|
|
14
|
+
常量区(享受 keep_system 永不压缩)
|
|
15
|
+
写入路径(tools.py) build_memory_tools:remember 工具工厂(模型自主写入)+
|
|
16
|
+
调用方直写 API(backend.add)
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from .backend import (
|
|
20
|
+
InMemoryBackend,
|
|
21
|
+
MemoryBackend,
|
|
22
|
+
MemoryRecord,
|
|
23
|
+
MemoryScope,
|
|
24
|
+
SqliteBackend,
|
|
25
|
+
)
|
|
26
|
+
from .recall import MemoryRecall
|
|
27
|
+
from .semantic import Embedder, SemanticBackend
|
|
28
|
+
from .tools import build_memory_tools
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"Embedder",
|
|
32
|
+
"InMemoryBackend",
|
|
33
|
+
"MemoryBackend",
|
|
34
|
+
"MemoryRecall",
|
|
35
|
+
"MemoryRecord",
|
|
36
|
+
"MemoryScope",
|
|
37
|
+
"SemanticBackend",
|
|
38
|
+
"SqliteBackend",
|
|
39
|
+
"build_memory_tools",
|
|
40
|
+
]
|
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
"""mainspring-memory 存储层(T6-1):数据模型 + MemoryBackend 抽象 + 两个后端。
|
|
2
|
+
|
|
3
|
+
ADR-002:记忆不进 core,以外挂交付;召回装配(MemoryRecall)见 recall.py。
|
|
4
|
+
|
|
5
|
+
MemoryScope 记忆命名空间:agent_id + user_id 二元组
|
|
6
|
+
MemoryRecord 一条长期记忆:id / scope / content / metadata / created_at / updated_at
|
|
7
|
+
MemoryBackend 存储抽象 Protocol:add / search / list / delete
|
|
8
|
+
InMemoryBackend 进程内实现(测试与参照实现,同 core MemoryStore / ConsoleSink 定位)
|
|
9
|
+
SqliteBackend SQLite 实现:FTS5 全文检索,无 FTS5 自动回退 LIKE
|
|
10
|
+
|
|
11
|
+
设计要点:
|
|
12
|
+
|
|
13
|
+
- 幂等语义与 core SessionStore 完全一致:同 id 跳过(first write wins),id=None 照写;
|
|
14
|
+
- 检索语义两后端一致:查询切词后「所有词元都命中」才算命中(FTS 隐式 AND / LIKE 逐词),
|
|
15
|
+
按 updated_at 倒序取前 k 条;空查询退化为「该 scope 最近 k 条」;
|
|
16
|
+
- 中文逐字切词(unicode61 对连续汉字只出一个词元,必须自己拆),不引 jieba;
|
|
17
|
+
- 读返回深拷贝:调用方改记录不污染库存(同 core MemoryStore 纪律);
|
|
18
|
+
- 无锁:InMemoryBackend 方法体内没有 await,单事件循环下天然原子;SqliteBackend 所有
|
|
19
|
+
sqlite3 调用走 `asyncio.to_thread` 串行执行,取消路径 `asyncio.shield` 等在途写收尾
|
|
20
|
+
(T2-6 / F9 竞态结论,不在这里重蹈);
|
|
21
|
+
- MemoryBackend 命名刻意避开 core 已占用的 MemoryStore(session.py,ADR-002 漂移的根源)。
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import asyncio
|
|
27
|
+
import contextlib
|
|
28
|
+
import json
|
|
29
|
+
import re
|
|
30
|
+
import sqlite3
|
|
31
|
+
import time
|
|
32
|
+
import uuid
|
|
33
|
+
from collections.abc import Callable
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
from typing import Any, Protocol, TypeVar, runtime_checkable
|
|
36
|
+
|
|
37
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
"InMemoryBackend",
|
|
41
|
+
"MemoryBackend",
|
|
42
|
+
"MemoryRecord",
|
|
43
|
+
"MemoryScope",
|
|
44
|
+
"SqliteBackend",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
DEFAULT_PATH = "mainspring-memory.db"
|
|
48
|
+
|
|
49
|
+
T = TypeVar("T")
|
|
50
|
+
|
|
51
|
+
# FTS5 的 unicode61 把连续汉字当单个词元,检索等于匹配整串——必须入库前逐字拆开。
|
|
52
|
+
# 范围:平假名 / 片假名 + CJK 统一表意 + 扩展 A + 兼容表意,全部逐字。
|
|
53
|
+
_CJK = re.compile(r"([\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _tokenize(text: str) -> str:
|
|
57
|
+
"""检索文本统一变换:全小写 + 汉字逐字拆开,FTS 索引与查询共用,保证词元对齐。"""
|
|
58
|
+
spaced = _CJK.sub(r" \1 ", text.casefold())
|
|
59
|
+
return " ".join(spaced.split())
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class MemoryScope(BaseModel):
|
|
63
|
+
"""记忆命名空间:agent_id + user_id 二元组,两个维度都参与隔离。
|
|
64
|
+
|
|
65
|
+
默认全空 = 单 agent 单租户的最简用法;多 agent / 多用户时各自独立,互不可见。
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
model_config = ConfigDict(frozen=True)
|
|
69
|
+
|
|
70
|
+
agent_id: str = ""
|
|
71
|
+
user_id: str = ""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class MemoryRecord(BaseModel):
|
|
75
|
+
"""一条长期记忆。id=None 交由后端分配;有 id 时按 id 幂等(同 id 跳过)。"""
|
|
76
|
+
|
|
77
|
+
id: str | None = None
|
|
78
|
+
scope: MemoryScope = Field(default_factory=MemoryScope)
|
|
79
|
+
content: str
|
|
80
|
+
metadata: dict[str, Any] = Field(default_factory=dict)
|
|
81
|
+
created_at: float = Field(default_factory=time.time)
|
|
82
|
+
updated_at: float = Field(default_factory=time.time)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@runtime_checkable
|
|
86
|
+
class MemoryBackend(Protocol):
|
|
87
|
+
"""记忆存储抽象(T6-1);InMemory / SQLite 实现在本外挂,向量后端留 v2 接口位。
|
|
88
|
+
|
|
89
|
+
契约:add 按 id 幂等,同 id 跳过并返回库存里的既有记录(先写者胜),id=None 分配
|
|
90
|
+
新 id;search 只返回「查询全部词元都命中」的记录,按 updated_at 倒序取前 k 条,
|
|
91
|
+
空 / 空白查询退化为最近 k 条;k<=0 返回空列表;delete 按 id 删除,不存在时静默;
|
|
92
|
+
list 返回 scope 内全部记录(按写入序)。返回值一律深拷贝,改动不污染库存。
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
async def add(self, record: MemoryRecord) -> MemoryRecord: ...
|
|
96
|
+
|
|
97
|
+
async def search(self, scope: MemoryScope, query: str, *, k: int = 5) -> list[MemoryRecord]: ...
|
|
98
|
+
|
|
99
|
+
async def list(self, scope: MemoryScope) -> list[MemoryRecord]: ...
|
|
100
|
+
|
|
101
|
+
async def delete(self, record_id: str) -> None: ...
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _matched(records: list[MemoryRecord], query: str, k: int) -> list[MemoryRecord]:
|
|
105
|
+
"""InMemory 与 LIKE 回退共用的匹配核:全词元命中 + updated_at 倒序 + k 截断。"""
|
|
106
|
+
if k <= 0:
|
|
107
|
+
return []
|
|
108
|
+
tokens = _tokenize(query).split()
|
|
109
|
+
hits = [
|
|
110
|
+
record for record in records if all(token in _tokenize(record.content) for token in tokens)
|
|
111
|
+
]
|
|
112
|
+
hits.sort(key=lambda record: -record.updated_at) # 稳定排序:同刻保持写入序
|
|
113
|
+
return hits[:k]
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class InMemoryBackend:
|
|
117
|
+
"""进程内 MemoryBackend(零依赖,同 core MemoryStore 定位)。
|
|
118
|
+
|
|
119
|
+
无锁:方法体内没有 await,单事件循环下天然原子;跨进程 / 多事件循环不保证
|
|
120
|
+
(与 core MemoryStore 同一单进程边界)。
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
def __init__(self) -> None:
|
|
124
|
+
self._records: dict[str, MemoryRecord] = {}
|
|
125
|
+
|
|
126
|
+
async def add(self, record: MemoryRecord) -> MemoryRecord:
|
|
127
|
+
if record.id is not None and record.id in self._records:
|
|
128
|
+
return self._records[record.id].model_copy(deep=True) # 幂等:先写者胜
|
|
129
|
+
stored = record.model_copy(deep=True)
|
|
130
|
+
if stored.id is None:
|
|
131
|
+
stored.id = uuid.uuid4().hex
|
|
132
|
+
self._records[stored.id] = stored
|
|
133
|
+
return stored.model_copy(deep=True)
|
|
134
|
+
|
|
135
|
+
async def search(self, scope: MemoryScope, query: str, *, k: int = 5) -> list[MemoryRecord]:
|
|
136
|
+
in_scope = [record for record in self._records.values() if record.scope == scope]
|
|
137
|
+
return [record.model_copy(deep=True) for record in _matched(in_scope, query, k)]
|
|
138
|
+
|
|
139
|
+
async def list(self, scope: MemoryScope) -> list[MemoryRecord]:
|
|
140
|
+
return [
|
|
141
|
+
record.model_copy(deep=True)
|
|
142
|
+
for record in self._records.values()
|
|
143
|
+
if record.scope == scope
|
|
144
|
+
]
|
|
145
|
+
|
|
146
|
+
async def delete(self, record_id: str) -> None:
|
|
147
|
+
self._records.pop(record_id, None)
|
|
148
|
+
|
|
149
|
+
def __len__(self) -> int:
|
|
150
|
+
"""当前持有的记忆条数(跨 scope 求和);测试与观测用。"""
|
|
151
|
+
return len(self._records)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class SqliteBackend:
|
|
155
|
+
"""MemoryBackend 的 SQLite 实现:FTS5 全文检索,无 FTS5 环境自动回退 LIKE。
|
|
156
|
+
|
|
157
|
+
并发不变量沿用 T2-6 / F9 的结论:单连接 + 串行执行;取消打在落库途中时等在途
|
|
158
|
+
操作收尾再放锁,杜绝「后到的写覆盖先前的写」。use_fts=False 可强制走 LIKE
|
|
159
|
+
(FTS 与 LIKE 契约用例双跑即一致性证明)。
|
|
160
|
+
"""
|
|
161
|
+
|
|
162
|
+
def __init__(self, path: str | Path, *, use_fts: bool = True) -> None:
|
|
163
|
+
self._db = _Database(path, use_fts=use_fts)
|
|
164
|
+
|
|
165
|
+
async def add(self, record: MemoryRecord) -> MemoryRecord:
|
|
166
|
+
assigned = record.id if record.id is not None else uuid.uuid4().hex
|
|
167
|
+
await self._db.add_row(record, assigned)
|
|
168
|
+
stored = await self._db.get(assigned)
|
|
169
|
+
assert stored is not None # 刚写入必在;断言收窄 Optional
|
|
170
|
+
return stored
|
|
171
|
+
|
|
172
|
+
async def search(self, scope: MemoryScope, query: str, *, k: int = 5) -> list[MemoryRecord]:
|
|
173
|
+
if k <= 0:
|
|
174
|
+
return []
|
|
175
|
+
return await self._db.search(scope, query, k)
|
|
176
|
+
|
|
177
|
+
async def list(self, scope: MemoryScope) -> list[MemoryRecord]:
|
|
178
|
+
return await self._db.list(scope)
|
|
179
|
+
|
|
180
|
+
async def delete(self, record_id: str) -> None:
|
|
181
|
+
await self._db.delete(record_id)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
_COLUMNS = "id, agent_id, user_id, content, metadata, created_at, updated_at"
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class _Database:
|
|
188
|
+
"""单连接 SQLite 封装(与 session-sqlite 的 _Database 同款;外挂独立不可互 import)。
|
|
189
|
+
|
|
190
|
+
`check_same_thread=False`:连接在事件循环线程创建,操作经 to_thread 落到任意工作
|
|
191
|
+
线程,线程归属检查必须关掉;安全完全靠 `_lock` 串行化——同一时刻至多一个线程持有
|
|
192
|
+
连接,这是取消不变量的前提。
|
|
193
|
+
"""
|
|
194
|
+
|
|
195
|
+
def __init__(self, path: str | Path, *, use_fts: bool) -> None:
|
|
196
|
+
self.path = Path(path)
|
|
197
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
198
|
+
self._use_fts = use_fts
|
|
199
|
+
self._fts_ready = False # 首次连接时尝试建虚拟表,失败即永久降级 LIKE
|
|
200
|
+
self._connection: sqlite3.Connection | None = None
|
|
201
|
+
self._lock = asyncio.Lock()
|
|
202
|
+
|
|
203
|
+
_SCHEMA = """
|
|
204
|
+
CREATE TABLE IF NOT EXISTS memories (
|
|
205
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
206
|
+
id TEXT NOT NULL UNIQUE,
|
|
207
|
+
agent_id TEXT NOT NULL,
|
|
208
|
+
user_id TEXT NOT NULL,
|
|
209
|
+
content TEXT NOT NULL,
|
|
210
|
+
metadata TEXT NOT NULL,
|
|
211
|
+
created_at REAL NOT NULL,
|
|
212
|
+
updated_at REAL NOT NULL,
|
|
213
|
+
content_tsv TEXT NOT NULL
|
|
214
|
+
);
|
|
215
|
+
CREATE INDEX IF NOT EXISTS idx_memories_scope ON memories (agent_id, user_id);
|
|
216
|
+
"""
|
|
217
|
+
|
|
218
|
+
async def run(self, operation: Callable[[sqlite3.Connection], T]) -> T:
|
|
219
|
+
async with self._lock: # 串行不变量:单连接同一时刻只被一个线程使用
|
|
220
|
+
task = asyncio.create_task(asyncio.to_thread(self._execute, operation))
|
|
221
|
+
try:
|
|
222
|
+
return await asyncio.shield(task)
|
|
223
|
+
except asyncio.CancelledError:
|
|
224
|
+
# 取消打在落库途中:等在途写收尾再放锁(F9 竞态同款收口),否则下一个
|
|
225
|
+
# 操作挤上同一连接,提交顺序未定义
|
|
226
|
+
while not task.done():
|
|
227
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
228
|
+
await task
|
|
229
|
+
raise
|
|
230
|
+
|
|
231
|
+
def _execute(self, operation: Callable[[sqlite3.Connection], T]) -> T:
|
|
232
|
+
connection = self._connect()
|
|
233
|
+
with connection: # 单次操作独立事务:成功提交、异常回滚
|
|
234
|
+
return operation(connection)
|
|
235
|
+
|
|
236
|
+
def _connect(self) -> sqlite3.Connection:
|
|
237
|
+
if self._connection is None:
|
|
238
|
+
connection = sqlite3.connect(self.path, check_same_thread=False)
|
|
239
|
+
connection.execute("PRAGMA journal_mode=WAL")
|
|
240
|
+
connection.executescript(self._SCHEMA)
|
|
241
|
+
self._connection = connection
|
|
242
|
+
assert self._connection is not None
|
|
243
|
+
if self._use_fts and not self._fts_ready:
|
|
244
|
+
try:
|
|
245
|
+
self._connection.execute(
|
|
246
|
+
"CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(content_tsv)"
|
|
247
|
+
)
|
|
248
|
+
self._fts_ready = True
|
|
249
|
+
except sqlite3.OperationalError: # 编译期未启用 FTS5:永久降级 LIKE
|
|
250
|
+
self._fts_ready = False
|
|
251
|
+
return self._connection
|
|
252
|
+
|
|
253
|
+
def _row_to_record(self, row: tuple[Any, ...]) -> MemoryRecord:
|
|
254
|
+
return MemoryRecord(
|
|
255
|
+
id=row[0],
|
|
256
|
+
scope=MemoryScope(agent_id=row[1], user_id=row[2]),
|
|
257
|
+
content=row[3],
|
|
258
|
+
metadata=json.loads(row[4]),
|
|
259
|
+
created_at=row[5],
|
|
260
|
+
updated_at=row[6],
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
# -- 行级操作(同步函数,在 _execute 的事务里跑) -----------------------------
|
|
264
|
+
|
|
265
|
+
async def add_row(self, record: MemoryRecord, assigned: str) -> None:
|
|
266
|
+
def operation(connection: sqlite3.Connection) -> None:
|
|
267
|
+
tsv = _tokenize(record.content)
|
|
268
|
+
cursor = connection.execute(
|
|
269
|
+
"INSERT OR IGNORE INTO memories (id, agent_id, user_id, content, metadata,"
|
|
270
|
+
" created_at, updated_at, content_tsv) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
|
271
|
+
(
|
|
272
|
+
assigned,
|
|
273
|
+
record.scope.agent_id,
|
|
274
|
+
record.scope.user_id,
|
|
275
|
+
record.content,
|
|
276
|
+
json.dumps(record.metadata, ensure_ascii=False),
|
|
277
|
+
record.created_at,
|
|
278
|
+
record.updated_at,
|
|
279
|
+
tsv,
|
|
280
|
+
),
|
|
281
|
+
)
|
|
282
|
+
if cursor.rowcount == 1 and self._fts_ready:
|
|
283
|
+
connection.execute(
|
|
284
|
+
"INSERT INTO memories_fts(rowid, content_tsv) VALUES (?, ?)",
|
|
285
|
+
(cursor.lastrowid, tsv),
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
await self.run(operation)
|
|
289
|
+
|
|
290
|
+
async def get(self, record_id: str) -> MemoryRecord | None:
|
|
291
|
+
def operation(connection: sqlite3.Connection) -> MemoryRecord | None:
|
|
292
|
+
row = connection.execute(
|
|
293
|
+
f"SELECT {_COLUMNS} FROM memories WHERE id = ?", (record_id,)
|
|
294
|
+
).fetchone()
|
|
295
|
+
return None if row is None else self._row_to_record(row)
|
|
296
|
+
|
|
297
|
+
return await self.run(operation)
|
|
298
|
+
|
|
299
|
+
async def search(self, scope: MemoryScope, query: str, k: int) -> list[MemoryRecord]:
|
|
300
|
+
def operation(connection: sqlite3.Connection) -> list[MemoryRecord]:
|
|
301
|
+
params: list[Any] = [scope.agent_id, scope.user_id]
|
|
302
|
+
sql = f"SELECT {_COLUMNS} FROM memories WHERE agent_id = ? AND user_id = ?"
|
|
303
|
+
match_expr = _fts_match_expr(query)
|
|
304
|
+
if match_expr is not None and self._fts_ready:
|
|
305
|
+
sql += " AND seq IN (SELECT rowid FROM memories_fts WHERE memories_fts MATCH ?)"
|
|
306
|
+
params.append(match_expr)
|
|
307
|
+
elif match_expr is not None: # LIKE 回退:逐词元 AND
|
|
308
|
+
for token in _tokenize(query).split():
|
|
309
|
+
sql += " AND content_tsv LIKE ? ESCAPE '\\'"
|
|
310
|
+
params.append(_like_pattern(token))
|
|
311
|
+
sql += " ORDER BY updated_at DESC, seq LIMIT ?"
|
|
312
|
+
params.append(k)
|
|
313
|
+
rows = connection.execute(sql, params).fetchall()
|
|
314
|
+
return [self._row_to_record(row) for row in rows]
|
|
315
|
+
|
|
316
|
+
return await self.run(operation)
|
|
317
|
+
|
|
318
|
+
async def list(self, scope: MemoryScope) -> list[MemoryRecord]:
|
|
319
|
+
def operation(connection: sqlite3.Connection) -> list[MemoryRecord]:
|
|
320
|
+
rows = connection.execute(
|
|
321
|
+
f"SELECT {_COLUMNS} FROM memories WHERE agent_id = ? AND user_id = ? ORDER BY seq",
|
|
322
|
+
(scope.agent_id, scope.user_id),
|
|
323
|
+
).fetchall()
|
|
324
|
+
return [self._row_to_record(row) for row in rows]
|
|
325
|
+
|
|
326
|
+
return await self.run(operation)
|
|
327
|
+
|
|
328
|
+
async def delete(self, record_id: str) -> None:
|
|
329
|
+
def operation(connection: sqlite3.Connection) -> None:
|
|
330
|
+
row = connection.execute(
|
|
331
|
+
"SELECT seq FROM memories WHERE id = ?", (record_id,)
|
|
332
|
+
).fetchone()
|
|
333
|
+
if row is None:
|
|
334
|
+
return
|
|
335
|
+
if self._fts_ready:
|
|
336
|
+
connection.execute("DELETE FROM memories_fts WHERE rowid = ?", (row[0],))
|
|
337
|
+
connection.execute("DELETE FROM memories WHERE id = ?", (record_id,))
|
|
338
|
+
|
|
339
|
+
await self.run(operation)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _fts_match_expr(query: str) -> str | None:
|
|
343
|
+
"""查询 → FTS5 MATCH 表达式;空 / 空白查询返回 None(退化为最近 k 条)。
|
|
344
|
+
|
|
345
|
+
词元逐个双引号包起(内部引号翻倍转义),空格连接 = FTS5 隐式 AND,
|
|
346
|
+
与 LIKE 回退的「全词元命中」语义一致。
|
|
347
|
+
"""
|
|
348
|
+
tokens = _tokenize(query).split()
|
|
349
|
+
if not tokens:
|
|
350
|
+
return None
|
|
351
|
+
return " ".join('"' + token.replace('"', '""') + '"' for token in tokens)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _like_pattern(token: str) -> str:
|
|
355
|
+
"""词元 → LIKE 模式:通配符按 ESCAPE '\\' 规则转义后两端加 %。"""
|
|
356
|
+
escaped = token.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
|
357
|
+
return f"%{escaped}%"
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""mainspring-memory Postgres 存储档(T15-⑭):MemoryBackend 的 asyncpg 实现。
|
|
2
|
+
|
|
3
|
+
与 backend.py 的 SqliteBackend 同一套契约(条文见 ``MemoryBackend`` docstring):
|
|
4
|
+
add 按 id 幂等(同 id 跳过,先写者胜)/ search 全词元命中 / list 写入序 /
|
|
5
|
+
delete 静默;返回值一律新建对象,改动不污染库存。
|
|
6
|
+
|
|
7
|
+
设计要点:
|
|
8
|
+
|
|
9
|
+
- **可选依赖**:asyncpg 不进 mainspring-memory 基础依赖(extras 零第三方纪律),
|
|
10
|
+
声明在 ``[project.optional-dependencies] postgres``——宿主不点 pg 档就永不 import
|
|
11
|
+
本模块,零依赖默认不绑架;
|
|
12
|
+
- **检索档位**:ILIKE 逐词元 AND,语义对齐 SQLite 的 LIKE 回退档(ILIKE 大小写
|
|
13
|
+
不敏感 ≡ LIKE 配 casefold 后的 content_tsv);不引 pg_trgm / FTS 扩展,
|
|
14
|
+
交付零扩展依赖的契约达标档;
|
|
15
|
+
- **连接池懒初始化**:构造只存 DSN,首次读写才建池建表——装配阶段不要求 Postgres
|
|
16
|
+
在线(与 session-postgres 外挂同口径);
|
|
17
|
+
- **table_prefix**:默认 ``ms_``;测试与多租户共用一库时给独立前缀即可表级隔离,
|
|
18
|
+
契约测试用它做每次用例的临时表(用毕即弃)。
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import asyncio
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
import uuid
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
from .backend import MemoryRecord, MemoryScope, _tokenize
|
|
30
|
+
|
|
31
|
+
__all__ = ["DEFAULT_DSN", "ENV_DSN", "PostgresBackend"]
|
|
32
|
+
|
|
33
|
+
DEFAULT_DSN = "postgresql://mainspring:mainspring@127.0.0.1:5432/mainspring"
|
|
34
|
+
ENV_DSN = "MAINSPRING_MEMORY_POSTGRES_DSN"
|
|
35
|
+
|
|
36
|
+
_COLUMNS = "id, agent_id, user_id, content, metadata, created_at, updated_at"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _schema(table: str) -> str:
|
|
40
|
+
"""建表 DDL:seq 承载写入序(list 契约),id 唯一约束承载幂等。"""
|
|
41
|
+
return f"""
|
|
42
|
+
CREATE TABLE IF NOT EXISTS {table} (
|
|
43
|
+
seq BIGSERIAL PRIMARY KEY,
|
|
44
|
+
id TEXT NOT NULL UNIQUE,
|
|
45
|
+
agent_id TEXT NOT NULL,
|
|
46
|
+
user_id TEXT NOT NULL,
|
|
47
|
+
content TEXT NOT NULL,
|
|
48
|
+
metadata TEXT NOT NULL,
|
|
49
|
+
created_at DOUBLE PRECISION NOT NULL,
|
|
50
|
+
updated_at DOUBLE PRECISION NOT NULL
|
|
51
|
+
);
|
|
52
|
+
CREATE INDEX IF NOT EXISTS idx_{table}_scope ON {table} (agent_id, user_id);
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _ilike_pattern(token: str) -> str:
|
|
57
|
+
"""词元 → ILIKE 模式:通配符转义后两端加 %(子串命中,与 LIKE 档同款)。"""
|
|
58
|
+
escaped = token.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
|
59
|
+
return f"%{escaped}%"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class PostgresBackend:
|
|
63
|
+
"""MemoryBackend 的 Postgres 实现:唯一约束幂等写 + ILIKE 全词元检索。"""
|
|
64
|
+
|
|
65
|
+
def __init__(self, dsn: str | None = None, *, table_prefix: str = "ms_") -> None:
|
|
66
|
+
self.dsn = dsn or os.environ.get(ENV_DSN) or DEFAULT_DSN
|
|
67
|
+
self._table = f"{table_prefix}memories"
|
|
68
|
+
self._pool: Any = None
|
|
69
|
+
self._lock = asyncio.Lock()
|
|
70
|
+
|
|
71
|
+
async def _acquire(self) -> Any:
|
|
72
|
+
"""取池化连接;首次调用建池建表(双重检查,并发首访只建一次)。"""
|
|
73
|
+
if self._pool is None:
|
|
74
|
+
async with self._lock:
|
|
75
|
+
if self._pool is None:
|
|
76
|
+
import asyncpg
|
|
77
|
+
|
|
78
|
+
pool = await asyncpg.create_pool(self.dsn, min_size=1, max_size=10)
|
|
79
|
+
async with pool.acquire() as connection:
|
|
80
|
+
await connection.execute(_schema(self._table))
|
|
81
|
+
self._pool = pool
|
|
82
|
+
return await self._pool.acquire()
|
|
83
|
+
|
|
84
|
+
async def _release(self, connection: Any) -> None:
|
|
85
|
+
"""归还连接:asyncpg 的 Pool.release 是协程,必须 await(否则连接悬挂,
|
|
86
|
+
池 close 时会等满 60 秒超时)。"""
|
|
87
|
+
if self._pool is not None:
|
|
88
|
+
await self._pool.release(connection)
|
|
89
|
+
|
|
90
|
+
async def aclose(self) -> None:
|
|
91
|
+
"""关闭连接池;短期进程退出可不管(连接随进程消亡),长期驻留建议显式收口。"""
|
|
92
|
+
if self._pool is not None:
|
|
93
|
+
await self._pool.close()
|
|
94
|
+
self._pool = None
|
|
95
|
+
|
|
96
|
+
@staticmethod
|
|
97
|
+
def _row_to_record(row: Any) -> MemoryRecord:
|
|
98
|
+
return MemoryRecord(
|
|
99
|
+
id=row["id"],
|
|
100
|
+
scope=MemoryScope(agent_id=row["agent_id"], user_id=row["user_id"]),
|
|
101
|
+
content=row["content"],
|
|
102
|
+
metadata=json.loads(row["metadata"]),
|
|
103
|
+
created_at=row["created_at"],
|
|
104
|
+
updated_at=row["updated_at"],
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
async def add(self, record: MemoryRecord) -> MemoryRecord:
|
|
108
|
+
assigned = record.id if record.id is not None else uuid.uuid4().hex
|
|
109
|
+
connection = await self._acquire()
|
|
110
|
+
try:
|
|
111
|
+
# 唯一约束 + ON CONFLICT DO NOTHING = 幂等(同 id 跳过,先写者胜)
|
|
112
|
+
await connection.execute(
|
|
113
|
+
f"INSERT INTO {self._table} ({_COLUMNS}) "
|
|
114
|
+
"VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (id) DO NOTHING",
|
|
115
|
+
assigned,
|
|
116
|
+
record.scope.agent_id,
|
|
117
|
+
record.scope.user_id,
|
|
118
|
+
record.content,
|
|
119
|
+
json.dumps(record.metadata, ensure_ascii=False),
|
|
120
|
+
record.created_at,
|
|
121
|
+
record.updated_at,
|
|
122
|
+
)
|
|
123
|
+
row = await connection.fetchrow(
|
|
124
|
+
f"SELECT {_COLUMNS} FROM {self._table} WHERE id = $1", assigned
|
|
125
|
+
)
|
|
126
|
+
finally:
|
|
127
|
+
await self._release(connection)
|
|
128
|
+
assert row is not None # 刚写入必在;断言收窄 Optional
|
|
129
|
+
return self._row_to_record(row)
|
|
130
|
+
|
|
131
|
+
async def search(self, scope: MemoryScope, query: str, *, k: int = 5) -> list[MemoryRecord]:
|
|
132
|
+
if k <= 0:
|
|
133
|
+
return []
|
|
134
|
+
tokens = _tokenize(query).split()
|
|
135
|
+
patterns = [_ilike_pattern(token) for token in tokens]
|
|
136
|
+
# 空 / 空白查询退化为最近 k 条;非空 = 逐词元 ILIKE AND(全词元命中),
|
|
137
|
+
# updated_at 倒序 + seq 稳定序,与 SQLite 两档完全一致
|
|
138
|
+
sql = f"SELECT {_COLUMNS} FROM {self._table} WHERE agent_id = $1 AND user_id = $2"
|
|
139
|
+
for index in range(len(patterns)):
|
|
140
|
+
sql += f" AND content ILIKE ${index + 3} ESCAPE '\\'"
|
|
141
|
+
sql += f" ORDER BY updated_at DESC, seq LIMIT ${len(patterns) + 3}"
|
|
142
|
+
connection = await self._acquire()
|
|
143
|
+
try:
|
|
144
|
+
rows = await connection.fetch(sql, scope.agent_id, scope.user_id, *patterns, k)
|
|
145
|
+
finally:
|
|
146
|
+
await self._release(connection)
|
|
147
|
+
return [self._row_to_record(row) for row in rows]
|
|
148
|
+
|
|
149
|
+
async def list(self, scope: MemoryScope) -> list[MemoryRecord]:
|
|
150
|
+
connection = await self._acquire()
|
|
151
|
+
try:
|
|
152
|
+
rows = await connection.fetch(
|
|
153
|
+
f"SELECT {_COLUMNS} FROM {self._table} "
|
|
154
|
+
"WHERE agent_id = $1 AND user_id = $2 ORDER BY seq",
|
|
155
|
+
scope.agent_id,
|
|
156
|
+
scope.user_id,
|
|
157
|
+
)
|
|
158
|
+
finally:
|
|
159
|
+
await self._release(connection)
|
|
160
|
+
return [self._row_to_record(row) for row in rows]
|
|
161
|
+
|
|
162
|
+
async def delete(self, record_id: str) -> None:
|
|
163
|
+
connection = await self._acquire()
|
|
164
|
+
try:
|
|
165
|
+
await connection.execute(f"DELETE FROM {self._table} WHERE id = $1", record_id)
|
|
166
|
+
finally:
|
|
167
|
+
await self._release(connection)
|
|
File without changes
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""mainspring-memory 召回装配(T6-2;T7-2 正名 MemorySkill → MemoryRecall):
|
|
2
|
+
core SystemFragmentSource 的记忆领域包装。
|
|
3
|
+
|
|
4
|
+
core 零改动的关键:召回天然就是「system 片段源」的形态——run 开始时 `_build_system`
|
|
5
|
+
对每个 source 求值一次,片段落 system 常量区尾部、按声明序拼接,随之享受 keep_system
|
|
6
|
+
永不压缩(core/context.py policy.keep_system)。写入路径见 tools.py(T6-3)。
|
|
7
|
+
|
|
8
|
+
命名纪律(ADR-005 修订决议):机制名(SystemFragmentSource)讲机制,领域包装类名
|
|
9
|
+
讲领域——记忆不是 skill,类名不带「Skill」后缀。
|
|
10
|
+
|
|
11
|
+
query 来源的契约:
|
|
12
|
+
|
|
13
|
+
- 默认 None → 空查询 → 后端退化为「该 scope 最近 k 条」(backend 契约的兜底行为);
|
|
14
|
+
- 需要按本轮输入检索时传 `query`:静态字符串,或(异步)回调。回调从 `ctx.deps` 取
|
|
15
|
+
当前用户输入——RunContext 不携带 messages(六轮终审口径),deps 是用户上下文的
|
|
16
|
+
唯一正规通道,不要试图从 ctx 里挖对话原文。
|
|
17
|
+
|
|
18
|
+
scope 同理:静态 `MemoryScope`,或(异步)回调按 ctx 动态取(多租户按 deps 路由)。
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import inspect
|
|
24
|
+
from collections.abc import Awaitable, Callable
|
|
25
|
+
from typing import Any, TypeVar
|
|
26
|
+
|
|
27
|
+
from mainspring.types import RunContext
|
|
28
|
+
|
|
29
|
+
from .backend import MemoryBackend, MemoryScope
|
|
30
|
+
|
|
31
|
+
__all__ = ["MemoryRecall"]
|
|
32
|
+
|
|
33
|
+
DEFAULT_K = 5
|
|
34
|
+
DEFAULT_MAX_CHARS = 500
|
|
35
|
+
DEFAULT_HEADER = "以下是关于当前用户的长期记忆,供回答时参考:"
|
|
36
|
+
|
|
37
|
+
ValueT = TypeVar("ValueT")
|
|
38
|
+
|
|
39
|
+
ScopeSource = (
|
|
40
|
+
MemoryScope
|
|
41
|
+
| Callable[[RunContext[Any]], MemoryScope]
|
|
42
|
+
| Callable[[RunContext[Any]], Awaitable[MemoryScope]]
|
|
43
|
+
)
|
|
44
|
+
QuerySource = str | Callable[[RunContext[Any]], str] | Callable[[RunContext[Any]], Awaitable[str]]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
async def _resolve_value(
|
|
48
|
+
source: ValueT | Callable[[RunContext[Any]], ValueT | Awaitable[ValueT]] | None,
|
|
49
|
+
ctx: RunContext[Any],
|
|
50
|
+
default: ValueT,
|
|
51
|
+
) -> ValueT:
|
|
52
|
+
"""静态值 / 同步回调 / 异步回调三态求值;None 落默认值。"""
|
|
53
|
+
if source is None:
|
|
54
|
+
return default
|
|
55
|
+
value = source(ctx) if callable(source) else source
|
|
56
|
+
if inspect.isawaitable(value):
|
|
57
|
+
value = await value
|
|
58
|
+
return value # type: ignore[no-any-return]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class MemoryRecall:
|
|
62
|
+
"""SystemFragmentSource 的记忆领域包装:resolve(ctx) 时检索记忆库,注入 system 常量区。
|
|
63
|
+
|
|
64
|
+
契约(对齐 SystemFragmentSource 原文):零命中返回 `[]`(不注入,不是错误);命中时返回
|
|
65
|
+
一个片段——首行 header,之后每条记忆一个 `- ` 行(按后端排序,即相关度 / 时间
|
|
66
|
+
倒序);单条 content 折叠空白后截断到 max_chars,防止长记忆吃穿 system 预算。
|
|
67
|
+
注入量结构性上界 = k x (max_chars + 列表开销),k=5、max_chars=500 是默认护栏,
|
|
68
|
+
条目多了吃 system token——调用方自行权衡(文档页详述)。
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
def __init__(
|
|
72
|
+
self,
|
|
73
|
+
backend: MemoryBackend,
|
|
74
|
+
*,
|
|
75
|
+
name: str = "memory",
|
|
76
|
+
scope: ScopeSource | None = None,
|
|
77
|
+
query: QuerySource | None = None,
|
|
78
|
+
k: int = DEFAULT_K,
|
|
79
|
+
max_chars: int = DEFAULT_MAX_CHARS,
|
|
80
|
+
header: str = DEFAULT_HEADER,
|
|
81
|
+
) -> None:
|
|
82
|
+
self.backend = backend
|
|
83
|
+
self.name = name
|
|
84
|
+
self._scope = scope
|
|
85
|
+
self._query = query
|
|
86
|
+
self.k = k
|
|
87
|
+
self.max_chars = max_chars
|
|
88
|
+
self.header = header
|
|
89
|
+
|
|
90
|
+
async def resolve(self, ctx: RunContext[Any]) -> list[str]:
|
|
91
|
+
scope = await _resolve_value(self._scope, ctx, MemoryScope())
|
|
92
|
+
query = await _resolve_value(self._query, ctx, "")
|
|
93
|
+
records = await self.backend.search(scope, query, k=self.k)
|
|
94
|
+
if not records:
|
|
95
|
+
return []
|
|
96
|
+
lines = [self.header]
|
|
97
|
+
for record in records:
|
|
98
|
+
content = " ".join(record.content.split())
|
|
99
|
+
if len(content) > self.max_chars:
|
|
100
|
+
content = content[: self.max_chars] + "…"
|
|
101
|
+
lines.append(f"- {content}")
|
|
102
|
+
return ["\n".join(lines)]
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""mainspring-memory 语义检索档(⑫):向量召回装饰器,keyword 后端的可选升级。
|
|
2
|
+
|
|
3
|
+
设计不变量(与外挂整体纪律同源):
|
|
4
|
+
|
|
5
|
+
- **零依赖默认不绑架**:本模块不引任何 embedding SDK / numpy——``Embedder``
|
|
6
|
+
是 Protocol,向量由宿主注入(OpenAI 兼容 embeddings 端点、本地模型、测试
|
|
7
|
+
桩均可);不配 embedder 就继续用 keyword 后端,库行为一字不变。
|
|
8
|
+
- **装饰器而非新后端**:`SemanticBackend` 包任意 ``MemoryBackend``(InMemory /
|
|
9
|
+
SQLite / 宿主自实现),存储与 scope 隔离全部复用内层,本层只管向量缓存与
|
|
10
|
+
相似度排序——后端契约(add 幂等 / search 全词元命中 / list 写入序)不变。
|
|
11
|
+
- **向量侧栏进程内存放,惰性回填**:重启或库存里先于 embedder 存在的记录,
|
|
12
|
+
首次 search 时按 scope 批量补算(一次 embed 调用),之后命中缓存;记忆库
|
|
13
|
+
典型规模(百条级)下补算成本可忽略,不做向量落库持久化(那是 v2 换真向量
|
|
14
|
+
后端时的事,不在装饰器里复刻一份存储)。
|
|
15
|
+
- **失败不静默**:embedder 异常一律向上抛(add / search 都如此)——检索质量
|
|
16
|
+
静默劣化成 keyword 比显式失败更难排查;要韧性的宿主自己包 embedder。
|
|
17
|
+
|
|
18
|
+
用法::
|
|
19
|
+
|
|
20
|
+
backend = SemanticBackend(SqliteBackend(path), embedder=my_embedder)
|
|
21
|
+
agent = attach_memory(agent, backend) # remember 工具与 MemoryRecall 原样可用
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import math
|
|
27
|
+
from typing import Protocol, runtime_checkable
|
|
28
|
+
|
|
29
|
+
from .backend import MemoryBackend, MemoryRecord, MemoryScope
|
|
30
|
+
|
|
31
|
+
__all__ = ["Embedder", "SemanticBackend"]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@runtime_checkable
|
|
35
|
+
class Embedder(Protocol):
|
|
36
|
+
"""文本 → 向量:宿主注入的嵌入实现(异步,批量接口)。
|
|
37
|
+
|
|
38
|
+
契约:返回向量数与输入数一致、维度一致且有限;实现方自行负责限流与重试
|
|
39
|
+
(本层不代管——见模块 docstring「失败不静默」)。
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
async def embed(self, texts: list[str]) -> list[list[float]]: ...
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _cosine(a: list[float], b: list[float]) -> float:
|
|
46
|
+
"""余弦相似度:纯 Python(零 numpy);零向量相似度记 0(无法定向)。"""
|
|
47
|
+
if len(a) != len(b):
|
|
48
|
+
raise ValueError(f"向量维度不一致:{len(a)} vs {len(b)}(embedder 换档了?)")
|
|
49
|
+
dot = sum(x * y for x, y in zip(a, b, strict=False)) # 长度已在上显式校验
|
|
50
|
+
norm_a = math.sqrt(sum(x * x for x in a))
|
|
51
|
+
norm_b = math.sqrt(sum(x * x for x in b))
|
|
52
|
+
if norm_a == 0.0 or norm_b == 0.0:
|
|
53
|
+
return 0.0
|
|
54
|
+
return dot / (norm_a * norm_b)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class SemanticBackend:
|
|
58
|
+
"""MemoryBackend 的语义检索装饰器:add 存向量,search 按余弦排序。
|
|
59
|
+
|
|
60
|
+
keyword 后端的契约全部透传保持:同 id 幂等先写者胜(inner.add)、空查询
|
|
61
|
+
退化为「该 scope 最近 k 条」(直接委托 inner.search)、list 写入序、delete
|
|
62
|
+
静默。差异只在**非空查询的排序口径**:keyword 是全词元命中,这里是余弦
|
|
63
|
+
相似度倒序(同分按 updated_at 倒序,与内层时间序口径一致)。
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
def __init__(self, inner: MemoryBackend, embedder: Embedder) -> None:
|
|
67
|
+
self.inner = inner
|
|
68
|
+
self.embedder = embedder
|
|
69
|
+
self._vectors: dict[str, list[float]] = {} # record_id → 向量(进程内侧栏)
|
|
70
|
+
|
|
71
|
+
async def add(self, record: MemoryRecord) -> MemoryRecord:
|
|
72
|
+
"""写入并缓存内容向量;向量缺失不阻塞写入(首次 search 惰性补算)。"""
|
|
73
|
+
stored = await self.inner.add(record)
|
|
74
|
+
vectors = await self.embedder.embed([stored.content])
|
|
75
|
+
self._vectors[stored.id or ""] = _checked(vectors, 1)[0]
|
|
76
|
+
return stored
|
|
77
|
+
|
|
78
|
+
async def search(self, scope: MemoryScope, query: str, *, k: int = 5) -> list[MemoryRecord]:
|
|
79
|
+
"""非空查询 = 余弦相似度倒序 top-k;空 / 空白查询委托内层(最近 k 条)。
|
|
80
|
+
|
|
81
|
+
相似度 ≤ 0 的记录不算命中(零向量 / 正交 / 负相似 = 没有召回信号),
|
|
82
|
+
与「零命中不注入」的召回口径一致,不让无信号记录挤占 k 个名额。
|
|
83
|
+
"""
|
|
84
|
+
if k <= 0:
|
|
85
|
+
return []
|
|
86
|
+
if not query.strip():
|
|
87
|
+
return await self.inner.search(scope, query, k=k)
|
|
88
|
+
records = await self.inner.list(scope)
|
|
89
|
+
await self._ensure_vectors(records) # 重启 / 历史记录批量补算
|
|
90
|
+
query_vec = _checked(await self.embedder.embed([query]), 1)[0]
|
|
91
|
+
scored = sorted(
|
|
92
|
+
((_cosine(query_vec, self._vectors[record.id or ""]), record) for record in records),
|
|
93
|
+
key=lambda pair: (-pair[0], -pair[1].updated_at), # 同分回退时间序,与 keyword 口径一致
|
|
94
|
+
)
|
|
95
|
+
return [record.model_copy(deep=True) for score, record in scored[:k] if score > 0.0]
|
|
96
|
+
|
|
97
|
+
async def list(self, scope: MemoryScope) -> list[MemoryRecord]:
|
|
98
|
+
return await self.inner.list(scope)
|
|
99
|
+
|
|
100
|
+
async def delete(self, record_id: str) -> None:
|
|
101
|
+
await self.inner.delete(record_id)
|
|
102
|
+
self._vectors.pop(record_id, None)
|
|
103
|
+
|
|
104
|
+
async def _ensure_vectors(self, records: list[MemoryRecord]) -> None:
|
|
105
|
+
"""缺向量的记录一次 embed 调用批量补齐(重启 / 先于 embedder 的库存)。"""
|
|
106
|
+
missing = [record for record in records if (record.id or "") not in self._vectors]
|
|
107
|
+
if not missing:
|
|
108
|
+
return
|
|
109
|
+
vectors = _checked(
|
|
110
|
+
await self.embedder.embed([record.content for record in missing]), len(missing)
|
|
111
|
+
)
|
|
112
|
+
for record, vector in zip(missing, vectors, strict=False): # 条数已在 _checked 校验
|
|
113
|
+
self._vectors[record.id or ""] = vector
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _checked(vectors: list[list[float]], expected: int) -> list[list[float]]:
|
|
117
|
+
"""embedder 返回值守卫:条数一致即放行,否则显式报错(不静默吞维度漂移)。"""
|
|
118
|
+
if len(vectors) != expected:
|
|
119
|
+
raise ValueError(f"embedder 返回 {len(vectors)} 条向量,期望 {expected} 条")
|
|
120
|
+
return vectors
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""mainspring-memory 写入路径(T6-3):remember 工具工厂 + 调用方直写 API。
|
|
2
|
+
|
|
3
|
+
两条显式写入通道,行为对调用方全可见;LLM 自动抽取(run 后从 Session 提炼)明确
|
|
4
|
+
不进 v1——「宿主拿到 Session 历史自行 backend.add」就是它的 v2 接口位。
|
|
5
|
+
|
|
6
|
+
- 工具通道:`build_memory_tools(backend)` 返回的 remember 工具进 `Agent.tools`,
|
|
7
|
+
模型在 run 中自主调用写入;T2 管控对它一视同仁(allowed_tools / 审批 / Hook)。
|
|
8
|
+
- 调用方通道:宿主代码直接 `backend.add(MemoryRecord(...))`(见 README 示例)。
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from mainspring.tool import Tool, tool
|
|
16
|
+
|
|
17
|
+
from .backend import MemoryBackend, MemoryRecord, MemoryScope
|
|
18
|
+
|
|
19
|
+
__all__ = ["build_memory_tools"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def build_memory_tools(
|
|
23
|
+
backend: MemoryBackend,
|
|
24
|
+
*,
|
|
25
|
+
scope: MemoryScope | None = None,
|
|
26
|
+
name: str = "remember",
|
|
27
|
+
) -> list[Tool]:
|
|
28
|
+
"""记忆写入工具工厂:返回可进 `Agent.tools` 的 remember 工具(v1 就一个)。
|
|
29
|
+
|
|
30
|
+
scope 在工厂期定死(多租户场景按 run 构建工具集,或用默认空命名空间);
|
|
31
|
+
工具结果只回固定确认文案、不回显记录 id——id 由后端分配,回显随机值会进
|
|
32
|
+
请求指纹,录制回放 strict 比对必误报(T5-2 deep_research 句柄教训同款)。
|
|
33
|
+
"""
|
|
34
|
+
resolved_scope = scope or MemoryScope()
|
|
35
|
+
|
|
36
|
+
async def remember(content: str, metadata: dict[str, Any] | None = None) -> str:
|
|
37
|
+
"""把一条长期记忆写入记忆库,之后的会话可以召回它。
|
|
38
|
+
|
|
39
|
+
content 要写成一句完整、自包含的陈述(例如「用户偏好深色主题」),
|
|
40
|
+
不要写代词或只有你知道上下文的缩写;metadata 可选,放结构化标签。
|
|
41
|
+
"""
|
|
42
|
+
record = MemoryRecord(content=content, metadata=metadata or {}, scope=resolved_scope)
|
|
43
|
+
await backend.add(record)
|
|
44
|
+
return "已记住:这条记忆会在之后的会话中自动可用。"
|
|
45
|
+
|
|
46
|
+
return [tool(remember, name=name)]
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mainspring-memory
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Long-term memory backends and semantic recall for mainspring.
|
|
5
|
+
Author: mainspring contributors
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Classifier: Development Status :: 4 - Beta
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
|
|
18
|
+
Requires-Dist: mainspring-agent
|
|
19
|
+
Requires-Dist: asyncpg>=0.29,<1 ; extra == 'postgres'
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Project-URL: Homepage, https://github.com/chyong/mainspring
|
|
22
|
+
Project-URL: Documentation, https://github.com/chyong/mainspring/tree/main/docs
|
|
23
|
+
Project-URL: Repository, https://github.com/chyong/mainspring
|
|
24
|
+
Project-URL: Issues, https://github.com/chyong/mainspring/issues
|
|
25
|
+
Provides-Extra: postgres
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# mainspring-memory
|
|
29
|
+
|
|
30
|
+
长期记忆外挂(M5):可插拔后端 + 语义召回 + 模型可调用的 `remember` 工具。记忆不进 core。
|
|
31
|
+
|
|
32
|
+
## 安装
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install mainspring-memory
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## 用法
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from mainspring_memory import InMemoryBackend, MemoryRecall, MemoryRecord, MemoryScope
|
|
42
|
+
|
|
43
|
+
backend = InMemoryBackend()
|
|
44
|
+
await backend.add(MemoryRecord(content="用户偏好深色模式"))
|
|
45
|
+
|
|
46
|
+
hits = await backend.search(MemoryScope(), "深色模式")
|
|
47
|
+
agent = Agent(..., fragment_sources=[MemoryRecall(backend)])
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
单文件场景用 `SqliteBackend`;`mainspring-memory[postgres]` 提供 asyncpg 后端,可与会话同库。
|
|
51
|
+
宿主注入 embedder 时,`SemanticBackend` 可把任意后端包装成向量召回。
|
|
52
|
+
|
|
53
|
+
mainspring 工作区成员,与 [core](https://github.com/chyong/mainspring) 同源。MIT。
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
mainspring_memory/__init__.py,sha256=5Vh5LPuwMS46dbgmLc6KpMwsd5gklgj93LATtVrXfaA,1570
|
|
2
|
+
mainspring_memory/backend.py,sha256=aldAdyz7M1-v6W1ArRfCQ7dCdJGLgC1mkIwVUVw68eA,15030
|
|
3
|
+
mainspring_memory/pg_backend.py,sha256=DG8tkoTm3VHpM5cb5GFmSVxZZZ1vLUfMySZBboSVd-4,7034
|
|
4
|
+
mainspring_memory/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
mainspring_memory/recall.py,sha256=IkI7VYq_by08iWpSCmklAU2kHNK-nuZaCV0cwI9Jr1c,3965
|
|
6
|
+
mainspring_memory/semantic.py,sha256=ToHd9jbmu_BIZY9s9rsPs04wuVOC4Bj_1jRSw9WplsQ,5871
|
|
7
|
+
mainspring_memory/tools.py,sha256=hrGALLf8xmM1F26uKfrO9-sEq2hb0gHxjNhzvlaOqZY,1987
|
|
8
|
+
mainspring_memory-0.1.0.dist-info/licenses/LICENSE,sha256=wRDF_w9CNQSolm8Pjiu3W13uQJ7Iw2K00IrirvJepqY,1080
|
|
9
|
+
mainspring_memory-0.1.0.dist-info/WHEEL,sha256=wfHFB5CQ4yOA68LQ_ISeFjKJGxj2GfVzMH9QxkYgrCw,81
|
|
10
|
+
mainspring_memory-0.1.0.dist-info/METADATA,sha256=LD_ULt6WeuZmkzQKYSJ8TankygRA_qs-kiZ5BAKDTuI,1968
|
|
11
|
+
mainspring_memory-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 mainspring contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|