-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathindex.ts
654 lines (579 loc) · 20.2 KB
/
index.ts
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
import { DatabaseAdapter } from "@ai16z/eliza/src/database.ts";
import { embeddingZeroVector } from "@ai16z/eliza/src/memory.ts";
import {
Account,
Actor,
GoalStatus,
Participant,
type Goal,
type Memory,
type Relationship,
type UUID,
} from "@ai16z/eliza/src/types.ts";
import { Database } from "better-sqlite3";
import { v4 } from "uuid";
import { load } from "./sqlite_vec.ts";
import { sqliteTables } from "./sqliteTables.ts";
export class SqliteDatabaseAdapter extends DatabaseAdapter {
async getRoom(roomId: UUID): Promise<UUID | null> {
const sql = "SELECT id FROM rooms WHERE id = ?";
const room = this.db.prepare(sql).get(roomId) as
| { id: string }
| undefined;
return room ? (room.id as UUID) : null;
}
async getParticipantsForAccount(userId: UUID): Promise<Participant[]> {
const sql = `
SELECT p.id, p.userId, p.roomId, p.last_message_read
FROM participants p
WHERE p.userId = ?
`;
const rows = this.db.prepare(sql).all(userId) as Participant[];
return rows;
}
async getParticipantsForRoom(roomId: UUID): Promise<UUID[]> {
const sql = "SELECT userId FROM participants WHERE roomId = ?";
const rows = this.db.prepare(sql).all(roomId) as { userId: string }[];
return rows.map((row) => row.userId as UUID);
}
async getParticipantUserState(
roomId: UUID,
userId: UUID
): Promise<"FOLLOWED" | "MUTED" | null> {
const stmt = this.db.prepare(
"SELECT userState FROM participants WHERE roomId = ? AND userId = ?"
);
const res = stmt.get(roomId, userId) as
| { userState: "FOLLOWED" | "MUTED" | null }
| undefined;
return res?.userState ?? null;
}
async setParticipantUserState(
roomId: UUID,
userId: UUID,
state: "FOLLOWED" | "MUTED" | null
): Promise<void> {
const stmt = this.db.prepare(
"UPDATE participants SET userState = ? WHERE roomId = ? AND userId = ?"
);
stmt.run(state, roomId, userId);
}
constructor(db: Database) {
super();
this.db = db;
load(db);
// Check if the 'accounts' table exists as a representative table
const tableExists = this.db
.prepare(
"SELECT name FROM sqlite_master WHERE type='table' AND name='accounts'"
)
.get();
if (!tableExists) {
// If the 'accounts' table doesn't exist, create all the tables
this.db.exec(sqliteTables);
}
}
async getAccountById(userId: UUID): Promise<Account | null> {
const sql = "SELECT * FROM accounts WHERE id = ?";
const account = this.db.prepare(sql).get(userId) as Account;
if (!account) return null;
if (account) {
if (typeof account.details === "string") {
account.details = JSON.parse(
account.details as unknown as string
);
}
}
return account;
}
async createAccount(account: Account): Promise<boolean> {
try {
const sql =
"INSERT INTO accounts (id, name, username, email, avatarUrl, details) VALUES (?, ?, ?, ?, ?, ?)";
this.db
.prepare(sql)
.run(
account.id ?? v4(),
account.name,
account.username,
account.email,
account.avatarUrl,
JSON.stringify(account.details)
);
return true;
} catch (error) {
console.log("Error creating account", error);
return false;
}
}
async getActorDetails(params: { roomId: UUID }): Promise<Actor[]> {
const sql = `
SELECT a.id, a.name, a.username, a.details
FROM participants p
LEFT JOIN accounts a ON p.userId = a.id
WHERE p.roomId = ?
`;
const rows = this.db
.prepare(sql)
.all(params.roomId) as (Actor | null)[];
return rows
.map((row) => {
if (row === null) {
return null;
}
return {
...row,
details:
typeof row.details === "string"
? JSON.parse(row.details)
: row.details,
};
})
.filter((row): row is Actor => row !== null);
}
async getMemoriesByRoomIds(params: {
roomIds: UUID[];
tableName: string;
agentId?: UUID;
}): Promise<Memory[]> {
if (!params.tableName) {
// default to messages
params.tableName = "messages";
}
const placeholders = params.roomIds.map(() => "?").join(", ");
let sql = `SELECT * FROM memories WHERE type = ? AND roomId IN (${placeholders})`;
let queryParams = [params.tableName, ...params.roomIds];
if (params.agentId) {
sql += ` AND agentId = ?`;
queryParams.push(params.agentId);
}
const stmt = this.db.prepare(sql);
const rows = stmt.all(...queryParams) as (Memory & {
content: string;
})[];
return rows.map((row) => ({
...row,
content: JSON.parse(row.content),
}));
}
async getMemoryById(memoryId: UUID): Promise<Memory | null> {
const sql = "SELECT * FROM memories WHERE id = ?";
const stmt = this.db.prepare(sql);
stmt.bind([memoryId]);
const memory = stmt.get() as Memory | undefined;
if (memory) {
return {
...memory,
content: JSON.parse(memory.content as unknown as string),
};
}
return null;
}
async createMemory(memory: Memory, tableName: string): Promise<void> {
// Delete any existing memory with the same ID first
const deleteSql = `DELETE FROM memories WHERE id = ? AND type = ?`;
this.db.prepare(deleteSql).run(memory.id, tableName);
let isUnique = true;
if (memory.embedding) {
// Check if a similar memory already exists
const similarMemories = await this.searchMemoriesByEmbedding(
memory.embedding,
{
tableName,
roomId: memory.roomId,
match_threshold: 0.95, // 5% similarity threshold
count: 1,
}
);
isUnique = similarMemories.length === 0;
}
const content = JSON.stringify(memory.content);
const createdAt = memory.createdAt ?? Date.now();
// Insert the memory with the appropriate 'unique' value
const sql = `INSERT OR REPLACE INTO memories (id, type, content, embedding, userId, roomId, agentId, \`unique\`, createdAt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`;
this.db.prepare(sql).run(
memory.id ?? v4(),
tableName,
content,
new Float32Array(memory.embedding ?? embeddingZeroVector), // Store as Float32Array
memory.userId,
memory.roomId,
memory.agentId,
isUnique ? 1 : 0,
createdAt
);
}
async searchMemories(params: {
tableName: string;
roomId: UUID;
agentId?: UUID;
embedding: number[];
match_threshold: number;
match_count: number;
unique: boolean;
}): Promise<Memory[]> {
const queryParams = [
new Float32Array(params.embedding), // Ensure embedding is Float32Array
params.tableName,
params.roomId,
params.match_count,
];
let sql = `
SELECT *, vec_distance_L2(embedding, ?) AS similarity
FROM memories
WHERE type = ?`;
if (params.unique) {
sql += " AND `unique` = 1";
}
if (params.agentId) {
sql += " AND agentId = ?";
queryParams.push(params.agentId);
}
sql += ` ORDER BY similarity ASC LIMIT ?`; // ASC for lower distance
// Updated queryParams order matches the placeholders
const memories = this.db.prepare(sql).all(...queryParams) as (Memory & {
similarity: number;
})[];
return memories.map((memory) => ({
...memory,
createdAt:
typeof memory.createdAt === "string"
? Date.parse(memory.createdAt as string)
: memory.createdAt,
content: JSON.parse(memory.content as unknown as string),
}));
}
async searchMemoriesByEmbedding(
embedding: number[],
params: {
match_threshold?: number;
count?: number;
roomId?: UUID;
agentId?: UUID;
unique?: boolean;
tableName: string;
}
): Promise<Memory[]> {
const queryParams = [
// JSON.stringify(embedding),
new Float32Array(embedding),
params.tableName,
];
let sql = `
SELECT *, vec_distance_L2(embedding, ?) AS similarity
FROM memories
WHERE type = ?`;
if (params.unique) {
sql += " AND `unique` = 1";
}
if (params.agentId) {
sql += " AND agentId = ?";
queryParams.push(params.agentId);
}
if (params.roomId) {
sql += " AND roomId = ?";
queryParams.push(params.roomId);
}
sql += ` ORDER BY similarity DESC`;
if (params.count) {
sql += " LIMIT ?";
queryParams.push(params.count.toString());
}
const memories = this.db.prepare(sql).all(...queryParams) as (Memory & {
similarity: number;
})[];
return memories.map((memory) => ({
...memory,
createdAt:
typeof memory.createdAt === "string"
? Date.parse(memory.createdAt as string)
: memory.createdAt,
content: JSON.parse(memory.content as unknown as string),
}));
}
async getCachedEmbeddings(opts: {
query_table_name: string;
query_threshold: number;
query_input: string;
query_field_name: string;
query_field_sub_name: string;
query_match_count: number;
}): Promise<
{
embedding: number[];
levenshtein_score: number;
}[]
> {
const sql = `
SELECT *
FROM memories
WHERE type = ?
AND vec_distance_L2(${opts.query_field_name}, ?) <= ?
ORDER BY vec_distance_L2(${opts.query_field_name}, ?) ASC
LIMIT ?
`;
console.log("sql", sql)
console.log("opts.query_input", opts.query_input)
const memories = this.db.prepare(sql).all(
opts.query_table_name,
new Float32Array(opts.query_input.split(",").map(Number)), // Convert string to Float32Array
opts.query_input,
new Float32Array(opts.query_input.split(",").map(Number))
) as Memory[];
return memories.map((memory) => ({
embedding: Array.from(
new Float32Array(memory.embedding as unknown as Buffer)
), // Convert Buffer to number[]
levenshtein_score: 0,
}));
}
async updateGoalStatus(params: {
goalId: UUID;
status: GoalStatus;
}): Promise<void> {
const sql = "UPDATE goals SET status = ? WHERE id = ?";
this.db.prepare(sql).run(params.status, params.goalId);
}
async log(params: {
body: { [key: string]: unknown };
userId: UUID;
roomId: UUID;
type: string;
}): Promise<void> {
const sql =
"INSERT INTO logs (body, userId, roomId, type) VALUES (?, ?, ?, ?)";
this.db
.prepare(sql)
.run(
JSON.stringify(params.body),
params.userId,
params.roomId,
params.type
);
}
async getMemories(params: {
roomId: UUID;
count?: number;
unique?: boolean;
tableName: string;
agentId?: UUID;
start?: number;
end?: number;
}): Promise<Memory[]> {
if (!params.tableName) {
throw new Error("tableName is required");
}
if (!params.roomId) {
throw new Error("roomId is required");
}
let sql = `SELECT * FROM memories WHERE type = ? AND roomId = ?`;
const queryParams = [params.tableName, params.roomId] as any[];
if (params.unique) {
sql += " AND `unique` = 1";
}
if (params.agentId) {
sql += " AND agentId = ?";
queryParams.push(params.agentId);
}
if (params.start) {
sql += ` AND createdAt >= ?`;
queryParams.push(params.start);
}
if (params.end) {
sql += ` AND createdAt <= ?`;
queryParams.push(params.end);
}
sql += " ORDER BY createdAt DESC";
if (params.count) {
sql += " LIMIT ?";
queryParams.push(params.count);
}
const memories = this.db.prepare(sql).all(...queryParams) as Memory[];
return memories.map((memory) => ({
...memory,
createdAt:
typeof memory.createdAt === "string"
? Date.parse(memory.createdAt as string)
: memory.createdAt,
content: JSON.parse(memory.content as unknown as string),
}));
}
async removeMemory(memoryId: UUID, tableName: string): Promise<void> {
const sql = `DELETE FROM memories WHERE type = ? AND id = ?`;
this.db.prepare(sql).run(tableName, memoryId);
}
async removeAllMemories(roomId: UUID, tableName: string): Promise<void> {
const sql = `DELETE FROM memories WHERE type = ? AND roomId = ?`;
this.db.prepare(sql).run(tableName, roomId);
}
async countMemories(
roomId: UUID,
unique = true,
tableName = ""
): Promise<number> {
if (!tableName) {
throw new Error("tableName is required");
}
let sql = `SELECT COUNT(*) as count FROM memories WHERE type = ? AND roomId = ?`;
const queryParams = [tableName, roomId] as string[];
if (unique) {
sql += " AND `unique` = 1";
}
return (this.db.prepare(sql).get(...queryParams) as { count: number })
.count;
}
async getGoals(params: {
roomId: UUID;
userId?: UUID | null;
onlyInProgress?: boolean;
count?: number;
}): Promise<Goal[]> {
let sql = "SELECT * FROM goals WHERE roomId = ?";
const queryParams = [params.roomId];
if (params.userId) {
sql += " AND userId = ?";
queryParams.push(params.userId);
}
if (params.onlyInProgress) {
sql += " AND status = 'IN_PROGRESS'";
}
if (params.count) {
sql += " LIMIT ?";
// @ts-expect-error - queryParams is an array of strings
queryParams.push(params.count.toString());
}
const goals = this.db.prepare(sql).all(...queryParams) as Goal[];
return goals.map((goal) => ({
...goal,
objectives:
typeof goal.objectives === "string"
? JSON.parse(goal.objectives)
: goal.objectives,
}));
}
async updateGoal(goal: Goal): Promise<void> {
const sql =
"UPDATE goals SET name = ?, status = ?, objectives = ? WHERE id = ?";
this.db
.prepare(sql)
.run(
goal.name,
goal.status,
JSON.stringify(goal.objectives),
goal.id
);
}
async createGoal(goal: Goal): Promise<void> {
const sql =
"INSERT INTO goals (id, roomId, userId, name, status, objectives) VALUES (?, ?, ?, ?, ?, ?)";
this.db
.prepare(sql)
.run(
goal.id ?? v4(),
goal.roomId,
goal.userId,
goal.name,
goal.status,
JSON.stringify(goal.objectives)
);
}
async removeGoal(goalId: UUID): Promise<void> {
const sql = "DELETE FROM goals WHERE id = ?";
this.db.prepare(sql).run(goalId);
}
async removeAllGoals(roomId: UUID): Promise<void> {
const sql = "DELETE FROM goals WHERE roomId = ?";
this.db.prepare(sql).run(roomId);
}
async createRoom(roomId?: UUID): Promise<UUID> {
roomId = roomId || (v4() as UUID);
try {
const sql = "INSERT INTO rooms (id) VALUES (?)";
this.db.prepare(sql).run(roomId ?? (v4() as UUID));
} catch (error) {
console.log("Error creating room", error);
}
return roomId as UUID;
}
async removeRoom(roomId: UUID): Promise<void> {
const sql = "DELETE FROM rooms WHERE id = ?";
this.db.prepare(sql).run(roomId);
}
async getRoomsForParticipant(userId: UUID): Promise<UUID[]> {
const sql = "SELECT roomId FROM participants WHERE userId = ?";
const rows = this.db.prepare(sql).all(userId) as { roomId: string }[];
return rows.map((row) => row.roomId as UUID);
}
async getRoomsForParticipants(userIds: UUID[]): Promise<UUID[]> {
// Assuming userIds is an array of UUID strings, prepare a list of placeholders
const placeholders = userIds.map(() => "?").join(", ");
// Construct the SQL query with the correct number of placeholders
const sql = `SELECT DISTINCT roomId FROM participants WHERE userId IN (${placeholders})`;
// Execute the query with the userIds array spread into arguments
const rows = this.db.prepare(sql).all(...userIds) as {
roomId: string;
}[];
// Map and return the roomId values as UUIDs
return rows.map((row) => row.roomId as UUID);
}
async addParticipant(userId: UUID, roomId: UUID): Promise<boolean> {
try {
const sql =
"INSERT INTO participants (id, userId, roomId) VALUES (?, ?, ?)";
this.db.prepare(sql).run(v4(), userId, roomId);
return true;
} catch (error) {
console.log("Error adding participant", error);
return false;
}
}
async removeParticipant(userId: UUID, roomId: UUID): Promise<boolean> {
try {
const sql =
"DELETE FROM participants WHERE userId = ? AND roomId = ?";
this.db.prepare(sql).run(userId, roomId);
return true;
} catch (error) {
console.log("Error removing participant", error);
return false;
}
}
async createRelationship(params: {
userA: UUID;
userB: UUID;
}): Promise<boolean> {
if (!params.userA || !params.userB) {
throw new Error("userA and userB are required");
}
const sql =
"INSERT INTO relationships (id, userA, userB, userId) VALUES (?, ?, ?, ?)";
this.db
.prepare(sql)
.run(v4(), params.userA, params.userB, params.userA);
return true;
}
async getRelationship(params: {
userA: UUID;
userB: UUID;
}): Promise<Relationship | null> {
const sql =
"SELECT * FROM relationships WHERE (userA = ? AND userB = ?) OR (userA = ? AND userB = ?)";
return (
(this.db
.prepare(sql)
.get(
params.userA,
params.userB,
params.userB,
params.userA
) as Relationship) || null
);
}
async getRelationships(params: { userId: UUID }): Promise<Relationship[]> {
const sql =
"SELECT * FROM relationships WHERE (userA = ? OR userB = ?)";
return this.db
.prepare(sql)
.all(params.userId, params.userId) as Relationship[];
}
}