Skip to content

Commit 10aa5d6

Browse files
authored
Merge pull request #508 from antpb/fix/gracefully-pull-node-dep
Wrap `fastembed` in try catch to allow non node environments to build
2 parents f2dde70 + a0c2bb8 commit 10aa5d6

File tree

1 file changed

+27
-9
lines changed

1 file changed

+27
-9
lines changed

packages/core/src/embedding.ts

+27-9
Original file line numberDiff line numberDiff line change
@@ -142,10 +142,31 @@ async function getLocalEmbedding(input: string): Promise<number[]> {
142142
process.versions != null &&
143143
process.versions.node != null;
144144

145-
if (isNode) {
146-
const fs = await import("fs");
147-
const { FlagEmbedding } = await import("fastembed");
148-
const { fileURLToPath } = await import("url");
145+
if (!isNode) {
146+
elizaLogger.warn(
147+
"Local embedding not supported in browser, falling back to remote embedding"
148+
);
149+
throw new Error("Local embedding not supported in browser");
150+
}
151+
152+
try {
153+
// Try to dynamically import all required Node.js modules
154+
const moduleImports = await Promise.all([
155+
import("fs"),
156+
import("url"),
157+
// Wrap fastembed import in a try-catch to prevent build errors for non-Node.js environments.
158+
(async () => {
159+
try {
160+
return await import("fastembed");
161+
} catch (error) {
162+
elizaLogger.error("Failed to load fastembed.");
163+
throw new Error("fastembed import failed, falling back to remote embedding");
164+
}
165+
})()
166+
]);
167+
168+
const [fs, { fileURLToPath }, fastEmbed] = moduleImports;
169+
const { FlagEmbedding } = fastEmbed;
149170

150171
function getRootPath() {
151172
const __filename = fileURLToPath(import.meta.url);
@@ -172,11 +193,8 @@ async function getLocalEmbedding(input: string): Promise<number[]> {
172193
const trimmedInput = trimTokens(input, 8191, "gpt-4o-mini");
173194
const embedding = await embeddingModel.queryEmbed(trimmedInput);
174195
return embedding;
175-
} else {
176-
// Browser implementation - fallback to remote embedding
177-
elizaLogger.warn(
178-
"Local embedding not supported in browser, falling back to remote embedding"
179-
);
196+
} catch (error) {
197+
elizaLogger.warn("Local embedding not supported in browser, falling back to remote embedding.");
180198
throw new Error("Local embedding not supported in browser");
181199
}
182200
}

0 commit comments

Comments
 (0)