forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore_src.txt
More file actions
11681 lines (10400 loc) · 375 KB
/
Copy pathcore_src.txt
File metadata and controls
11681 lines (10400 loc) · 375 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
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
Project Path: src
Source Tree:
```
src
├── posts.ts
├── index.ts
├── actions.ts
├── evaluators.ts
├── localembeddingManager.ts
├── database.ts
├── embedding.ts
├── database
│ └── CircuitBreaker.ts
├── ragknowledge.ts
├── memory.ts
├── environment.ts
├── types.ts
├── relationships.ts
├── parsing.ts
├── goals.ts
├── knowledge.ts
├── logger.ts
├── providers.ts
├── test_resources
│ ├── types.ts
│ ├── createRuntime.ts
│ ├── testSetup.ts
│ └── constants.ts
├── cache.ts
├── utils.ts
├── uuid.ts
├── runtime.ts
├── config.ts
├── models.ts
├── generation.ts
├── messages.ts
├── settings.ts
└── context.ts
```
`/root/eliza/packages/core/src/posts.ts`:
```ts
import { formatTimestamp } from "./messages.ts";
import type { Actor, Memory } from "./types.ts";
export const formatPosts = ({
messages,
actors,
conversationHeader = true,
}: {
messages: Memory[];
actors: Actor[];
conversationHeader?: boolean;
}) => {
// Group messages by roomId
const groupedMessages: { [roomId: string]: Memory[] } = {};
messages.forEach((message) => {
if (message.roomId) {
if (!groupedMessages[message.roomId]) {
groupedMessages[message.roomId] = [];
}
groupedMessages[message.roomId].push(message);
}
});
// Sort messages within each roomId by createdAt (oldest to newest)
Object.values(groupedMessages).forEach((roomMessages) => {
roomMessages.sort((a, b) => a.createdAt - b.createdAt);
});
// Sort rooms by the newest message's createdAt
const sortedRooms = Object.entries(groupedMessages).sort(
([, messagesA], [, messagesB]) =>
messagesB[messagesB.length - 1].createdAt -
messagesA[messagesA.length - 1].createdAt
);
const formattedPosts = sortedRooms.map(([roomId, roomMessages]) => {
const messageStrings = roomMessages
.filter((message: Memory) => message.userId)
.map((message: Memory) => {
const actor = actors.find(
(actor: Actor) => actor.id === message.userId
);
const userName = actor?.name || "Unknown User";
const displayName = actor?.username || "unknown";
return `Name: ${userName} (@${displayName})
ID: ${message.id}${message.content.inReplyTo ? `\nIn reply to: ${message.content.inReplyTo}` : ""}
Date: ${formatTimestamp(message.createdAt)}
Text:
${message.content.text}`;
});
const header = conversationHeader
? `Conversation: ${roomId.slice(-5)}\n`
: "";
return `${header}${messageStrings.join("\n\n")}`;
});
return formattedPosts.join("\n\n");
};
```
`/root/eliza/packages/core/src/index.ts`:
```ts
import "./config.ts"; // Add this line first
export * from "./actions.ts";
export * from "./context.ts";
export * from "./database.ts";
export * from "./embedding.ts";
export * from "./evaluators.ts";
export * from "./generation.ts";
export * from "./goals.ts";
export * from "./memory.ts";
export * from "./messages.ts";
export * from "./models.ts";
export * from "./posts.ts";
export * from "./providers.ts";
export * from "./relationships.ts";
export * from "./runtime.ts";
export * from "./settings.ts";
export * from "./types.ts";
export * from "./logger.ts";
export * from "./parsing.ts";
export * from "./uuid.ts";
export * from "./environment.ts";
export * from "./cache.ts";
export { default as knowledge } from "./knowledge.ts";
export * from "./ragknowledge.ts";
export * from "./utils.ts";
```
`/root/eliza/packages/core/src/actions.ts`:
```ts
import { names, uniqueNamesGenerator } from "unique-names-generator";
import type { Action, ActionExample } from "./types.ts";
/**
* Composes a set of example conversations based on provided actions and a specified count.
* It randomly selects examples from the provided actions and formats them with generated names.
* @param actionsData - An array of `Action` objects from which to draw examples.
* @param count - The number of examples to generate.
* @returns A string containing formatted examples of conversations.
*/
export const composeActionExamples = (actionsData: Action[], count: number) => {
const data: ActionExample[][][] = actionsData.map((action: Action) => [
...action.examples,
]);
const actionExamples: ActionExample[][] = [];
let length = data.length;
for (let i = 0; i < count && length; i++) {
const actionId = i % length;
const examples = data[actionId];
if (examples.length) {
const rand = ~~(Math.random() * examples.length);
actionExamples[i] = examples.splice(rand, 1)[0];
} else {
i--;
}
if (examples.length == 0) {
data.splice(actionId, 1);
length--;
}
}
const formattedExamples = actionExamples.map((example) => {
const exampleNames = Array.from({ length: 5 }, () =>
uniqueNamesGenerator({ dictionaries: [names] })
);
return `\n${example
.map((message) => {
let messageString = `${message.user}: ${message.content.text}${message.content.action ? ` (${message.content.action})` : ""}`;
for (let i = 0; i < exampleNames.length; i++) {
messageString = messageString.replaceAll(
`{{user${i + 1}}}`,
exampleNames[i]
);
}
return messageString;
})
.join("\n")}`;
});
return formattedExamples.join("\n");
};
/**
* Formats the names of the provided actions into a comma-separated string.
* @param actions - An array of `Action` objects from which to extract names.
* @returns A comma-separated string of action names.
*/
export function formatActionNames(actions: Action[]) {
return actions
.sort(() => 0.5 - Math.random())
.map((action: Action) => `${action.name}`)
.join(", ");
}
/**
* Formats the provided actions into a detailed string listing each action's name and description, separated by commas and newlines.
* @param actions - An array of `Action` objects to format.
* @returns A detailed string of actions, including names and descriptions.
*/
export function formatActions(actions: Action[]) {
return actions
.sort(() => 0.5 - Math.random())
.map((action: Action) => `${action.name}: ${action.description}`)
.join(",\n");
}
```
`/root/eliza/packages/core/src/evaluators.ts`:
```ts
import { names, uniqueNamesGenerator } from "unique-names-generator";
import type { ActionExample, Evaluator } from "./types.ts";
import { stringArrayFooter } from "./parsing.ts";
/**
* Template used for the evaluation generateText.
*/
export const evaluationTemplate =
`TASK: Based on the conversation and conditions, determine which evaluation functions are appropriate to call.
Examples:
{{evaluatorExamples}}
INSTRUCTIONS: You are helping me to decide which appropriate functions to call based on the conversation between {{senderName}} and {{agentName}}.
{{recentMessages}}
Evaluator Functions:
{{evaluators}}
TASK: Based on the most recent conversation, determine which evaluators functions are appropriate to call to call.
Include the name of evaluators that are relevant and should be called in the array
Available evaluator names to include are {{evaluatorNames}}
` + stringArrayFooter;
/**
* Formats the names of evaluators into a comma-separated list, each enclosed in single quotes.
* @param evaluators - An array of evaluator objects.
* @returns A string that concatenates the names of all evaluators, each enclosed in single quotes and separated by commas.
*/
export function formatEvaluatorNames(evaluators: Evaluator[]) {
return evaluators
.map((evaluator: Evaluator) => `'${evaluator.name}'`)
.join(",\n");
}
/**
* Formats evaluator details into a string, including both the name and description of each evaluator.
* @param evaluators - An array of evaluator objects.
* @returns A string that concatenates the name and description of each evaluator, separated by a colon and a newline character.
*/
export function formatEvaluators(evaluators: Evaluator[]) {
return evaluators
.map(
(evaluator: Evaluator) =>
`'${evaluator.name}: ${evaluator.description}'`
)
.join(",\n");
}
/**
* Formats evaluator examples into a readable string, replacing placeholders with generated names.
* @param evaluators - An array of evaluator objects, each containing examples to format.
* @returns A string that presents each evaluator example in a structured format, including context, messages, and outcomes, with placeholders replaced by generated names.
*/
export function formatEvaluatorExamples(evaluators: Evaluator[]) {
return evaluators
.map((evaluator) => {
return evaluator.examples
.map((example) => {
const exampleNames = Array.from({ length: 5 }, () =>
uniqueNamesGenerator({ dictionaries: [names] })
);
let formattedContext = example.context;
let formattedOutcome = example.outcome;
exampleNames.forEach((name, index) => {
const placeholder = `{{user${index + 1}}}`;
formattedContext = formattedContext.replaceAll(
placeholder,
name
);
formattedOutcome = formattedOutcome.replaceAll(
placeholder,
name
);
});
const formattedMessages = example.messages
.map((message: ActionExample) => {
let messageString = `${message.user}: ${message.content.text}`;
exampleNames.forEach((name, index) => {
const placeholder = `{{user${index + 1}}}`;
messageString = messageString.replaceAll(
placeholder,
name
);
});
return (
messageString +
(message.content.action
? ` (${message.content.action})`
: "")
);
})
.join("\n");
return `Context:\n${formattedContext}\n\nMessages:\n${formattedMessages}\n\nOutcome:\n${formattedOutcome}`;
})
.join("\n\n");
})
.join("\n\n");
}
/**
* Generates a string summarizing the descriptions of each evaluator example.
* @param evaluators - An array of evaluator objects, each containing examples.
* @returns A string that summarizes the descriptions for each evaluator example, formatted with the evaluator name, example number, and description.
*/
export function formatEvaluatorExampleDescriptions(evaluators: Evaluator[]) {
return evaluators
.map((evaluator) =>
evaluator.examples
.map(
(_example, index) =>
`${evaluator.name} Example ${index + 1}: ${evaluator.description}`
)
.join("\n")
)
.join("\n\n");
}
```
`/root/eliza/packages/core/src/localembeddingManager.ts`:
```ts
import path from "node:path";
import { fileURLToPath } from "url";
import { FlagEmbedding, EmbeddingModel } from "fastembed";
import elizaLogger from "./logger";
class LocalEmbeddingModelManager {
private static instance: LocalEmbeddingModelManager | null;
private model: FlagEmbedding | null = null;
private initPromise: Promise<void> | null = null;
private initializationLock = false;
private constructor() {}
public static getInstance(): LocalEmbeddingModelManager {
if (!LocalEmbeddingModelManager.instance) {
LocalEmbeddingModelManager.instance =
new LocalEmbeddingModelManager();
}
return LocalEmbeddingModelManager.instance;
}
private async getRootPath(): Promise<string> {
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const rootPath = path.resolve(__dirname, "..");
return rootPath.includes("/eliza/")
? rootPath.split("/eliza/")[0] + "/eliza/"
: path.resolve(__dirname, "..");
}
public async initialize(): Promise<void> {
// If already initialized, return immediately
if (this.model) {
return;
}
// If initialization is in progress, wait for it
if (this.initPromise) {
return this.initPromise;
}
// Use a lock to prevent multiple simultaneous initializations
if (this.initializationLock) {
// Wait for current initialization to complete
while (this.initializationLock) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
return;
}
this.initializationLock = true;
try {
this.initPromise = this.initializeModel();
await this.initPromise;
} finally {
this.initializationLock = false;
this.initPromise = null;
}
}
private async initializeModel(): Promise<void> {
const isNode =
typeof process !== "undefined" &&
process.versions != null &&
process.versions.node != null;
if (!isNode) {
throw new Error("Local embedding not supported in browser");
}
try {
const fs = await import("fs");
const cacheDir = (await this.getRootPath()) + "/cache/";
if (!fs.existsSync(cacheDir)) {
fs.mkdirSync(cacheDir, { recursive: true });
}
elizaLogger.debug("Initializing BGE embedding model...");
this.model = await FlagEmbedding.init({
cacheDir: cacheDir,
model: EmbeddingModel.BGESmallENV15,
maxLength: 512,
});
elizaLogger.debug("BGE model initialized successfully");
} catch (error) {
elizaLogger.error("Failed to initialize BGE model:", error);
throw error;
}
}
public async generateEmbedding(input: string): Promise<number[]> {
if (!this.model) {
await this.initialize();
}
if (!this.model) {
throw new Error("Failed to initialize model");
}
try {
// Let fastembed handle tokenization internally
const embedding = await this.model.queryEmbed(input);
// Debug the raw embedding - uncomment if debugging embeddings
// elizaLogger.debug("Raw embedding from BGE:", {
// type: typeof embedding,
// isArray: Array.isArray(embedding),
// dimensions: Array.isArray(embedding)
// ? embedding.length
// : "not an array",
// sample: Array.isArray(embedding)
// ? embedding.slice(0, 5)
// : embedding,
// });
return this.processEmbedding(embedding);
} catch (error) {
elizaLogger.error("Embedding generation failed:", error);
throw error;
}
}
private processEmbedding(embedding: number[]): number[] {
let finalEmbedding: number[];
if (
ArrayBuffer.isView(embedding) &&
embedding.constructor === Float32Array
) {
finalEmbedding = Array.from(embedding);
} else if (
Array.isArray(embedding) &&
ArrayBuffer.isView(embedding[0]) &&
embedding[0].constructor === Float32Array
) {
finalEmbedding = Array.from(embedding[0]);
} else if (Array.isArray(embedding)) {
finalEmbedding = embedding;
} else {
throw new Error(`Unexpected embedding format: ${typeof embedding}`);
}
finalEmbedding = finalEmbedding.map((n) => Number(n));
if (!Array.isArray(finalEmbedding) || finalEmbedding[0] === undefined) {
throw new Error(
"Invalid embedding format: must be an array starting with a number"
);
}
if (finalEmbedding.length !== 384) {
elizaLogger.warn(
`Unexpected embedding dimension: ${finalEmbedding.length}`
);
}
return finalEmbedding;
}
public async reset(): Promise<void> {
if (this.model) {
// Add any cleanup logic here if needed
this.model = null;
}
this.initPromise = null;
this.initializationLock = false;
}
// For testing purposes
public static resetInstance(): void {
if (LocalEmbeddingModelManager.instance) {
LocalEmbeddingModelManager.instance.reset();
LocalEmbeddingModelManager.instance = null;
}
}
}
export default LocalEmbeddingModelManager;
```
`/root/eliza/packages/core/src/database.ts`:
```ts
import type {
Account,
Actor,
GoalStatus,
Goal,
Memory,
Relationship,
UUID,
RAGKnowledgeItem,
Participant,
IDatabaseAdapter,
} from "./types.ts";
import { CircuitBreaker } from "./database/CircuitBreaker";
import { elizaLogger } from "./logger";
/**
* An abstract class representing a database adapter for managing various entities
* like accounts, memories, actors, goals, and rooms.
*/
export abstract class DatabaseAdapter<DB = any> implements IDatabaseAdapter {
/**
* The database instance.
*/
db: DB;
/**
* Circuit breaker instance used to handle fault tolerance and prevent cascading failures.
* Implements the Circuit Breaker pattern to temporarily disable operations when a failure threshold is reached.
*
* The circuit breaker has three states:
* - CLOSED: Normal operation, requests pass through
* - OPEN: Failure threshold exceeded, requests are blocked
* - HALF_OPEN: Testing if service has recovered
*
* @protected
*/
protected circuitBreaker: CircuitBreaker;
/**
* Creates a new DatabaseAdapter instance with optional circuit breaker configuration.
*
* @param circuitBreakerConfig - Configuration options for the circuit breaker
* @param circuitBreakerConfig.failureThreshold - Number of failures before circuit opens (defaults to 5)
* @param circuitBreakerConfig.resetTimeout - Time in ms before attempting to close circuit (defaults to 60000)
* @param circuitBreakerConfig.halfOpenMaxAttempts - Number of successful attempts needed to close circuit (defaults to 3)
*/
constructor(circuitBreakerConfig?: {
failureThreshold?: number;
resetTimeout?: number;
halfOpenMaxAttempts?: number;
}) {
this.circuitBreaker = new CircuitBreaker(circuitBreakerConfig);
}
/**
* Optional initialization method for the database adapter.
* @returns A Promise that resolves when initialization is complete.
*/
abstract init(): Promise<void>;
/**
* Optional close method for the database adapter.
* @returns A Promise that resolves when closing is complete.
*/
abstract close(): Promise<void>;
/**
* Retrieves an account by its ID.
* @param userId The UUID of the user account to retrieve.
* @returns A Promise that resolves to the Account object or null if not found.
*/
abstract getAccountById(userId: UUID): Promise<Account | null>;
/**
* Creates a new account in the database.
* @param account The account object to create.
* @returns A Promise that resolves when the account creation is complete.
*/
abstract createAccount(account: Account): Promise<boolean>;
/**
* Retrieves memories based on the specified parameters.
* @param params An object containing parameters for the memory retrieval.
* @returns A Promise that resolves to an array of Memory objects.
*/
abstract getMemories(params: {
agentId: UUID;
roomId: UUID;
count?: number;
unique?: boolean;
tableName: string;
}): Promise<Memory[]>;
abstract getMemoriesByRoomIds(params: {
agentId: UUID;
roomIds: UUID[];
tableName: string;
limit?: number;
}): Promise<Memory[]>;
abstract getMemoryById(id: UUID): Promise<Memory | null>;
/**
* Retrieves multiple memories by their IDs
* @param memoryIds Array of UUIDs of the memories to retrieve
* @param tableName Optional table name to filter memories by type
* @returns Promise resolving to array of Memory objects
*/
abstract getMemoriesByIds(
memoryIds: UUID[],
tableName?: string
): Promise<Memory[]>;
/**
* Retrieves cached embeddings based on the specified query parameters.
* @param params An object containing parameters for the embedding retrieval.
* @returns A Promise that resolves to an array of objects containing embeddings and levenshtein scores.
*/
abstract getCachedEmbeddings({
query_table_name,
query_threshold,
query_input,
query_field_name,
query_field_sub_name,
query_match_count,
}: {
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;
}[]
>;
/**
* Logs an event or action with the specified details.
* @param params An object containing parameters for the log entry.
* @returns A Promise that resolves when the log entry has been saved.
*/
abstract log(params: {
body: { [key: string]: unknown };
userId: UUID;
roomId: UUID;
type: string;
}): Promise<void>;
/**
* Retrieves details of actors in a given room.
* @param params An object containing the roomId to search for actors.
* @returns A Promise that resolves to an array of Actor objects.
*/
abstract getActorDetails(params: { roomId: UUID }): Promise<Actor[]>;
/**
* Searches for memories based on embeddings and other specified parameters.
* @param params An object containing parameters for the memory search.
* @returns A Promise that resolves to an array of Memory objects.
*/
abstract searchMemories(params: {
tableName: string;
agentId: UUID;
roomId: UUID;
embedding: number[];
match_threshold: number;
match_count: number;
unique: boolean;
}): Promise<Memory[]>;
/**
* Updates the status of a specific goal.
* @param params An object containing the goalId and the new status.
* @returns A Promise that resolves when the goal status has been updated.
*/
abstract updateGoalStatus(params: {
goalId: UUID;
status: GoalStatus;
}): Promise<void>;
/**
* Searches for memories by embedding and other specified parameters.
* @param embedding The embedding vector to search with.
* @param params Additional parameters for the search.
* @returns A Promise that resolves to an array of Memory objects.
*/
abstract searchMemoriesByEmbedding(
embedding: number[],
params: {
match_threshold?: number;
count?: number;
roomId?: UUID;
agentId?: UUID;
unique?: boolean;
tableName: string;
}
): Promise<Memory[]>;
/**
* Creates a new memory in the database.
* @param memory The memory object to create.
* @param tableName The table where the memory should be stored.
* @param unique Indicates if the memory should be unique.
* @returns A Promise that resolves when the memory has been created.
*/
abstract createMemory(
memory: Memory,
tableName: string,
unique?: boolean
): Promise<void>;
/**
* Removes a specific memory from the database.
* @param memoryId The UUID of the memory to remove.
* @param tableName The table from which the memory should be removed.
* @returns A Promise that resolves when the memory has been removed.
*/
abstract removeMemory(memoryId: UUID, tableName: string): Promise<void>;
/**
* Removes all memories associated with a specific room.
* @param roomId The UUID of the room whose memories should be removed.
* @param tableName The table from which the memories should be removed.
* @returns A Promise that resolves when all memories have been removed.
*/
abstract removeAllMemories(roomId: UUID, tableName: string): Promise<void>;
/**
* Counts the number of memories in a specific room.
* @param roomId The UUID of the room for which to count memories.
* @param unique Specifies whether to count only unique memories.
* @param tableName Optional table name to count memories from.
* @returns A Promise that resolves to the number of memories.
*/
abstract countMemories(
roomId: UUID,
unique?: boolean,
tableName?: string
): Promise<number>;
/**
* Retrieves goals based on specified parameters.
* @param params An object containing parameters for goal retrieval.
* @returns A Promise that resolves to an array of Goal objects.
*/
abstract getGoals(params: {
agentId: UUID;
roomId: UUID;
userId?: UUID | null;
onlyInProgress?: boolean;
count?: number;
}): Promise<Goal[]>;
/**
* Updates a specific goal in the database.
* @param goal The goal object with updated properties.
* @returns A Promise that resolves when the goal has been updated.
*/
abstract updateGoal(goal: Goal): Promise<void>;
/**
* Creates a new goal in the database.
* @param goal The goal object to create.
* @returns A Promise that resolves when the goal has been created.
*/
abstract createGoal(goal: Goal): Promise<void>;
/**
* Removes a specific goal from the database.
* @param goalId The UUID of the goal to remove.
* @returns A Promise that resolves when the goal has been removed.
*/
abstract removeGoal(goalId: UUID): Promise<void>;
/**
* Removes all goals associated with a specific room.
* @param roomId The UUID of the room whose goals should be removed.
* @returns A Promise that resolves when all goals have been removed.
*/
abstract removeAllGoals(roomId: UUID): Promise<void>;
/**
* Retrieves the room ID for a given room, if it exists.
* @param roomId The UUID of the room to retrieve.
* @returns A Promise that resolves to the room ID or null if not found.
*/
abstract getRoom(roomId: UUID): Promise<UUID | null>;
/**
* Creates a new room with an optional specified ID.
* @param roomId Optional UUID to assign to the new room.
* @returns A Promise that resolves to the UUID of the created room.
*/
abstract createRoom(roomId?: UUID): Promise<UUID>;
/**
* Removes a specific room from the database.
* @param roomId The UUID of the room to remove.
* @returns A Promise that resolves when the room has been removed.
*/
abstract removeRoom(roomId: UUID): Promise<void>;
/**
* Retrieves room IDs for which a specific user is a participant.
* @param userId The UUID of the user.
* @returns A Promise that resolves to an array of room IDs.
*/
abstract getRoomsForParticipant(userId: UUID): Promise<UUID[]>;
/**
* Retrieves room IDs for which specific users are participants.
* @param userIds An array of UUIDs of the users.
* @returns A Promise that resolves to an array of room IDs.
*/
abstract getRoomsForParticipants(userIds: UUID[]): Promise<UUID[]>;
/**
* Adds a user as a participant to a specific room.
* @param userId The UUID of the user to add as a participant.
* @param roomId The UUID of the room to which the user will be added.
* @returns A Promise that resolves to a boolean indicating success or failure.
*/
abstract addParticipant(userId: UUID, roomId: UUID): Promise<boolean>;
/**
* Removes a user as a participant from a specific room.
* @param userId The UUID of the user to remove as a participant.
* @param roomId The UUID of the room from which the user will be removed.
* @returns A Promise that resolves to a boolean indicating success or failure.
*/
abstract removeParticipant(userId: UUID, roomId: UUID): Promise<boolean>;
/**
* Retrieves participants associated with a specific account.
* @param userId The UUID of the account.
* @returns A Promise that resolves to an array of Participant objects.
*/
abstract getParticipantsForAccount(userId: UUID): Promise<Participant[]>;
/**
* Retrieves participants associated with a specific account.
* @param userId The UUID of the account.
* @returns A Promise that resolves to an array of Participant objects.
*/
abstract getParticipantsForAccount(userId: UUID): Promise<Participant[]>;
/**
* Retrieves participants for a specific room.
* @param roomId The UUID of the room for which to retrieve participants.
* @returns A Promise that resolves to an array of UUIDs representing the participants.
*/
abstract getParticipantsForRoom(roomId: UUID): Promise<UUID[]>;
abstract getParticipantUserState(
roomId: UUID,
userId: UUID
): Promise<"FOLLOWED" | "MUTED" | null>;
abstract setParticipantUserState(
roomId: UUID,
userId: UUID,
state: "FOLLOWED" | "MUTED" | null
): Promise<void>;
/**
* Creates a new relationship between two users.
* @param params An object containing the UUIDs of the two users (userA and userB).
* @returns A Promise that resolves to a boolean indicating success or failure of the creation.
*/
abstract createRelationship(params: {
userA: UUID;
userB: UUID;
}): Promise<boolean>;
/**
* Retrieves a relationship between two users if it exists.
* @param params An object containing the UUIDs of the two users (userA and userB).
* @returns A Promise that resolves to the Relationship object or null if not found.
*/
abstract getRelationship(params: {
userA: UUID;
userB: UUID;
}): Promise<Relationship | null>;
/**
* Retrieves all relationships for a specific user.
* @param params An object containing the UUID of the user.
* @returns A Promise that resolves to an array of Relationship objects.
*/
abstract getRelationships(params: {
userId: UUID;
}): Promise<Relationship[]>;
/**
* Retrieves knowledge items based on specified parameters.
* @param params Object containing search parameters
* @returns Promise resolving to array of knowledge items
*/
abstract getKnowledge(params: {
id?: UUID;
agentId: UUID;
limit?: number;
query?: string;
conversationContext?: string;
}): Promise<RAGKnowledgeItem[]>;
abstract searchKnowledge(params: {
agentId: UUID;
embedding: Float32Array;
match_threshold: number;
match_count: number;
searchText?: string;
}): Promise<RAGKnowledgeItem[]>;
/**
* Creates a new knowledge item in the database.
* @param knowledge The knowledge item to create
* @returns Promise resolving when creation is complete
*/
abstract createKnowledge(knowledge: RAGKnowledgeItem): Promise<void>;
/**
* Removes a knowledge item and its associated chunks from the database.
* @param id The ID of the knowledge item to remove
* @returns Promise resolving when removal is complete
*/
abstract removeKnowledge(id: UUID): Promise<void>;
/**
* Removes an agents full knowledge database and its associated chunks from the database.
* @param agentId The Agent ID of the knowledge items to remove
* @returns Promise resolving when removal is complete
*/
abstract clearKnowledge(agentId: UUID, shared?: boolean): Promise<void>;
/**
* Executes an operation with circuit breaker protection.
* @param operation A function that returns a Promise to be executed with circuit breaker protection
* @param context A string describing the context/operation being performed for logging purposes
* @returns A Promise that resolves to the result of the operation
* @throws Will throw an error if the circuit breaker is open or if the operation fails
* @protected
*/
protected async withCircuitBreaker<T>(
operation: () => Promise<T>,
context: string
): Promise<T> {
try {
return await this.circuitBreaker.execute(operation);
} catch (error) {
elizaLogger.error(`Circuit breaker error in ${context}:`, {
error: error instanceof Error ? error.message : String(error),
state: this.circuitBreaker.getState(),
});
throw error;
}
}