1- import { pipeline } from '@huggingface/transformers' ;
2- import { EmbeddingError } from './errors' ;
1+ import { EmbeddingError , ConfigurationError } from './errors' ;
2+
3+ // Dynamic import type for @huggingface /transformers
4+ type PipelineFunction = typeof import ( '@huggingface/transformers' ) . pipeline ;
35
46/**
57 * Service for generating embeddings using transformers.js
8+ *
9+ * NOTE: This service requires @huggingface/transformers to be installed.
10+ * Install it with: npm install @huggingface/transformers
11+ *
12+ * For a zero-dependency alternative, use TFIDFEmbeddingService instead.
613 */
714export class EmbeddingService {
815 private pipeline : any = null ;
@@ -17,6 +24,23 @@ export class EmbeddingService {
1724 this . cacheDir = cacheDir ;
1825 }
1926
27+ /**
28+ * Dynamically import @huggingface/transformers
29+ * This allows the package to be optional - only loaded when actually used
30+ */
31+ private async loadTransformers ( ) : Promise < PipelineFunction > {
32+ try {
33+ const transformers = await import ( '@huggingface/transformers' ) ;
34+ return transformers . pipeline ;
35+ } catch ( error ) {
36+ throw new ConfigurationError (
37+ '@huggingface/transformers is not installed. ' +
38+ 'Install it with: npm install @huggingface/transformers\n' +
39+ 'Or use TFIDFVectoria/TFIDFEmbeddingService for a zero-dependency alternative.' ,
40+ ) ;
41+ }
42+ }
43+
2044 /**
2145 * Initialize the embedding model
2246 */
@@ -36,8 +60,11 @@ export class EmbeddingService {
3660
3761 private async _initialize ( ) : Promise < void > {
3862 try {
63+ // Dynamically load transformers
64+ const pipelineFn = await this . loadTransformers ( ) ;
65+
3966 // Create feature extraction pipeline
40- this . pipeline = await pipeline ( 'feature-extraction' , this . modelName , {
67+ this . pipeline = await pipelineFn ( 'feature-extraction' , this . modelName , {
4168 // Use local models directory to cache models
4269 cache_dir : this . cacheDir ,
4370 // // Don't require progress bars in production
@@ -54,6 +81,9 @@ export class EmbeddingService {
5481 this . isInitialized = true ;
5582 } catch ( error ) {
5683 this . initializationPromise = null ;
84+ if ( error instanceof ConfigurationError ) {
85+ throw error ;
86+ }
5787 throw new EmbeddingError (
5888 `Failed to initialize embedding model: ${ error instanceof Error ? error . message : String ( error ) } ` ,
5989 error instanceof Error ? error : undefined ,
0 commit comments