llm.ts 43 KB

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