forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathruntime.ts
1821 lines (1613 loc) · 65.2 KB
/
runtime.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 { readFile } from "fs/promises";
import { join } from "path";
import { names, uniqueNamesGenerator } from "unique-names-generator";
import { v4 as uuidv4 } from "uuid";
import {
composeActionExamples,
formatActionNames,
formatActions,
} from "./actions.ts";
import { addHeader, composeContext } from "./context.ts";
import {
evaluationTemplate,
formatEvaluatorExamples,
formatEvaluatorNames,
formatEvaluators,
} from "./evaluators.ts";
import { generateText } from "./generation.ts";
import { formatGoalsAsString, getGoals } from "./goals.ts";
import { elizaLogger } from "./index.ts";
import knowledge from "./knowledge.ts";
import { MemoryManager } from "./memory.ts";
import { formatActors, formatMessages, getActorDetails } from "./messages.ts";
import { parseJsonArrayFromText } from "./parsing.ts";
import { formatPosts } from "./posts.ts";
import { getProviders } from "./providers.ts";
import { RAGKnowledgeManager } from "./ragknowledge.ts";
import settings from "./settings.ts";
import {
type Character,
type Goal,
type HandlerCallback,
type IAgentRuntime,
type ICacheManager,
type IDatabaseAdapter,
type IMemoryManager,
type IRAGKnowledgeManager,
// type IVerifiableInferenceAdapter,
type KnowledgeItem,
// RAGKnowledgeItem,
//Media,
ModelClass,
ModelProviderName,
type Plugin,
type Provider,
type Adapter,
type Service,
type ServiceType,
type State,
type UUID,
type Action,
type Actor,
type Evaluator,
type Memory,
type DirectoryItem,
type ClientInstance,
} from "./types.ts";
import { stringToUuid } from "./uuid.ts";
import { glob } from "glob";
import { existsSync } from "fs";
/**
* Represents the runtime environment for an agent, handling message processing,
* action registration, and interaction with external services like OpenAI and Supabase.
*/
function isDirectoryItem(item: any): item is DirectoryItem {
return (
typeof item === "object" &&
item !== null &&
"directory" in item &&
typeof item.directory === "string"
);
}
export class AgentRuntime implements IAgentRuntime {
/**
* Default count for recent messages to be kept in memory.
* @private
*/
readonly #conversationLength = 32 as number;
/**
* The ID of the agent
*/
agentId: UUID;
/**
* The base URL of the server where the agent's requests are processed.
*/
//serverUrl = "http://localhost:7998";
/**
* The database adapter used for interacting with the database.
*/
databaseAdapter: IDatabaseAdapter;
/**
* Authentication token used for securing requests.
*/
token: string | null;
/**
* Custom actions that the agent can perform.
*/
actions: Action[] = [];
/**
* Evaluators used to assess and guide the agent's responses.
*/
evaluators: Evaluator[] = [];
/**
* Context providers used to provide context for message generation.
*/
providers: Provider[] = [];
/**
* Database adapters used to interact with the database.
*/
adapters: Adapter[] = [];
plugins: Plugin[] = [];
/**
* The model to use for generateText.
*/
modelProvider: ModelProviderName;
/**
* The model to use for generateImage.
*/
imageModelProvider: ModelProviderName;
/**
* The model to use for describing images.
*/
imageVisionModelProvider: ModelProviderName;
/**
* Fetch function to use
* Some environments may not have access to the global fetch function and need a custom fetch override.
*/
fetch = fetch;
/**
* The character to use for the agent
*/
character: Character;
/**
* Store messages that are sent and received by the agent.
*/
messageManager: IMemoryManager;
/**
* Store and recall descriptions of users based on conversations.
*/
descriptionManager: IMemoryManager;
/**
* Manage the creation and recall of static information (documents, historical game lore, etc)
*/
loreManager: IMemoryManager;
/**
* Hold large documents that can be referenced
*/
documentsManager: IMemoryManager;
/**
* Searchable document fragments
*/
knowledgeManager: IMemoryManager;
ragKnowledgeManager: IRAGKnowledgeManager;
private readonly knowledgeRoot: string;
services: Map<ServiceType, Service> = new Map();
memoryManagers: Map<string, IMemoryManager> = new Map();
cacheManager: ICacheManager;
clients: ClientInstance[] = [];
// verifiableInferenceAdapter?: IVerifiableInferenceAdapter;
registerMemoryManager(manager: IMemoryManager): void {
if (!manager.tableName) {
throw new Error("Memory manager must have a tableName");
}
if (this.memoryManagers.has(manager.tableName)) {
elizaLogger.warn(
`Memory manager ${manager.tableName} is already registered. Skipping registration.`,
);
return;
}
this.memoryManagers.set(manager.tableName, manager);
}
getMemoryManager(tableName: string): IMemoryManager | null {
return this.memoryManagers.get(tableName) || null;
}
getService<T extends Service>(service: ServiceType): T | null {
const serviceInstance = this.services.get(service);
if (!serviceInstance) {
elizaLogger.error(`Service ${service} not found`);
return null;
}
return serviceInstance as T;
}
async registerService(service: Service): Promise<void> {
const serviceType = service.serviceType;
elizaLogger.log(`${this.character.name}(${this.agentId}) - Registering service:`, serviceType);
if (this.services.has(serviceType)) {
elizaLogger.warn(
`${this.character.name}(${this.agentId}) - Service ${serviceType} is already registered. Skipping registration.`
);
return;
}
// Add the service to the services map
this.services.set(serviceType, service);
elizaLogger.success(`${this.character.name}(${this.agentId}) - Service ${serviceType} registered successfully`);
}
/**
* Creates an instance of AgentRuntime.
* @param opts - The options for configuring the AgentRuntime.
* @param opts.conversationLength - The number of messages to hold in the recent message cache.
* @param opts.token - The JWT token, can be a JWT token if outside worker, or an OpenAI token if inside worker.
* @param opts.serverUrl - The URL of the worker.
* @param opts.actions - Optional custom actions.
* @param opts.evaluators - Optional custom evaluators.
* @param opts.services - Optional custom services.
* @param opts.memoryManagers - Optional custom memory managers.
* @param opts.providers - Optional context providers.
* @param opts.model - The model to use for generateText.
* @param opts.embeddingModel - The model to use for embedding.
* @param opts.agentId - Optional ID of the agent.
* @param opts.databaseAdapter - The database adapter used for interacting with the database.
* @param opts.fetch - Custom fetch function to use for making requests.
*/
constructor(opts: {
conversationLength?: number; // number of messages to hold in the recent message cache
agentId?: UUID; // ID of the agent
character?: Character; // The character to use for the agent
token: string; // JWT token, can be a JWT token if outside worker, or an OpenAI token if inside worker
serverUrl?: string; // The URL of the worker
actions?: Action[]; // Optional custom actions
evaluators?: Evaluator[]; // Optional custom evaluators
plugins?: Plugin[];
providers?: Provider[];
modelProvider: ModelProviderName;
services?: Service[]; // Map of service name to service instance
managers?: IMemoryManager[]; // Map of table name to memory manager
databaseAdapter?: IDatabaseAdapter; // The database adapter used for interacting with the database
fetch?: typeof fetch | unknown;
speechModelPath?: string;
cacheManager?: ICacheManager;
logging?: boolean;
// verifiableInferenceAdapter?: IVerifiableInferenceAdapter;
}) {
// use the character id if it exists, otherwise use the agentId if it is passed in, otherwise use the character name
this.agentId =
opts.character?.id ??
opts?.agentId ??
stringToUuid(opts.character?.name ?? uuidv4());
this.character = opts.character;
if(!this.character) {
throw new Error("Character input is required");
}
elizaLogger.info(`${this.character.name}(${this.agentId}) - Initializing AgentRuntime with options:`, {
character: opts.character?.name,
modelProvider: opts.modelProvider,
characterModelProvider: opts.character?.modelProvider,
});
elizaLogger.debug(
`[AgentRuntime] Process working directory: ${process.cwd()}`,
);
// Define the root path once
this.knowledgeRoot = join(
process.cwd(),
"..",
"characters",
"knowledge",
);
elizaLogger.debug(
`[AgentRuntime] Process knowledgeRoot: ${this.knowledgeRoot}`,
);
this.#conversationLength =
opts.conversationLength ?? this.#conversationLength;
this.databaseAdapter = opts.databaseAdapter;
elizaLogger.success(`Agent ID: ${this.agentId}`);
this.fetch = (opts.fetch as typeof fetch) ?? this.fetch;
this.cacheManager = opts.cacheManager;
this.messageManager = new MemoryManager({
runtime: this,
tableName: "messages",
});
this.descriptionManager = new MemoryManager({
runtime: this,
tableName: "descriptions",
});
this.loreManager = new MemoryManager({
runtime: this,
tableName: "lore",
});
this.documentsManager = new MemoryManager({
runtime: this,
tableName: "documents",
});
this.knowledgeManager = new MemoryManager({
runtime: this,
tableName: "fragments",
});
this.ragKnowledgeManager = new RAGKnowledgeManager({
runtime: this,
tableName: "knowledge",
knowledgeRoot: this.knowledgeRoot,
});
(opts.managers ?? []).forEach((manager: IMemoryManager) => {
this.registerMemoryManager(manager);
});
(opts.services ?? []).forEach((service: Service) => {
this.registerService(service);
});
//this.serverUrl = opts.serverUrl ?? this.serverUrl;
elizaLogger.info(`${this.character.name}(${this.agentId}) - Setting Model Provider:`, {
characterModelProvider: this.character.modelProvider,
optsModelProvider: opts.modelProvider,
currentModelProvider: this.modelProvider,
finalSelection:
this.character.modelProvider ??
opts.modelProvider ??
this.modelProvider,
});
this.modelProvider =
this.character.modelProvider ??
opts.modelProvider ??
this.modelProvider;
this.imageModelProvider =
this.character.imageModelProvider ?? this.modelProvider;
this.imageVisionModelProvider =
this.character.imageVisionModelProvider ?? this.modelProvider;
elizaLogger.info(
`${this.character.name}(${this.agentId}) - Selected model provider:`,
this.modelProvider
);
elizaLogger.info(
`${this.character.name}(${this.agentId}) - Selected image model provider:`,
this.imageModelProvider
);
elizaLogger.info(
`${this.character.name}(${this.agentId}) - Selected image vision model provider:`,
this.imageVisionModelProvider
);
// Validate model provider
if (!Object.values(ModelProviderName).includes(this.modelProvider)) {
elizaLogger.error("Invalid model provider:", this.modelProvider);
elizaLogger.error(
"Available providers:",
Object.values(ModelProviderName),
);
throw new Error(`Invalid model provider: ${this.modelProvider}`);
}
//if (!this.serverUrl) {
// elizaLogger.warn("No serverUrl provided, defaulting to localhost");
//}
this.token = opts.token;
this.plugins = [
...(opts.character?.plugins ?? []),
...(opts.plugins ?? []),
];
this.plugins.forEach((plugin) => {
plugin.actions?.forEach((action) => {
this.registerAction(action);
});
plugin.evaluators?.forEach((evaluator) => {
this.registerEvaluator(evaluator);
});
plugin.services?.forEach((service) => {
this.registerService(service);
});
plugin.providers?.forEach((provider) => {
this.registerContextProvider(provider);
});
plugin.adapters?.forEach((adapter) => {
this.registerAdapter(adapter);
});
});
(opts.actions ?? []).forEach((action) => {
this.registerAction(action);
});
(opts.providers ?? []).forEach((provider) => {
this.registerContextProvider(provider);
});
(opts.evaluators ?? []).forEach((evaluator: Evaluator) => {
this.registerEvaluator(evaluator);
});
// this.verifiableInferenceAdapter = opts.verifiableInferenceAdapter;
}
private async initializeDatabase() {
// By convention, we create a user and room using the agent id.
// Memories related to it are considered global context for the agent.
this.ensureRoomExists(this.agentId);
this.ensureUserExists(
this.agentId,
this.character.username || this.character.name,
this.character.name,
).then(() => {
// postgres needs the user to exist before you can add a participant
this.ensureParticipantExists(this.agentId, this.agentId);
});
}
async initialize() {
this.initializeDatabase();
for (const [serviceType, service] of this.services.entries()) {
try {
await service.initialize(this);
this.services.set(serviceType, service);
elizaLogger.success(
`${this.character.name}(${this.agentId}) - Service ${serviceType} initialized successfully`
);
} catch (error) {
elizaLogger.error(
`${this.character.name}(${this.agentId}) - Failed to initialize service ${serviceType}:`,
error
);
throw error;
}
}
// should already be initiailized
/*
for (const plugin of this.plugins) {
if (plugin.services)
await Promise.all(
plugin.services?.map((service) => service.initialize(this)),
);
}
*/
if (
this.character &&
this.character.knowledge &&
this.character.knowledge.length > 0
) {
elizaLogger.info(
`[RAG Check] RAG Knowledge enabled: ${this.character.settings.ragKnowledge ? true : false}`,
);
elizaLogger.debug(
`[RAG Check] Knowledge items:`,
this.character.knowledge,
);
if (this.character.settings.ragKnowledge) {
// Type guards with logging for each knowledge type
const [directoryKnowledge, pathKnowledge, stringKnowledge] =
this.character.knowledge.reduce(
(acc, item) => {
if (typeof item === "object") {
if (isDirectoryItem(item)) {
elizaLogger.debug(
`[RAG Filter] Found directory item: ${JSON.stringify(item)}`,
);
acc[0].push(item);
} else if ("path" in item) {
elizaLogger.debug(
`[RAG Filter] Found path item: ${JSON.stringify(item)}`,
);
acc[1].push(item);
}
} else if (typeof item === "string") {
elizaLogger.debug(
`[RAG Filter] Found string item: ${item.slice(0, 100)}...`,
);
acc[2].push(item);
}
return acc;
},
[[], [], []] as [
Array<{ directory: string; shared?: boolean }>,
Array<{ path: string; shared?: boolean }>,
Array<string>,
],
);
elizaLogger.info(
`[RAG Summary] Found ${directoryKnowledge.length} directories, ${pathKnowledge.length} paths, and ${stringKnowledge.length} strings`,
);
// Process each type of knowledge
if (directoryKnowledge.length > 0) {
elizaLogger.info(
`[RAG Process] Processing directory knowledge sources:`,
);
for (const dir of directoryKnowledge) {
elizaLogger.info(
` - Directory: ${dir.directory} (shared: ${!!dir.shared})`,
);
await this.processCharacterRAGDirectory(dir);
}
}
if (pathKnowledge.length > 0) {
elizaLogger.info(
`[RAG Process] Processing individual file knowledge sources`,
);
await this.processCharacterRAGKnowledge(pathKnowledge);
}
if (stringKnowledge.length > 0) {
elizaLogger.info(
`[RAG Process] Processing direct string knowledge`,
);
await this.processCharacterRAGKnowledge(stringKnowledge);
}
} else {
// Non-RAG mode: only process string knowledge
const stringKnowledge = this.character.knowledge.filter(
(item): item is string => typeof item === "string",
);
await this.processCharacterKnowledge(stringKnowledge);
}
// After all new knowledge is processed, clean up any deleted files
elizaLogger.info(
`[RAG Cleanup] Starting cleanup of deleted knowledge files`,
);
await this.ragKnowledgeManager.cleanupDeletedKnowledgeFiles();
elizaLogger.info(`[RAG Cleanup] Cleanup complete`);
}
}
async stop() {
elizaLogger.debug("runtime::stop - character", this.character.name);
// stop services, they don't have a stop function
// just initialize
// plugins
// have actions, providers, evaluators (no start/stop)
// services (just initialized), clients
// client have a start
for (const c of this.clients) {
elizaLogger.log(
"runtime::stop - requesting",
c,
"client stop for",
this.character.name,
);
c.stop(this);
}
// we don't need to unregister with directClient
// don't need to worry about knowledge
}
/**
* Processes character knowledge by creating document memories and fragment memories.
* This function takes an array of knowledge items, creates a document memory for each item if it doesn't exist,
* then chunks the content into fragments, embeds each fragment, and creates fragment memories.
* @param knowledge An array of knowledge items containing id, path, and content.
*/
private async processCharacterKnowledge(items: string[]) {
const ids = items.map(i => stringToUuid(i));
const exists = await this.documentsManager.getMemoriesByIds(ids);
const toAdd = [];
for(const i in items) {
const exist = exists[i];
if (!exist) {
toAdd.push([items[i], ids[i]]);
}
}
if (!toAdd.length) return;
elizaLogger.info('discovered ' + toAdd.length + ' new knowledge items')
const chunkSize = 512;
const ps = [];
for (const a of toAdd) {
const item = a[0];
const knowledgeId = a[1];
if (item.length > chunkSize) {
// these are just slower
elizaLogger.info(
this.character.name,
" knowledge item over 512 characters, splitting - ",
item.slice(0, 100),
);
}
ps.push(knowledge.set(this, {
id: knowledgeId,
content: {
text: item,
},
}));
}
// wait for it all to be added
await Promise.all(ps);
elizaLogger.success(this.character.name, 'knowledge is synchronized');
}
/**
* Processes character knowledge by creating document memories and fragment memories.
* This function takes an array of knowledge items, creates a document knowledge for each item if it doesn't exist,
* then chunks the content into fragments, embeds each fragment, and creates fragment knowledge.
* An array of knowledge items or objects containing id, path, and content.
*/
private async processCharacterRAGKnowledge(
items: (string | { path: string; shared?: boolean })[],
) {
let hasError = false;
for (const item of items) {
if (!item) continue;
try {
// Check if item is marked as shared
let isShared = false;
let contentItem = item;
// Only treat as shared if explicitly marked
if (typeof item === "object" && "path" in item) {
isShared = item.shared === true;
contentItem = item.path;
} else {
contentItem = item;
}
// const knowledgeId = stringToUuid(contentItem);
const knowledgeId = this.ragKnowledgeManager.generateScopedId(
contentItem,
isShared,
);
const fileExtension = contentItem
.split(".")
.pop()
?.toLowerCase();
// Check if it's a file or direct knowledge
if (
fileExtension &&
["md", "txt", "pdf"].includes(fileExtension)
) {
try {
const filePath = join(this.knowledgeRoot, contentItem);
// Get existing knowledge first with more detailed logging
elizaLogger.debug("[RAG Query]", {
knowledgeId,
agentId: this.agentId,
relativePath: contentItem,
fullPath: filePath,
isShared,
knowledgeRoot: this.knowledgeRoot,
});
// Get existing knowledge first
const existingKnowledge =
await this.ragKnowledgeManager.getKnowledge({
id: knowledgeId,
agentId: this.agentId, // Keep agentId as it's used in OR query
});
elizaLogger.debug("[RAG Query Result]", {
relativePath: contentItem,
fullPath: filePath,
knowledgeId,
isShared,
exists: existingKnowledge.length > 0,
knowledgeCount: existingKnowledge.length,
firstResult: existingKnowledge[0]
? {
id: existingKnowledge[0].id,
agentId: existingKnowledge[0].agentId,
contentLength:
existingKnowledge[0].content.text
.length,
}
: null,
results: existingKnowledge.map((k) => ({
id: k.id,
agentId: k.agentId,
isBaseKnowledge: !k.id.includes("chunk"),
})),
});
// Read file content
const content: string = await readFile(
filePath,
"utf8",
);
if (!content) {
hasError = true;
continue;
}
if (existingKnowledge.length > 0) {
const existingContent =
existingKnowledge[0].content.text;
elizaLogger.debug("[RAG Compare]", {
path: contentItem,
knowledgeId,
isShared,
existingContentLength: existingContent.length,
newContentLength: content.length,
contentSample: content.slice(0, 100),
existingContentSample: existingContent.slice(
0,
100,
),
matches: existingContent === content,
});
if (existingContent === content) {
elizaLogger.info(
`${isShared ? "Shared knowledge" : "Knowledge"} ${contentItem} unchanged, skipping`,
);
continue;
}
// Content changed, remove old knowledge before adding new
elizaLogger.info(
`${isShared ? "Shared knowledge" : "Knowledge"} ${contentItem} changed, updating...`,
);
await this.ragKnowledgeManager.removeKnowledge(
knowledgeId,
);
await this.ragKnowledgeManager.removeKnowledge(
`${knowledgeId}-chunk-*` as UUID,
);
}
elizaLogger.info(
`Processing ${fileExtension.toUpperCase()} file content for`,
this.character.name,
"-",
contentItem,
);
await this.ragKnowledgeManager.processFile({
path: contentItem,
content: content,
type: fileExtension as "pdf" | "md" | "txt",
isShared: isShared,
});
} catch (error: any) {
hasError = true;
elizaLogger.error(
`Failed to read knowledge file ${contentItem}. Error details:`,
error?.message || error || "Unknown error",
);
continue;
}
} else {
// Handle direct knowledge string
elizaLogger.info(
"Processing direct knowledge for",
this.character.name,
"-",
contentItem.slice(0, 100),
);
const existingKnowledge =
await this.ragKnowledgeManager.getKnowledge({
id: knowledgeId,
agentId: this.agentId,
});
if (existingKnowledge.length > 0) {
elizaLogger.info(
`Direct knowledge ${knowledgeId} already exists, skipping`,
);
continue;
}
await this.ragKnowledgeManager.createKnowledge({
id: knowledgeId,
agentId: this.agentId,
content: {
text: contentItem,
metadata: {
type: "direct",
},
},
});
}
} catch (error: any) {
hasError = true;
elizaLogger.error(
`Error processing knowledge item ${item}:`,
error?.message || error || "Unknown error",
);
continue;
}
}
if (hasError) {
elizaLogger.warn(
"Some knowledge items failed to process, but continuing with available knowledge",
);
}
}
/**
* Processes directory-based RAG knowledge by recursively loading and processing files.
* @param dirConfig The directory configuration containing path and shared flag
*/
private async processCharacterRAGDirectory(dirConfig: {
directory: string;
shared?: boolean;
}) {
if (!dirConfig.directory) {
elizaLogger.error("[RAG Directory] No directory specified");
return;
}
// Sanitize directory path to prevent traversal attacks
const sanitizedDir = dirConfig.directory.replace(/\.\./g, "");
const dirPath = join(this.knowledgeRoot, sanitizedDir);
try {
// Check if directory exists
const dirExists = existsSync(dirPath);
if (!dirExists) {
elizaLogger.error(
`[RAG Directory] Directory does not exist: ${sanitizedDir}`,
);
return;
}
elizaLogger.debug(`[RAG Directory] Searching in: ${dirPath}`);
// Use glob to find all matching files in directory
const files = await glob("**/*.{md,txt,pdf}", {
cwd: dirPath,
nodir: true,
absolute: false,
});
if (files.length === 0) {
elizaLogger.warn(
`No matching files found in directory: ${dirConfig.directory}`,
);
return;
}
elizaLogger.info(
`[RAG Directory] Found ${files.length} files in ${dirConfig.directory}`,
);
// Process files in batches to avoid memory issues
const BATCH_SIZE = 5;
for (let i = 0; i < files.length; i += BATCH_SIZE) {
const batch = files.slice(i, i + BATCH_SIZE);
await Promise.all(
batch.map(async (file) => {
try {
const relativePath = join(sanitizedDir, file);
elizaLogger.debug(
`[RAG Directory] Processing file ${i + 1}/${files.length}:`,
{
file,
relativePath,
shared: dirConfig.shared,
},
);
await this.processCharacterRAGKnowledge([
{
path: relativePath,
shared: dirConfig.shared,
},
]);
} catch (error) {
elizaLogger.error(
`[RAG Directory] Failed to process file: ${file}`,
error instanceof Error
? {
name: error.name,
message: error.message,
stack: error.stack,
}
: error,
);
}
}),
);
elizaLogger.debug(
`[RAG Directory] Completed batch ${Math.min(i + BATCH_SIZE, files.length)}/${files.length} files`,
);
}
elizaLogger.success(
`[RAG Directory] Successfully processed directory: ${sanitizedDir}`,
);
} catch (error) {
elizaLogger.error(
`[RAG Directory] Failed to process directory: ${sanitizedDir}`,
error instanceof Error
? {
name: error.name,
message: error.message,
stack: error.stack,
}
: error,
);
throw error; // Re-throw to let caller handle it
}
}
getSetting(key: string) {
// check if the key is in the character.settings.secrets object
if (this.character.settings?.secrets?.[key]) {
return this.character.settings.secrets[key];
}
// if not, check if it's in the settings object
if (this.character.settings?.[key]) {
return this.character.settings[key];
}
// if not, check if it's in the settings object
if (settings[key]) {
return settings[key];
}
return null;
}
/**
* Get the number of messages that are kept in the conversation buffer.
* @returns The number of recent messages to be kept in memory.
*/
getConversationLength() {
return this.#conversationLength;
}
/**
* Register an action for the agent to perform.
* @param action The action to register.
*/
registerAction(action: Action) {
elizaLogger.success(`${this.character.name}(${this.agentId}) - Registering action: ${action.name}`);
this.actions.push(action);
}
/**
* Register an evaluator to assess and guide the agent's responses.
* @param evaluator The evaluator to register.
*/
registerEvaluator(evaluator: Evaluator) {
this.evaluators.push(evaluator);
}