-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathllm.ts
More file actions
1923 lines (1698 loc) · 63.3 KB
/
Copy pathllm.ts
File metadata and controls
1923 lines (1698 loc) · 63.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* llm.ts - LLM abstraction layer for QMD using node-llama-cpp
*
* Provides embeddings, text generation, and reranking using local GGUF models.
*/
import {
getLlama,
resolveModelFile,
LlamaChatSession,
LlamaLogLevel,
type Llama,
type LlamaModel,
type LlamaEmbeddingContext,
type Token as LlamaToken,
} from "node-llama-cpp";
import { homedir } from "os";
import { join } from "path";
import { existsSync, mkdirSync, statSync, unlinkSync, readdirSync, readFileSync, writeFileSync } from "fs";
import {
JinaEmbedder,
JinaReranker,
jinaEmbedderFromEnv,
jinaRerankerFromEnv,
type UsageReporter,
} from "./embedders/jina.js";
// =============================================================================
// Embedding Formatting Functions
// =============================================================================
/**
* Detect if a model URI uses the Qwen3-Embedding format.
* Qwen3-Embedding uses a different prompting style than nomic/embeddinggemma.
*/
export function isQwen3EmbeddingModel(modelUri: string): boolean {
return /qwen.*embed/i.test(modelUri) || /embed.*qwen/i.test(modelUri);
}
/**
* Detect if a model URI targets the Jina remote provider.
* Jina URIs are synthesised as `jina:<model>` (see JinaEmbedder.modelUri).
* Jina handles task prefixing server-side via the `task` API field, so we must
* NOT wrap inputs in local template prefixes.
*/
export function isJinaProvider(modelUri: string): boolean {
return modelUri.startsWith("jina:");
}
/**
* Format a query for embedding.
*
* - Jina: raw text (task prefix is sent as API parameter, not inline).
* - Qwen3-Embedding: instruct format.
* - Default (embeddinggemma/nomic): `task: search result | query: …` prefix.
*/
export function formatQueryForEmbedding(query: string, modelUri?: string): string {
const uri = modelUri ?? process.env.QMD_EMBED_MODEL ?? DEFAULT_EMBED_MODEL;
if (isJinaProvider(uri)) {
return query;
}
if (isQwen3EmbeddingModel(uri)) {
return `Instruct: Retrieve relevant documents for the given query\nQuery: ${query}`;
}
return `task: search result | query: ${query}`;
}
/**
* Format a document for embedding.
*
* - Jina: title prepended to text (no synthetic prefixes). Jina task is set to
* `retrieval.passage` via the API.
* - Qwen3-Embedding: raw text, optional title.
* - Default (embeddinggemma/nomic): `title: … | text: …` prefix.
*/
export function formatDocForEmbedding(text: string, title?: string, modelUri?: string): string {
const uri = modelUri ?? process.env.QMD_EMBED_MODEL ?? DEFAULT_EMBED_MODEL;
if (isJinaProvider(uri)) {
return title ? `${title}\n${text}` : text;
}
if (isQwen3EmbeddingModel(uri)) {
// Qwen3-Embedding: documents are raw text, no task prefix
return title ? `${title}\n${text}` : text;
}
return `title: ${title || "none"} | text: ${text}`;
}
// =============================================================================
// Types
// =============================================================================
/**
* Token with log probability
*/
export type TokenLogProb = {
token: string;
logprob: number;
};
/**
* Embedding result
*/
export type EmbeddingResult = {
embedding: number[];
model: string;
};
/**
* Generation result with optional logprobs
*/
export type GenerateResult = {
text: string;
model: string;
logprobs?: TokenLogProb[];
done: boolean;
};
/**
* Rerank result for a single document
*/
export type RerankDocumentResult = {
file: string;
score: number;
index: number;
};
/**
* Batch rerank result
*/
export type RerankResult = {
results: RerankDocumentResult[];
model: string;
};
/**
* Model info
*/
export type ModelInfo = {
name: string;
exists: boolean;
path?: string;
};
/**
* Options for embedding
*/
export type EmbedOptions = {
model?: string;
isQuery?: boolean;
title?: string;
};
/**
* Options for text generation
*/
export type GenerateOptions = {
model?: string;
maxTokens?: number;
temperature?: number;
};
/**
* Options for reranking
*/
export type RerankOptions = {
model?: string;
};
/**
* Options for LLM sessions
*/
export type LLMSessionOptions = {
/** Max session duration in ms (default: 10 minutes) */
maxDuration?: number;
/** External abort signal */
signal?: AbortSignal;
/** Debug name for logging */
name?: string;
};
/**
* Session interface for scoped LLM access with lifecycle guarantees
*/
export interface ILLMSession {
embed(text: string, options?: EmbedOptions): Promise<EmbeddingResult | null>;
embedBatch(texts: string[], options?: EmbedOptions): Promise<(EmbeddingResult | null)[]>;
expandQuery(query: string, options?: { context?: string; includeLexical?: boolean }): Promise<Queryable[]>;
rerank(query: string, documents: RerankDocument[], options?: RerankOptions): Promise<RerankResult>;
/** Whether this session is still valid (not released or aborted) */
readonly isValid: boolean;
/** Abort signal for this session (aborts on release or maxDuration) */
readonly signal: AbortSignal;
}
/**
* Supported query types for different search backends
*/
export type QueryType = 'lex' | 'vec' | 'hyde';
/**
* A single query and its target backend type
*/
export type Queryable = {
type: QueryType;
text: string;
};
/**
* Document to rerank
*/
export type RerankDocument = {
file: string;
text: string;
title?: string;
};
// =============================================================================
// Model Configuration
// =============================================================================
// HuggingFace model URIs for node-llama-cpp
// Format: hf:<user>/<repo>/<file>
// Override via QMD_EMBED_MODEL env var (e.g. hf:Qwen/Qwen3-Embedding-0.6B-GGUF/Qwen3-Embedding-0.6B-Q8_0.gguf)
const DEFAULT_EMBED_MODEL = "hf:ggml-org/embeddinggemma-300M-GGUF/embeddinggemma-300M-Q8_0.gguf";
const DEFAULT_RERANK_MODEL = "hf:ggml-org/Qwen3-Reranker-0.6B-Q8_0-GGUF/qwen3-reranker-0.6b-q8_0.gguf";
// const DEFAULT_GENERATE_MODEL = "hf:ggml-org/Qwen3-0.6B-GGUF/Qwen3-0.6B-Q8_0.gguf";
const DEFAULT_GENERATE_MODEL = "hf:tobil/qmd-query-expansion-1.7B-gguf/qmd-query-expansion-1.7B-q4_k_m.gguf";
// Alternative generation models for query expansion:
// LiquidAI LFM2 - hybrid architecture optimized for edge/on-device inference
// Use these as base for fine-tuning with configs/sft_lfm2.yaml
export const LFM2_GENERATE_MODEL = "hf:LiquidAI/LFM2-1.2B-GGUF/LFM2-1.2B-Q4_K_M.gguf";
export const LFM2_INSTRUCT_MODEL = "hf:LiquidAI/LFM2.5-1.2B-Instruct-GGUF/LFM2.5-1.2B-Instruct-Q4_K_M.gguf";
export const DEFAULT_EMBED_MODEL_URI = DEFAULT_EMBED_MODEL;
export const DEFAULT_RERANK_MODEL_URI = DEFAULT_RERANK_MODEL;
export const DEFAULT_GENERATE_MODEL_URI = DEFAULT_GENERATE_MODEL;
/**
* Build a JinaEmbedder from a `jina:<model>` URI. The model name is taken
* from the URI; API key and shared config still come from environment.
* Returns null if the URI doesn't target Jina so callers can fall through.
*/
function buildJinaEmbedderFromUri(uri: string): JinaEmbedder | null {
if (!uri.startsWith("jina:")) return null;
const model = uri.slice("jina:".length).trim();
if (!model) return null;
const apiKey = (process.env.JINA_API_KEY ?? process.env.QMD_JINA_API_KEY ?? "").trim();
if (!apiKey) {
throw new Error(
`Config specifies jina embed model "${model}" but JINA_API_KEY is not set. ` +
`Export JINA_API_KEY=jina_... or unset the jina: prefix in your config.`,
);
}
// Shared env knobs still apply; the URI only overrides the model name.
const dimEnv = process.env.QMD_JINA_DIMENSION?.trim();
const dimensions = dimEnv ? Number.parseInt(dimEnv, 10) : undefined;
return new JinaEmbedder({
apiKey,
model,
dimensions: Number.isFinite(dimensions) && (dimensions ?? 0) > 0 ? dimensions : undefined,
baseUrl: process.env.QMD_JINA_BASE_URL?.trim() || undefined,
});
}
/** Same as buildJinaEmbedderFromUri but for the reranker. */
function buildJinaRerankerFromUri(uri: string): JinaReranker | null {
if (!uri.startsWith("jina:")) return null;
const model = uri.slice("jina:".length).trim();
if (!model) return null;
const apiKey = (process.env.JINA_API_KEY ?? process.env.QMD_JINA_API_KEY ?? "").trim();
if (!apiKey) {
throw new Error(
`Config specifies jina rerank model "${model}" but JINA_API_KEY is not set. ` +
`Export JINA_API_KEY=jina_... or unset the jina: prefix in your config.`,
);
}
return new JinaReranker({
apiKey,
model,
baseUrl: process.env.QMD_JINA_BASE_URL?.trim() || undefined,
});
}
// Local model cache directory
const MODEL_CACHE_DIR = process.env.XDG_CACHE_HOME
? join(process.env.XDG_CACHE_HOME, "qmd", "models")
: join(homedir(), ".cache", "qmd", "models");
export const DEFAULT_MODEL_CACHE_DIR = MODEL_CACHE_DIR;
export type PullResult = {
model: string;
path: string;
sizeBytes: number;
refreshed: boolean;
};
type HfRef = {
repo: string;
file: string;
};
function parseHfUri(model: string): HfRef | null {
if (!model.startsWith("hf:")) return null;
const without = model.slice(3);
const parts = without.split("/");
if (parts.length < 3) return null;
const repo = parts.slice(0, 2).join("/");
const file = parts.slice(2).join("/");
return { repo, file };
}
async function getRemoteEtag(ref: HfRef): Promise<string | null> {
const url = `https://huggingface.co/${ref.repo}/resolve/main/${ref.file}`;
try {
const resp = await fetch(url, { method: "HEAD" });
if (!resp.ok) return null;
const etag = resp.headers.get("etag");
return etag || null;
} catch {
return null;
}
}
export async function pullModels(
models: string[],
options: { refresh?: boolean; cacheDir?: string } = {}
): Promise<PullResult[]> {
const cacheDir = options.cacheDir || MODEL_CACHE_DIR;
if (!existsSync(cacheDir)) {
mkdirSync(cacheDir, { recursive: true });
}
const results: PullResult[] = [];
for (const model of models) {
let refreshed = false;
const hfRef = parseHfUri(model);
const filename = model.split("/").pop();
const entries = readdirSync(cacheDir, { withFileTypes: true });
const cached = filename
? entries
.filter((entry) => entry.isFile() && entry.name.includes(filename))
.map((entry) => join(cacheDir, entry.name))
: [];
if (hfRef && filename) {
const etagPath = join(cacheDir, `${filename}.etag`);
const remoteEtag = await getRemoteEtag(hfRef);
const localEtag = existsSync(etagPath)
? readFileSync(etagPath, "utf-8").trim()
: null;
const shouldRefresh =
options.refresh || !remoteEtag || remoteEtag !== localEtag || cached.length === 0;
if (shouldRefresh) {
for (const candidate of cached) {
if (existsSync(candidate)) unlinkSync(candidate);
}
if (existsSync(etagPath)) unlinkSync(etagPath);
refreshed = cached.length > 0;
}
} else if (options.refresh && filename) {
for (const candidate of cached) {
if (existsSync(candidate)) unlinkSync(candidate);
refreshed = true;
}
}
const path = await resolveModelFile(model, cacheDir);
const sizeBytes = existsSync(path) ? statSync(path).size : 0;
if (hfRef && filename) {
const remoteEtag = await getRemoteEtag(hfRef);
if (remoteEtag) {
const etagPath = join(cacheDir, `${filename}.etag`);
writeFileSync(etagPath, remoteEtag + "\n", "utf-8");
}
}
results.push({ model, path, sizeBytes, refreshed });
}
return results;
}
// =============================================================================
// LLM Interface
// =============================================================================
/**
* Abstract LLM interface - implement this for different backends
*/
export interface LLM {
/**
* Get embeddings for text
*/
embed(text: string, options?: EmbedOptions): Promise<EmbeddingResult | null>;
/**
* Generate text completion
*/
generate(prompt: string, options?: GenerateOptions): Promise<GenerateResult | null>;
/**
* Check if a model exists/is available
*/
modelExists(model: string): Promise<ModelInfo>;
/**
* Expand a search query into multiple variations for different backends.
* Returns a list of Queryable objects.
*/
expandQuery(query: string, options?: { context?: string, includeLexical?: boolean }): Promise<Queryable[]>;
/**
* Rerank documents by relevance to a query
* Returns list of documents with relevance scores (higher = more relevant)
*/
rerank(query: string, documents: RerankDocument[], options?: RerankOptions): Promise<RerankResult>;
/**
* Dispose of resources
*/
dispose(): Promise<void>;
}
// =============================================================================
// node-llama-cpp Implementation
// =============================================================================
export type LlamaCppConfig = {
embedModel?: string;
generateModel?: string;
rerankModel?: string;
modelCacheDir?: string;
/**
* Optional remote embedding provider. When set, embed()/embedBatch() are
* routed to this provider instead of loading a local embedding model.
* Can also be configured via QMD_EMBED_PROVIDER=jina + JINA_API_KEY env vars.
*/
remoteEmbedder?: JinaEmbedder | null;
/**
* Optional remote reranker. When set, rerank() delegates to this provider
* instead of loading qwen3-reranker locally.
* Can also be configured via QMD_RERANK_PROVIDER=jina + JINA_API_KEY env vars.
*/
remoteReranker?: JinaReranker | null;
/**
* Context size used for query expansion generation contexts.
* Default: 2048. Can also be set via QMD_EXPAND_CONTEXT_SIZE.
*/
expandContextSize?: number;
/**
* Inactivity timeout in ms before unloading contexts (default: 2 minutes, 0 to disable).
*
* Per node-llama-cpp lifecycle guidance, we prefer keeping models loaded and only disposing
* contexts when idle, since contexts (and their sequences) are the heavy per-session objects.
* @see https://node-llama-cpp.withcat.ai/guide/objects-lifecycle
*/
inactivityTimeoutMs?: number;
/**
* Whether to dispose models on inactivity (default: false).
*
* Keeping models loaded avoids repeated VRAM thrash; set to true only if you need aggressive
* memory reclaim.
*/
disposeModelsOnInactivity?: boolean;
};
/**
* LLM implementation using node-llama-cpp
*/
// Default inactivity timeout: 5 minutes (keep models warm during typical search sessions)
const DEFAULT_INACTIVITY_TIMEOUT_MS = 5 * 60 * 1000;
const DEFAULT_EXPAND_CONTEXT_SIZE = 2048;
function resolveExpandContextSize(configValue?: number): number {
if (configValue !== undefined) {
if (!Number.isInteger(configValue) || configValue <= 0) {
throw new Error(`Invalid expandContextSize: ${configValue}. Must be a positive integer.`);
}
return configValue;
}
const envValue = process.env.QMD_EXPAND_CONTEXT_SIZE?.trim();
if (!envValue) return DEFAULT_EXPAND_CONTEXT_SIZE;
const parsed = Number.parseInt(envValue, 10);
if (!Number.isInteger(parsed) || parsed <= 0) {
process.stderr.write(
`QMD Warning: invalid QMD_EXPAND_CONTEXT_SIZE="${envValue}", using default ${DEFAULT_EXPAND_CONTEXT_SIZE}.\n`
);
return DEFAULT_EXPAND_CONTEXT_SIZE;
}
return parsed;
}
export class LlamaCpp implements LLM {
private readonly _ciMode = !!process.env.CI;
private llama: Llama | null = null;
private embedModel: LlamaModel | null = null;
private embedContexts: LlamaEmbeddingContext[] = [];
private generateModel: LlamaModel | null = null;
private rerankModel: LlamaModel | null = null;
private rerankContexts: Awaited<ReturnType<LlamaModel["createRankingContext"]>>[] = [];
private embedModelUri: string;
private generateModelUri: string;
private rerankModelUri: string;
private modelCacheDir: string;
private expandContextSize: number;
// Optional remote embedding provider. When set, LlamaCpp delegates
// embed()/embedBatch() to this provider and skips loading a local embed
// model. Generate + rerank still run locally unless remoteReranker is also
// set.
private remoteEmbedder: JinaEmbedder | null;
// Optional remote reranker. When set, rerank() delegates instead of loading
// qwen3-reranker locally.
private remoteReranker: JinaReranker | null;
// Ensure we don't load the same model/context concurrently (which can allocate duplicate VRAM).
private embedModelLoadPromise: Promise<LlamaModel> | null = null;
private generateModelLoadPromise: Promise<LlamaModel> | null = null;
private rerankModelLoadPromise: Promise<LlamaModel> | null = null;
// Inactivity timer for auto-unloading models
private inactivityTimer: ReturnType<typeof setTimeout> | null = null;
private inactivityTimeoutMs: number;
private disposeModelsOnInactivity: boolean;
// Track disposal state to prevent double-dispose
private disposed = false;
constructor(config: LlamaCppConfig = {}) {
// Resolve the embed backend. Priority:
// 1. Explicit config.remoteEmbedder instance (SDK use case)
// 2. `config.embedModel` starting with `jina:` (YAML models.embed override)
// 3. Env var QMD_EMBED_PROVIDER=jina
// 4. Local model URI (config.embedModel | QMD_EMBED_MODEL | default)
this.remoteEmbedder = config.remoteEmbedder ?? null;
if (!this.remoteEmbedder && config.embedModel?.startsWith("jina:")) {
this.remoteEmbedder = buildJinaEmbedderFromUri(config.embedModel);
}
if (!this.remoteEmbedder) {
this.remoteEmbedder = jinaEmbedderFromEnv();
}
// Resolve the rerank backend. Same priority as embed.
this.remoteReranker = config.remoteReranker ?? null;
if (!this.remoteReranker && config.rerankModel?.startsWith("jina:")) {
this.remoteReranker = buildJinaRerankerFromUri(config.rerankModel);
}
if (!this.remoteReranker) {
this.remoteReranker = jinaRerankerFromEnv();
}
this.embedModelUri = this.remoteEmbedder
? this.remoteEmbedder.modelUri
: (config.embedModel || process.env.QMD_EMBED_MODEL || DEFAULT_EMBED_MODEL);
this.generateModelUri = config.generateModel || process.env.QMD_GENERATE_MODEL || DEFAULT_GENERATE_MODEL;
this.rerankModelUri = this.remoteReranker
? this.remoteReranker.modelUri
: (config.rerankModel || process.env.QMD_RERANK_MODEL || DEFAULT_RERANK_MODEL);
this.modelCacheDir = config.modelCacheDir || MODEL_CACHE_DIR;
this.expandContextSize = resolveExpandContextSize(config.expandContextSize);
this.inactivityTimeoutMs = config.inactivityTimeoutMs ?? DEFAULT_INACTIVITY_TIMEOUT_MS;
this.disposeModelsOnInactivity = config.disposeModelsOnInactivity ?? false;
}
/**
* Attach usage reporters to the active remote providers, if any. Called by
* the store layer after the SQLite DB is ready so embed + rerank usage
* lands in the `jina_usage` table.
*/
setRemoteUsageReporter(reporter: UsageReporter | null): void {
this.remoteEmbedder?.setUsageReporter(reporter);
this.remoteReranker?.setUsageReporter(reporter);
}
/** Stable identifier for the active embedding backend. Used by callers to pick formatting / detect Jina. */
get embedModelName(): string {
return this.embedModelUri;
}
/** True when a remote embedding provider is configured. */
get usingRemoteEmbedder(): boolean {
return this.remoteEmbedder !== null;
}
/** True when a remote reranker is configured. */
get usingRemoteReranker(): boolean {
return this.remoteReranker !== null;
}
/** Human-readable provider name for status output. */
get embedProviderName(): string {
if (this.remoteEmbedder) return `jina (${this.remoteEmbedder.model})`;
return "local (node-llama-cpp)";
}
/** Human-readable rerank provider name for status output. */
get rerankProviderName(): string {
if (this.remoteReranker) return `jina (${this.remoteReranker.model})`;
return "local (node-llama-cpp)";
}
/** Stable identifier for the active rerank backend. */
get rerankModelName(): string {
return this.rerankModelUri;
}
/**
* Reset the inactivity timer. Called after each model operation.
* When timer fires, models are unloaded to free memory (if no active sessions).
*/
private touchActivity(): void {
// Clear existing timer
if (this.inactivityTimer) {
clearTimeout(this.inactivityTimer);
this.inactivityTimer = null;
}
// Only set timer if we have disposable contexts and timeout is enabled
if (this.inactivityTimeoutMs > 0 && this.hasLoadedContexts()) {
this.inactivityTimer = setTimeout(() => {
// Check if session manager allows unloading
// canUnloadLLM is defined later in this file - it checks the session manager
// We use dynamic import pattern to avoid circular dependency issues
if (typeof canUnloadLLM === 'function' && !canUnloadLLM()) {
// Active sessions/operations - reschedule timer
this.touchActivity();
return;
}
this.unloadIdleResources().catch(err => {
console.error("Error unloading idle resources:", err);
});
}, this.inactivityTimeoutMs);
// Don't keep process alive just for this timer
this.inactivityTimer.unref();
}
}
/**
* Check if any contexts are currently loaded (and therefore worth unloading on inactivity).
*/
private hasLoadedContexts(): boolean {
return !!(this.embedContexts.length > 0 || this.rerankContexts.length > 0);
}
/**
* Unload idle resources but keep the instance alive for future use.
*
* By default, this disposes contexts (and their dependent sequences), while keeping models loaded.
* This matches the intended lifecycle: model → context → sequence, where contexts are per-session.
*/
async unloadIdleResources(): Promise<void> {
// Don't unload if already disposed
if (this.disposed) {
return;
}
// Clear timer
if (this.inactivityTimer) {
clearTimeout(this.inactivityTimer);
this.inactivityTimer = null;
}
// Dispose contexts first
for (const ctx of this.embedContexts) {
await ctx.dispose();
}
this.embedContexts = [];
for (const ctx of this.rerankContexts) {
await ctx.dispose();
}
this.rerankContexts = [];
// Optionally dispose models too (opt-in)
if (this.disposeModelsOnInactivity) {
if (this.embedModel) {
await this.embedModel.dispose();
this.embedModel = null;
}
if (this.generateModel) {
await this.generateModel.dispose();
this.generateModel = null;
}
if (this.rerankModel) {
await this.rerankModel.dispose();
this.rerankModel = null;
}
// Reset load promises so models can be reloaded later
this.embedModelLoadPromise = null;
this.generateModelLoadPromise = null;
this.rerankModelLoadPromise = null;
}
// Note: We keep llama instance alive - it's lightweight
}
/**
* Ensure model cache directory exists
*/
private ensureModelCacheDir(): void {
if (!existsSync(this.modelCacheDir)) {
mkdirSync(this.modelCacheDir, { recursive: true });
}
}
/**
* Initialize the llama instance (lazy)
*/
private async ensureLlama(): Promise<Llama> {
if (!this.llama) {
// Allow override via QMD_LLAMA_GPU: "false" | "off" | "none" forces CPU
const gpuOverride = (process.env.QMD_LLAMA_GPU ?? "").toLowerCase();
const forceCpu = ["false", "off", "none", "disable", "disabled", "0"].includes(gpuOverride);
const loadLlama = async (gpu: "auto" | false) =>
await getLlama({
build: "autoAttempt",
logLevel: LlamaLogLevel.error,
gpu,
});
let llama: Llama;
if (forceCpu) {
llama = await loadLlama(false);
} else {
try {
llama = await loadLlama("auto");
} catch (err) {
// GPU backend (e.g. Vulkan on headless/driverless machines) can throw at init.
// Fall back to CPU so qmd still works.
process.stderr.write(
`QMD Warning: GPU init failed (${err instanceof Error ? err.message : String(err)}), falling back to CPU.\n`
);
llama = await loadLlama(false);
}
}
if (llama.gpu === false) {
process.stderr.write(
"QMD Warning: no GPU acceleration, running on CPU (slow). Run 'qmd status' for details.\n"
);
}
this.llama = llama;
}
return this.llama;
}
/**
* Resolve a model URI to a local path, downloading if needed
*/
private async resolveModel(modelUri: string): Promise<string> {
this.ensureModelCacheDir();
// resolveModelFile handles HF URIs and downloads to the cache dir
return await resolveModelFile(modelUri, this.modelCacheDir);
}
/**
* Load embedding model (lazy)
*/
private async ensureEmbedModel(): Promise<LlamaModel> {
if (this.embedModel) {
return this.embedModel;
}
if (this.embedModelLoadPromise) {
return await this.embedModelLoadPromise;
}
this.embedModelLoadPromise = (async () => {
const llama = await this.ensureLlama();
const modelPath = await this.resolveModel(this.embedModelUri);
const model = await llama.loadModel({ modelPath });
this.embedModel = model;
// Model loading counts as activity - ping to keep alive
this.touchActivity();
return model;
})();
try {
return await this.embedModelLoadPromise;
} finally {
// Keep the resolved model cached; clear only the in-flight promise.
this.embedModelLoadPromise = null;
}
}
/**
* Compute how many parallel contexts to create.
*
* GPU: constrained by VRAM (25% of free, capped at 8).
* CPU: constrained by cores. Splitting threads across contexts enables
* true parallelism (each context runs on its own cores). Use at most
* half the math cores, with at least 4 threads per context.
*/
private async computeParallelism(perContextMB: number): Promise<number> {
const llama = await this.ensureLlama();
if (llama.gpu) {
try {
const vram = await llama.getVramState();
const freeMB = vram.free / (1024 * 1024);
const maxByVram = Math.floor((freeMB * 0.25) / perContextMB);
return Math.max(1, Math.min(8, maxByVram));
} catch {
return 2;
}
}
// CPU: split cores across contexts. At least 4 threads per context.
const cores = llama.cpuMathCores || 4;
const maxContexts = Math.floor(cores / 4);
return Math.max(1, Math.min(4, maxContexts));
}
/**
* Get the number of threads each context should use, given N parallel contexts.
* Splits available math cores evenly across contexts.
*/
private async threadsPerContext(parallelism: number): Promise<number> {
const llama = await this.ensureLlama();
if (llama.gpu) return 0; // GPU: let the library decide
const cores = llama.cpuMathCores || 4;
return Math.max(1, Math.floor(cores / parallelism));
}
/**
* Load embedding contexts (lazy). Creates multiple for parallel embedding.
* Uses promise guard to prevent concurrent context creation race condition.
*/
private embedContextsCreatePromise: Promise<LlamaEmbeddingContext[]> | null = null;
private async ensureEmbedContexts(): Promise<LlamaEmbeddingContext[]> {
if (this.embedContexts.length > 0) {
this.touchActivity();
return this.embedContexts;
}
if (this.embedContextsCreatePromise) {
return await this.embedContextsCreatePromise;
}
this.embedContextsCreatePromise = (async () => {
const model = await this.ensureEmbedModel();
// Embed contexts are ~143 MB each (nomic-embed 2048 ctx)
const n = await this.computeParallelism(150);
const threads = await this.threadsPerContext(n);
for (let i = 0; i < n; i++) {
try {
this.embedContexts.push(await model.createEmbeddingContext({
contextSize: LlamaCpp.EMBED_CONTEXT_SIZE,
...(threads > 0 ? { threads } : {}),
}));
} catch {
if (this.embedContexts.length === 0) throw new Error("Failed to create any embedding context");
break;
}
}
this.touchActivity();
return this.embedContexts;
})();
try {
return await this.embedContextsCreatePromise;
} finally {
this.embedContextsCreatePromise = null;
}
}
/**
* Get a single embed context (for single-embed calls). Uses first from pool.
*/
private async ensureEmbedContext(): Promise<LlamaEmbeddingContext> {
const contexts = await this.ensureEmbedContexts();
return contexts[0]!;
}
/**
* Load generation model (lazy) - context is created fresh per call
*/
private async ensureGenerateModel(): Promise<LlamaModel> {
if (!this.generateModel) {
if (this.generateModelLoadPromise) {
return await this.generateModelLoadPromise;
}
this.generateModelLoadPromise = (async () => {
const llama = await this.ensureLlama();
const modelPath = await this.resolveModel(this.generateModelUri);
const model = await llama.loadModel({ modelPath });
this.generateModel = model;
return model;
})();
try {
await this.generateModelLoadPromise;
} finally {
this.generateModelLoadPromise = null;
}
}
this.touchActivity();
if (!this.generateModel) {
throw new Error("Generate model not loaded");
}
return this.generateModel;
}
/**
* Load rerank model (lazy)
*/
private async ensureRerankModel(): Promise<LlamaModel> {
if (this.rerankModel) {
return this.rerankModel;
}
if (this.rerankModelLoadPromise) {
return await this.rerankModelLoadPromise;
}
this.rerankModelLoadPromise = (async () => {
const llama = await this.ensureLlama();
const modelPath = await this.resolveModel(this.rerankModelUri);
const model = await llama.loadModel({ modelPath });
this.rerankModel = model;
// Model loading counts as activity - ping to keep alive
this.touchActivity();
return model;
})();
try {
return await this.rerankModelLoadPromise;
} finally {
this.rerankModelLoadPromise = null;
}
}
/**
* Load rerank contexts (lazy). Creates multiple contexts for parallel ranking.
* Each context has its own sequence, so they can evaluate independently.
*
* Tuning choices:
* - contextSize 1024: reranking chunks are ~800 tokens max, 1024 is plenty
* - flashAttention: ~20% less VRAM per context (568 vs 711 MB)
* - Combined: drops from 11.6 GB (auto, no flash) to 568 MB per context (20×)
*/
// Qwen3 reranker template adds ~200 tokens overhead (system prompt, tags, etc.)
// Default 2048 was too small for longer documents (e.g. session transcripts,
// CJK text, or large markdown files) — callers hit "input lengths exceed
// context size" errors even after truncation because the overhead estimate
// was insufficient. 4096 comfortably fits the largest real-world chunks
// while staying well below the 40 960-token auto size.
// Override with QMD_RERANK_CONTEXT_SIZE env var if you need more headroom.
private static readonly RERANK_CONTEXT_SIZE: number = (() => {
const v = parseInt(process.env.QMD_RERANK_CONTEXT_SIZE ?? "", 10);
return Number.isFinite(v) && v > 0 ? v : 4096;
})();
private static readonly EMBED_CONTEXT_SIZE: number = (() => {
const v = parseInt(process.env.QMD_EMBED_CONTEXT_SIZE ?? "", 10);
return Number.isFinite(v) && v > 0 ? v : 2048;
})();
private async ensureRerankContexts(): Promise<Awaited<ReturnType<LlamaModel["createRankingContext"]>>[]> {
if (this.rerankContexts.length === 0) {
const model = await this.ensureRerankModel();
// ~960 MB per context with flash attention at contextSize 2048
const n = Math.min(await this.computeParallelism(1000), 4);
const threads = await this.threadsPerContext(n);
for (let i = 0; i < n; i++) {
try {
this.rerankContexts.push(await model.createRankingContext({
contextSize: LlamaCpp.RERANK_CONTEXT_SIZE,
flashAttention: true,
...(threads > 0 ? { threads } : {}),
} as any));
} catch {
if (this.rerankContexts.length === 0) {
// Flash attention might not be supported — retry without it
try {
this.rerankContexts.push(await model.createRankingContext({
contextSize: LlamaCpp.RERANK_CONTEXT_SIZE,
...(threads > 0 ? { threads } : {}),
}));
} catch {
throw new Error("Failed to create any rerank context");
}
}
break;
}
}
}
this.touchActivity();
return this.rerankContexts;
}
// ==========================================================================