Skip to content

Commit

Permalink
add retry import
Browse files Browse the repository at this point in the history
  • Loading branch information
tcm390 committed Feb 11, 2025
1 parent c934cde commit 388bd43
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 4 deletions.
11 changes: 9 additions & 2 deletions packages/agent/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import {
parseBooleanFromText,
settings,
stringToUuid,
validateCharacterConfig
validateCharacterConfig,
importWithRetry
} from "@elizaos/core";
import fs from "node:fs";
import net from "node:net";
Expand Down Expand Up @@ -342,13 +343,19 @@ function initializeCache(
);
}
}


async function findDatabaseAdapter(runtime: IAgentRuntime) {
const { adapters } = runtime;
let adapter: Adapter | undefined;
// if not found, default to sqlite
if (adapters.length === 0) {
const sqliteAdapterPlugin = await import('@elizaos-plugins/sqlite');
const sqliteAdapterPlugin = await importWithRetry<any>(
'@elizaos-plugins/sqlite',
3,
1000
);
// const sqliteAdapterPlugin = await import('@elizaos-plugins/sqlite');
const sqliteAdapterPluginDefault = sqliteAdapterPlugin.default;
adapter = sqliteAdapterPluginDefault.adapters[0];
if (!adapter) {
Expand Down
40 changes: 38 additions & 2 deletions packages/core/src/import.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,45 @@
import logger from "./logger";

/**
* Attempts to import a module with retry logic.
* @param modulePath - The module path to import.
* @param retries - Number of retry attempts (default: 3).
* @param delay - Delay between retries in milliseconds (default: 1000).
* @returns The imported module.
* @throws An error if all attempts fail.
*/
export async function importWithRetry<T = any>(
modulePath: string,
retries = 3,
delay = 1000
): Promise<T> {
for (let attempt = 1; attempt <= retries; attempt++) {
try {
return await import(modulePath);
} catch (error) {
if (attempt === retries) {
throw new Error(
`Failed to import ${modulePath} after ${retries} attempts: ${error}`
);
}
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
throw new Error("Unexpected error in importWithRetry");
}

const registrations = new Map<string, any>();

export const dynamicImport = async (specifier: string) => {
const module = registrations.get(specifier);
if (module !== undefined) {
return module;
} else {
return await import(specifier);
return await importWithRetry<any>(
specifier,
3,
1000
);
}
};

Expand All @@ -21,7 +53,11 @@ export async function handlePluginImporting(plugins: string[]) {
const importedPlugins = await Promise.all(
plugins.map(async (plugin) => {
try {
const importedPlugin = await import(plugin);
const importedPlugin = await importWithRetry<any>(
plugin,
3,
1000
);
const functionName =
`${plugin
.replace("@elizaos/plugin-", "")
Expand Down

0 comments on commit 388bd43

Please sign in to comment.