llm.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  1. /**
  2. * llm.ts - LLM abstraction layer for QMD using node-llama-cpp
  3. *
  4. * Provides embeddings, text generation, and reranking using local GGUF models.
  5. */
  6. import {
  7. getLlama,
  8. getLlamaGpuTypes,
  9. resolveModelFile,
  10. LlamaChatSession,
  11. LlamaLogLevel,
  12. type Llama,
  13. type LlamaModel,
  14. type LlamaEmbeddingContext,
  15. type Token as LlamaToken,
  16. } from "node-llama-cpp";
  17. import { homedir } from "os";
  18. import { join } from "path";
  19. import { existsSync, mkdirSync, statSync, unlinkSync, readdirSync, readFileSync, writeFileSync } from "fs";
  20. // =============================================================================
  21. // Embedding Formatting Functions
  22. // =============================================================================
  23. /**
  24. * Format a query for embedding.
  25. * Uses nomic-style task prefix format for embeddinggemma.
  26. */
  27. export function formatQueryForEmbedding(query: string): string {
  28. return `task: search result | query: ${query}`;
  29. }
  30. /**
  31. * Format a document for embedding.
  32. * Uses nomic-style format with title and text fields.
  33. */
  34. export function formatDocForEmbedding(text: string, title?: string): string {
  35. return `title: ${title || "none"} | text: ${text}`;
  36. }
  37. // =============================================================================
  38. // Types
  39. // =============================================================================
  40. /**
  41. * Token with log probability
  42. */
  43. export type TokenLogProb = {
  44. token: string;
  45. logprob: number;
  46. };
  47. /**
  48. * Embedding result
  49. */
  50. export type EmbeddingResult = {
  51. embedding: number[];
  52. model: string;
  53. };
  54. /**
  55. * Generation result with optional logprobs
  56. */
  57. export type GenerateResult = {
  58. text: string;
  59. model: string;
  60. logprobs?: TokenLogProb[];
  61. done: boolean;
  62. };
  63. /**
  64. * Rerank result for a single document
  65. */
  66. export type RerankDocumentResult = {
  67. file: string;
  68. score: number;
  69. index: number;
  70. };
  71. /**
  72. * Batch rerank result
  73. */
  74. export type RerankResult = {
  75. results: RerankDocumentResult[];
  76. model: string;
  77. };
  78. /**
  79. * Model info
  80. */
  81. export type ModelInfo = {
  82. name: string;
  83. exists: boolean;
  84. path?: string;
  85. };
  86. /**
  87. * Options for embedding
  88. */
  89. export type EmbedOptions = {
  90. model?: string;
  91. isQuery?: boolean;
  92. title?: string;
  93. };
  94. /**
  95. * Options for text generation
  96. */
  97. export type GenerateOptions = {
  98. model?: string;
  99. maxTokens?: number;
  100. temperature?: number;
  101. };
  102. /**
  103. * Options for reranking
  104. */
  105. export type RerankOptions = {
  106. model?: string;
  107. };
  108. /**
  109. * Options for LLM sessions
  110. */
  111. export type LLMSessionOptions = {
  112. /** Max session duration in ms (default: 10 minutes) */
  113. maxDuration?: number;
  114. /** External abort signal */
  115. signal?: AbortSignal;
  116. /** Debug name for logging */
  117. name?: string;
  118. };
  119. /**
  120. * Session interface for scoped LLM access with lifecycle guarantees
  121. */
  122. export interface ILLMSession {
  123. embed(text: string, options?: EmbedOptions): Promise<EmbeddingResult | null>;
  124. embedBatch(texts: string[]): Promise<(EmbeddingResult | null)[]>;
  125. expandQuery(query: string, options?: { context?: string; includeLexical?: boolean }): Promise<Queryable[]>;
  126. rerank(query: string, documents: RerankDocument[], options?: RerankOptions): Promise<RerankResult>;
  127. /** Whether this session is still valid (not released or aborted) */
  128. readonly isValid: boolean;
  129. /** Abort signal for this session (aborts on release or maxDuration) */
  130. readonly signal: AbortSignal;
  131. }
  132. /**
  133. * Supported query types for different search backends
  134. */
  135. export type QueryType = 'lex' | 'vec' | 'hyde';
  136. /**
  137. * A single query and its target backend type
  138. */
  139. export type Queryable = {
  140. type: QueryType;
  141. text: string;
  142. };
  143. /**
  144. * Document to rerank
  145. */
  146. export type RerankDocument = {
  147. file: string;
  148. text: string;
  149. title?: string;
  150. };
  151. // =============================================================================
  152. // Model Configuration
  153. // =============================================================================
  154. // HuggingFace model URIs for node-llama-cpp
  155. // Format: hf:<user>/<repo>/<file>
  156. const DEFAULT_EMBED_MODEL = "hf:ggml-org/embeddinggemma-300M-GGUF/embeddinggemma-300M-Q8_0.gguf";
  157. const DEFAULT_RERANK_MODEL = "hf:ggml-org/Qwen3-Reranker-0.6B-Q8_0-GGUF/qwen3-reranker-0.6b-q8_0.gguf";
  158. // const DEFAULT_GENERATE_MODEL = "hf:ggml-org/Qwen3-0.6B-GGUF/Qwen3-0.6B-Q8_0.gguf";
  159. const DEFAULT_GENERATE_MODEL = "hf:tobil/qmd-query-expansion-1.7B-gguf/qmd-query-expansion-1.7B-q4_k_m.gguf";
  160. export const DEFAULT_EMBED_MODEL_URI = DEFAULT_EMBED_MODEL;
  161. export const DEFAULT_RERANK_MODEL_URI = DEFAULT_RERANK_MODEL;
  162. export const DEFAULT_GENERATE_MODEL_URI = DEFAULT_GENERATE_MODEL;
  163. // Local model cache directory
  164. const MODEL_CACHE_DIR = join(homedir(), ".cache", "qmd", "models");
  165. export const DEFAULT_MODEL_CACHE_DIR = MODEL_CACHE_DIR;
  166. export type PullResult = {
  167. model: string;
  168. path: string;
  169. sizeBytes: number;
  170. refreshed: boolean;
  171. };
  172. type HfRef = {
  173. repo: string;
  174. file: string;
  175. };
  176. function parseHfUri(model: string): HfRef | null {
  177. if (!model.startsWith("hf:")) return null;
  178. const without = model.slice(3);
  179. const parts = without.split("/");
  180. if (parts.length < 3) return null;
  181. const repo = parts.slice(0, 2).join("/");
  182. const file = parts.slice(2).join("/");
  183. return { repo, file };
  184. }
  185. async function getRemoteEtag(ref: HfRef): Promise<string | null> {
  186. const url = `https://huggingface.co/${ref.repo}/resolve/main/${ref.file}`;
  187. try {
  188. const resp = await fetch(url, { method: "HEAD" });
  189. if (!resp.ok) return null;
  190. const etag = resp.headers.get("etag");
  191. return etag || null;
  192. } catch {
  193. return null;
  194. }
  195. }
  196. export async function pullModels(
  197. models: string[],
  198. options: { refresh?: boolean; cacheDir?: string } = {}
  199. ): Promise<PullResult[]> {
  200. const cacheDir = options.cacheDir || MODEL_CACHE_DIR;
  201. if (!existsSync(cacheDir)) {
  202. mkdirSync(cacheDir, { recursive: true });
  203. }
  204. const results: PullResult[] = [];
  205. for (const model of models) {
  206. let refreshed = false;
  207. const hfRef = parseHfUri(model);
  208. const filename = model.split("/").pop();
  209. const entries = readdirSync(cacheDir, { withFileTypes: true });
  210. const cached = filename
  211. ? entries
  212. .filter((entry) => entry.isFile() && entry.name.includes(filename))
  213. .map((entry) => join(cacheDir, entry.name))
  214. : [];
  215. if (hfRef && filename) {
  216. const etagPath = join(cacheDir, `${filename}.etag`);
  217. const remoteEtag = await getRemoteEtag(hfRef);
  218. const localEtag = existsSync(etagPath)
  219. ? readFileSync(etagPath, "utf-8").trim()
  220. : null;
  221. const shouldRefresh =
  222. options.refresh || !remoteEtag || remoteEtag !== localEtag || cached.length === 0;
  223. if (shouldRefresh) {
  224. for (const candidate of cached) {
  225. if (existsSync(candidate)) unlinkSync(candidate);
  226. }
  227. if (existsSync(etagPath)) unlinkSync(etagPath);
  228. refreshed = cached.length > 0;
  229. }
  230. } else if (options.refresh && filename) {
  231. for (const candidate of cached) {
  232. if (existsSync(candidate)) unlinkSync(candidate);
  233. refreshed = true;
  234. }
  235. }
  236. const path = await resolveModelFile(model, cacheDir);
  237. const sizeBytes = existsSync(path) ? statSync(path).size : 0;
  238. if (hfRef && filename) {
  239. const remoteEtag = await getRemoteEtag(hfRef);
  240. if (remoteEtag) {
  241. const etagPath = join(cacheDir, `${filename}.etag`);
  242. writeFileSync(etagPath, remoteEtag + "\n", "utf-8");
  243. }
  244. }
  245. results.push({ model, path, sizeBytes, refreshed });
  246. }
  247. return results;
  248. }
  249. // =============================================================================
  250. // LLM Interface
  251. // =============================================================================
  252. /**
  253. * Abstract LLM interface - implement this for different backends
  254. */
  255. export interface LLM {
  256. /**
  257. * Get embeddings for text
  258. */
  259. embed(text: string, options?: EmbedOptions): Promise<EmbeddingResult | null>;
  260. /**
  261. * Generate text completion
  262. */
  263. generate(prompt: string, options?: GenerateOptions): Promise<GenerateResult | null>;
  264. /**
  265. * Check if a model exists/is available
  266. */
  267. modelExists(model: string): Promise<ModelInfo>;
  268. /**
  269. * Expand a search query into multiple variations for different backends.
  270. * Returns a list of Queryable objects.
  271. */
  272. expandQuery(query: string, options?: { context?: string, includeLexical?: boolean }): Promise<Queryable[]>;
  273. /**
  274. * Rerank documents by relevance to a query
  275. * Returns list of documents with relevance scores (higher = more relevant)
  276. */
  277. rerank(query: string, documents: RerankDocument[], options?: RerankOptions): Promise<RerankResult>;
  278. /**
  279. * Dispose of resources
  280. */
  281. dispose(): Promise<void>;
  282. }
  283. // =============================================================================
  284. // node-llama-cpp Implementation
  285. // =============================================================================
  286. export type LlamaCppConfig = {
  287. embedModel?: string;
  288. generateModel?: string;
  289. rerankModel?: string;
  290. modelCacheDir?: string;
  291. /**
  292. * Inactivity timeout in ms before unloading contexts (default: 2 minutes, 0 to disable).
  293. *
  294. * Per node-llama-cpp lifecycle guidance, we prefer keeping models loaded and only disposing
  295. * contexts when idle, since contexts (and their sequences) are the heavy per-session objects.
  296. * @see https://node-llama-cpp.withcat.ai/guide/objects-lifecycle
  297. */
  298. inactivityTimeoutMs?: number;
  299. /**
  300. * Whether to dispose models on inactivity (default: false).
  301. *
  302. * Keeping models loaded avoids repeated VRAM thrash; set to true only if you need aggressive
  303. * memory reclaim.
  304. */
  305. disposeModelsOnInactivity?: boolean;
  306. };
  307. /**
  308. * LLM implementation using node-llama-cpp
  309. */
  310. // Default inactivity timeout: 5 minutes (keep models warm during typical search sessions)
  311. const DEFAULT_INACTIVITY_TIMEOUT_MS = 5 * 60 * 1000;
  312. export class LlamaCpp implements LLM {
  313. private llama: Llama | null = null;
  314. private embedModel: LlamaModel | null = null;
  315. private embedContexts: LlamaEmbeddingContext[] = [];
  316. private generateModel: LlamaModel | null = null;
  317. private rerankModel: LlamaModel | null = null;
  318. private rerankContexts: Awaited<ReturnType<LlamaModel["createRankingContext"]>>[] = [];
  319. private embedModelUri: string;
  320. private generateModelUri: string;
  321. private rerankModelUri: string;
  322. private modelCacheDir: string;
  323. // Ensure we don't load the same model/context concurrently (which can allocate duplicate VRAM).
  324. private embedModelLoadPromise: Promise<LlamaModel> | null = null;
  325. private generateModelLoadPromise: Promise<LlamaModel> | null = null;
  326. private rerankModelLoadPromise: Promise<LlamaModel> | null = null;
  327. // Inactivity timer for auto-unloading models
  328. private inactivityTimer: ReturnType<typeof setTimeout> | null = null;
  329. private inactivityTimeoutMs: number;
  330. private disposeModelsOnInactivity: boolean;
  331. // Track disposal state to prevent double-dispose
  332. private disposed = false;
  333. constructor(config: LlamaCppConfig = {}) {
  334. this.embedModelUri = config.embedModel || DEFAULT_EMBED_MODEL;
  335. this.generateModelUri = config.generateModel || DEFAULT_GENERATE_MODEL;
  336. this.rerankModelUri = config.rerankModel || DEFAULT_RERANK_MODEL;
  337. this.modelCacheDir = config.modelCacheDir || MODEL_CACHE_DIR;
  338. this.inactivityTimeoutMs = config.inactivityTimeoutMs ?? DEFAULT_INACTIVITY_TIMEOUT_MS;
  339. this.disposeModelsOnInactivity = config.disposeModelsOnInactivity ?? false;
  340. }
  341. /**
  342. * Reset the inactivity timer. Called after each model operation.
  343. * When timer fires, models are unloaded to free memory (if no active sessions).
  344. */
  345. private touchActivity(): void {
  346. // Clear existing timer
  347. if (this.inactivityTimer) {
  348. clearTimeout(this.inactivityTimer);
  349. this.inactivityTimer = null;
  350. }
  351. // Only set timer if we have disposable contexts and timeout is enabled
  352. if (this.inactivityTimeoutMs > 0 && this.hasLoadedContexts()) {
  353. this.inactivityTimer = setTimeout(() => {
  354. // Check if session manager allows unloading
  355. // canUnloadLLM is defined later in this file - it checks the session manager
  356. // We use dynamic import pattern to avoid circular dependency issues
  357. if (typeof canUnloadLLM === 'function' && !canUnloadLLM()) {
  358. // Active sessions/operations - reschedule timer
  359. this.touchActivity();
  360. return;
  361. }
  362. this.unloadIdleResources().catch(err => {
  363. console.error("Error unloading idle resources:", err);
  364. });
  365. }, this.inactivityTimeoutMs);
  366. // Don't keep process alive just for this timer
  367. this.inactivityTimer.unref();
  368. }
  369. }
  370. /**
  371. * Check if any contexts are currently loaded (and therefore worth unloading on inactivity).
  372. */
  373. private hasLoadedContexts(): boolean {
  374. return !!(this.embedContexts.length > 0 || this.rerankContexts.length > 0);
  375. }
  376. /**
  377. * Unload idle resources but keep the instance alive for future use.
  378. *
  379. * By default, this disposes contexts (and their dependent sequences), while keeping models loaded.
  380. * This matches the intended lifecycle: model → context → sequence, where contexts are per-session.
  381. */
  382. async unloadIdleResources(): Promise<void> {
  383. // Don't unload if already disposed
  384. if (this.disposed) {
  385. return;
  386. }
  387. // Clear timer
  388. if (this.inactivityTimer) {
  389. clearTimeout(this.inactivityTimer);
  390. this.inactivityTimer = null;
  391. }
  392. // Dispose contexts first
  393. for (const ctx of this.embedContexts) {
  394. await ctx.dispose();
  395. }
  396. this.embedContexts = [];
  397. for (const ctx of this.rerankContexts) {
  398. await ctx.dispose();
  399. }
  400. this.rerankContexts = [];
  401. // Optionally dispose models too (opt-in)
  402. if (this.disposeModelsOnInactivity) {
  403. if (this.embedModel) {
  404. await this.embedModel.dispose();
  405. this.embedModel = null;
  406. }
  407. if (this.generateModel) {
  408. await this.generateModel.dispose();
  409. this.generateModel = null;
  410. }
  411. if (this.rerankModel) {
  412. await this.rerankModel.dispose();
  413. this.rerankModel = null;
  414. }
  415. // Reset load promises so models can be reloaded later
  416. this.embedModelLoadPromise = null;
  417. this.generateModelLoadPromise = null;
  418. this.rerankModelLoadPromise = null;
  419. }
  420. // Note: We keep llama instance alive - it's lightweight
  421. }
  422. /**
  423. * Ensure model cache directory exists
  424. */
  425. private ensureModelCacheDir(): void {
  426. if (!existsSync(this.modelCacheDir)) {
  427. mkdirSync(this.modelCacheDir, { recursive: true });
  428. }
  429. }
  430. /**
  431. * Initialize the llama instance (lazy)
  432. */
  433. private async ensureLlama(): Promise<Llama> {
  434. if (!this.llama) {
  435. // Detect available GPU types and use the best one.
  436. // We can't rely on gpu:"auto" — it returns false even when CUDA is available
  437. // (likely a binary/build config issue in node-llama-cpp).
  438. const gpuTypes = await getLlamaGpuTypes();
  439. // Prefer CUDA > Metal > Vulkan > CPU
  440. const preferred = (["cuda", "metal", "vulkan"] as const).find(g => gpuTypes.includes(g));
  441. let llama: Llama;
  442. if (preferred) {
  443. try {
  444. llama = await getLlama({ gpu: preferred, logLevel: LlamaLogLevel.error });
  445. } catch {
  446. llama = await getLlama({ gpu: false, logLevel: LlamaLogLevel.error });
  447. process.stderr.write(
  448. `QMD Warning: ${preferred} reported available but failed to initialize. Falling back to CPU.\n`
  449. );
  450. }
  451. } else {
  452. llama = await getLlama({ gpu: false, logLevel: LlamaLogLevel.error });
  453. }
  454. if (!llama.gpu) {
  455. process.stderr.write(
  456. "QMD Warning: no GPU acceleration, running on CPU (slow). Run 'qmd status' for details.\n"
  457. );
  458. }
  459. this.llama = llama;
  460. }
  461. return this.llama;
  462. }
  463. /**
  464. * Resolve a model URI to a local path, downloading if needed
  465. */
  466. private async resolveModel(modelUri: string): Promise<string> {
  467. this.ensureModelCacheDir();
  468. // resolveModelFile handles HF URIs and downloads to the cache dir
  469. return await resolveModelFile(modelUri, this.modelCacheDir);
  470. }
  471. /**
  472. * Load embedding model (lazy)
  473. */
  474. private async ensureEmbedModel(): Promise<LlamaModel> {
  475. if (this.embedModel) {
  476. return this.embedModel;
  477. }
  478. if (this.embedModelLoadPromise) {
  479. return await this.embedModelLoadPromise;
  480. }
  481. this.embedModelLoadPromise = (async () => {
  482. const llama = await this.ensureLlama();
  483. const modelPath = await this.resolveModel(this.embedModelUri);
  484. const model = await llama.loadModel({ modelPath });
  485. this.embedModel = model;
  486. // Model loading counts as activity - ping to keep alive
  487. this.touchActivity();
  488. return model;
  489. })();
  490. try {
  491. return await this.embedModelLoadPromise;
  492. } finally {
  493. // Keep the resolved model cached; clear only the in-flight promise.
  494. this.embedModelLoadPromise = null;
  495. }
  496. }
  497. /**
  498. * Compute how many parallel contexts to create based on available VRAM.
  499. * Conservative: uses at most 25% of free VRAM for contexts, capped at 8.
  500. */
  501. private async computeParallelism(perContextMB: number): Promise<number> {
  502. const llama = await this.ensureLlama();
  503. if (!llama.gpu) return 1; // CPU: no benefit from multiple contexts
  504. try {
  505. const vram = await llama.getVramState();
  506. const freeMB = vram.free / (1024 * 1024);
  507. // Use at most 25% of free VRAM, min 1, max 8
  508. const maxByVram = Math.floor((freeMB * 0.25) / perContextMB);
  509. return Math.max(1, Math.min(8, maxByVram));
  510. } catch {
  511. return 2; // Conservative fallback
  512. }
  513. }
  514. /**
  515. * Load embedding contexts (lazy). Creates multiple for parallel embedding.
  516. * Uses promise guard to prevent concurrent context creation race condition.
  517. */
  518. private embedContextsCreatePromise: Promise<LlamaEmbeddingContext[]> | null = null;
  519. private async ensureEmbedContexts(): Promise<LlamaEmbeddingContext[]> {
  520. if (this.embedContexts.length > 0) {
  521. this.touchActivity();
  522. return this.embedContexts;
  523. }
  524. if (this.embedContextsCreatePromise) {
  525. return await this.embedContextsCreatePromise;
  526. }
  527. this.embedContextsCreatePromise = (async () => {
  528. const model = await this.ensureEmbedModel();
  529. // Embed contexts are ~143 MB each (nomic-embed 2048 ctx)
  530. const n = await this.computeParallelism(150);
  531. for (let i = 0; i < n; i++) {
  532. try {
  533. this.embedContexts.push(await model.createEmbeddingContext());
  534. } catch {
  535. if (this.embedContexts.length === 0) throw new Error("Failed to create any embedding context");
  536. break;
  537. }
  538. }
  539. this.touchActivity();
  540. return this.embedContexts;
  541. })();
  542. try {
  543. return await this.embedContextsCreatePromise;
  544. } finally {
  545. this.embedContextsCreatePromise = null;
  546. }
  547. }
  548. /**
  549. * Get a single embed context (for single-embed calls). Uses first from pool.
  550. */
  551. private async ensureEmbedContext(): Promise<LlamaEmbeddingContext> {
  552. const contexts = await this.ensureEmbedContexts();
  553. return contexts[0]!;
  554. }
  555. /**
  556. * Load generation model (lazy) - context is created fresh per call
  557. */
  558. private async ensureGenerateModel(): Promise<LlamaModel> {
  559. if (!this.generateModel) {
  560. if (this.generateModelLoadPromise) {
  561. return await this.generateModelLoadPromise;
  562. }
  563. this.generateModelLoadPromise = (async () => {
  564. const llama = await this.ensureLlama();
  565. const modelPath = await this.resolveModel(this.generateModelUri);
  566. const model = await llama.loadModel({ modelPath });
  567. this.generateModel = model;
  568. return model;
  569. })();
  570. try {
  571. await this.generateModelLoadPromise;
  572. } finally {
  573. this.generateModelLoadPromise = null;
  574. }
  575. }
  576. this.touchActivity();
  577. if (!this.generateModel) {
  578. throw new Error("Generate model not loaded");
  579. }
  580. return this.generateModel;
  581. }
  582. /**
  583. * Load rerank model (lazy)
  584. */
  585. private async ensureRerankModel(): Promise<LlamaModel> {
  586. if (this.rerankModel) {
  587. return this.rerankModel;
  588. }
  589. if (this.rerankModelLoadPromise) {
  590. return await this.rerankModelLoadPromise;
  591. }
  592. this.rerankModelLoadPromise = (async () => {
  593. const llama = await this.ensureLlama();
  594. const modelPath = await this.resolveModel(this.rerankModelUri);
  595. const model = await llama.loadModel({ modelPath });
  596. this.rerankModel = model;
  597. // Model loading counts as activity - ping to keep alive
  598. this.touchActivity();
  599. return model;
  600. })();
  601. try {
  602. return await this.rerankModelLoadPromise;
  603. } finally {
  604. this.rerankModelLoadPromise = null;
  605. }
  606. }
  607. /**
  608. * Load rerank contexts (lazy). Creates multiple contexts for parallel ranking.
  609. * Each context has its own sequence, so they can evaluate independently.
  610. *
  611. * Tuning choices:
  612. * - contextSize 1024: reranking chunks are ~800 tokens max, 1024 is plenty
  613. * - flashAttention: ~20% less VRAM per context (568 vs 711 MB)
  614. * - Combined: drops from 11.6 GB (auto, no flash) to 568 MB per context (20×)
  615. */
  616. // Qwen3 reranker template adds ~200 tokens overhead (system prompt, tags, etc.)
  617. // Chunks are max 800 tokens, so 800 + 200 + query ≈ 1100 tokens typical.
  618. // Use 2048 for safety margin. Still 17× less than auto (40960).
  619. private static readonly RERANK_CONTEXT_SIZE = 2048;
  620. private async ensureRerankContexts(): Promise<Awaited<ReturnType<LlamaModel["createRankingContext"]>>[]> {
  621. if (this.rerankContexts.length === 0) {
  622. const model = await this.ensureRerankModel();
  623. // ~960 MB per context with flash attention at contextSize 2048
  624. const n = await this.computeParallelism(1000);
  625. for (let i = 0; i < n; i++) {
  626. try {
  627. this.rerankContexts.push(await model.createRankingContext({
  628. contextSize: LlamaCpp.RERANK_CONTEXT_SIZE,
  629. flashAttention: true,
  630. }));
  631. } catch {
  632. if (this.rerankContexts.length === 0) {
  633. // Flash attention might not be supported — retry without it
  634. try {
  635. this.rerankContexts.push(await model.createRankingContext({
  636. contextSize: LlamaCpp.RERANK_CONTEXT_SIZE,
  637. }));
  638. } catch {
  639. throw new Error("Failed to create any rerank context");
  640. }
  641. }
  642. break;
  643. }
  644. }
  645. }
  646. this.touchActivity();
  647. return this.rerankContexts;
  648. }
  649. // ==========================================================================
  650. // Tokenization
  651. // ==========================================================================
  652. /**
  653. * Tokenize text using the embedding model's tokenizer
  654. * Returns tokenizer tokens (opaque type from node-llama-cpp)
  655. */
  656. async tokenize(text: string): Promise<readonly LlamaToken[]> {
  657. await this.ensureEmbedContext(); // Ensure model is loaded
  658. if (!this.embedModel) {
  659. throw new Error("Embed model not loaded");
  660. }
  661. return this.embedModel.tokenize(text);
  662. }
  663. /**
  664. * Count tokens in text using the embedding model's tokenizer
  665. */
  666. async countTokens(text: string): Promise<number> {
  667. const tokens = await this.tokenize(text);
  668. return tokens.length;
  669. }
  670. /**
  671. * Detokenize token IDs back to text
  672. */
  673. async detokenize(tokens: readonly LlamaToken[]): Promise<string> {
  674. await this.ensureEmbedContext();
  675. if (!this.embedModel) {
  676. throw new Error("Embed model not loaded");
  677. }
  678. return this.embedModel.detokenize(tokens);
  679. }
  680. // ==========================================================================
  681. // Core API methods
  682. // ==========================================================================
  683. async embed(text: string, options: EmbedOptions = {}): Promise<EmbeddingResult | null> {
  684. // Ping activity at start to keep models alive during this operation
  685. this.touchActivity();
  686. try {
  687. const context = await this.ensureEmbedContext();
  688. const embedding = await context.getEmbeddingFor(text);
  689. return {
  690. embedding: Array.from(embedding.vector),
  691. model: this.embedModelUri,
  692. };
  693. } catch (error) {
  694. console.error("Embedding error:", error);
  695. return null;
  696. }
  697. }
  698. /**
  699. * Batch embed multiple texts efficiently
  700. * Uses Promise.all for parallel embedding - node-llama-cpp handles batching internally
  701. */
  702. async embedBatch(texts: string[]): Promise<(EmbeddingResult | null)[]> {
  703. // Ping activity at start to keep models alive during this operation
  704. this.touchActivity();
  705. if (texts.length === 0) return [];
  706. try {
  707. const contexts = await this.ensureEmbedContexts();
  708. const n = contexts.length;
  709. if (n === 1) {
  710. // Single context: sequential (no point splitting)
  711. const context = contexts[0]!;
  712. const embeddings = [];
  713. for (const text of texts) {
  714. try {
  715. const embedding = await context.getEmbeddingFor(text);
  716. this.touchActivity();
  717. embeddings.push({ embedding: Array.from(embedding.vector), model: this.embedModelUri });
  718. } catch (err) {
  719. console.error("Embedding error for text:", err);
  720. embeddings.push(null);
  721. }
  722. }
  723. return embeddings;
  724. }
  725. // Multiple contexts: split texts across contexts for parallel evaluation
  726. const chunkSize = Math.ceil(texts.length / n);
  727. const chunks = Array.from({ length: n }, (_, i) =>
  728. texts.slice(i * chunkSize, (i + 1) * chunkSize)
  729. );
  730. const chunkResults = await Promise.all(
  731. chunks.map(async (chunk, i) => {
  732. const ctx = contexts[i]!;
  733. const results: (EmbeddingResult | null)[] = [];
  734. for (const text of chunk) {
  735. try {
  736. const embedding = await ctx.getEmbeddingFor(text);
  737. this.touchActivity();
  738. results.push({ embedding: Array.from(embedding.vector), model: this.embedModelUri });
  739. } catch (err) {
  740. console.error("Embedding error for text:", err);
  741. results.push(null);
  742. }
  743. }
  744. return results;
  745. })
  746. );
  747. return chunkResults.flat();
  748. } catch (error) {
  749. console.error("Batch embedding error:", error);
  750. return texts.map(() => null);
  751. }
  752. }
  753. async generate(prompt: string, options: GenerateOptions = {}): Promise<GenerateResult | null> {
  754. // Ping activity at start to keep models alive during this operation
  755. this.touchActivity();
  756. // Ensure model is loaded
  757. await this.ensureGenerateModel();
  758. // Create fresh context -> sequence -> session for each call
  759. const context = await this.generateModel!.createContext();
  760. const sequence = context.getSequence();
  761. const session = new LlamaChatSession({ contextSequence: sequence });
  762. const maxTokens = options.maxTokens ?? 150;
  763. // Qwen3 recommends temp=0.7, topP=0.8, topK=20 for non-thinking mode
  764. // DO NOT use greedy decoding (temp=0) - causes repetition loops
  765. const temperature = options.temperature ?? 0.7;
  766. let result = "";
  767. try {
  768. await session.prompt(prompt, {
  769. maxTokens,
  770. temperature,
  771. topK: 20,
  772. topP: 0.8,
  773. onTextChunk: (text) => {
  774. result += text;
  775. },
  776. });
  777. return {
  778. text: result,
  779. model: this.generateModelUri,
  780. done: true,
  781. };
  782. } finally {
  783. // Dispose context (which disposes dependent sequences/sessions per lifecycle rules)
  784. await context.dispose();
  785. }
  786. }
  787. async modelExists(modelUri: string): Promise<ModelInfo> {
  788. // For HuggingFace URIs, we assume they exist
  789. // For local paths, check if file exists
  790. if (modelUri.startsWith("hf:")) {
  791. return { name: modelUri, exists: true };
  792. }
  793. const exists = existsSync(modelUri);
  794. return {
  795. name: modelUri,
  796. exists,
  797. path: exists ? modelUri : undefined,
  798. };
  799. }
  800. // ==========================================================================
  801. // High-level abstractions
  802. // ==========================================================================
  803. async expandQuery(query: string, options: { context?: string, includeLexical?: boolean } = {}): Promise<Queryable[]> {
  804. // Ping activity at start to keep models alive during this operation
  805. this.touchActivity();
  806. const llama = await this.ensureLlama();
  807. await this.ensureGenerateModel();
  808. const includeLexical = options.includeLexical ?? true;
  809. const context = options.context;
  810. const grammar = await llama.createGrammar({
  811. grammar: `
  812. root ::= line+
  813. line ::= type ": " content "\\n"
  814. type ::= "lex" | "vec" | "hyde"
  815. content ::= [^\\n]+
  816. `
  817. });
  818. const prompt = `/no_think Expand this search query: ${query}`;
  819. // Create fresh context for each call
  820. const genContext = await this.generateModel!.createContext();
  821. const sequence = genContext.getSequence();
  822. const session = new LlamaChatSession({ contextSequence: sequence });
  823. try {
  824. // Qwen3 recommended settings for non-thinking mode:
  825. // temp=0.7, topP=0.8, topK=20, presence_penalty for repetition
  826. // DO NOT use greedy decoding (temp=0) - causes infinite loops
  827. const result = await session.prompt(prompt, {
  828. grammar,
  829. maxTokens: 600,
  830. temperature: 0.7,
  831. topK: 20,
  832. topP: 0.8,
  833. repeatPenalty: {
  834. lastTokens: 64,
  835. presencePenalty: 0.5,
  836. },
  837. });
  838. const lines = result.trim().split("\n");
  839. const queryLower = query.toLowerCase();
  840. const queryTerms = queryLower.replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter(Boolean);
  841. const hasQueryTerm = (text: string): boolean => {
  842. const lower = text.toLowerCase();
  843. if (queryTerms.length === 0) return true;
  844. return queryTerms.some(term => lower.includes(term));
  845. };
  846. const queryables: Queryable[] = lines.map(line => {
  847. const colonIdx = line.indexOf(":");
  848. if (colonIdx === -1) return null;
  849. const type = line.slice(0, colonIdx).trim();
  850. if (type !== 'lex' && type !== 'vec' && type !== 'hyde') return null;
  851. const text = line.slice(colonIdx + 1).trim();
  852. if (!hasQueryTerm(text)) return null;
  853. return { type: type as QueryType, text };
  854. }).filter((q): q is Queryable => q !== null);
  855. // Filter out lex entries if not requested
  856. const filtered = includeLexical ? queryables : queryables.filter(q => q.type !== 'lex');
  857. if (filtered.length > 0) return filtered;
  858. const fallback: Queryable[] = [
  859. { type: 'hyde', text: `Information about ${query}` },
  860. { type: 'lex', text: query },
  861. { type: 'vec', text: query },
  862. ];
  863. return includeLexical ? fallback : fallback.filter(q => q.type !== 'lex');
  864. } catch (error) {
  865. console.error("Structured query expansion failed:", error);
  866. // Fallback to original query
  867. const fallback: Queryable[] = [{ type: 'vec', text: query }];
  868. if (includeLexical) fallback.unshift({ type: 'lex', text: query });
  869. return fallback;
  870. } finally {
  871. await genContext.dispose();
  872. }
  873. }
  874. async rerank(
  875. query: string,
  876. documents: RerankDocument[],
  877. options: RerankOptions = {}
  878. ): Promise<RerankResult> {
  879. // Ping activity at start to keep models alive during this operation
  880. this.touchActivity();
  881. const contexts = await this.ensureRerankContexts();
  882. // Build a map from document text to original indices (for lookup after sorting)
  883. const textToDoc = new Map<string, { file: string; index: number }>();
  884. documents.forEach((doc, index) => {
  885. textToDoc.set(doc.text, { file: doc.file, index });
  886. });
  887. // Extract just the text for ranking
  888. const texts = documents.map((doc) => doc.text);
  889. // Split documents across contexts for parallel evaluation.
  890. // Each context has its own sequence with a lock, so parallelism comes
  891. // from multiple contexts evaluating different chunks simultaneously.
  892. const n = contexts.length;
  893. const chunkSize = Math.ceil(texts.length / n);
  894. const chunks = Array.from({ length: n }, (_, i) =>
  895. texts.slice(i * chunkSize, (i + 1) * chunkSize)
  896. ).filter(chunk => chunk.length > 0);
  897. const allScores = await Promise.all(
  898. chunks.map((chunk, i) => contexts[i]!.rankAll(query, chunk))
  899. );
  900. // Reassemble scores in original order and sort
  901. const flatScores = allScores.flat();
  902. const ranked = texts
  903. .map((text, i) => ({ document: text, score: flatScores[i]! }))
  904. .sort((a, b) => b.score - a.score);
  905. // Map back to our result format using the text-to-doc map
  906. const results: RerankDocumentResult[] = ranked.map((item) => {
  907. const docInfo = textToDoc.get(item.document)!;
  908. return {
  909. file: docInfo.file,
  910. score: item.score,
  911. index: docInfo.index,
  912. };
  913. });
  914. return {
  915. results,
  916. model: this.rerankModelUri,
  917. };
  918. }
  919. /**
  920. * Get device/GPU info for status display.
  921. * Initializes llama if not already done.
  922. */
  923. async getDeviceInfo(): Promise<{
  924. gpu: string | false;
  925. gpuOffloading: boolean;
  926. gpuDevices: string[];
  927. vram?: { total: number; used: number; free: number };
  928. cpuCores: number;
  929. }> {
  930. const llama = await this.ensureLlama();
  931. const gpuDevices = await llama.getGpuDeviceNames();
  932. let vram: { total: number; used: number; free: number } | undefined;
  933. if (llama.gpu) {
  934. try {
  935. const state = await llama.getVramState();
  936. vram = { total: state.total, used: state.used, free: state.free };
  937. } catch { /* no vram info */ }
  938. }
  939. return {
  940. gpu: llama.gpu,
  941. gpuOffloading: llama.supportsGpuOffloading,
  942. gpuDevices,
  943. vram,
  944. cpuCores: llama.cpuMathCores,
  945. };
  946. }
  947. async dispose(): Promise<void> {
  948. // Prevent double-dispose
  949. if (this.disposed) {
  950. return;
  951. }
  952. this.disposed = true;
  953. // Clear inactivity timer
  954. if (this.inactivityTimer) {
  955. clearTimeout(this.inactivityTimer);
  956. this.inactivityTimer = null;
  957. }
  958. // Disposing llama cascades to models and contexts automatically
  959. // See: https://node-llama-cpp.withcat.ai/guide/objects-lifecycle
  960. // Note: llama.dispose() can hang indefinitely, so we use a timeout
  961. if (this.llama) {
  962. const disposePromise = this.llama.dispose();
  963. const timeoutPromise = new Promise<void>((resolve) => setTimeout(resolve, 1000));
  964. await Promise.race([disposePromise, timeoutPromise]);
  965. }
  966. // Clear references
  967. this.embedContexts = [];
  968. this.rerankContexts = [];
  969. this.embedModel = null;
  970. this.generateModel = null;
  971. this.rerankModel = null;
  972. this.llama = null;
  973. // Clear any in-flight load/create promises
  974. this.embedModelLoadPromise = null;
  975. this.embedContextsCreatePromise = null;
  976. this.generateModelLoadPromise = null;
  977. this.rerankModelLoadPromise = null;
  978. }
  979. }
  980. // =============================================================================
  981. // Session Management Layer
  982. // =============================================================================
  983. /**
  984. * Manages LLM session lifecycle with reference counting.
  985. * Coordinates with LlamaCpp idle timeout to prevent disposal during active sessions.
  986. */
  987. class LLMSessionManager {
  988. private llm: LlamaCpp;
  989. private _activeSessionCount = 0;
  990. private _inFlightOperations = 0;
  991. constructor(llm: LlamaCpp) {
  992. this.llm = llm;
  993. }
  994. get activeSessionCount(): number {
  995. return this._activeSessionCount;
  996. }
  997. get inFlightOperations(): number {
  998. return this._inFlightOperations;
  999. }
  1000. /**
  1001. * Returns true only when both session count and in-flight operations are 0.
  1002. * Used by LlamaCpp to determine if idle unload is safe.
  1003. */
  1004. canUnload(): boolean {
  1005. return this._activeSessionCount === 0 && this._inFlightOperations === 0;
  1006. }
  1007. acquire(): void {
  1008. this._activeSessionCount++;
  1009. }
  1010. release(): void {
  1011. this._activeSessionCount = Math.max(0, this._activeSessionCount - 1);
  1012. }
  1013. operationStart(): void {
  1014. this._inFlightOperations++;
  1015. }
  1016. operationEnd(): void {
  1017. this._inFlightOperations = Math.max(0, this._inFlightOperations - 1);
  1018. }
  1019. getLlamaCpp(): LlamaCpp {
  1020. return this.llm;
  1021. }
  1022. }
  1023. /**
  1024. * Error thrown when an operation is attempted on a released or aborted session.
  1025. */
  1026. export class SessionReleasedError extends Error {
  1027. constructor(message = "LLM session has been released or aborted") {
  1028. super(message);
  1029. this.name = "SessionReleasedError";
  1030. }
  1031. }
  1032. /**
  1033. * Scoped LLM session with automatic lifecycle management.
  1034. * Wraps LlamaCpp methods with operation tracking and abort handling.
  1035. */
  1036. class LLMSession implements ILLMSession {
  1037. private manager: LLMSessionManager;
  1038. private released = false;
  1039. private abortController: AbortController;
  1040. private maxDurationTimer: ReturnType<typeof setTimeout> | null = null;
  1041. private name: string;
  1042. constructor(manager: LLMSessionManager, options: LLMSessionOptions = {}) {
  1043. this.manager = manager;
  1044. this.name = options.name || "unnamed";
  1045. this.abortController = new AbortController();
  1046. // Link external abort signal if provided
  1047. if (options.signal) {
  1048. if (options.signal.aborted) {
  1049. this.abortController.abort(options.signal.reason);
  1050. } else {
  1051. options.signal.addEventListener("abort", () => {
  1052. this.abortController.abort(options.signal!.reason);
  1053. }, { once: true });
  1054. }
  1055. }
  1056. // Set up max duration timer
  1057. const maxDuration = options.maxDuration ?? 10 * 60 * 1000; // Default 10 minutes
  1058. if (maxDuration > 0) {
  1059. this.maxDurationTimer = setTimeout(() => {
  1060. this.abortController.abort(new Error(`Session "${this.name}" exceeded max duration of ${maxDuration}ms`));
  1061. }, maxDuration);
  1062. this.maxDurationTimer.unref(); // Don't keep process alive
  1063. }
  1064. // Acquire session lease
  1065. this.manager.acquire();
  1066. }
  1067. get isValid(): boolean {
  1068. return !this.released && !this.abortController.signal.aborted;
  1069. }
  1070. get signal(): AbortSignal {
  1071. return this.abortController.signal;
  1072. }
  1073. /**
  1074. * Release the session and decrement ref count.
  1075. * Called automatically by withLLMSession when the callback completes.
  1076. */
  1077. release(): void {
  1078. if (this.released) return;
  1079. this.released = true;
  1080. if (this.maxDurationTimer) {
  1081. clearTimeout(this.maxDurationTimer);
  1082. this.maxDurationTimer = null;
  1083. }
  1084. this.abortController.abort(new Error("Session released"));
  1085. this.manager.release();
  1086. }
  1087. /**
  1088. * Wrap an operation with tracking and abort checking.
  1089. */
  1090. private async withOperation<T>(fn: () => Promise<T>): Promise<T> {
  1091. if (!this.isValid) {
  1092. throw new SessionReleasedError();
  1093. }
  1094. this.manager.operationStart();
  1095. try {
  1096. // Check abort before starting
  1097. if (this.abortController.signal.aborted) {
  1098. throw new SessionReleasedError(
  1099. this.abortController.signal.reason?.message || "Session aborted"
  1100. );
  1101. }
  1102. return await fn();
  1103. } finally {
  1104. this.manager.operationEnd();
  1105. }
  1106. }
  1107. async embed(text: string, options?: EmbedOptions): Promise<EmbeddingResult | null> {
  1108. return this.withOperation(() => this.manager.getLlamaCpp().embed(text, options));
  1109. }
  1110. async embedBatch(texts: string[]): Promise<(EmbeddingResult | null)[]> {
  1111. return this.withOperation(() => this.manager.getLlamaCpp().embedBatch(texts));
  1112. }
  1113. async expandQuery(
  1114. query: string,
  1115. options?: { context?: string; includeLexical?: boolean }
  1116. ): Promise<Queryable[]> {
  1117. return this.withOperation(() => this.manager.getLlamaCpp().expandQuery(query, options));
  1118. }
  1119. async rerank(
  1120. query: string,
  1121. documents: RerankDocument[],
  1122. options?: RerankOptions
  1123. ): Promise<RerankResult> {
  1124. return this.withOperation(() => this.manager.getLlamaCpp().rerank(query, documents, options));
  1125. }
  1126. }
  1127. // Session manager for the default LlamaCpp instance
  1128. let defaultSessionManager: LLMSessionManager | null = null;
  1129. /**
  1130. * Get the session manager for the default LlamaCpp instance.
  1131. */
  1132. function getSessionManager(): LLMSessionManager {
  1133. const llm = getDefaultLlamaCpp();
  1134. if (!defaultSessionManager || defaultSessionManager.getLlamaCpp() !== llm) {
  1135. defaultSessionManager = new LLMSessionManager(llm);
  1136. }
  1137. return defaultSessionManager;
  1138. }
  1139. /**
  1140. * Execute a function with a scoped LLM session.
  1141. * The session provides lifecycle guarantees - resources won't be disposed mid-operation.
  1142. *
  1143. * @example
  1144. * ```typescript
  1145. * await withLLMSession(async (session) => {
  1146. * const expanded = await session.expandQuery(query);
  1147. * const embeddings = await session.embedBatch(texts);
  1148. * const reranked = await session.rerank(query, docs);
  1149. * return reranked;
  1150. * }, { maxDuration: 10 * 60 * 1000, name: 'querySearch' });
  1151. * ```
  1152. */
  1153. export async function withLLMSession<T>(
  1154. fn: (session: ILLMSession) => Promise<T>,
  1155. options?: LLMSessionOptions
  1156. ): Promise<T> {
  1157. const manager = getSessionManager();
  1158. const session = new LLMSession(manager, options);
  1159. try {
  1160. return await fn(session);
  1161. } finally {
  1162. session.release();
  1163. }
  1164. }
  1165. /**
  1166. * Check if idle unload is safe (no active sessions or operations).
  1167. * Used internally by LlamaCpp idle timer.
  1168. */
  1169. export function canUnloadLLM(): boolean {
  1170. if (!defaultSessionManager) return true;
  1171. return defaultSessionManager.canUnload();
  1172. }
  1173. // =============================================================================
  1174. // Singleton for default LlamaCpp instance
  1175. // =============================================================================
  1176. let defaultLlamaCpp: LlamaCpp | null = null;
  1177. /**
  1178. * Get the default LlamaCpp instance (creates one if needed)
  1179. */
  1180. export function getDefaultLlamaCpp(): LlamaCpp {
  1181. if (!defaultLlamaCpp) {
  1182. defaultLlamaCpp = new LlamaCpp();
  1183. }
  1184. return defaultLlamaCpp;
  1185. }
  1186. /**
  1187. * Set a custom default LlamaCpp instance (useful for testing)
  1188. */
  1189. export function setDefaultLlamaCpp(llm: LlamaCpp | null): void {
  1190. defaultLlamaCpp = llm;
  1191. }
  1192. /**
  1193. * Dispose the default LlamaCpp instance if it exists.
  1194. * Call this before process exit to prevent NAPI crashes.
  1195. */
  1196. export async function disposeDefaultLlamaCpp(): Promise<void> {
  1197. if (defaultLlamaCpp) {
  1198. await defaultLlamaCpp.dispose();
  1199. defaultLlamaCpp = null;
  1200. }
  1201. }