llm.ts 49 KB

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