Skip to content

Commit

Permalink
package up core and introduce plugins
Browse files Browse the repository at this point in the history
  • Loading branch information
ponderingdemocritus committed Nov 6, 2024
1 parent 52467d6 commit 04c9bac
Show file tree
Hide file tree
Showing 36 changed files with 1,562 additions and 314 deletions.
124 changes: 124 additions & 0 deletions agent/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import {
Character,
createAgentRuntime,
createDirectRuntime,
DirectClient,
getTokenForProvider,
IAgentRuntime,
initializeClients,
initializeDatabase,
loadCharacters,
parseArguments,
} from "@eliza/core";
import { Arguments } from "@eliza/core/src/types";
import readline from "readline";

let argv: Arguments = parseArguments();
let basePath = "./";
// if argv.isroot is true, then set the base path to "../"
if (argv.isRoot) {
basePath = "../";
}

// if the path doesnt start with a /, add the base path to the beginning of the path
if (!argv.characters?.startsWith("/")) {
argv.characters = `${basePath}${argv.characters}`;
}

let characters = loadCharacters(argv.characters);
if (!characters || characters.length === 0) {
console.error("No characters loaded. Please check the characters file.");
process.exit(1);
}

characters.forEach((char, index) => {
if (!char.name || !char.modelProvider) {
console.error(
`Character at index ${index} is missing required fields.`
);
process.exit(1);
}
});

const directClient = new DirectClient();

const serverPort = parseInt(process.env.SERVER_PORT || "3000");
directClient.start(serverPort);

async function startAgent(character: Character) {
try {
const token = getTokenForProvider(character.modelProvider, character);
const db = initializeDatabase();

const runtime = await createAgentRuntime(character, db, token);
const directRuntime = createDirectRuntime(character, db, token);

const clients = await initializeClients(
character,
runtime as IAgentRuntime
);
directClient.registerAgent(await directRuntime);

return clients;
} catch (error) {
console.error(
`Error starting agent for character ${character.name}:`,
error
);
throw error; // Re-throw after logging
}
}

const startAgents = async () => {
try {
for (const character of characters) {
await startAgent(character);
}
} catch (error) {
console.error("Error starting agents:", error);
}
};

startAgents().catch((error) => {
console.error("Unhandled error in startAgents:", error);
process.exit(1); // Exit the process after logging
});

const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});

function chat() {
rl.question("You: ", async (input) => {
if (input.toLowerCase() === "exit") {
rl.close();
return;
}

const agentId = characters[0].name.toLowerCase();
const response = await fetch(
`http://localhost:3000/${agentId}/message`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
text: input,
userId: "user",
userName: "User",
}),
}
);

const data = await response.json();
for (const message of data) {
console.log(`${characters[0].name}: ${message.text}`);
}
chat();
});
}

console.log("Chat started. Type 'exit' to quit.");
chat();
18 changes: 18 additions & 0 deletions agent/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "@eliza/agent",
"version": "0.0.1",
"main": "index.ts",
"type": "module",
"scripts": {
"build": "tsup --format esm --dts",
"start": "node --loader ts-node/esm index.ts --characters=\"../characters/blobert.character.json\""
},
"dependencies": {
"@eliza/core": "workspace:*",
"readline": "^1.3.0",
"tsup": "^8.3.5"
},
"devDependencies": {
"ts-node": "10.9.2"
}
}
7 changes: 7 additions & 0 deletions agent/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "dist"
},
"include": ["."]
}
8 changes: 8 additions & 0 deletions agent/tsup.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { defineConfig } from "tsup";

export default defineConfig({
entry: ["index.ts"],
outDir: "dist",
sourcemap: true,
clean: true,
});
9 changes: 5 additions & 4 deletions core/package.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
{
"name": "eliza",
"name": "@eliza/core",
"version": "1.0.0",
"description": "",
"main": "dist/index.js",
"type": "module",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc -p tsconfig.json",
"build": "tsup --format esm --dts",
"lint": "eslint . --fix",
"start": "node --loader ts-node/esm src/index.ts",
"start": "node --loader ts-node/esm src/index.ts --characters=\"../characters/blobert.character.json\"",
"start:arok": "node --loader ts-node/esm src/index.ts --characters=\"../characters/arok.character.json\"",
"start:service:ruby": "pm2 start pnpm --name=\"ruby\" --restart-delay=3000 --max-restarts=10 -- run start:ruby",
"stop:service:ruby": "pm2 stop ruby",
Expand Down Expand Up @@ -84,8 +84,8 @@
"@anthropic-ai/sdk": "^0.30.1",
"@cliqz/adblocker-playwright": "1.34.0",
"@coral-xyz/anchor": "^0.30.1",
"@discordjs/rest": "2.4.0",
"@discordjs/opus": "github:discordjs/opus",
"@discordjs/rest": "2.4.0",
"@discordjs/voice": "0.17.0",
"@echogarden/espeak-ng-emscripten": "0.3.0",
"@echogarden/kissfft-wasm": "0.2.0",
Expand Down Expand Up @@ -163,6 +163,7 @@
"tiktoken": "1.0.17",
"tinyld": "1.3.4",
"together-ai": "^0.7.0",
"tsup": "^8.3.5",
"unique-names-generator": "4.7.1",
"uuid": "11.0.2",
"wav": "1.0.2",
Expand Down
18 changes: 9 additions & 9 deletions core/src/actions/imageGeneration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
State,
Action,
} from "../core/types.ts";
import { prettyConsole } from "../index.ts";
import { elizaLog } from "../index.ts";
import { generateCaption, generateImage } from "./imageGenerationUtils.ts";

export const imageGeneration: Action = {
Expand All @@ -27,19 +27,19 @@ export const imageGeneration: Action = {
options: any,
callback: HandlerCallback
) => {
prettyConsole.log("Composing state for message:", message);
elizaLog.log("Composing state for message:", message);
state = (await runtime.composeState(message)) as State;
const userId = runtime.agentId;
prettyConsole.log("User ID:", userId);
elizaLog.log("User ID:", userId);

const imagePrompt = message.content.text;
prettyConsole.log("Image prompt received:", imagePrompt);
elizaLog.log("Image prompt received:", imagePrompt);

// TODO: Generate a prompt for the image

const res: { image: string; caption: string }[] = [];

prettyConsole.log("Generating image with prompt:", imagePrompt);
elizaLog.log("Generating image with prompt:", imagePrompt);
const images = await generateImage(
{
prompt: imagePrompt,
Expand All @@ -51,13 +51,13 @@ export const imageGeneration: Action = {
);

if (images.success && images.data && images.data.length > 0) {
prettyConsole.log(
elizaLog.log(
"Image generation successful, number of images:",
images.data.length
);
for (let i = 0; i < images.data.length; i++) {
const image = images.data[i];
prettyConsole.log(`Processing image ${i + 1}:`, image);
elizaLog.log(`Processing image ${i + 1}:`, image);

const caption = await generateCaption(
{
Expand All @@ -66,7 +66,7 @@ export const imageGeneration: Action = {
runtime
);

prettyConsole.log(
elizaLog.log(
`Generated caption for image ${i + 1}:`,
caption.title
);
Expand All @@ -90,7 +90,7 @@ export const imageGeneration: Action = {
);
}
} else {
prettyConsole.error("Image generation failed or returned no data.");
elizaLog.error("Image generation failed or returned no data.");
}
},
examples: [
Expand Down
6 changes: 3 additions & 3 deletions core/src/adapters/sqlite/sqlite_vec.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import * as sqliteVec from "sqlite-vec";
import { Database } from "better-sqlite3";
import { prettyConsole } from "../../index.ts";
import { elizaLog } from "../../index.ts";

// Loads the sqlite-vec extensions into the provided SQLite database
export function loadVecExtensions(db: Database): void {
try {
// Load sqlite-vec extensions
sqliteVec.load(db);
prettyConsole.log("sqlite-vec extensions loaded successfully.");
elizaLog.log("sqlite-vec extensions loaded successfully.");
} catch (error) {
prettyConsole.error("Failed to load sqlite-vec extensions:", error);
elizaLog.error("Failed to load sqlite-vec extensions:", error);
throw error;
}
}
Expand Down
2 changes: 1 addition & 1 deletion core/src/cli/colors.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export class PrettyConsole {
export class elizaLog {
closeByNewLine = true;
useIcons = true;
logsTitle = "LOGS";
Expand Down
6 changes: 3 additions & 3 deletions core/src/cli/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import yaml from "js-yaml";
import path from "path";
import { fileURLToPath } from "url";
import { Action } from "../core/types";
import { prettyConsole } from "../index.ts";
import { elizaLog } from "../index.ts";

const ROOT_DIR = path.resolve(fileURLToPath(import.meta.url), "../../../src");

Expand All @@ -30,13 +30,13 @@ export async function loadCustomActions(

for (const config of actionConfigs) {
const resolvedPath = path.resolve(ROOT_DIR, config.path);
prettyConsole.log(`Importing action from: ${resolvedPath}`); // Debugging log
elizaLog.log(`Importing action from: ${resolvedPath}`); // Debugging log

try {
const actionModule = await import(resolvedPath);
actions.push(actionModule[config.name]);
} catch (error) {
prettyConsole.error(
elizaLog.error(
`Failed to import action from ${resolvedPath}:`,
error
);
Expand Down
13 changes: 6 additions & 7 deletions core/src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { AgentRuntime } from "../core/runtime.ts";
import { defaultActions } from "../core/actions.ts";
import { Arguments } from "../types/index.ts";
import { loadActionConfigs, loadCustomActions } from "./config.ts";
import { prettyConsole } from "../index.ts";
import { elizaLog } from "../index.ts";

export async function initializeClients(
character: Character,
Expand Down Expand Up @@ -76,7 +76,6 @@ export function loadCharacters(charactersArg: string): Character[] {
return path;
});


const loadedCharacters = [];

if (characterPaths?.length > 0) {
Expand Down Expand Up @@ -210,11 +209,11 @@ export async function startTelegram(
runtime: IAgentRuntime,
character: Character
) {
prettyConsole.log("🔍 Attempting to start Telegram bot...");
elizaLog.log("🔍 Attempting to start Telegram bot...");
const botToken = runtime.getSetting("TELEGRAM_BOT_TOKEN");

if (!botToken) {
prettyConsole.error(
elizaLog.error(
`❌ Telegram bot token is not set for character ${character.name}.`
);
return null;
Expand All @@ -223,12 +222,12 @@ export async function startTelegram(
try {
const telegramClient = new Client.TelegramClient(runtime, botToken);
await telegramClient.start();
prettyConsole.success(
elizaLog.success(
`✅ Telegram client successfully started for character ${character.name}`
);
return telegramClient;
} catch (error) {
prettyConsole.error(
elizaLog.error(
`❌ Error creating/starting Telegram client for ${character.name}:`,
error
);
Expand All @@ -237,7 +236,7 @@ export async function startTelegram(
}

export async function startTwitter(runtime: IAgentRuntime) {
prettyConsole.log("Starting Twitter clients...");
elizaLog.log("Starting Twitter clients...");
const twitterSearchClient = new Client.TwitterSearchClient(runtime);
await wait();
const twitterInteractionClient = new Client.TwitterInteractionClient(
Expand Down
Loading

0 comments on commit 04c9bac

Please sign in to comment.