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

fix: move fastembed import to the isnode condition check #709

Merged
merged 2 commits into from
Nov 30, 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
33 changes: 26 additions & 7 deletions packages/core/src/embedding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { models } from "./models.ts";
import { IAgentRuntime, ModelProviderName } from "./types.ts";
import settings from "./settings.ts";
import elizaLogger from "./logger.ts";
import { EmbeddingModel } from "fastembed";

interface EmbeddingOptions {
model: string;
endpoint: string;
Expand All @@ -27,7 +27,7 @@ export const getEmbeddingConfig = () => ({
? "text-embedding-3-small"
: settings.USE_OLLAMA_EMBEDDING?.toLowerCase() === "true"
? settings.OLLAMA_EMBEDDING_MODEL || "mxbai-embed-large"
: EmbeddingModel.BGESmallENV15,
: "BGE-small-en-v1.5",
provider:
settings.USE_OPENAI_EMBEDDING?.toLowerCase() === "true"
? "OpenAI"
Expand Down Expand Up @@ -215,10 +215,29 @@ export async function embed(runtime: IAgentRuntime, input: string) {
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 {
const moduleImports = await Promise.all([
import("fs"),
import("url"),
(async () => {
try {
return await import("fastembed");
} catch {
elizaLogger.error("Failed to load fastembed.");
throw new Error("fastembed import failed, falling back to remote embedding");
}
})()
]);

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

function getRootPath() {
const __filename = fileURLToPath(import.meta.url);
Expand Down Expand Up @@ -319,7 +338,7 @@ export async function embed(runtime: IAgentRuntime, input: string) {
}

return finalEmbedding;
} else {
} catch {
// Browser implementation - fallback to remote embedding
elizaLogger.warn(
"Local embedding not supported in browser, falling back to remote embedding"
Expand Down
Loading