forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathruntime.ts
1283 lines (1135 loc) · 43.8 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 { 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 { defaultCharacter } from "./defaultCharacter.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 settings from "./settings.ts";
import {
Character,
Goal,
HandlerCallback,
IAgentRuntime,
ICacheManager,
IDatabaseAdapter,
IMemoryManager,
KnowledgeItem,
ModelClass,
ModelProviderName,
Plugin,
Provider,
Service,
ServiceType,
State,
UUID,
type Action,
type Actor,
type Evaluator,
type Memory,
} from "./types.ts";
import { stringToUuid } from "./uuid.ts";
/**
* Represents the runtime environment for an agent, handling message processing,
* action registration, and interaction with external services like OpenAI and Supabase.
*/
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[] = [];
plugins: Plugin[] = [];
/**
* The model to use for generateText.
*/
modelProvider: ModelProviderName;
/**
* The model to use for generateImage.
*/
imageModelProvider: 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;
services: Map<ServiceType, Service> = new Map();
memoryManagers: Map<string, IMemoryManager> = new Map();
cacheManager: ICacheManager;
clients: Record<string, any>;
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("Registering service:", serviceType);
if (this.services.has(serviceType)) {
elizaLogger.warn(
`Service ${serviceType} is already registered. Skipping registration.`
);
return;
}
// Add the service to the services map
this.services.set(serviceType, service);
elizaLogger.success(`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;
}) {
elizaLogger.info("Initializing AgentRuntime with options:", {
character: opts.character?.name,
modelProvider: opts.modelProvider,
characterModelProvider: opts.character?.modelProvider,
});
this.#conversationLength =
opts.conversationLength ?? this.#conversationLength;
this.databaseAdapter = opts.databaseAdapter;
// 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 || defaultCharacter;
// 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.name,
this.character.name
);
this.ensureParticipantExists(this.agentId, this.agentId);
elizaLogger.success("Agent ID", this.agentId);
this.fetch = (opts.fetch as typeof fetch) ?? this.fetch;
if (!opts.databaseAdapter) {
throw new Error("No database adapter provided");
}
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",
});
(opts.managers ?? []).forEach((manager: IMemoryManager) => {
this.registerMemoryManager(manager);
});
(opts.services ?? []).forEach((service: Service) => {
this.registerService(service);
});
this.serverUrl = opts.serverUrl ?? this.serverUrl;
elizaLogger.info("Setting model provider...");
elizaLogger.info("Model Provider Selection:", {
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;
elizaLogger.info("Selected model provider:", this.modelProvider);
elizaLogger.info(
"Selected image model provider:",
this.imageModelProvider
);
// 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);
});
});
(opts.actions ?? []).forEach((action) => {
this.registerAction(action);
});
(opts.providers ?? []).forEach((provider) => {
this.registerContextProvider(provider);
});
(opts.evaluators ?? []).forEach((evaluator: Evaluator) => {
this.registerEvaluator(evaluator);
});
}
async initialize() {
for (const [serviceType, service] of this.services.entries()) {
try {
await service.initialize(this);
this.services.set(serviceType, service);
elizaLogger.success(
`Service ${serviceType} initialized successfully`
);
} catch (error) {
elizaLogger.error(
`Failed to initialize service ${serviceType}:`,
error
);
throw error;
}
}
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
) {
await this.processCharacterKnowledge(this.character.knowledge);
}
}
async stop() {
elizaLogger.debug('runtime::stop - character', this.character)
// 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 cStr in this.clients) {
const c = this.clients[cStr]
elizaLogger.log('runtime::stop - requesting', cStr, 'client stop for', this.character.name)
c.stop()
}
// 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[]) {
for (const item of items) {
const knowledgeId = stringToUuid(item);
const existingDocument =
await this.documentsManager.getMemoryById(knowledgeId);
if (existingDocument) {
continue;
}
elizaLogger.info(
"Processing knowledge for ",
this.character.name,
" - ",
item.slice(0, 100)
);
await knowledge.set(this, {
id: knowledgeId,
content: {
text: item,
},
});
}
}
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(`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);
}
/**
* Register a context provider to provide context for message generation.
* @param provider The context provider to register.
*/
registerContextProvider(provider: Provider) {
this.providers.push(provider);
}
/**
* Process the actions of a message.
* @param message The message to process.
* @param content The content of the message to process actions from.
*/
async processActions(
message: Memory,
responses: Memory[],
state?: State,
callback?: HandlerCallback
): Promise<void> {
for (const response of responses) {
if (!response.content?.action) {
elizaLogger.warn("No action found in the response content.");
continue;
}
const normalizedAction = response.content.action
.toLowerCase()
.replace("_", "");
elizaLogger.success(`Normalized action: ${normalizedAction}`);
let action = this.actions.find(
(a: { name: string }) =>
a.name
.toLowerCase()
.replace("_", "")
.includes(normalizedAction) ||
normalizedAction.includes(
a.name.toLowerCase().replace("_", "")
)
);
if (!action) {
elizaLogger.info("Attempting to find action in similes.");
for (const _action of this.actions) {
const simileAction = _action.similes.find(
(simile) =>
simile
.toLowerCase()
.replace("_", "")
.includes(normalizedAction) ||
normalizedAction.includes(
simile.toLowerCase().replace("_", "")
)
);
if (simileAction) {
action = _action;
elizaLogger.success(
`Action found in similes: ${action.name}`
);
break;
}
}
}
if (!action) {
elizaLogger.error(
"No action found for",
response.content.action
);
continue;
}
if (!action.handler) {
elizaLogger.error(`Action ${action.name} has no handler.`);
continue;
}
try {
elizaLogger.info(
`Executing handler for action: ${action.name}`
);
await action.handler(this, message, state, {}, callback);
} catch (error) {
elizaLogger.error(error);
}
}
}
/**
* Evaluate the message and state using the registered evaluators.
* @param message The message to evaluate.
* @param state The state of the agent.
* @param didRespond Whether the agent responded to the message.~
* @param callback The handler callback
* @returns The results of the evaluation.
*/
async evaluate(
message: Memory,
state?: State,
didRespond?: boolean,
callback?: HandlerCallback
) {
const evaluatorPromises = this.evaluators.map(
async (evaluator: Evaluator) => {
elizaLogger.log("Evaluating", evaluator.name);
if (!evaluator.handler) {
return null;
}
if (!didRespond && !evaluator.alwaysRun) {
return null;
}
const result = await evaluator.validate(this, message, state);
if (result) {
return evaluator;
}
return null;
}
);
const resolvedEvaluators = await Promise.all(evaluatorPromises);
const evaluatorsData = resolvedEvaluators.filter(Boolean);
// if there are no evaluators this frame, return
if (evaluatorsData.length === 0) {
return [];
}
const context = composeContext({
state: {
...state,
evaluators: formatEvaluators(evaluatorsData),
evaluatorNames: formatEvaluatorNames(evaluatorsData),
},
template:
this.character.templates?.evaluationTemplate ||
evaluationTemplate,
});
const result = await generateText({
runtime: this,
context,
modelClass: ModelClass.SMALL,
});
const evaluators = parseJsonArrayFromText(
result
) as unknown as string[];
for (const evaluator of this.evaluators) {
if (!evaluators.includes(evaluator.name)) continue;
if (evaluator.handler)
await evaluator.handler(this, message, state, {}, callback);
}
return evaluators;
}
/**
* Ensure the existence of a participant in the room. If the participant does not exist, they are added to the room.
* @param userId - The user ID to ensure the existence of.
* @throws An error if the participant cannot be added.
*/
async ensureParticipantExists(userId: UUID, roomId: UUID) {
const participants =
await this.databaseAdapter.getParticipantsForAccount(userId);
if (participants?.length === 0) {
await this.databaseAdapter.addParticipant(userId, roomId);
}
}
/**
* Ensure the existence of a user in the database. If the user does not exist, they are added to the database.
* @param userId - The user ID to ensure the existence of.
* @param userName - The user name to ensure the existence of.
* @returns
*/
async ensureUserExists(
userId: UUID,
userName: string | null,
name: string | null,
email?: string | null,
source?: string | null
) {
const account = await this.databaseAdapter.getAccountById(userId);
if (!account) {
await this.databaseAdapter.createAccount({
id: userId,
name: name || userName || "Unknown User",
username: userName || name || "Unknown",
email: email || (userName || "Bot") + "@" + source || "Unknown", // Temporary
details: { summary: "" },
});
elizaLogger.success(`User ${userName} created successfully.`);
}
}
async ensureParticipantInRoom(userId: UUID, roomId: UUID) {
const participants =
await this.databaseAdapter.getParticipantsForRoom(roomId);
if (!participants.includes(userId)) {
await this.databaseAdapter.addParticipant(userId, roomId);
if (userId === this.agentId) {
elizaLogger.log(
`Agent ${this.character.name} linked to room ${roomId} successfully.`
);
} else {
elizaLogger.log(
`User ${userId} linked to room ${roomId} successfully.`
);
}
}
}
async ensureConnection(
userId: UUID,
roomId: UUID,
userName?: string,
userScreenName?: string,
source?: string
) {
await Promise.all([
this.ensureUserExists(
this.agentId,
this.character.name ?? "Agent",
this.character.name ?? "Agent",
source
),
this.ensureUserExists(
userId,
userName ?? "User" + userId,
userScreenName ?? "User" + userId,
source
),
this.ensureRoomExists(roomId),
]);
await Promise.all([
this.ensureParticipantInRoom(userId, roomId),
this.ensureParticipantInRoom(this.agentId, roomId),
]);
}
/**
* Ensure the existence of a room between the agent and a user. If no room exists, a new room is created and the user
* and agent are added as participants. The room ID is returned.
* @param userId - The user ID to create a room with.
* @returns The room ID of the room between the agent and the user.
* @throws An error if the room cannot be created.
*/
async ensureRoomExists(roomId: UUID) {
const room = await this.databaseAdapter.getRoom(roomId);
if (!room) {
await this.databaseAdapter.createRoom(roomId);
elizaLogger.log(`Room ${roomId} created successfully.`);
}
}
/**
* Compose the state of the agent into an object that can be passed or used for response generation.
* @param message The message to compose the state from.
* @returns The state of the agent.
*/
async composeState(
message: Memory,
additionalKeys: { [key: string]: unknown } = {}
) {
const { userId, roomId } = message;
const conversationLength = this.getConversationLength();
const [actorsData, recentMessagesData, goalsData]: [
Actor[],
Memory[],
Goal[],
] = await Promise.all([
getActorDetails({ runtime: this, roomId }),
this.messageManager.getMemories({
roomId,
count: conversationLength,
unique: false,
}),
getGoals({
runtime: this,
count: 10,
onlyInProgress: false,
roomId,
}),
]);
const goals = formatGoalsAsString({ goals: goalsData });
const actors = formatActors({ actors: actorsData ?? [] });
const recentMessages = formatMessages({
messages: recentMessagesData,
actors: actorsData,
});
const recentPosts = formatPosts({
messages: recentMessagesData,
actors: actorsData,
conversationHeader: false,
});
// const lore = formatLore(loreData);
const senderName = actorsData?.find(
(actor: Actor) => actor.id === userId
)?.name;
// TODO: We may wish to consolidate and just accept character.name here instead of the actor name
const agentName =
actorsData?.find((actor: Actor) => actor.id === this.agentId)
?.name || this.character.name;
let allAttachments = message.content.attachments || [];
if (recentMessagesData && Array.isArray(recentMessagesData)) {
const lastMessageWithAttachment = recentMessagesData.find(
(msg) =>
msg.content.attachments &&
msg.content.attachments.length > 0
);
if (lastMessageWithAttachment) {
const lastMessageTime = lastMessageWithAttachment.createdAt;
const oneHourBeforeLastMessage =
lastMessageTime - 60 * 60 * 1000; // 1 hour before last message
allAttachments = recentMessagesData
.reverse()
.map((msg) => {
const msgTime = msg.createdAt ?? Date.now();
const isWithinTime =
msgTime >= oneHourBeforeLastMessage;
const attachments = msg.content.attachments || [];
if (!isWithinTime) {
attachments.forEach((attachment) => {
attachment.text = "[Hidden]";
});
}
return attachments;
})
.flat();
}
}
const formattedAttachments = allAttachments
.map(
(attachment) =>
`ID: ${attachment.id}
Name: ${attachment.title}
URL: ${attachment.url}
Type: ${attachment.source}
Description: ${attachment.description}
Text: ${attachment.text}
`
)
.join("\n");
// randomly get 3 bits of lore and join them into a paragraph, divided by \n
let lore = "";
// Assuming this.lore is an array of lore bits
if (this.character.lore && this.character.lore.length > 0) {
const shuffledLore = [...this.character.lore].sort(
() => Math.random() - 0.5
);
const selectedLore = shuffledLore.slice(0, 10);
lore = selectedLore.join("\n");
}
const formattedCharacterPostExamples = this.character.postExamples
.sort(() => 0.5 - Math.random())
.map((post) => {
const messageString = `${post}`;
return messageString;
})
.slice(0, 50)
.join("\n");
const formattedCharacterMessageExamples = this.character.messageExamples
.sort(() => 0.5 - Math.random())
.slice(0, 5)
.map((example) => {
const exampleNames = Array.from({ length: 5 }, () =>
uniqueNamesGenerator({ dictionaries: [names] })
);
return example
.map((message) => {
let messageString = `${message.user}: ${message.content.text}`;
exampleNames.forEach((name, index) => {
const placeholder = `{{user${index + 1}}}`;
messageString = messageString.replaceAll(
placeholder,
name
);
});
return messageString;
})
.join("\n");
})
.join("\n\n");
const getRecentInteractions = async (
userA: UUID,
userB: UUID
): Promise<Memory[]> => {
// Find all rooms where userA and userB are participants
const rooms = await this.databaseAdapter.getRoomsForParticipants([
userA,
userB,
]);
// Check the existing memories in the database
const existingMemories =
await this.messageManager.getMemoriesByRoomIds({
// filter out the current room id from rooms
roomIds: rooms.filter((room) => room !== roomId),
});
// Sort messages by timestamp in descending order
existingMemories.sort((a, b) => b.createdAt - a.createdAt);
// Take the most recent messages
const recentInteractionsData = existingMemories.slice(0, 20);
return recentInteractionsData;
};
const recentInteractions =
userId !== this.agentId
? await getRecentInteractions(userId, this.agentId)
: [];
const getRecentMessageInteractions = async (
recentInteractionsData: Memory[]
): Promise<string> => {
// Format the recent messages
const formattedInteractions = await Promise.all(
recentInteractionsData.map(async (message) => {
const isSelf = message.userId === this.agentId;
let sender: string;
if (isSelf) {
sender = this.character.name;
} else {
const accountId =
await this.databaseAdapter.getAccountById(
message.userId
);
sender = accountId?.username || "unknown";
}
return `${sender}: ${message.content.text}`;
})
);
return formattedInteractions.join("\n");
};
const formattedMessageInteractions =
await getRecentMessageInteractions(recentInteractions);
const getRecentPostInteractions = async (
recentInteractionsData: Memory[],
actors: Actor[]
): Promise<string> => {
const formattedInteractions = formatPosts({
messages: recentInteractionsData,
actors,
conversationHeader: true,
});
return formattedInteractions;
};
const formattedPostInteractions = await getRecentPostInteractions(
recentInteractions,
actorsData
);
// if bio is a string, use it. if its an array, pick one at random
let bio = this.character.bio || "";
if (Array.isArray(bio)) {
// get three random bio strings and join them with " "
bio = bio
.sort(() => 0.5 - Math.random())
.slice(0, 3)
.join(" ");
}
const knowledegeData = await knowledge.get(this, message);
const formattedKnowledge = formatKnowledge(knowledegeData);
const initialState = {
agentId: this.agentId,