forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbase.ts
2457 lines (2209 loc) · 83.5 KB
/
base.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 {
type Agent,
type Component,
DatabaseAdapter,
type Entity,
type Memory,
type MemoryMetadata,
type Participant,
type Relationship,
type Room,
type Task,
type UUID,
type World,
type Log,
logger,
} from '@elizaos/core';
import {
Column,
and,
cosineDistance,
count,
desc,
eq,
gte,
inArray,
lte,
or,
sql,
not,
} from 'drizzle-orm';
import { v4 } from 'uuid';
import { DIMENSION_MAP, type EmbeddingDimensionColumn } from './schema/embedding';
import {
agentTable,
cacheTable,
componentTable,
embeddingTable,
entityTable,
logTable,
memoryTable,
participantTable,
relationshipTable,
roomTable,
taskTable,
worldTable,
} from './schema/index';
import type { DrizzleOperations } from './types';
// Define the metadata type inline since we can't import it
/**
* Represents metadata information about memory.
* @typedef {Object} MemoryMetadata
* @property {string} type - The type of memory.
* @property {string} [source] - The source of the memory.
* @property {UUID} [sourceId] - The ID of the source.
* @property {string} [scope] - The scope of the memory.
* @property {number} [timestamp] - The timestamp of the memory.
* @property {string[]} [tags] - The tags associated with the memory.
* @property {UUID} [documentId] - The ID of the document associated with the memory.
* @property {number} [position] - The position of the memory.
*/
/**
* Abstract class representing a base Drizzle adapter for working with databases.
* This adapter provides a comprehensive set of methods for interacting with a database
* using Drizzle ORM. It implements the DatabaseAdapter interface and handles operations
* for various entity types including agents, entities, components, memories, rooms,
* participants, relationships, tasks, and more.
*
* The adapter includes built-in retry logic for database operations, embedding dimension
* management, and transaction support. Concrete implementations must provide the
* withDatabase method to execute operations against their specific database.
*
* @template TDatabase - The type of Drizzle operations supported by the adapter.
*/
export abstract class BaseDrizzleAdapter<
TDatabase extends DrizzleOperations,
> extends DatabaseAdapter<TDatabase> {
protected readonly maxRetries: number = 3;
protected readonly baseDelay: number = 1000;
protected readonly maxDelay: number = 10000;
protected readonly jitterMax: number = 1000;
protected embeddingDimension: EmbeddingDimensionColumn = DIMENSION_MAP[384];
protected abstract withDatabase<T>(operation: () => Promise<T>): Promise<T>;
public abstract init(): Promise<void>;
public abstract close(): Promise<void>;
protected agentId: UUID;
/**
* Constructor for creating a new instance of Agent with the specified agentId.
*
* @param {UUID} agentId - The unique identifier for the agent.
*/
constructor(agentId: UUID) {
super();
this.agentId = agentId;
}
/**
* Executes the given operation with retry logic.
* @template T
* @param {() => Promise<T>} operation - The operation to be executed.
* @returns {Promise<T>} A promise that resolves with the result of the operation.
*/
protected async withRetry<T>(operation: () => Promise<T>): Promise<T> {
let lastError: Error = new Error('Unknown error');
for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
try {
return await operation();
} catch (error) {
lastError = error as Error;
if (attempt < this.maxRetries) {
const backoffDelay = Math.min(this.baseDelay * 2 ** (attempt - 1), this.maxDelay);
const jitter = Math.random() * this.jitterMax;
const delay = backoffDelay + jitter;
logger.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 {
logger.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;
}
/**
* Asynchronously ensures that an agent exists by checking if an agent with the same name already exists in the system.
* If the agent does not exist, it will be created with the provided data.
*
* @param {Partial<Agent>} agent - The partial data of the agent to ensure its existence.
* @returns {Promise<void>} - A promise that resolves when the agent is successfully ensured.
* @throws {Error} - If the agent name is not provided or if there is an issue creating the agent.
*/
async ensureAgentExists(agent: Partial<Agent>): Promise<void> {
if (!agent.name) {
throw new Error('Agent name is required');
}
const agents = await this.getAgents();
const existingAgent = agents.find(
(a: Partial<Agent & { status: string }>) => a.name === agent.name
);
if (!existingAgent) {
await this.createAgent(agent);
}
}
/**
* Asynchronously ensures that the given embedding dimension is valid for the agent.
*
* @param {number} dimension - The dimension to ensure for the embedding.
* @returns {Promise<void>} - Resolves once the embedding dimension is ensured.
*/
async ensureEmbeddingDimension(dimension: number) {
const existingMemory = await this.db
.select({
embedding: embeddingTable,
})
.from(memoryTable)
.innerJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id))
.where(eq(memoryTable.agentId, this.agentId))
.limit(1);
if (existingMemory.length > 0) {
const usedDimension = Object.entries(DIMENSION_MAP).find(
([_, colName]) => existingMemory[0].embedding[colName] !== null
);
}
this.embeddingDimension = DIMENSION_MAP[dimension];
}
/**
* Asynchronously retrieves an agent by their ID from the database.
* @param {UUID} agentId - The ID of the agent to retrieve.
* @returns {Promise<Agent | null>} A promise that resolves to the retrieved agent or null if not found.
*/
async getAgent(agentId: UUID): Promise<Agent | null> {
return this.withDatabase(async () => {
const result = await this.db
.select()
.from(agentTable)
.where(eq(agentTable.id, agentId))
.limit(1);
if (result.length === 0) return null;
return result[0];
});
}
/**
* Asynchronously retrieves a list of agents from the database.
*
* @returns {Promise<Agent[]>} A Promise that resolves to an array of Agent objects.
*/
async getAgents(): Promise<Agent[]> {
return this.withDatabase(async () => {
const result = await this.db.select().from(agentTable);
return result;
});
}
/**
* Asynchronously creates a new agent record in the database.
*
* @param {Partial<Agent>} agent The agent object to be created.
* @returns {Promise<boolean>} A promise that resolves to a boolean indicating the success of the operation.
*/
async createAgent(agent: Partial<Agent>): Promise<boolean> {
return this.withDatabase(async () => {
try {
await this.db.transaction(async (tx) => {
await tx.insert(agentTable).values({
...agent,
});
});
logger.debug('Agent created successfully:', {
agentId: agent.id,
});
return true;
} catch (error) {
logger.error('Error creating agent:', {
error: error instanceof Error ? error.message : String(error),
agentId: agent.id,
agent,
});
return false;
}
});
}
/**
* Validates the agent update request
* @param agentId The ID of the agent to update
* @param agent The agent data to validate
* @throws Error if validation fails
*/
private validateAgentUpdate(agentId: UUID, agent: Partial<Agent>): void {
if (!agent.id) {
throw new Error('Agent ID is required for update');
}
}
/**
* Merges nested JSONb objects within the agent settings
* @param existingAgent The current agent data
* @param updates The updates to apply
* @returns Merged settings object
*/
private mergeAgentSettings(existingAgent: Agent, updates: Partial<Agent>): Agent['settings'] {
if (!updates.settings || !existingAgent.settings) {
return updates.settings || existingAgent.settings;
}
const mergedSettings = {
...existingAgent.settings,
...updates.settings,
};
// Handle nested secrets within settings
if (updates.settings.secrets && existingAgent.settings.secrets) {
mergedSettings.secrets = {
...existingAgent.settings.secrets,
...updates.settings.secrets,
};
}
return mergedSettings;
}
/**
* Merges style-related fields, handling arrays appropriately
* @param existingAgent The current agent data
* @param updates The updates to apply
* @returns Merged style object
*/
private mergeAgentStyle(existingAgent: Agent, updates: Partial<Agent>): Agent['style'] {
if (!updates.style) {
return existingAgent.style;
}
return {
...existingAgent.style,
...updates.style,
};
}
/**
* Merges array fields, replacing them entirely if provided
* @param existingAgent The current agent data
* @param updates The updates to apply
* @returns Object containing merged array fields
*/
private mergeArrayFields(existingAgent: Agent, updates: Partial<Agent>): Partial<Agent> {
const mergedFields: Partial<Agent> = {};
// Handle array JSONb fields - these should be replaced entirely if provided
if (updates.plugins !== undefined) mergedFields.plugins = updates.plugins;
if (updates.bio !== undefined) mergedFields.bio = updates.bio;
if (updates.topics !== undefined) mergedFields.topics = updates.topics;
if (updates.adjectives !== undefined) mergedFields.adjectives = updates.adjectives;
if (updates.knowledge !== undefined) mergedFields.knowledge = updates.knowledge;
return mergedFields;
}
/**
* Updates an agent in the database with the provided agent ID and data.
* Properly handles merging of nested JSONb fields.
*
* @param {UUID} agentId - The unique identifier of the agent to update.
* @param {Partial<Agent>} agent - The partial agent object containing the fields to update.
* @returns {Promise<boolean>} - A boolean indicating if the agent was successfully updated.
*/
async updateAgent(agentId: UUID, agent: Partial<Agent>): Promise<boolean> {
return this.withDatabase(async () => {
try {
this.validateAgentUpdate(agentId, agent);
// Get the existing agent to properly merge JSONb fields
const existingAgent = await this.getAgent(agentId);
if (!existingAgent) {
throw new Error(`Agent with ID ${agentId} not found`);
}
// Merge all fields using helper functions
const mergedAgent: Partial<Agent> = {
...existingAgent,
...agent,
updatedAt: Date.now(),
settings: this.mergeAgentSettings(existingAgent, agent),
style: this.mergeAgentStyle(existingAgent, agent),
...this.mergeArrayFields(existingAgent, agent),
};
await this.db.transaction(async (tx) => {
await tx.update(agentTable).set(mergedAgent).where(eq(agentTable.id, agentId));
});
logger.debug('Agent updated successfully:', {
agentId,
});
return true;
} catch (error) {
logger.error('Error updating agent:', {
error: error instanceof Error ? error.message : String(error),
agentId,
agent,
});
return false;
}
});
}
/**
* Asynchronously deletes an agent with the specified UUID and all related entries.
*
* @param {UUID} agentId - The UUID of the agent to be deleted.
* @returns {Promise<boolean>} - A boolean indicating if the deletion was successful.
*/
async deleteAgent(agentId: UUID): Promise<boolean> {
return this.withDatabase(async () => {
await this.db.transaction(async (tx) => {
const entities = await this.db
.select({ entityId: entityTable.id })
.from(entityTable)
.where(eq(entityTable.agentId, agentId));
const entityIds = entities.map((e) => e.entityId);
let memoryIds: UUID[] = [];
if (entityIds.length > 0) {
const entityMemories = await this.db
.select({ memoryId: memoryTable.id })
.from(memoryTable)
.where(inArray(memoryTable.entityId, entityIds));
memoryIds = entityMemories.map((m) => m.memoryId);
}
const agentMemories = await this.db
.select({ memoryId: memoryTable.id })
.from(memoryTable)
.where(eq(memoryTable.agentId, agentId));
memoryIds.push(...agentMemories.map((m) => m.memoryId));
if (memoryIds.length > 0) {
await tx.delete(embeddingTable).where(inArray(embeddingTable.memoryId, memoryIds));
await tx.delete(memoryTable).where(inArray(memoryTable.id, memoryIds));
}
const rooms = await this.db
.select({ roomId: roomTable.id })
.from(roomTable)
.where(eq(roomTable.agentId, agentId));
const roomIds = rooms.map((r) => r.roomId);
if (entityIds.length > 0) {
await tx.delete(logTable).where(inArray(logTable.entityId, entityIds));
await tx.delete(participantTable).where(inArray(participantTable.entityId, entityIds));
}
if (roomIds.length > 0) {
await tx.delete(logTable).where(inArray(logTable.roomId, roomIds));
await tx.delete(participantTable).where(inArray(participantTable.roomId, roomIds));
}
await tx.delete(participantTable).where(eq(participantTable.agentId, agentId));
if (roomIds.length > 0) {
await tx.delete(roomTable).where(inArray(roomTable.id, roomIds));
}
await tx.delete(cacheTable).where(eq(cacheTable.agentId, agentId));
await tx.delete(relationshipTable).where(eq(relationshipTable.agentId, agentId));
await tx.delete(entityTable).where(eq(entityTable.agentId, agentId));
const newAgent = await this.db
.select({ newAgentId: agentTable.id })
.from(agentTable)
.where(not(eq(agentTable.id, agentId)))
.limit(1);
if (newAgent.length > 0) {
await tx
.update(worldTable)
.set({ agentId: newAgent[0].newAgentId })
.where(eq(worldTable.agentId, agentId));
} else {
await tx.delete(worldTable).where(eq(worldTable.agentId, agentId));
}
await tx.delete(agentTable).where(eq(agentTable.id, agentId));
});
return true;
});
}
/**
* Count all agents in the database
* Used primarily for maintenance and cleanup operations
*/
/**
* Asynchronously counts the number of agents in the database.
* @returns {Promise<number>} A Promise that resolves to the number of agents in the database.
*/
async countAgents(): Promise<number> {
return this.withDatabase(async () => {
try {
const result = await this.db.select({ count: count() }).from(agentTable);
return result[0]?.count || 0;
} catch (error) {
logger.error('Error counting agents:', {
error: error instanceof Error ? error.message : String(error),
});
return 0;
}
});
}
/**
* Clean up the agents table by removing all agents
* This is used during server startup to ensure no orphaned agents exist
* from previous crashes or improper shutdowns
*/
async cleanupAgents(): Promise<void> {
return this.withDatabase(async () => {
try {
await this.db.delete(agentTable);
logger.success('Successfully cleaned up agent table');
} catch (error) {
logger.error('Error cleaning up agent table:', {
error: error instanceof Error ? error.message : String(error),
});
throw error;
}
});
}
/**
* Asynchronously retrieves an entity and its components by entity ID.
* @param {UUID} entityId - The unique identifier of the entity to retrieve.
* @returns {Promise<Entity | null>} A Promise that resolves to the entity with its components if found, null otherwise.
*/
async getEntityById(entityId: UUID): Promise<Entity | null> {
return this.withDatabase(async () => {
const result = await this.db
.select({
entity: entityTable,
components: componentTable,
})
.from(entityTable)
.leftJoin(componentTable, eq(componentTable.entityId, entityTable.id))
.where(and(eq(entityTable.id, entityId), eq(entityTable.agentId, this.agentId)));
if (result.length === 0) return null;
// Group components by entity
const entity = result[0].entity;
entity.components = result.filter((row) => row.components).map((row) => row.components);
return entity;
});
}
/**
* Asynchronously retrieves all entities for a given room, optionally including their components.
* @param {UUID} roomId - The unique identifier of the room to get entities for
* @param {boolean} [includeComponents] - Whether to include component data for each entity
* @returns {Promise<Entity[]>} A Promise that resolves to an array of entities in the room
*/
async getEntitiesForRoom(roomId: UUID, includeComponents?: boolean): Promise<Entity[]> {
return this.withDatabase(async () => {
const query = this.db
.select({
entity: entityTable,
...(includeComponents && { components: componentTable }),
})
.from(participantTable)
.leftJoin(
entityTable,
and(eq(participantTable.entityId, entityTable.id), eq(entityTable.agentId, this.agentId))
);
if (includeComponents) {
query.leftJoin(componentTable, eq(componentTable.entityId, entityTable.id));
}
const result = await query.where(eq(participantTable.roomId, roomId));
// Group components by entity if includeComponents is true
const entitiesByIdMap = new Map<UUID, Entity>();
for (const row of result) {
if (!row.entity) continue;
const entityId = row.entity.id as UUID;
if (!entitiesByIdMap.has(entityId)) {
const entity: Entity = {
...row.entity,
components: includeComponents ? [] : undefined,
};
entitiesByIdMap.set(entityId, entity);
}
if (includeComponents && row.components) {
const entity = entitiesByIdMap.get(entityId);
if (entity) {
if (!entity.components) {
entity.components = [];
}
entity.components.push(row.components);
}
}
}
return Array.from(entitiesByIdMap.values());
});
}
/**
* Asynchronously creates a new entity in the database.
* @param {Entity} entity - The entity object to be created.
* @returns {Promise<boolean>} A Promise that resolves to a boolean indicating the success of the operation.
*/
async createEntity(entity: Entity): Promise<boolean> {
return this.withDatabase(async () => {
try {
return await this.db.transaction(async (tx) => {
await tx.insert(entityTable).values(entity);
logger.debug('Entity created successfully:', {
entity,
});
return true;
});
} catch (error) {
logger.error('Error creating entity:', {
error: error instanceof Error ? error.message : String(error),
entityId: entity.id,
name: entity.metadata?.name,
});
// trace the error
logger.trace(error);
return false;
}
});
}
/**
* Asynchronously ensures an entity exists, creating it if it doesn't
* @param entity The entity to ensure exists
* @returns Promise resolving to boolean indicating success
*/
protected async ensureEntityExists(entity: Entity): Promise<boolean> {
if (!entity.id) {
logger.error('Entity ID is required for ensureEntityExists');
return false;
}
try {
const existingEntity = await this.getEntityById(entity.id);
if (!existingEntity) {
return await this.createEntity(entity);
}
return true;
} catch (error) {
logger.error('Error ensuring entity exists:', {
error: error instanceof Error ? error.message : String(error),
entityId: entity.id,
});
return false;
}
}
/**
* Asynchronously updates an entity in the database.
* @param {Entity} entity - The entity object to be updated.
* @returns {Promise<void>} A Promise that resolves when the entity is updated.
*/
async updateEntity(entity: Entity): Promise<void> {
return this.withDatabase(async () => {
await this.db
.update(entityTable)
.set(entity)
.where(and(eq(entityTable.id, entity.id as UUID), eq(entityTable.agentId, entity.agentId)));
});
}
async getComponent(
entityId: UUID,
type: string,
worldId?: UUID,
sourceEntityId?: UUID
): Promise<Component | null> {
return this.withDatabase(async () => {
const conditions = [eq(componentTable.entityId, entityId), eq(componentTable.type, type)];
if (worldId) {
conditions.push(eq(componentTable.worldId, worldId));
}
if (sourceEntityId) {
conditions.push(eq(componentTable.sourceEntityId, sourceEntityId));
}
const result = await this.db
.select()
.from(componentTable)
.where(and(...conditions));
return result.length > 0 ? result[0] : null;
});
}
/**
* Asynchronously retrieves all components for a given entity, optionally filtered by world and source entity.
* @param {UUID} entityId - The unique identifier of the entity to retrieve components for
* @param {UUID} [worldId] - Optional world ID to filter components by
* @param {UUID} [sourceEntityId] - Optional source entity ID to filter components by
* @returns {Promise<Component[]>} A Promise that resolves to an array of components
*/
async getComponents(entityId: UUID, worldId?: UUID, sourceEntityId?: UUID): Promise<Component[]> {
return this.withDatabase(async () => {
const conditions = [eq(componentTable.entityId, entityId)];
if (worldId) {
conditions.push(eq(componentTable.worldId, worldId));
}
if (sourceEntityId) {
conditions.push(eq(componentTable.sourceEntityId, sourceEntityId));
}
const result = await this.db
.select({
id: componentTable.id,
entityId: componentTable.entityId,
type: componentTable.type,
data: componentTable.data,
worldId: componentTable.worldId,
sourceEntityId: componentTable.sourceEntityId,
createdAt: componentTable.createdAt,
})
.from(componentTable)
.where(and(...conditions));
return result;
});
}
/**
* Asynchronously creates a new component in the database.
* @param {Component} component - The component object to be created.
* @returns {Promise<boolean>} A Promise that resolves to a boolean indicating the success of the operation.
*/
async createComponent(component: Component): Promise<boolean> {
return this.withDatabase(async () => {
await this.db.insert(componentTable).values(component);
return true;
});
}
/**
* Asynchronously updates an existing component in the database.
* @param {Component} component - The component object to be updated.
* @returns {Promise<void>} A Promise that resolves when the component is updated.
*/
async updateComponent(component: Component): Promise<void> {
return this.withDatabase(async () => {
await this.db
.update(componentTable)
.set(component)
.where(eq(componentTable.id, component.id));
});
}
/**
* Asynchronously deletes a component from the database.
* @param {UUID} componentId - The unique identifier of the component to delete.
* @returns {Promise<void>} A Promise that resolves when the component is deleted.
*/
async deleteComponent(componentId: UUID): Promise<void> {
return this.withDatabase(async () => {
await this.db.delete(componentTable).where(eq(componentTable.id, componentId));
});
}
/**
* Asynchronously retrieves memories from the database based on the provided parameters.
* @param {Object} params - The parameters for retrieving memories.
* @param {UUID} params.roomId - The ID of the room to retrieve memories for.
* @param {number} [params.count] - The maximum number of memories to retrieve.
* @param {boolean} [params.unique] - Whether to retrieve unique memories only.
* @param {string} [params.tableName] - The name of the table to retrieve memories from.
* @param {number} [params.start] - The start date to retrieve memories from.
* @param {number} [params.end] - The end date to retrieve memories from.
* @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.
*/
async getMemories(params: {
entityId?: UUID;
agentId?: UUID;
roomId?: UUID;
count?: number;
unique?: boolean;
tableName: string;
start?: number;
end?: number;
}): Promise<Memory[]> {
const { entityId, agentId, roomId, tableName, count, unique, start, end } = params;
if (!tableName) throw new Error('tableName is required');
if (!roomId && !entityId && !agentId)
throw new Error('roomId, entityId, or agentId is required');
return this.withDatabase(async () => {
const conditions = [eq(memoryTable.type, tableName)];
if (start) {
conditions.push(gte(memoryTable.createdAt, start));
}
if (entityId) {
conditions.push(eq(memoryTable.entityId, entityId));
}
if (roomId) {
conditions.push(eq(memoryTable.roomId, roomId));
}
if (end) {
conditions.push(lte(memoryTable.createdAt, end));
}
if (unique) {
conditions.push(eq(memoryTable.unique, true));
}
if (agentId) {
conditions.push(eq(memoryTable.agentId, agentId));
}
const query = this.db
.select({
memory: {
id: memoryTable.id,
type: memoryTable.type,
createdAt: memoryTable.createdAt,
content: memoryTable.content,
entityId: memoryTable.entityId,
agentId: memoryTable.agentId,
roomId: memoryTable.roomId,
unique: memoryTable.unique,
metadata: memoryTable.metadata,
},
embedding: embeddingTable[this.embeddingDimension],
})
.from(memoryTable)
.leftJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id))
.where(and(...conditions))
.orderBy(desc(memoryTable.createdAt));
const rows = params.count ? await query.limit(params.count) : await query;
return rows.map((row) => ({
id: row.memory.id as UUID,
type: row.memory.type,
createdAt: row.memory.createdAt,
content:
typeof row.memory.content === 'string'
? JSON.parse(row.memory.content)
: row.memory.content,
entityId: row.memory.entityId as UUID,
agentId: row.memory.agentId as UUID,
roomId: row.memory.roomId as UUID,
unique: row.memory.unique,
metadata: row.memory.metadata,
embedding: row.embedding ? Array.from(row.embedding) : undefined,
}));
});
}
/**
* Asynchronously retrieves memories from the database based on the provided parameters.
* @param {Object} params - The parameters for retrieving memories.
* @param {UUID[]} params.roomIds - The IDs of the rooms to retrieve memories for.
* @param {string} params.tableName - The name of the table to retrieve memories from.
* @param {number} [params.limit] - The maximum number of memories to retrieve.
* @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.
*/
async getMemoriesByRoomIds(params: {
roomIds: UUID[];
tableName: string;
limit?: number;
}): Promise<Memory[]> {
return this.withDatabase(async () => {
if (params.roomIds.length === 0) return [];
const conditions = [
eq(memoryTable.type, params.tableName),
inArray(memoryTable.roomId, params.roomIds),
];
conditions.push(eq(memoryTable.agentId, this.agentId));
const query = this.db
.select({
id: memoryTable.id,
type: memoryTable.type,
createdAt: memoryTable.createdAt,
content: memoryTable.content,
entityId: memoryTable.entityId,
agentId: memoryTable.agentId,
roomId: memoryTable.roomId,
unique: memoryTable.unique,
metadata: memoryTable.metadata,
})
.from(memoryTable)
.where(and(...conditions))
.orderBy(desc(memoryTable.createdAt));
const rows = params.limit ? await query.limit(params.limit) : await query;
return rows.map((row) => ({
id: row.id as UUID,
createdAt: row.createdAt,
content: typeof row.content === 'string' ? JSON.parse(row.content) : row.content,
entityId: row.entityId as UUID,
agentId: row.agentId as UUID,
roomId: row.roomId as UUID,
unique: row.unique,
metadata: row.metadata,
})) as Memory[];
});
}
/**
* Asynchronously retrieves a memory by its unique identifier.
* @param {UUID} id - The unique identifier of the memory to retrieve.
* @returns {Promise<Memory | null>} A Promise that resolves to the memory if found, null otherwise.
*/
async getMemoryById(id: UUID): Promise<Memory | null> {
return this.withDatabase(async () => {
const result = await this.db
.select({
memory: memoryTable,
embedding: embeddingTable[this.embeddingDimension],
})
.from(memoryTable)
.leftJoin(embeddingTable, eq(memoryTable.id, embeddingTable.memoryId))
.where(eq(memoryTable.id, id))
.limit(1);
if (result.length === 0) return null;
const row = result[0];
return {
id: row.memory.id as UUID,
createdAt: row.memory.createdAt,
content:
typeof row.memory.content === 'string'
? JSON.parse(row.memory.content)
: row.memory.content,
entityId: row.memory.entityId as UUID,
agentId: row.memory.agentId as UUID,
roomId: row.memory.roomId as UUID,
unique: row.memory.unique,
embedding: row.embedding ?? undefined,
};
});
}
/**
* Asynchronously retrieves memories from the database based on the provided parameters.
* @param {Object} params - The parameters for retrieving memories.
* @param {UUID[]} params.memoryIds - The IDs of the memories to retrieve.
* @param {string} [params.tableName] - The name of the table to retrieve memories from.
* @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.
*/
async getMemoriesByIds(memoryIds: UUID[], tableName?: string): Promise<Memory[]> {
return this.withDatabase(async () => {
if (memoryIds.length === 0) return [];
const conditions = [inArray(memoryTable.id, memoryIds)];
if (tableName) {
conditions.push(eq(memoryTable.type, tableName));
}
const rows = await this.db
.select({
memory: memoryTable,
embedding: embeddingTable[this.embeddingDimension],
})
.from(memoryTable)
.leftJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id))
.where(and(...conditions))
.orderBy(desc(memoryTable.createdAt));
return rows.map((row) => ({
id: row.memory.id as UUID,
createdAt: row.memory.createdAt,
content:
typeof row.memory.content === 'string'
? JSON.parse(row.memory.content)
: row.memory.content,
entityId: row.memory.entityId as UUID,
agentId: row.memory.agentId as UUID,
roomId: row.memory.roomId as UUID,
unique: row.memory.unique,
metadata: row.memory.metadata,
embedding: row.embedding ?? undefined,
}));
});
}
/**
* Asynchronously retrieves cached embeddings from the database based on the provided parameters.
* @param {Object} opts - The parameters for retrieving cached embeddings.
* @param {string} opts.query_table_name - The name of the table to retrieve embeddings from.
* @param {number} opts.query_threshold - The threshold for the levenshtein distance.
* @param {string} opts.query_input - The input string to search for.
* @param {string} opts.query_field_name - The name of the field to retrieve embeddings from.
* @param {string} opts.query_field_sub_name - The name of the sub-field to retrieve embeddings from.
* @param {number} opts.query_match_count - The maximum number of matches to retrieve.
* @returns {Promise<{ embedding: number[]; levenshtein_score: number }[]>} A Promise that resolves to an array of cached embeddings.
*/
async getCachedEmbeddings(opts: {
query_table_name: string;
query_threshold: number;
query_input: string;
query_field_name: string;
query_field_sub_name: string;