forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
1440 lines (1300 loc) · 48.3 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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { v4 } from "uuid";
import postgres from "pg";
const { Pool } = postgres;
type PoolType = typeof postgres.Pool;
import {
QueryConfig,
QueryConfigValues,
QueryResult,
QueryResultRow,
} from "pg";
import {
Account,
Actor,
GoalStatus,
type Goal,
type Memory,
type Relationship,
type UUID,
type IDatabaseCacheAdapter,
Participant,
DatabaseAdapter,
elizaLogger,
getEmbeddingConfig,
} from "@ai16z/eliza";
import fs from "fs";
import { fileURLToPath } from "url";
import path from "path";
const __filename = fileURLToPath(import.meta.url); // get the resolved path to the file
const __dirname = path.dirname(__filename); // get the name of the directory
export class PostgresDatabaseAdapter
extends DatabaseAdapter<PoolType>
implements IDatabaseCacheAdapter
{
private pool: InstanceType<PoolType>;
private readonly maxRetries: number = 3;
private readonly baseDelay: number = 1000; // 1 second
private readonly maxDelay: number = 10000; // 10 seconds
private readonly jitterMax: number = 1000; // 1 second
private readonly connectionTimeout: number = 5000; // 5 seconds
constructor(connectionConfig: any) {
super();
const defaultConfig = {
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: this.connectionTimeout,
};
this.pool = new Pool({
...defaultConfig,
...connectionConfig, // Allow overriding defaults
});
this.pool.on("error", (err) => {
elizaLogger.error("Unexpected pool error", err);
this.handlePoolError(err);
});
this.setupPoolErrorHandling();
this.testConnection();
}
private setupPoolErrorHandling() {
process.on("SIGINT", async () => {
await this.cleanup();
process.exit(0);
});
process.on("SIGTERM", async () => {
await this.cleanup();
process.exit(0);
});
}
private async withRetry<T>(operation: () => Promise<T>): Promise<T> {
let lastError: Error = new Error("Unknown error"); // Initialize with default
for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
try {
return await operation();
} catch (error) {
lastError = error as Error;
if (attempt < this.maxRetries) {
// Calculate delay with exponential backoff
const backoffDelay = Math.min(
this.baseDelay * Math.pow(2, attempt - 1),
this.maxDelay
);
// Add jitter to prevent thundering herd
const jitter = Math.random() * this.jitterMax;
const delay = backoffDelay + jitter;
elizaLogger.warn(
`Database operation failed (attempt ${attempt}/${this.maxRetries}):`,
{
error:
error instanceof Error
? error.message
: String(error),
nextRetryIn: `${(delay / 1000).toFixed(1)}s`,
}
);
await new Promise((resolve) => setTimeout(resolve, delay));
} else {
elizaLogger.error("Max retry attempts reached:", {
error:
error instanceof Error
? error.message
: String(error),
totalAttempts: attempt,
});
throw error instanceof Error
? error
: new Error(String(error));
}
}
}
throw lastError;
}
private async handlePoolError(error: Error) {
elizaLogger.error("Pool error occurred, attempting to reconnect", {
error: error.message,
});
try {
// Close existing pool
await this.pool.end();
// Create new pool
this.pool = new Pool({
...this.pool.options,
connectionTimeoutMillis: this.connectionTimeout,
});
await this.testConnection();
elizaLogger.success("Pool reconnection successful");
} catch (reconnectError) {
elizaLogger.error("Failed to reconnect pool", {
error:
reconnectError instanceof Error
? reconnectError.message
: String(reconnectError),
});
throw reconnectError;
}
}
async query<R extends QueryResultRow = any, I = any[]>(
queryTextOrConfig: string | QueryConfig<I>,
values?: QueryConfigValues<I>
): Promise<QueryResult<R>> {
const client = await this.pool.connect();
try {
return client.query(queryTextOrConfig, values);
} catch (error) {
elizaLogger.error(error);
throw error;
} finally {
client.release();
}
}
async init() {
await this.testConnection();
const client = await this.pool.connect();
try {
await client.query("BEGIN");
// Check if schema already exists (check for a core table)
const { rows } = await client.query(`
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_name = 'rooms'
);
`);
if (!rows[0].exists) {
const schema = fs.readFileSync(
path.resolve(__dirname, "../schema.sql"),
"utf8"
);
await client.query(schema);
}
await client.query("COMMIT");
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
}
async close() {
await this.pool.end();
}
async testConnection(): Promise<boolean> {
let client;
try {
client = await this.pool.connect();
const result = await client.query("SELECT NOW()");
elizaLogger.success(
"Database connection test successful:",
result.rows[0]
);
return true;
} catch (error) {
elizaLogger.error("Database connection test failed:", error);
throw new Error(
`Failed to connect to database: ${(error as Error).message}`
);
} finally {
if (client) client.release();
}
}
async cleanup(): Promise<void> {
try {
await this.pool.end();
elizaLogger.info("Database pool closed");
} catch (error) {
elizaLogger.error("Error closing database pool:", error);
}
}
async getRoom(roomId: UUID): Promise<UUID | null> {
return this.withRetry(async () => {
const { rows } = await this.pool.query(
"SELECT id FROM rooms WHERE id = $1",
[roomId]
);
return rows.length > 0 ? (rows[0].id as UUID) : null;
});
}
async getParticipantsForAccount(userId: UUID): Promise<Participant[]> {
return this.withRetry(async () => {
const { rows } = await this.pool.query(
`SELECT id, "userId", "roomId", "last_message_read"
FROM participants
WHERE "userId" = $1`,
[userId]
);
return rows as Participant[];
});
}
async getParticipantUserState(
roomId: UUID,
userId: UUID
): Promise<"FOLLOWED" | "MUTED" | null> {
return this.withRetry(async () => {
const { rows } = await this.pool.query(
`SELECT "userState" FROM participants WHERE "roomId" = $1 AND "userId" = $2`,
[roomId, userId]
);
return rows.length > 0 ? rows[0].userState : null;
});
}
async getMemoriesByRoomIds(params: {
roomIds: UUID[];
agentId?: UUID;
tableName: string;
}): Promise<Memory[]> {
return this.withRetry(async () => {
if (params.roomIds.length === 0) return [];
const placeholders = params.roomIds
.map((_, i) => `$${i + 2}`)
.join(", ");
let query = `SELECT * FROM memories WHERE type = $1 AND "roomId" IN (${placeholders})`;
let queryParams = [params.tableName, ...params.roomIds];
if (params.agentId) {
query += ` AND "agentId" = $${params.roomIds.length + 2}`;
queryParams = [...queryParams, params.agentId];
}
const { rows } = await this.pool.query(query, queryParams);
return rows.map((row) => ({
...row,
content:
typeof row.content === "string"
? JSON.parse(row.content)
: row.content,
}));
});
}
async setParticipantUserState(
roomId: UUID,
userId: UUID,
state: "FOLLOWED" | "MUTED" | null
): Promise<void> {
return this.withRetry(async () => {
await this.pool.query(
`UPDATE participants SET "userState" = $1 WHERE "roomId" = $2 AND "userId" = $3`,
[state, roomId, userId]
);
});
}
async getParticipantsForRoom(roomId: UUID): Promise<UUID[]> {
return this.withRetry(async () => {
const { rows } = await this.pool.query(
'SELECT "userId" FROM participants WHERE "roomId" = $1',
[roomId]
);
return rows.map((row) => row.userId);
});
}
async getAccountById(userId: UUID): Promise<Account | null> {
return this.withRetry(async () => {
const { rows } = await this.pool.query(
"SELECT * FROM accounts WHERE id = $1",
[userId]
);
if (rows.length === 0) {
elizaLogger.debug("Account not found:", { userId });
return null;
}
const account = rows[0];
// elizaLogger.debug("Account retrieved:", {
// userId,
// hasDetails: !!account.details,
// });
return {
...account,
details:
typeof account.details === "string"
? JSON.parse(account.details)
: account.details,
};
});
}
async createAccount(account: Account): Promise<boolean> {
return this.withRetry(async () => {
try {
const accountId = account.id ?? v4();
await this.pool.query(
`INSERT INTO accounts (id, name, username, email, "avatarUrl", details)
VALUES ($1, $2, $3, $4, $5, $6)`,
[
accountId,
account.name,
account.username || "",
account.email || "",
account.avatarUrl || "",
JSON.stringify(account.details),
]
);
elizaLogger.debug("Account created successfully:", {
accountId,
});
return true;
} catch (error) {
elizaLogger.error("Error creating account:", {
error:
error instanceof Error ? error.message : String(error),
accountId: account.id,
name: account.name, // Only log non-sensitive fields
});
return false; // Return false instead of throwing to maintain existing behavior
}
});
}
async getActorById(params: { roomId: UUID }): Promise<Actor[]> {
return this.withRetry(async () => {
const { rows } = await this.pool.query(
`SELECT a.id, a.name, a.username, a.details
FROM participants p
LEFT JOIN accounts a ON p."userId" = a.id
WHERE p."roomId" = $1`,
[params.roomId]
);
elizaLogger.debug("Retrieved actors:", {
roomId: params.roomId,
actorCount: rows.length,
});
return rows.map((row) => {
try {
return {
...row,
details:
typeof row.details === "string"
? JSON.parse(row.details)
: row.details,
};
} catch (error) {
elizaLogger.warn("Failed to parse actor details:", {
actorId: row.id,
error:
error instanceof Error
? error.message
: String(error),
});
return {
...row,
details: {}, // Provide default empty details on parse error
};
}
});
}).catch((error) => {
elizaLogger.error("Failed to get actors:", {
roomId: params.roomId,
error: error.message,
});
throw error; // Re-throw to let caller handle database errors
});
}
async getMemoryById(id: UUID): Promise<Memory | null> {
return this.withRetry(async () => {
const { rows } = await this.pool.query(
"SELECT * FROM memories WHERE id = $1",
[id]
);
if (rows.length === 0) return null;
return {
...rows[0],
content:
typeof rows[0].content === "string"
? JSON.parse(rows[0].content)
: rows[0].content,
};
});
}
async createMemory(memory: Memory, tableName: string): Promise<void> {
return this.withRetry(async () => {
elizaLogger.debug("PostgresAdapter createMemory:", {
memoryId: memory.id,
embeddingLength: memory.embedding?.length,
contentLength: memory.content?.text?.length,
});
let isUnique = true;
if (memory.embedding) {
const similarMemories = await this.searchMemoriesByEmbedding(
memory.embedding,
{
tableName,
roomId: memory.roomId,
match_threshold: 0.95,
count: 1,
}
);
isUnique = similarMemories.length === 0;
}
await this.pool.query(
`INSERT INTO memories (
id, type, content, embedding, "userId", "roomId", "agentId", "unique", "createdAt"
) VALUES ($1, $2, $3, $4, $5::uuid, $6::uuid, $7::uuid, $8, to_timestamp($9/1000.0))`,
[
memory.id ?? v4(),
tableName,
JSON.stringify(memory.content),
memory.embedding ? `[${memory.embedding.join(",")}]` : null,
memory.userId,
memory.roomId,
memory.agentId,
memory.unique ?? isUnique,
Date.now(),
]
);
});
}
async searchMemories(params: {
tableName: string;
agentId: UUID;
roomId: UUID;
embedding: number[];
match_threshold: number;
match_count: number;
unique: boolean;
}): Promise<Memory[]> {
return await this.searchMemoriesByEmbedding(params.embedding, {
match_threshold: params.match_threshold,
count: params.match_count,
agentId: params.agentId,
roomId: params.roomId,
unique: params.unique,
tableName: params.tableName,
});
}
async getMemories(params: {
roomId: UUID;
count?: number;
unique?: boolean;
tableName: string;
agentId?: UUID;
start?: number;
end?: number;
}): Promise<Memory[]> {
// Parameter validation
if (!params.tableName) throw new Error("tableName is required");
if (!params.roomId) throw new Error("roomId is required");
return this.withRetry(async () => {
// Build query
let sql = `SELECT * FROM memories WHERE type = $1 AND "roomId" = $2`;
const values: any[] = [params.tableName, params.roomId];
let paramCount = 2;
// Add time range filters
if (params.start) {
paramCount++;
sql += ` AND "createdAt" >= to_timestamp($${paramCount})`;
values.push(params.start / 1000);
}
if (params.end) {
paramCount++;
sql += ` AND "createdAt" <= to_timestamp($${paramCount})`;
values.push(params.end / 1000);
}
// Add other filters
if (params.unique) {
sql += ` AND "unique" = true`;
}
if (params.agentId) {
paramCount++;
sql += ` AND "agentId" = $${paramCount}`;
values.push(params.agentId);
}
// Add ordering and limit
sql += ' ORDER BY "createdAt" DESC';
if (params.count) {
paramCount++;
sql += ` LIMIT $${paramCount}`;
values.push(params.count);
}
elizaLogger.debug("Fetching memories:", {
roomId: params.roomId,
tableName: params.tableName,
unique: params.unique,
agentId: params.agentId,
timeRange:
params.start || params.end
? {
start: params.start
? new Date(params.start).toISOString()
: undefined,
end: params.end
? new Date(params.end).toISOString()
: undefined,
}
: undefined,
limit: params.count,
});
const { rows } = await this.pool.query(sql, values);
return rows.map((row) => ({
...row,
content:
typeof row.content === "string"
? JSON.parse(row.content)
: row.content,
}));
});
}
async getGoals(params: {
roomId: UUID;
userId?: UUID | null;
onlyInProgress?: boolean;
count?: number;
}): Promise<Goal[]> {
return this.withRetry(async () => {
let sql = `SELECT * FROM goals WHERE "roomId" = $1`;
const values: any[] = [params.roomId];
let paramCount = 1;
if (params.userId) {
paramCount++;
sql += ` AND "userId" = $${paramCount}`;
values.push(params.userId);
}
if (params.onlyInProgress) {
sql += " AND status = 'IN_PROGRESS'";
}
if (params.count) {
paramCount++;
sql += ` LIMIT $${paramCount}`;
values.push(params.count);
}
const { rows } = await this.pool.query(sql, values);
return rows.map((row) => ({
...row,
objectives:
typeof row.objectives === "string"
? JSON.parse(row.objectives)
: row.objectives,
}));
});
}
async updateGoal(goal: Goal): Promise<void> {
return this.withRetry(async () => {
try {
await this.pool.query(
`UPDATE goals SET name = $1, status = $2, objectives = $3 WHERE id = $4`,
[
goal.name,
goal.status,
JSON.stringify(goal.objectives),
goal.id,
]
);
} catch (error) {
elizaLogger.error("Failed to update goal:", {
goalId: goal.id,
error:
error instanceof Error ? error.message : String(error),
status: goal.status,
});
throw error;
}
});
}
async createGoal(goal: Goal): Promise<void> {
return this.withRetry(async () => {
await this.pool.query(
`INSERT INTO goals (id, "roomId", "userId", name, status, objectives)
VALUES ($1, $2, $3, $4, $5, $6)`,
[
goal.id ?? v4(),
goal.roomId,
goal.userId,
goal.name,
goal.status,
JSON.stringify(goal.objectives),
]
);
});
}
async removeGoal(goalId: UUID): Promise<void> {
if (!goalId) throw new Error("Goal ID is required");
return this.withRetry(async () => {
try {
const result = await this.pool.query(
"DELETE FROM goals WHERE id = $1 RETURNING id",
[goalId]
);
elizaLogger.debug("Goal removal attempt:", {
goalId,
removed: result?.rowCount ?? 0 > 0,
});
} catch (error) {
elizaLogger.error("Failed to remove goal:", {
goalId,
error:
error instanceof Error ? error.message : String(error),
});
throw error;
}
});
}
async createRoom(roomId?: UUID): Promise<UUID> {
return this.withRetry(async () => {
const newRoomId = roomId || v4();
await this.pool.query("INSERT INTO rooms (id) VALUES ($1)", [
newRoomId,
]);
return newRoomId as UUID;
});
}
async removeRoom(roomId: UUID): Promise<void> {
if (!roomId) throw new Error("Room ID is required");
return this.withRetry(async () => {
const client = await this.pool.connect();
try {
await client.query("BEGIN");
// First check if room exists
const checkResult = await client.query(
"SELECT id FROM rooms WHERE id = $1",
[roomId]
);
if (checkResult.rowCount === 0) {
elizaLogger.warn("No room found to remove:", { roomId });
throw new Error(`Room not found: ${roomId}`);
}
// Remove related data first (if not using CASCADE)
await client.query('DELETE FROM memories WHERE "roomId" = $1', [
roomId,
]);
await client.query(
'DELETE FROM participants WHERE "roomId" = $1',
[roomId]
);
await client.query('DELETE FROM goals WHERE "roomId" = $1', [
roomId,
]);
// Finally remove the room
const result = await client.query(
"DELETE FROM rooms WHERE id = $1 RETURNING id",
[roomId]
);
await client.query("COMMIT");
elizaLogger.debug(
"Room and related data removed successfully:",
{
roomId,
removed: result?.rowCount ?? 0 > 0,
}
);
} catch (error) {
await client.query("ROLLBACK");
elizaLogger.error("Failed to remove room:", {
roomId,
error:
error instanceof Error ? error.message : String(error),
});
throw error;
} finally {
client.release();
}
});
}
async createRelationship(params: {
userA: UUID;
userB: UUID;
}): Promise<boolean> {
// Input validation
if (!params.userA || !params.userB) {
throw new Error("userA and userB are required");
}
return this.withRetry(async () => {
try {
const relationshipId = v4();
await this.pool.query(
`INSERT INTO relationships (id, "userA", "userB", "userId")
VALUES ($1, $2, $3, $4)
RETURNING id`,
[relationshipId, params.userA, params.userB, params.userA]
);
elizaLogger.debug("Relationship created successfully:", {
relationshipId,
userA: params.userA,
userB: params.userB,
});
return true;
} catch (error) {
// Check for unique constraint violation or other specific errors
if ((error as { code?: string }).code === "23505") {
// Unique violation
elizaLogger.warn("Relationship already exists:", {
userA: params.userA,
userB: params.userB,
error:
error instanceof Error
? error.message
: String(error),
});
} else {
elizaLogger.error("Failed to create relationship:", {
userA: params.userA,
userB: params.userB,
error:
error instanceof Error
? error.message
: String(error),
});
}
return false;
}
});
}
async getRelationship(params: {
userA: UUID;
userB: UUID;
}): Promise<Relationship | null> {
if (!params.userA || !params.userB) {
throw new Error("userA and userB are required");
}
return this.withRetry(async () => {
try {
const { rows } = await this.pool.query(
`SELECT * FROM relationships
WHERE ("userA" = $1 AND "userB" = $2)
OR ("userA" = $2 AND "userB" = $1)`,
[params.userA, params.userB]
);
if (rows.length > 0) {
elizaLogger.debug("Relationship found:", {
relationshipId: rows[0].id,
userA: params.userA,
userB: params.userB,
});
return rows[0];
}
elizaLogger.debug("No relationship found between users:", {
userA: params.userA,
userB: params.userB,
});
return null;
} catch (error) {
elizaLogger.error("Error fetching relationship:", {
userA: params.userA,
userB: params.userB,
error:
error instanceof Error ? error.message : String(error),
});
throw error;
}
});
}
async getRelationships(params: { userId: UUID }): Promise<Relationship[]> {
if (!params.userId) {
throw new Error("userId is required");
}
return this.withRetry(async () => {
try {
const { rows } = await this.pool.query(
`SELECT * FROM relationships
WHERE "userA" = $1 OR "userB" = $1
ORDER BY "createdAt" DESC`, // Add ordering if you have this field
[params.userId]
);
elizaLogger.debug("Retrieved relationships:", {
userId: params.userId,
count: rows.length,
});
return rows;
} catch (error) {
elizaLogger.error("Failed to fetch relationships:", {
userId: params.userId,
error:
error instanceof Error ? error.message : String(error),
});
throw error;
}
});
}
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 }[]> {
// Input validation
if (!opts.query_table_name)
throw new Error("query_table_name is required");
if (!opts.query_input) throw new Error("query_input is required");
if (!opts.query_field_name)
throw new Error("query_field_name is required");
if (!opts.query_field_sub_name)
throw new Error("query_field_sub_name is required");
if (opts.query_match_count <= 0)
throw new Error("query_match_count must be positive");
return this.withRetry(async () => {
try {
elizaLogger.debug("Fetching cached embeddings:", {
tableName: opts.query_table_name,
fieldName: opts.query_field_name,
subFieldName: opts.query_field_sub_name,
matchCount: opts.query_match_count,
inputLength: opts.query_input.length,
});
const sql = `
WITH content_text AS (
SELECT
embedding,
COALESCE(
content->$2->>$3,
''
) as content_text
FROM memories
WHERE type = $4
AND content->$2->>$3 IS NOT NULL
)
SELECT
embedding,
levenshtein(
$1,
content_text
) as levenshtein_score
FROM content_text
WHERE levenshtein(
$1,
content_text
) <= $6 -- Add threshold check
ORDER BY levenshtein_score
LIMIT $5
`;
const { rows } = await this.pool.query(sql, [
opts.query_input,
opts.query_field_name,
opts.query_field_sub_name,
opts.query_table_name,
opts.query_match_count,
opts.query_threshold,
]);
elizaLogger.debug("Retrieved cached embeddings:", {
count: rows.length,
tableName: opts.query_table_name,
matchCount: opts.query_match_count,
});
return rows
.map(
(
row
): {
embedding: number[];
levenshtein_score: number;
} | null => {
if (!Array.isArray(row.embedding)) return null;
return {
embedding: row.embedding,
levenshtein_score: Number(
row.levenshtein_score
),
};
}
)
.filter(
(
row
): row is {
embedding: number[];
levenshtein_score: number;
} => row !== null
);
} catch (error) {
elizaLogger.error("Error in getCachedEmbeddings:", {
error:
error instanceof Error ? error.message : String(error),
tableName: opts.query_table_name,
fieldName: opts.query_field_name,
});
throw error;
}
});
}