-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory.js
More file actions
268 lines (225 loc) · 7.78 KB
/
Copy pathmemory.js
File metadata and controls
268 lines (225 loc) · 7.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import {BaseCheckpointSaver} from '@langchain/langgraph-checkpoint';
import {DatabaseSync} from 'node:sqlite';
import {createIndex, serializeIndex, deserializeIndex} from './lib/minisearch.mjs';
export class SchemaMemory extends BaseCheckpointSaver {
#db;
constructor(db = new DatabaseSync(':memory:')) {
super();
this.#db = db;
this.#db.exec(`
CREATE TABLE IF NOT EXISTS checkpoints (
thread_id TEXT NOT NULL,
checkpoint_ns TEXT NOT NULL,
checkpoint_id TEXT NOT NULL,
checkpoint BLOB NOT NULL,
metadata BLOB NOT NULL,
parent_checkpoint_id TEXT,
created_at INTEGER DEFAULT (unixepoch()),
updated_at INTEGER NOT NULL,
PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id)
) STRICT
`);
this.#db.exec(`
CREATE TABLE IF NOT EXISTS search_indexes (
thread_id TEXT PRIMARY KEY,
index_data TEXT NOT NULL,
updated_at INTEGER NOT NULL
) STRICT
`);
}
indexMessage(thread_id, {id, role, content}) {
if (!id || !content) return;
const row = this.#db
.prepare(`SELECT index_data FROM search_indexes WHERE thread_id = ?`)
.get(thread_id);
const ms = row ? deserializeIndex(row.index_data) : createIndex();
// TODO: дедупликация — проверять ms.has(id) перед добавлением
ms.add({id, role, content});
this.#db
.prepare(
`INSERT INTO search_indexes (thread_id, index_data, updated_at)
VALUES (?, ?, ?)
ON CONFLICT(thread_id)
DO UPDATE SET index_data = excluded.index_data, updated_at = excluded.updated_at`
)
.run(thread_id, serializeIndex(ms), Date.now());
}
search(thread_id, query) {
if (!query || !thread_id) return [];
const row = this.#db
.prepare(`SELECT index_data FROM search_indexes WHERE thread_id = ?`)
.get(thread_id);
if (!row) return [];
const ms = deserializeIndex(row.index_data);
return ms.search(query, {
fuzzy: 0.2,
prefix: true,
limit: 3,
});
}
async getTuple(config) {
const thread_id = config.configurable?.thread_id;
const checkpoint_ns = config.configurable?.checkpoint_ns ?? '';
const checkpoint_id = config.configurable?.checkpoint_id;
if (!thread_id) {
return undefined;
}
let row;
if (checkpoint_id) {
row = this.#db
.prepare(
`SELECT checkpoint, metadata, parent_checkpoint_id FROM checkpoints
WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ?`
)
.get(thread_id, checkpoint_ns, checkpoint_id);
} else {
row = this.#db
.prepare(
`SELECT checkpoint, metadata, parent_checkpoint_id, checkpoint_id FROM checkpoints
WHERE thread_id = ? AND checkpoint_ns = ?
ORDER BY updated_at DESC, checkpoint_id DESC
LIMIT 1`
)
.get(thread_id, checkpoint_ns);
}
if (!row) {
return undefined;
}
const deserializedCheckpoint = await this.serde.loadsTyped('json', row.checkpoint);
const deserializedMetadata = await this.serde.loadsTyped('json', row.metadata);
const checkpointTuple = {
config: checkpoint_id ? config : {
configurable: {
thread_id,
checkpoint_ns,
checkpoint_id: row.checkpoint_id,
},
},
checkpoint: deserializedCheckpoint,
metadata: deserializedMetadata,
pendingWrites: [],
};
if (row.parent_checkpoint_id) {
checkpointTuple.parentConfig = {
configurable: {
thread_id,
checkpoint_ns,
checkpoint_id: row.parent_checkpoint_id,
},
};
}
return checkpointTuple;
}
async put(config, checkpoint, metadata) {
const thread_id = config.configurable?.thread_id;
const checkpoint_ns = String(config.configurable?.checkpoint_ns ?? '');
const parent_checkpoint_id = config.configurable?.checkpoint_id || null;
if (!thread_id) {
throw new Error('Failed to put checkpoint. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property.');
}
const [[, serializedCheckpoint], [, serializedMetadata]] = await Promise.all([
this.serde.dumpsTyped(checkpoint),
this.serde.dumpsTyped(metadata),
]);
const checkpoint_id = checkpoint.id;
this.#db
.prepare(
`INSERT INTO checkpoints (thread_id, checkpoint_ns, checkpoint_id, checkpoint, metadata, parent_checkpoint_id, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(thread_id, checkpoint_ns, checkpoint_id)
DO UPDATE SET
checkpoint = excluded.checkpoint,
metadata = excluded.metadata,
parent_checkpoint_id = excluded.parent_checkpoint_id,
updated_at = excluded.updated_at`
)
.run(
thread_id,
checkpoint_ns,
checkpoint_id,
serializedCheckpoint,
serializedMetadata,
parent_checkpoint_id,
Date.now()
);
// Индексируем новые сообщения из чекпоинта для поиска по истории
const messages = checkpoint.channel_values?.messages ?? [];
for (const msg of messages) {
const role = msg._getType?.() ?? msg.role ?? 'unknown';
const content = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content);
this.indexMessage(thread_id, {id: msg.id, role, content});
}
return {
configurable: {
thread_id,
checkpoint_ns,
checkpoint_id,
},
};
}
async putWrites(config, writes, taskId) {
// Обычно writes не нужны для SQLite memory
// но хук обязателен
}
async* list(config, options) {
const {before, limit, filter} = options ?? {};
const thread_id = config.configurable?.thread_id;
const checkpoint_ns = config.configurable?.checkpoint_ns ?? '';
let query = `SELECT thread_id, checkpoint_ns, checkpoint_id, checkpoint, metadata, parent_checkpoint_id FROM checkpoints`;
const params = [];
const conditions = [];
if (thread_id) {
conditions.push('thread_id = ?');
params.push(thread_id);
}
if (checkpoint_ns) {
conditions.push('checkpoint_ns = ?');
params.push(checkpoint_ns);
}
if (before?.configurable?.checkpoint_id) {
conditions.push('checkpoint_id < ?');
params.push(before.configurable.checkpoint_id);
}
if (conditions.length > 0) {
query += ' WHERE ' + conditions.join(' AND ');
}
query += ' ORDER BY updated_at DESC, checkpoint_id DESC';
if (limit !== undefined) {
query += ' LIMIT ?';
params.push(limit);
}
const rows = this.#db.prepare(query).all(...params);
for (const row of rows) {
const deserializedCheckpoint = await this.serde.loadsTyped('json', row.checkpoint);
const deserializedMetadata = await this.serde.loadsTyped('json', row.metadata);
if (filter && !Object.entries(filter).every(([key, value]) => deserializedMetadata[key] === value)) {
continue;
}
const checkpointTuple = {
config: {
configurable: {
thread_id: row.thread_id,
checkpoint_ns: row.checkpoint_ns,
checkpoint_id: row.checkpoint_id,
},
},
checkpoint: deserializedCheckpoint,
metadata: deserializedMetadata,
pendingWrites: [],
};
if (row.parent_checkpoint_id) {
checkpointTuple.parentConfig = {
configurable: {
thread_id: row.thread_id,
checkpoint_ns: row.checkpoint_ns,
checkpoint_id: row.parent_checkpoint_id,
},
};
}
yield checkpointTuple;
}
}
clear() {
this.#db.exec(`DELETE FROM checkpoints`);
}
}