@@ -142,10 +142,31 @@ async function getLocalEmbedding(input: string): Promise<number[]> {
142
142
process . versions != null &&
143
143
process . versions . node != null ;
144
144
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 ;
149
170
150
171
function getRootPath ( ) {
151
172
const __filename = fileURLToPath ( import . meta. url ) ;
@@ -172,11 +193,8 @@ async function getLocalEmbedding(input: string): Promise<number[]> {
172
193
const trimmedInput = trimTokens ( input , 8191 , "gpt-4o-mini" ) ;
173
194
const embedding = await embeddingModel . queryEmbed ( trimmedInput ) ;
174
195
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." ) ;
180
198
throw new Error ( "Local embedding not supported in browser" ) ;
181
199
}
182
200
}
0 commit comments