-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
374 lines (327 loc) · 10.5 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import { PostgresDatabaseAdapter } from "@ai16z/adapter-postgres";
import { SqliteDatabaseAdapter } from "@ai16z/adapter-sqlite";
import { DirectClientInterface } from "@ai16z/client-direct";
import { DiscordClientInterface } from "@ai16z/client-discord";
import { AutoClientInterface } from "@ai16z/client-auto";
import { TelegramClientInterface } from "@ai16z/client-telegram";
import { TwitterClientInterface } from "@ai16z/client-twitter";
import {
DbCacheAdapter,
defaultCharacter,
FsCacheAdapter,
ICacheManager,
IDatabaseCacheAdapter,
stringToUuid,
AgentRuntime,
CacheManager,
Character,
IAgentRuntime,
ModelProviderName,
elizaLogger,
settings,
IDatabaseAdapter,
validateCharacterConfig,
} from "@ai16z/eliza";
import { bootstrapPlugin } from "@ai16z/plugin-bootstrap";
import { solanaPlugin } from "@ai16z/plugin-solana";
import { nodePlugin } from "@ai16z/plugin-node";
import Database from "better-sqlite3";
import fs from "fs";
import readline from "readline";
import yargs from "yargs";
import path from "path";
import { fileURLToPath } from "url";
import { character } from "./character.ts";
import type { DirectClient } from "@ai16z/client-direct";
import { StorageService } from "./services/storage.service.ts";
const __filename = fileURLToPath(import.meta.url); // get the resolved path to the file
const __dirname = path.dirname(__filename); // get the name of the directory
export const wait = (minTime: number = 1000, maxTime: number = 3000) => {
const waitTime =
Math.floor(Math.random() * (maxTime - minTime + 1)) + minTime;
return new Promise((resolve) => setTimeout(resolve, waitTime));
};
export function parseArguments(): {
character?: string;
characters?: string;
} {
try {
return yargs(process.argv.slice(2))
.option("character", {
type: "string",
description: "Path to the character JSON file",
})
.option("characters", {
type: "string",
description: "Comma separated list of paths to character JSON files",
}).argv;
} catch (error) {
console.error("Error parsing arguments:", error);
return {};
}
}
export async function loadCharacters(
charactersArg: string
): Promise<Character[]> {
let characterPaths = charactersArg?.split(",").map((filePath) => {
if (path.basename(filePath) === filePath) {
filePath = "../characters/" + filePath;
}
return path.resolve(process.cwd(), filePath.trim());
});
const loadedCharacters = [];
if (characterPaths?.length > 0) {
for (const path of characterPaths) {
try {
const character = JSON.parse(fs.readFileSync(path, "utf8"));
validateCharacterConfig(character);
loadedCharacters.push(character);
} catch (e) {
console.error(`Error loading character from ${path}: ${e}`);
// don't continue to load if a specified file is not found
process.exit(1);
}
}
}
if (loadedCharacters.length === 0) {
console.log("No characters found, using default character");
loadedCharacters.push(defaultCharacter);
}
return loadedCharacters;
}
export function getTokenForProvider(
provider: ModelProviderName,
character: Character
) {
switch (provider) {
case ModelProviderName.OPENAI:
return (
character.settings?.secrets?.OPENAI_API_KEY || settings.OPENAI_API_KEY
);
case ModelProviderName.LLAMACLOUD:
return (
character.settings?.secrets?.LLAMACLOUD_API_KEY ||
settings.LLAMACLOUD_API_KEY ||
character.settings?.secrets?.TOGETHER_API_KEY ||
settings.TOGETHER_API_KEY ||
character.settings?.secrets?.XAI_API_KEY ||
settings.XAI_API_KEY ||
character.settings?.secrets?.OPENAI_API_KEY ||
settings.OPENAI_API_KEY
);
case ModelProviderName.ANTHROPIC:
return (
character.settings?.secrets?.ANTHROPIC_API_KEY ||
character.settings?.secrets?.CLAUDE_API_KEY ||
settings.ANTHROPIC_API_KEY ||
settings.CLAUDE_API_KEY
);
case ModelProviderName.REDPILL:
return (
character.settings?.secrets?.REDPILL_API_KEY || settings.REDPILL_API_KEY
);
case ModelProviderName.OPENROUTER:
return (
character.settings?.secrets?.OPENROUTER || settings.OPENROUTER_API_KEY
);
case ModelProviderName.GROK:
return character.settings?.secrets?.GROK_API_KEY || settings.GROK_API_KEY;
case ModelProviderName.HEURIST:
return (
character.settings?.secrets?.HEURIST_API_KEY || settings.HEURIST_API_KEY
);
case ModelProviderName.GROQ:
return character.settings?.secrets?.GROQ_API_KEY || settings.GROQ_API_KEY;
}
}
function initializeDatabase(dataDir: string) {
if (process.env.POSTGRES_URL) {
const db = new PostgresDatabaseAdapter({
connectionString: process.env.POSTGRES_URL,
});
return db;
} else {
const filePath =
process.env.SQLITE_FILE ?? path.resolve(dataDir, "db.sqlite");
// ":memory:";
const db = new SqliteDatabaseAdapter(new Database(filePath));
return db;
}
}
export async function initializeClients(
character: Character,
runtime: IAgentRuntime
) {
const clients = [];
const clientTypes = character.clients?.map((str) => str.toLowerCase()) || [];
if (clientTypes.includes("auto")) {
const autoClient = await AutoClientInterface.start(runtime);
if (autoClient) clients.push(autoClient);
}
if (clientTypes.includes("discord")) {
clients.push(await DiscordClientInterface.start(runtime));
}
if (clientTypes.includes("telegram")) {
const telegramClient = await TelegramClientInterface.start(runtime);
if (telegramClient) clients.push(telegramClient);
}
if (clientTypes.includes("twitter")) {
const twitterClients = await TwitterClientInterface.start(runtime);
clients.push(twitterClients);
}
if (character.plugins?.length > 0) {
for (const plugin of character.plugins) {
if (plugin.clients) {
for (const client of plugin.clients) {
clients.push(await client.start(runtime));
}
}
}
}
return clients;
}
export function createAgent(
character: Character,
db: IDatabaseAdapter,
cache: ICacheManager,
token: string
) {
elizaLogger.success(
elizaLogger.successesTitle,
"Creating runtime for character",
character.name
);
return new AgentRuntime({
databaseAdapter: db,
token,
modelProvider: character.modelProvider,
evaluators: [],
character,
plugins: [
bootstrapPlugin,
nodePlugin,
character.settings.secrets?.WALLET_PUBLIC_KEY ? solanaPlugin : null,
].filter(Boolean),
providers: [],
actions: [],
services: [],
managers: [],
cacheManager: cache,
});
}
function intializeFsCache(baseDir: string, character: Character) {
const cacheDir = path.resolve(baseDir, character.id, "cache");
const cache = new CacheManager(new FsCacheAdapter(cacheDir));
return cache;
}
function intializeDbCache(character: Character, db: IDatabaseCacheAdapter) {
const cache = new CacheManager(new DbCacheAdapter(db, character.id));
return cache;
}
async function startAgent(character: Character, directClient: DirectClient) {
try {
character.id ??= stringToUuid(character.name);
character.username ??= character.name;
const token = getTokenForProvider(character.modelProvider, character);
const dataDir = path.join(__dirname, "../data");
if (!fs.existsSync(dataDir)) {
fs.mkdirSync(dataDir, { recursive: true });
}
const db = initializeDatabase(dataDir);
await db.init();
const cache = intializeDbCache(character, db);
const runtime = createAgent(character, db, cache, token);
await runtime.initialize();
const clients = await initializeClients(character, runtime);
directClient.registerAgent(runtime);
return clients;
} catch (error) {
elizaLogger.error(
`Error starting agent for character ${character.name}:`,
error
);
console.error(error);
throw error;
}
}
const startAgents = async () => {
const directClient = await DirectClientInterface.start();
const args = parseArguments();
let charactersArg = args.characters || args.character;
let characters = [character];
console.log("charactersArg", charactersArg);
if (charactersArg) {
characters = await loadCharacters(charactersArg);
}
console.log("characters", characters);
try {
for (const character of characters) {
await startAgent(character, directClient as DirectClient);
}
} catch (error) {
elizaLogger.error("Error starting agents:", error);
}
function chat() {
const agentId = characters[0].name ?? "Agent";
rl.question("You: ", async (input) => {
await handleUserInput(input, agentId);
if (input.toLowerCase() !== "exit") {
chat(); // Loop back to ask another question
}
});
}
elizaLogger.log("Chat started. Type 'exit' to quit.");
chat();
};
startAgents().catch((error) => {
elizaLogger.error("Unhandled error in startAgents:", error);
process.exit(1); // Exit the process after logging
});
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.on("SIGINT", () => {
rl.close();
process.exit(0);
});
async function handleUserInput(input, agentId) {
if (input.toLowerCase() === "exit") {
rl.close();
process.exit(0);
return;
}
try {
const storageService = StorageService.getInstance();
await storageService.start();
const serverPort = parseInt(settings.SERVER_PORT || "3000");
// create embedding, encrypt plaintext, and store in Orbis
await storageService.storeMessageWithEmbedding(input, true);
// obtain relevant context from encrypted database
const relevantContext = await storageService.getEmbeddingContext(input);
console.log("Relevant Context: ", relevantContext);
const combined =
input +
" This is some additional context that might help with your response" +
relevantContext;
const response = await fetch(
`http://localhost:${serverPort}/${agentId}/message`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
text: combined,
userId: "user",
userName: "User",
}),
}
);
const data = await response.json();
data.forEach(async (message) => {
await storageService.storeMessageWithEmbedding(input, false);
console.log(`${"Agent"}: ${message.text}`);
});
} catch (error) {
console.error("Error fetching response:", error);
}
}