import { Injectable, Logger } from '@nestjs/common'; import { EMBEDDING_DIM, env } from '../config/env'; import { EmbedKind, EmbeddingProvider } from './types'; /** CommonJS 빌드에서 ESM 전용 패키지를 로드하기 위한 우회 (TS 가 require 로 바꾸지 못하게 한다) */ const esmImport = new Function('s', 'return import(s)') as (s: string) => Promise; /** 로컬 multilingual-e5-small (384차원, onnxruntime CPU). */ @Injectable() export class LocalEmbeddingProvider extends EmbeddingProvider { readonly name = 'local:multilingual-e5-small'; readonly dimensions = EMBEDDING_DIM; private readonly logger = new Logger(LocalEmbeddingProvider.name); private extractor: any | null = null; private loading: Promise | null = null; private async pipe() { if (this.extractor) return this.extractor; if (!this.loading) { this.loading = (async () => { const t0 = Date.now(); const { pipeline } = await esmImport('@huggingface/transformers'); const fe = await pipeline('feature-extraction', env.embedding.localModel); this.logger.log(`model ready: ${env.embedding.localModel} (${Date.now() - t0}ms)`); this.extractor = fe; return fe; })(); } return this.loading; } async embed(texts: string[], kind: EmbedKind = 'passage'): Promise { if (texts.length === 0) return []; const fe = await this.pipe(); const prefixed = texts.map((t) => `${kind}: ${t}`); const out: number[][] = []; const BATCH = 64; for (let i = 0; i < prefixed.length; i += BATCH) { const slice = prefixed.slice(i, i + BATCH); const res = await fe(slice, { pooling: 'mean', normalize: true }); out.push(...(res.tolist() as number[][])); } return out; } }