MCPcopy Create free account
hub / github.com/PatrickSys/codebase-context / TransformersEmbeddingProvider

Class TransformersEmbeddingProvider

src/embeddings/transformers.ts:41–154  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

39}
40
41export class TransformersEmbeddingProvider implements EmbeddingProvider {
42 readonly name = 'transformers';
43 readonly modelName: string;
44 readonly dimensions: number;
45
46 private pipeline: FeatureExtractionPipelineType | null = null;
47 private ready = false;
48 private initPromise: Promise<void> | null = null;
49
50 constructor(modelName: string = DEFAULT_MODEL) {
51 this.modelName = modelName;
52 this.dimensions = MODEL_CONFIGS[modelName]?.dimensions || 384;
53 }
54
55 async initialize(): Promise<void> {
56 if (this.ready) return;
57 if (this.initPromise) return this.initPromise;
58
59 this.initPromise = this._initialize();
60 return this.initPromise;
61 }
62
63 private async _initialize(): Promise<void> {
64 try {
65 if (process.env.CODEBASE_CONTEXT_DEBUG) {
66 console.error(`Loading embedding model: ${this.modelName}`);
67 console.error('(First run will download the model - this may take a moment)');
68 }
69
70 const { pipeline } = await import('@huggingface/transformers');
71
72 // TS2590: pipeline() resolves AllTasks[T] — a union too complex for TSC to represent.
73 // Cast to a simpler signature; the actual return type IS FeatureExtractionPipelineType.
74 type PipelineFn = (
75 task: 'feature-extraction',
76 model: string,
77 opts: Record<string, unknown>
78 ) => Promise<FeatureExtractionPipelineType>;
79 this.pipeline = await (pipeline as PipelineFn)('feature-extraction', this.modelName, {
80 dtype: 'q8',
81 // Limit ONNX Runtime to half cores by default — prevents system freeze during indexing.
82 // interOpNumThreads: 1 — no benefit for single-model pipelines.
83 // Override via CODEBASE_CONTEXT_ONNX_THREADS env var.
84 session_options: {
85 intraOpNumThreads: getOnnxThreadCount(),
86 interOpNumThreads: 1
87 }
88 });
89
90 this.ready = true;
91 if (process.env.CODEBASE_CONTEXT_DEBUG) {
92 console.error(`Model loaded successfully: ${this.modelName}`);
93 }
94 } catch (error) {
95 console.error('Failed to initialize embedding model:', error);
96 throw error;
97 }
98 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected