llm.ts 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509
  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. async embed(text: string, options: EmbedOptions = {}): Promise<EmbeddingResult | null> {
  744. // Ping activity at start to keep models alive during this operation
  745. this.touchActivity();
  746. try {
  747. const context = await this.ensureEmbedContext();
  748. const embedding = await context.getEmbeddingFor(text);
  749. return {
  750. embedding: Array.from(embedding.vector),
  751. model: this.embedModelUri,
  752. };
  753. } catch (error) {
  754. console.error("Embedding error:", error);
  755. return null;
  756. }
  757. }
  758. /**
  759. * Batch embed multiple texts efficiently
  760. * Uses Promise.all for parallel embedding - node-llama-cpp handles batching internally
  761. */
  762. async embedBatch(texts: string[]): Promise<(EmbeddingResult | null)[]> {
  763. if (this._ciMode) throw new Error("LLM operations are disabled in CI (set CI=true)");
  764. // Ping activity at start to keep models alive during this operation
  765. this.touchActivity();
  766. if (texts.length === 0) return [];
  767. try {
  768. const contexts = await this.ensureEmbedContexts();
  769. const n = contexts.length;
  770. if (n === 1) {
  771. // Single context: sequential (no point splitting)
  772. const context = contexts[0]!;
  773. const embeddings: ({ embedding: number[]; model: string } | null)[] = [];
  774. for (const text of texts) {
  775. try {
  776. const embedding = await context.getEmbeddingFor(text);
  777. this.touchActivity();
  778. embeddings.push({ embedding: Array.from(embedding.vector), model: this.embedModelUri });
  779. } catch (err) {
  780. console.error("Embedding error for text:", err);
  781. embeddings.push(null);
  782. }
  783. }
  784. return embeddings;
  785. }
  786. // Multiple contexts: split texts across contexts for parallel evaluation
  787. const chunkSize = Math.ceil(texts.length / n);
  788. const chunks = Array.from({ length: n }, (_, i) =>
  789. texts.slice(i * chunkSize, (i + 1) * chunkSize)
  790. );
  791. const chunkResults = await Promise.all(
  792. chunks.map(async (chunk, i) => {
  793. const ctx = contexts[i]!;
  794. const results: (EmbeddingResult | null)[] = [];
  795. for (const text of chunk) {
  796. try {
  797. const embedding = await ctx.getEmbeddingFor(text);
  798. this.touchActivity();
  799. results.push({ embedding: Array.from(embedding.vector), model: this.embedModelUri });
  800. } catch (err) {
  801. console.error("Embedding error for text:", err);
  802. results.push(null);
  803. }
  804. }
  805. return results;
  806. })
  807. );
  808. return chunkResults.flat();
  809. } catch (error) {
  810. console.error("Batch embedding error:", error);
  811. return texts.map(() => null);
  812. }
  813. }
  814. async generate(prompt: string, options: GenerateOptions = {}): Promise<GenerateResult | null> {
  815. if (this._ciMode) throw new Error("LLM operations are disabled in CI (set CI=true)");
  816. // Ping activity at start to keep models alive during this operation
  817. this.touchActivity();
  818. // Ensure model is loaded
  819. await this.ensureGenerateModel();
  820. // Create fresh context -> sequence -> session for each call
  821. const context = await this.generateModel!.createContext();
  822. const sequence = context.getSequence();
  823. const session = new LlamaChatSession({ contextSequence: sequence });
  824. const maxTokens = options.maxTokens ?? 150;
  825. // Qwen3 recommends temp=0.7, topP=0.8, topK=20 for non-thinking mode
  826. // DO NOT use greedy decoding (temp=0) - causes repetition loops
  827. const temperature = options.temperature ?? 0.7;
  828. let result = "";
  829. try {
  830. await session.prompt(prompt, {
  831. maxTokens,
  832. temperature,
  833. topK: 20,
  834. topP: 0.8,
  835. onTextChunk: (text) => {
  836. result += text;
  837. },
  838. });
  839. return {
  840. text: result,
  841. model: this.generateModelUri,
  842. done: true,
  843. };
  844. } finally {
  845. // Dispose context (which disposes dependent sequences/sessions per lifecycle rules)
  846. await context.dispose();
  847. }
  848. }
  849. async modelExists(modelUri: string): Promise<ModelInfo> {
  850. // For HuggingFace URIs, we assume they exist
  851. // For local paths, check if file exists
  852. if (modelUri.startsWith("hf:")) {
  853. return { name: modelUri, exists: true };
  854. }
  855. const exists = existsSync(modelUri);
  856. return {
  857. name: modelUri,
  858. exists,
  859. path: exists ? modelUri : undefined,
  860. };
  861. }
  862. // ==========================================================================
  863. // High-level abstractions
  864. // ==========================================================================
  865. async expandQuery(query: string, options: { context?: string, includeLexical?: boolean, intent?: string } = {}): Promise<Queryable[]> {
  866. if (this._ciMode) throw new Error("LLM operations are disabled in CI (set CI=true)");
  867. // Ping activity at start to keep models alive during this operation
  868. this.touchActivity();
  869. const llama = await this.ensureLlama();
  870. await this.ensureGenerateModel();
  871. const includeLexical = options.includeLexical ?? true;
  872. const context = options.context;
  873. const grammar = await llama.createGrammar({
  874. grammar: `
  875. root ::= line+
  876. line ::= type ": " content "\\n"
  877. type ::= "lex" | "vec" | "hyde"
  878. content ::= [^\\n]+
  879. `
  880. });
  881. const intent = options.intent;
  882. const prompt = intent
  883. ? `/no_think Expand this search query: ${query}\nQuery intent: ${intent}`
  884. : `/no_think Expand this search query: ${query}`;
  885. // Create a bounded context for expansion to prevent large default VRAM allocations.
  886. const genContext = await this.generateModel!.createContext({
  887. contextSize: this.expandContextSize,
  888. });
  889. const sequence = genContext.getSequence();
  890. const session = new LlamaChatSession({ contextSequence: sequence });
  891. try {
  892. // Qwen3 recommended settings for non-thinking mode:
  893. // temp=0.7, topP=0.8, topK=20, presence_penalty for repetition
  894. // DO NOT use greedy decoding (temp=0) - causes infinite loops
  895. const result = await session.prompt(prompt, {
  896. grammar,
  897. maxTokens: 600,
  898. temperature: 0.7,
  899. topK: 20,
  900. topP: 0.8,
  901. repeatPenalty: {
  902. lastTokens: 64,
  903. presencePenalty: 0.5,
  904. },
  905. });
  906. const lines = result.trim().split("\n");
  907. const queryLower = query.toLowerCase();
  908. const queryTerms = queryLower.replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter(Boolean);
  909. const hasQueryTerm = (text: string): boolean => {
  910. const lower = text.toLowerCase();
  911. if (queryTerms.length === 0) return true;
  912. return queryTerms.some(term => lower.includes(term));
  913. };
  914. const queryables: Queryable[] = lines.map(line => {
  915. const colonIdx = line.indexOf(":");
  916. if (colonIdx === -1) return null;
  917. const type = line.slice(0, colonIdx).trim();
  918. if (type !== 'lex' && type !== 'vec' && type !== 'hyde') return null;
  919. const text = line.slice(colonIdx + 1).trim();
  920. if (!hasQueryTerm(text)) return null;
  921. return { type: type as QueryType, text };
  922. }).filter((q): q is Queryable => q !== null);
  923. // Filter out lex entries if not requested
  924. const filtered = includeLexical ? queryables : queryables.filter(q => q.type !== 'lex');
  925. if (filtered.length > 0) return filtered;
  926. const fallback: Queryable[] = [
  927. { type: 'hyde', text: `Information about ${query}` },
  928. { type: 'lex', text: query },
  929. { type: 'vec', text: query },
  930. ];
  931. return includeLexical ? fallback : fallback.filter(q => q.type !== 'lex');
  932. } catch (error) {
  933. console.error("Structured query expansion failed:", error);
  934. // Fallback to original query
  935. const fallback: Queryable[] = [{ type: 'vec', text: query }];
  936. if (includeLexical) fallback.unshift({ type: 'lex', text: query });
  937. return fallback;
  938. } finally {
  939. await genContext.dispose();
  940. }
  941. }
  942. // Qwen3 reranker chat template overhead (system prompt, tags, separators)
  943. private static readonly RERANK_TEMPLATE_OVERHEAD = 200;
  944. private static readonly RERANK_TARGET_DOCS_PER_CONTEXT = 10;
  945. async rerank(
  946. query: string,
  947. documents: RerankDocument[],
  948. options: RerankOptions = {}
  949. ): Promise<RerankResult> {
  950. if (this._ciMode) throw new Error("LLM operations are disabled in CI (set CI=true)");
  951. // Ping activity at start to keep models alive during this operation
  952. this.touchActivity();
  953. const contexts = await this.ensureRerankContexts();
  954. const model = await this.ensureRerankModel();
  955. // Truncate documents that would exceed the rerank context size.
  956. // Budget = contextSize - template overhead - query tokens
  957. const queryTokens = model.tokenize(query).length;
  958. const maxDocTokens = LlamaCpp.RERANK_CONTEXT_SIZE - LlamaCpp.RERANK_TEMPLATE_OVERHEAD - queryTokens;
  959. const truncationCache = new Map<string, string>();
  960. const truncatedDocs = documents.map((doc) => {
  961. const cached = truncationCache.get(doc.text);
  962. if (cached !== undefined) {
  963. return cached === doc.text ? doc : { ...doc, text: cached };
  964. }
  965. const tokens = model.tokenize(doc.text);
  966. const truncatedText = tokens.length <= maxDocTokens
  967. ? doc.text
  968. : model.detokenize(tokens.slice(0, maxDocTokens));
  969. truncationCache.set(doc.text, truncatedText);
  970. if (truncatedText === doc.text) return doc;
  971. return { ...doc, text: truncatedText };
  972. });
  973. // Deduplicate identical effective texts before scoring.
  974. // This avoids redundant work for repeated chunks and fixes collisions where
  975. // multiple docs map to the same chunk text.
  976. const textToDocs = new Map<string, { file: string; index: number }[]>();
  977. truncatedDocs.forEach((doc, index) => {
  978. const existing = textToDocs.get(doc.text);
  979. if (existing) {
  980. existing.push({ file: doc.file, index });
  981. } else {
  982. textToDocs.set(doc.text, [{ file: doc.file, index }]);
  983. }
  984. });
  985. // Extract just the text for ranking
  986. const texts = Array.from(textToDocs.keys());
  987. // Split documents across contexts for parallel evaluation.
  988. // Each context has its own sequence with a lock, so parallelism comes
  989. // from multiple contexts evaluating different chunks simultaneously.
  990. const activeContextCount = Math.max(
  991. 1,
  992. Math.min(
  993. contexts.length,
  994. Math.ceil(texts.length / LlamaCpp.RERANK_TARGET_DOCS_PER_CONTEXT)
  995. )
  996. );
  997. const activeContexts = contexts.slice(0, activeContextCount);
  998. const chunkSize = Math.ceil(texts.length / activeContexts.length);
  999. const chunks = Array.from({ length: activeContexts.length }, (_, i) =>
  1000. texts.slice(i * chunkSize, (i + 1) * chunkSize)
  1001. ).filter(chunk => chunk.length > 0);
  1002. const allScores = await Promise.all(
  1003. chunks.map((chunk, i) => activeContexts[i]!.rankAll(query, chunk))
  1004. );
  1005. // Reassemble scores in original order and sort
  1006. const flatScores = allScores.flat();
  1007. const ranked = texts
  1008. .map((text, i) => ({ document: text, score: flatScores[i]! }))
  1009. .sort((a, b) => b.score - a.score);
  1010. // Map back to our result format.
  1011. const results: RerankDocumentResult[] = [];
  1012. for (const item of ranked) {
  1013. const docInfos = textToDocs.get(item.document) ?? [];
  1014. for (const docInfo of docInfos) {
  1015. results.push({
  1016. file: docInfo.file,
  1017. score: item.score,
  1018. index: docInfo.index,
  1019. });
  1020. }
  1021. }
  1022. return {
  1023. results,
  1024. model: this.rerankModelUri,
  1025. };
  1026. }
  1027. /**
  1028. * Get device/GPU info for status display.
  1029. * Initializes llama if not already done.
  1030. */
  1031. async getDeviceInfo(): Promise<{
  1032. gpu: string | false;
  1033. gpuOffloading: boolean;
  1034. gpuDevices: string[];
  1035. vram?: { total: number; used: number; free: number };
  1036. cpuCores: number;
  1037. }> {
  1038. const llama = await this.ensureLlama();
  1039. const gpuDevices = await llama.getGpuDeviceNames();
  1040. let vram: { total: number; used: number; free: number } | undefined;
  1041. if (llama.gpu) {
  1042. try {
  1043. const state = await llama.getVramState();
  1044. vram = { total: state.total, used: state.used, free: state.free };
  1045. } catch { /* no vram info */ }
  1046. }
  1047. return {
  1048. gpu: llama.gpu,
  1049. gpuOffloading: llama.supportsGpuOffloading,
  1050. gpuDevices,
  1051. vram,
  1052. cpuCores: llama.cpuMathCores,
  1053. };
  1054. }
  1055. async dispose(): Promise<void> {
  1056. // Prevent double-dispose
  1057. if (this.disposed) {
  1058. return;
  1059. }
  1060. this.disposed = true;
  1061. // Clear inactivity timer
  1062. if (this.inactivityTimer) {
  1063. clearTimeout(this.inactivityTimer);
  1064. this.inactivityTimer = null;
  1065. }
  1066. // Disposing llama cascades to models and contexts automatically
  1067. // See: https://node-llama-cpp.withcat.ai/guide/objects-lifecycle
  1068. // Note: llama.dispose() can hang indefinitely, so we use a timeout
  1069. if (this.llama) {
  1070. const disposePromise = this.llama.dispose();
  1071. const timeoutPromise = new Promise<void>((resolve) => setTimeout(resolve, 1000));
  1072. await Promise.race([disposePromise, timeoutPromise]);
  1073. }
  1074. // Clear references
  1075. this.embedContexts = [];
  1076. this.rerankContexts = [];
  1077. this.embedModel = null;
  1078. this.generateModel = null;
  1079. this.rerankModel = null;
  1080. this.llama = null;
  1081. // Clear any in-flight load/create promises
  1082. this.embedModelLoadPromise = null;
  1083. this.embedContextsCreatePromise = null;
  1084. this.generateModelLoadPromise = null;
  1085. this.rerankModelLoadPromise = null;
  1086. }
  1087. }
  1088. // =============================================================================
  1089. // Session Management Layer
  1090. // =============================================================================
  1091. /**
  1092. * Manages LLM session lifecycle with reference counting.
  1093. * Coordinates with LlamaCpp idle timeout to prevent disposal during active sessions.
  1094. */
  1095. class LLMSessionManager {
  1096. private llm: LlamaCpp;
  1097. private _activeSessionCount = 0;
  1098. private _inFlightOperations = 0;
  1099. constructor(llm: LlamaCpp) {
  1100. this.llm = llm;
  1101. }
  1102. get activeSessionCount(): number {
  1103. return this._activeSessionCount;
  1104. }
  1105. get inFlightOperations(): number {
  1106. return this._inFlightOperations;
  1107. }
  1108. /**
  1109. * Returns true only when both session count and in-flight operations are 0.
  1110. * Used by LlamaCpp to determine if idle unload is safe.
  1111. */
  1112. canUnload(): boolean {
  1113. return this._activeSessionCount === 0 && this._inFlightOperations === 0;
  1114. }
  1115. acquire(): void {
  1116. this._activeSessionCount++;
  1117. }
  1118. release(): void {
  1119. this._activeSessionCount = Math.max(0, this._activeSessionCount - 1);
  1120. }
  1121. operationStart(): void {
  1122. this._inFlightOperations++;
  1123. }
  1124. operationEnd(): void {
  1125. this._inFlightOperations = Math.max(0, this._inFlightOperations - 1);
  1126. }
  1127. getLlamaCpp(): LlamaCpp {
  1128. return this.llm;
  1129. }
  1130. }
  1131. /**
  1132. * Error thrown when an operation is attempted on a released or aborted session.
  1133. */
  1134. export class SessionReleasedError extends Error {
  1135. constructor(message = "LLM session has been released or aborted") {
  1136. super(message);
  1137. this.name = "SessionReleasedError";
  1138. }
  1139. }
  1140. /**
  1141. * Scoped LLM session with automatic lifecycle management.
  1142. * Wraps LlamaCpp methods with operation tracking and abort handling.
  1143. */
  1144. class LLMSession implements ILLMSession {
  1145. private manager: LLMSessionManager;
  1146. private released = false;
  1147. private abortController: AbortController;
  1148. private maxDurationTimer: ReturnType<typeof setTimeout> | null = null;
  1149. private name: string;
  1150. constructor(manager: LLMSessionManager, options: LLMSessionOptions = {}) {
  1151. this.manager = manager;
  1152. this.name = options.name || "unnamed";
  1153. this.abortController = new AbortController();
  1154. // Link external abort signal if provided
  1155. if (options.signal) {
  1156. if (options.signal.aborted) {
  1157. this.abortController.abort(options.signal.reason);
  1158. } else {
  1159. options.signal.addEventListener("abort", () => {
  1160. this.abortController.abort(options.signal!.reason);
  1161. }, { once: true });
  1162. }
  1163. }
  1164. // Set up max duration timer
  1165. const maxDuration = options.maxDuration ?? 10 * 60 * 1000; // Default 10 minutes
  1166. if (maxDuration > 0) {
  1167. this.maxDurationTimer = setTimeout(() => {
  1168. this.abortController.abort(new Error(`Session "${this.name}" exceeded max duration of ${maxDuration}ms`));
  1169. }, maxDuration);
  1170. this.maxDurationTimer.unref(); // Don't keep process alive
  1171. }
  1172. // Acquire session lease
  1173. this.manager.acquire();
  1174. }
  1175. get isValid(): boolean {
  1176. return !this.released && !this.abortController.signal.aborted;
  1177. }
  1178. get signal(): AbortSignal {
  1179. return this.abortController.signal;
  1180. }
  1181. /**
  1182. * Release the session and decrement ref count.
  1183. * Called automatically by withLLMSession when the callback completes.
  1184. */
  1185. release(): void {
  1186. if (this.released) return;
  1187. this.released = true;
  1188. if (this.maxDurationTimer) {
  1189. clearTimeout(this.maxDurationTimer);
  1190. this.maxDurationTimer = null;
  1191. }
  1192. this.abortController.abort(new Error("Session released"));
  1193. this.manager.release();
  1194. }
  1195. /**
  1196. * Wrap an operation with tracking and abort checking.
  1197. */
  1198. private async withOperation<T>(fn: () => Promise<T>): Promise<T> {
  1199. if (!this.isValid) {
  1200. throw new SessionReleasedError();
  1201. }
  1202. this.manager.operationStart();
  1203. try {
  1204. // Check abort before starting
  1205. if (this.abortController.signal.aborted) {
  1206. throw new SessionReleasedError(
  1207. this.abortController.signal.reason?.message || "Session aborted"
  1208. );
  1209. }
  1210. return await fn();
  1211. } finally {
  1212. this.manager.operationEnd();
  1213. }
  1214. }
  1215. async embed(text: string, options?: EmbedOptions): Promise<EmbeddingResult | null> {
  1216. return this.withOperation(() => this.manager.getLlamaCpp().embed(text, options));
  1217. }
  1218. async embedBatch(texts: string[]): Promise<(EmbeddingResult | null)[]> {
  1219. return this.withOperation(() => this.manager.getLlamaCpp().embedBatch(texts));
  1220. }
  1221. async expandQuery(
  1222. query: string,
  1223. options?: { context?: string; includeLexical?: boolean }
  1224. ): Promise<Queryable[]> {
  1225. return this.withOperation(() => this.manager.getLlamaCpp().expandQuery(query, options));
  1226. }
  1227. async rerank(
  1228. query: string,
  1229. documents: RerankDocument[],
  1230. options?: RerankOptions
  1231. ): Promise<RerankResult> {
  1232. return this.withOperation(() => this.manager.getLlamaCpp().rerank(query, documents, options));
  1233. }
  1234. }
  1235. // Session manager for the default LlamaCpp instance
  1236. let defaultSessionManager: LLMSessionManager | null = null;
  1237. /**
  1238. * Get the session manager for the default LlamaCpp instance.
  1239. */
  1240. function getSessionManager(): LLMSessionManager {
  1241. const llm = getDefaultLlamaCpp();
  1242. if (!defaultSessionManager || defaultSessionManager.getLlamaCpp() !== llm) {
  1243. defaultSessionManager = new LLMSessionManager(llm);
  1244. }
  1245. return defaultSessionManager;
  1246. }
  1247. /**
  1248. * Execute a function with a scoped LLM session.
  1249. * The session provides lifecycle guarantees - resources won't be disposed mid-operation.
  1250. *
  1251. * @example
  1252. * ```typescript
  1253. * await withLLMSession(async (session) => {
  1254. * const expanded = await session.expandQuery(query);
  1255. * const embeddings = await session.embedBatch(texts);
  1256. * const reranked = await session.rerank(query, docs);
  1257. * return reranked;
  1258. * }, { maxDuration: 10 * 60 * 1000, name: 'querySearch' });
  1259. * ```
  1260. */
  1261. export async function withLLMSession<T>(
  1262. fn: (session: ILLMSession) => Promise<T>,
  1263. options?: LLMSessionOptions
  1264. ): Promise<T> {
  1265. const manager = getSessionManager();
  1266. const session = new LLMSession(manager, options);
  1267. try {
  1268. return await fn(session);
  1269. } finally {
  1270. session.release();
  1271. }
  1272. }
  1273. /**
  1274. * Execute a function with a scoped LLM session using a specific LlamaCpp instance.
  1275. * Unlike withLLMSession, this does not use the global singleton.
  1276. */
  1277. export async function withLLMSessionForLlm<T>(
  1278. llm: LlamaCpp,
  1279. fn: (session: ILLMSession) => Promise<T>,
  1280. options?: LLMSessionOptions
  1281. ): Promise<T> {
  1282. const manager = new LLMSessionManager(llm);
  1283. const session = new LLMSession(manager, options);
  1284. try {
  1285. return await fn(session);
  1286. } finally {
  1287. session.release();
  1288. }
  1289. }
  1290. /**
  1291. * Check if idle unload is safe (no active sessions or operations).
  1292. * Used internally by LlamaCpp idle timer.
  1293. */
  1294. export function canUnloadLLM(): boolean {
  1295. if (!defaultSessionManager) return true;
  1296. return defaultSessionManager.canUnload();
  1297. }
  1298. // =============================================================================
  1299. // Singleton for default LlamaCpp instance
  1300. // =============================================================================
  1301. let defaultLlamaCpp: LlamaCpp | null = null;
  1302. /**
  1303. * Get the default LlamaCpp instance (creates one if needed)
  1304. */
  1305. export function getDefaultLlamaCpp(): LlamaCpp {
  1306. if (!defaultLlamaCpp) {
  1307. const embedModel = process.env.QMD_EMBED_MODEL;
  1308. defaultLlamaCpp = new LlamaCpp(embedModel ? { embedModel } : {});
  1309. }
  1310. return defaultLlamaCpp;
  1311. }
  1312. /**
  1313. * Set a custom default LlamaCpp instance (useful for testing)
  1314. */
  1315. export function setDefaultLlamaCpp(llm: LlamaCpp | null): void {
  1316. defaultLlamaCpp = llm;
  1317. }
  1318. /**
  1319. * Dispose the default LlamaCpp instance if it exists.
  1320. * Call this before process exit to prevent NAPI crashes.
  1321. */
  1322. export async function disposeDefaultLlamaCpp(): Promise<void> {
  1323. if (defaultLlamaCpp) {
  1324. await defaultLlamaCpp.dispose();
  1325. defaultLlamaCpp = null;
  1326. }
  1327. }