Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrap fastembed in try catch to allow non node environments to build #508

Merged
merged 3 commits into from
Nov 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 27 additions & 9 deletions packages/core/src/embedding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,10 +126,31 @@ async function getLocalEmbedding(input: string): Promise<number[]> {
process.versions != null &&
process.versions.node != null;

if (isNode) {
const fs = await import("fs");
const { FlagEmbedding } = await import("fastembed");
const { fileURLToPath } = await import("url");
if (!isNode) {
elizaLogger.warn(
"Local embedding not supported in browser, falling back to remote embedding"
);
throw new Error("Local embedding not supported in browser");
}

try {
// Try to dynamically import all required Node.js modules
const moduleImports = await Promise.all([
import("fs"),
import("url"),
// Wrap fastembed import in a try-catch to prevent build errors for non-Node.js environments.
(async () => {
try {
return await import("fastembed");
} catch (error) {
elizaLogger.error("Failed to load fastembed.");
throw new Error("fastembed import failed, falling back to remote embedding");
}
})()
]);

const [fs, { fileURLToPath }, fastEmbed] = moduleImports;
const { FlagEmbedding } = fastEmbed;

function getRootPath() {
const __filename = fileURLToPath(import.meta.url);
Expand All @@ -156,11 +177,8 @@ async function getLocalEmbedding(input: string): Promise<number[]> {
const trimmedInput = trimTokens(input, 8000, "gpt-4o-mini");
const embedding = await embeddingModel.queryEmbed(trimmedInput);
return embedding;
} else {
// Browser implementation - fallback to remote embedding
elizaLogger.warn(
"Local embedding not supported in browser, falling back to remote embedding"
);
} catch (error) {
elizaLogger.warn("Local embedding not supported in browser, falling back to remote embedding.");
throw new Error("Local embedding not supported in browser");
}
}
Expand Down
Loading